On a SQL Server I have a table namespace
Namespace
---------
Prefix
com.foo
com.bar
com.foobar
And I want to prevent inserts if a conflicting namespace already exists. A namespace includes all sub namespace. E.g. com.foo includes everything 'below' com.foo e.g. com.foo.bar and com.foo.bar.baz but not com.foobar or com.foobar.baz (com.foobar is a different namespace than com.foo)
The check should be atomic to prevent concurrency issues.
I have this insert that does the insert conditionally. But I am not sure if it is atomic.
INSERT INTO namespace
(PREFIX)
SELECT t1.PREFIX
FROM namespace t1
WHERE NOT EXISTS(SELECT t2.PREFIX
FROM namespace t2
WHERE t2.PREFIX in ('com.foo.bar','com.foo','com'))
The comment here https://stackoverflow.com/a/16636779/1844551 suggests that with Postgres it is not guaranteed to be atomic. How about MSSQL?
Ideally this would be a check constraint, but I don't know how to construct the where t2.PREFIX in ('com.foo.bar','com.foo','com')
from an input like com.foo.bar
.
Note: a simple startswith doesn't do the trick since com.foo
and com.foobar
are different namespaces that don't conflict each other. So com.foobar
can be inserted if com.foo
exists.
So my current idea is to implement this query in the client code and check the result if something was inserted.
Is there a better way to implement this in the DB as a constraint?