Atomically Creating An SQLite Database
From
Lawrence D?Oliveiro@3:633/10 to
All on Thu Nov 12 04:00:50 2026
Thinking about how one might use O_EXCL mode when opening an SQLite
database that would be automatically created if it didn?t exist, I
discovered that SQLite is not bothered if there is already a
zero-length file with the same name as the database you ask it to open
-- it will automatically fill it out as appropriate. It is easy enough
to create such a file, using O_EXCL to error out if the file already
exists.
With this in mind, I offer some code for opening a database file, with
a choice of opening modes: read-only (must exist); read-write (also
must exist), or read-write-create (will be created and initialized if
it does not exist):
class DB_OPEN(enum.IntEnum) :
"database opening modes."
READONLY = 0 # existing database, only for reading
READWRITE = 1 # existing database, for reading and writing
READWRITECREATE = 2 # create database if it doesn?t exist, open for reading and writing
#end DB_OPEN
def open_db(dbname, mode) :
"opens the specified database file and returns a new connection. mode is DB_OPEN value."
if mode == DB_OPEN.READWRITECREATE :
fd = os.open(dbname, flags = os.O_RDWR | os.O_CREAT | os.O_EXCL)
# try to guarantee not overwriting existing file when creating database
else :
fd = None
#end if
db = sqlite.Connection \
(
dbname,
flags =
(sqlite.SQLITE_OPEN_READONLY, sqlite.SQLITE_OPEN_READWRITE)
[mode >= DB_OPEN.READWRITE]
)
if fd != None :
os.close(fd)
#end if
... initialize database tables as appropriate ...
return db
#end open_db_common
--- PyGate Linux v1.5.19
* Origin: Dragon's Lair, PyGate NNTP<>Fido Gate (3:633/10)