SQLite Forum

Opening a DB with SQLITE_OPEN_EXCLUSIVE
Login
I'm the anonymous who wrote (6), I created an account now :)

Yeah, it's not actually a bug, the documentation exhaustively lists the flags you can use and `SQLITE_OPEN_EXCLUSIVE` is simply not among them.

> What harm would come about if another rogue process created the database in between steps 1 and 2?

Unfortunately, a detailed response will inevitably lead to a contrived example, as you expected. Suppose you launch the program twice, let's call the instances A and B.

1. A checks if DB exists. It does not.
2. B checks if DB exists. It does not.
3. A creates DB file with `sqlite3_open_v2()`
4. A moves on to do initialisation jobs (set up tables, insert rows, etc.)
5. B opens existing DB file with `sqlite3_open_v2()`. B also thinks it created the file.
6. B moves on to do initialisation jobs (set up tables, insert rows, etc.)

I now have to expect races in the initialisation jobs and guess whether there was a race in file creation. This complicates the logic. Of course I could just interpret the failure of CREATE TABLE with "already exists" as such a race condition and back out of the initialisation logic in this case. But now I'm already working around downstream consequences of not knowing whether it was me who created the file. With a working `SQLITE_OPEN_EXCLUSIVE`, I am reasonably confident that only A will ever run an initialisation job and it will not be possible for any other process to ever run this initialisation job on this database.

Now, I admit that this has never happened to me. You may be correct if you point out that it will never happen to me. What bothers me is that I am forced to write code that suffers from a race condition, especially given the flag to solve it exists and is even used internally. In a similar vein, the `open(2)` implementers could say: "Do you really need `O_EXCL`? You could just check for file existence and then create it. A race condition is exceedingly rare. If another program already created it, why does that matter? After all, the file is now there for you to use, and you can handle any races between two processes inside that file."