🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: comp.programming
1 messages
1 total messages Started by Lawrence D’Oliveiro Thu, 12 Nov 2026 04:00
Atomically Creating An SQLite Database
#23
Author: Lawrence D’Oliveiro
Date: Thu, 12 Nov 2026 04:00
41 lines
2917 bytes
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
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads