SQL conditional inserts, and other multiple queries done in a atomic/all
or nothing/non interleaved way
Let's say i have an application relying on a SQL 'users' table and want to
avoid multiple users with the same name:
When I insert a new user in my table, I must make sure that there is no
similar rows already. So that is 2 queries, the second one only happening
if the first one returned nothing:
-query1: select * from users where username='Marie-Antoinette'
-query2: insert into users ('','Marie-Antoinette','37')
Multiple applications instances access the shared database simultaneously,
how do I make sure that no query is inserted between query1 and query2?
That it is done as an atomic operation in the DB with nothing in between?
There may be a way, a syntax to do conditional inserts but my question is
more about "how to make sure i can make N queries with the guarantee that
no queries from other clients will be interleaved in my batch"?
Let's say I have, in my application, an operation that requires 4 queries:
my operation consists of:
-query1: insert stuff in table 1
-query2: select stuff from table 2
-query3: insert stuff in table 3
-query4: update stuff in table 4
Those should be considered as an atomic operation, it's all or nothing,
but not only that, during that sequence, there must be the guarantee that
there won't be anything interleaved (since between those queries the
database has no integrity, and that those 4 tables must be frozen while
this operation happens) and that multiple clients can trigger that
operation and that the multiple calls will be somehow queued rather than
failing.
over time, that would be:
-client #1 query 1
-client #1 query 2
-client #1 query 3
-client #1 query 4
-client #2 query 1
-client #2 query 2
-client #2 query 3
-client #2 query 4
-client #1 query 1
-client #1 query 2
-client #1 query 3
-client #1 query 4
What is the recommended approach to achieve that?
No comments:
Post a Comment