| summary | How the driver is built: the layers from the SQLite C to database/sql, how the C becomes Go assembly, what the Go host gives SQLite, group commit, how replication follows the database, the rules for making the engine faster, and the routes that were left out and why | ||||
|---|---|---|---|---|---|
| read_when |
|
||||
| audience | users |
English · 简体中文
flowchart TB
app["Your program, through database/sql"] --> drv["Driver (root package)<br>one writer per file, group commit"]
drv --> api["internal/csqlite<br>the C API and the Go host:<br>shadow stacks, malloc, mutexes"]
api --> eng["SQLite as Go assembly<br>generated from engine/"]
eng -- "VFS and mutex calls" --> api
api --> vfs["internal/vfs<br>files, locks, shared memory"]
vfs --> os["The kernel"]
From the bottom up:
- The C tree (
engine/): the SQLite amalgamation as released, the compile options (engine/sqlite.c), a VFS and mutexes that call Go (engine/os.c,engine/host.h) and a small libc (engine/libc/). It is compiled freestanding, with no system headers. - The generator (
internal/goasm/gen/): turns the C tree into Go assembly, one Go function per C function, and a Go file that declares them. Maintainers run it (make gen). Users never do. - The engine package (
internal/csqlite): the generated Go assembly and its declarations, checked in, beside the Go host: shadow stacks, polls, malloc, mutexes, the VFS callbacks, and the small C API the driver calls. - The files (
internal/vfs): pure Go, no engine. On linux and darwin, it follows SQLite's file and lock rules from os_unix. Connections in one process to the same database share one set of locks, tracked apart in memory, and the driver calls the kernel only when the process's lock changes. Each WAL index slot has its own state and lock. A reader that takes a read slot the process has locked counts itself in with one atomic step. The write slot has a lock no reader takes, because a goroutine that sleeps on a lock waits a long time for a core when every core is busy. A connection asking for an exclusive slot is refused at once while another connection holds, takes, or releases the slot, and waits only for an operation that leaves the slot with no holder (see When every core is busy). Kernel locks are OFD locks (locks tied to an open file), so closing one connection never drops another's locks. The-shmfile is mapped for WAL. On windows, files and locks follow os_win. Each connection takesLockFileExlocks on its own handle, and Windows keeps each handle's locks apart, so connections in one process exclude each other just as processes do. The-shmfile is mapped withCreateFileMapping, one view per region, and each connection locks its slots on its own handle. The byte ranges match os_unix and os_win, so SQLite built from C can use a database at the same time. - The driver (the root package):
database/sql/driveron top of that API, with one writer per database file and group commit.
make gen runs scripts/gen-engine.sh, which runs the generator over engine/sqlite.c, engine/libc/string/*.c, engine/libc/math/*.c and engine/libc/math.c:
flowchart LR
c["engine/<br>SQLite, os.c, libc"] -->|clang| ir["LLVM IR<br>per file"]
ir -->|"llvm-link, opt"| mod["one module"]
mod -->|"shadow-stack pass"| mod2["locals on the<br>shadow stack, polls"]
mod2 -->|llc| mc["machine code"]
mc -->|"generator"| goasm["Go assembly<br>internal/csqlite"]
goasm -->|"go build, then<br>the post-link check"| bin["binary"]
- clang compiles each file to LLVM IR using the flags in
engine/flags.shplus the generator's own flags (target, frame pointer, no tail calls, registers Go keeps). - llvm-link joins the files, and the optimizer runs once more over the whole module.
- The shadow-stack pass (
internal/goasm/gen/pass/, an LLVM plugin) moves every local whose address is taken onto a separate stack that the host gives, since Go's stack moves when it grows. It adds a poll to every loop so Go can stop the goroutine, and passes the extra arguments of a variadic call in a block on that stack. - llc writes the machine code. The generator rewrites each function as Go assembly, adding Go's prologue and stack check, taking arguments from Go's stack, and making calls the way Go does.
- A check reads the linked binary and compares each function against what llc wrote.
SQLite needs no edits for this. SQLite 3.54.1 lowers whole on both targets: about 1900 functions with FTS5, R*Tree and the math functions, and no stubs. It produces 14 MB of assembly in under a minute, and the post-link check passes on both linux/arm64 and linux/amd64 binaries.
SQLite keeps 33 writable globals: its configuration, allocator and page cache state, and the built-in function tables it links at start. The whole process shares them like Go globals, so they go into the one Go data symbol alongside the read-only data, written without RODATA. SQLite's read-only data becomes writable memory too, though SQLite never writes to it.
The lowering can only rewrite a data reference that takes an address. A direct load would have to become a copy inside the function body, which is wrong for data that changes. So before llc runs, the generator marks every writable global external and preemptible in the IR (ExposeWritableData). Position-independent code then reaches each global only by loading its address from the GOT, and the lowering turns that load into the address in the data symbol. On x86, instructions sometimes fold the load into a compare, add, or subtract (cmpq sym@GOTPCREL(%rip), %rdi). For those globals, the data symbol ends with an 8-byte slot holding the global's address, and the instruction reads that slot. Any direct reference to writable data stops the build. SQLITE_OMIT_WSD was tried and does not fit: it leaves 21 of 33 globals writable (3.50.4) and adds a lookup to every configuration read.
A constant holding pointers has the same problem when C copies it. A local array or struct with an initializer (FTS5's table of built-in tokenizers) is a memcpy from a constant, which llc turns into direct loads. The lowering cannot copy that constant into the function body because its pointers need relocations. So the generator also sends constants that hold pointers and are copied by memcpy or memmove through the GOT (ExposeCopiedPointerTables). Every other constant is left alone.
A call to a C function host_x declared in engine/host.h becomes a call to the Go function host_x in internal/csqlite, with the shadow pointer first. The generator recognizes them by the prefix.
- Shadow stacks. Each connection has a 32 MiB region, aligned to its size and followed by a guard page, mapped with mmap and touched only as C uses it. Windows has no mapping that holds no memory back, so there
VirtualAllocreserves and commits the region: it counts against the commit limit, and uses memory only as C touches it. Each call into C passes a pointer into this region. Strings and out-parameters go there too, so a call allocates nothing. - Polls. The C calls
host_pollevery 10000 ticks of its loops. Its stack check is where the Go runtime can stop the goroutine. - Room for a fault on windows/amd64. On a fault, such as reading a bad pointer in C, windows writes CPU state below the thread's stack pointer, which in the engine is the goroutine's stack. Go leaves 4 KiB there, while AMX state takes 12.8 KiB, so near the bottom of a stack the rest spills into the heap (golang/go#81238). On windows/amd64, every generated function checks after Go's stack check that 12 KiB more are free, and grows the stack if not (
roomCheckininternal/goasm/gen/emit.go). Go may shrink the stack while a Go function called from C runs (a callback ormalloc), in its own code, in its defers, or as the runtime ends a recovered panic. So on windows, C calls Go through a generated wrapper that restores the extra room after the call returns (callText,engine_room_windows_amd64.go). The linux and darwin code does not change because#ifdef GOOS_windowswraps the check. windows/arm64 has no check because its CPU state fits in 4 KiB (2.5 KiB measured on GitHub's Arm runner by liustack/beastjs). The check adds 4 instructions in functions with Go's stack check and 7 in functions without one, which load g first, and each call into Go passes through one extra function. Timed on linux/amd64 with the windows code enabled (AMD EPYC 7B13, 6 alternating rounds, median change per round), insert transactions took 3.3% longer, queries of 10 to 1,000 rows 2.4%, an aggregate 2.0%, and a point query 1.5%, while the other benchmarks inbench/changed by less than their noise. A fault in Go code, such as a nil pointer in a program's Go function, still has only Go's 4 KiB, as in any Go program on windows, until Go fixes it. - Memory.
malloc,reallocandfreerun in Go. Allocations up to 256 KiB use size classes cut from spans of about 256 KiB mapped with mmap, and larger allocations get their own mapping. When all blocks in a span are free, the span returns to the system after its size class goes a second or two without needing it, except for a few spans kept for good per size class. Spans do not return at once because a reader frees every page of its cache after another connection commits and takes them again as it reads, which would otherwise map and unmap memory on every commit. The size classes are split across 32 arenas with their own locks. Each connection uses the arena given to its shadow stack, chosen as the one with the fewest connections, so concurrent connections do not wait on each other inmalloc. Each arena keeps its own empty spans: about 160 KiB more per connection with 16 active connections, and at most 17 MiB per arena when a connection has used every size class. An arena with no connections for a second or two returns those empty spans, so a brief spike in connections does not leave empty spans held in every arena. The garbage collector never sees SQLite's memory. - Threads. SQLite runs in multi-thread mode: many goroutines can use different connections at once, with one goroutine per connection at a time.
engine/os.cinstalls Gosync.Mutexvalues as SQLite mutexes (SQLITE_CONFIG_MUTEX, since SQLite 3.54 has no compile option for this). - Files.
engine/os.cis the VFS (namedgo). Each method callsinternal/vfs. - Local time. The
localtimeandutcmodifiers calllocaltime_rinengine/os.c, which asks Go: the zone istime.Local(theTZvariable, or/etc/localtime). A program in an image without zone files gets UTC unless it importstime/tzdata. - Virtual tables. A Go module (
WithModule) maps to asqlite3_moduleinengine/os.cwhose methods call Go with the table or cursor handle. A module created withModuleWritableuses a secondsqlite3_modulethat addsxUpdateand the transaction methods. Writes to its tables never merge because the Go code may keep state outside the database that a rolled-back batch or another connection could not undo.goClassifylooks up the table and marks those statements to run alone. Statements that read a Go table do not merge either, such asINSERT INTO t SELECT ... FROMone, because each connection has its own instance of the table, which may return other rows than another connection's. SQLite adds a newly created table to the transaction without callingxBegin, so a writable module'sxCreatecallsxBeginitself. Every table that getsxSync,xCommitorxRollbackhas therefore had itsxBegin. Because SQLite callsxEofafter every row,engine/os.canswers it from a field Go sets afterFilterandNext. - Go code that panics. If a Go function, aggregate, or virtual table method panics, its statement fails just as an error would. A collation has no way to fail, so on a panic
engine/os.ccallssqlite3OomFault, SQLite's own function for a failed allocation. SQLite then stops the statement withSQLITE_NOMEMand rolls back the statement or the whole transaction, on the error path it tests for every allocation. Becauseengine/os.ccompiles withsqlite3.c, the host also reads two other SQLite internals (below):db->nVTrans, and the links from aParseto the statement it belongs to. If another statement's error rolls back the transaction while a write statement is running, that write ends with an error instead of succeeding (a rollback hook counts rollbacks). - A panic in the host. A panic in driver code called by SQLite (the VFS, allocator, or mutexes) is a driver bug. The call fails and marks the connection broken. Because its C code may have stopped halfway, no C runs on that connection again. When the connection is dropped, the driver closes the files SQLite opened for it in Go, releasing its file and shared-memory locks. To other connections, this looks like a dead process, which SQLite recovers from. A commit in progress when the connection broke may or may not be in the file, as after a crash, and its call gets an error either way.
A query run without a *sql.Stmt (Query, QueryRow) keeps its prepared statement on the connection, up to 64 per connection (cache.go). The next query with the same SQL on that connection reuses that statement instead of preparing a new one. While its rows are open, the statement is not shared, so another query of the same SQL prepares its own statement. Only statements that read the main database are kept. An Exec of a single write to the main database keeps its statement the same way, but only on a connection that has never changed itself, the same rule as group commit. SQLite bakes settings such as foreign_keys and defer_foreign_keys into a write when preparing it and does not always prepare it again when they change, so a write kept across such a change could skip a foreign key check. Any PRAGMA, ATTACH, EXPLAIN, DDL, or statement on another schema is prepared each time. When a connection prepares a statement that changes the connection (a PRAGMA with an argument but the few that set nothing, ATTACH, or a temporary object), it drops all kept statements, whether the statement runs or not. After a schema change, SQLite prepares a kept statement again on its own. Every rule is in query-cache.md.
This makes many readers fast. A *sql.Stmt locks its *sql.DB mutex on every query, even when prepared on a *sql.Conn. With a few readers, that mutex sets the rate, not SQLite. A query on a *sql.Conn without a Stmt takes no lock shared by readers, and keeping the statement avoids preparing it again.
Inside the driver, a connection takes its file's write lock before running any statement that may write (sqlite3_stmt_readonly, plus PRAGMA optimize and a read of pragma_optimize, which SQLite counts as reads even though they may run ANALYZE). It releases the lock once SQLite has no write transaction open on that connection: when the transaction ends, or when SQLite refuses the write before writing begins, such as on a connection that only reads. Readers never take this lock. Without it, concurrent writers in one process wait in SQLite's busy handler, whose sleeps grow (1, 2, 5 ms and up to 100 ms) while the writer holding SQLite's lock waits for a thread. On an Apple M4, 64 goroutines each inserting one row took 1.7 ms per insert without the lock, and 12 µs with it. With cgo, each call holds its own thread, which is why mattn/go-sqlite3 does not see this. A connection in a read transaction does not wait for the lock and gets SQLITE_BUSY at once, just as SQLite gives it. In rollback journal mode, the writer holding the lock waits for that connection's read lock to clear before committing, so both would wait out the busy timeout. Writers in other processes still meet SQLite's own locks.
In the default rollback journal mode, readers still meet SQLite's locks. While a COMMIT holds the file locked during its fsyncs, no connection can start a read, and a writer cannot commit while a connection reads. SQLite's busy handler sleeps for growing times (1, 2, 5 ms and up to 100 ms) before trying again, so it can miss every gap between back-to-back commits. While writes are running, a read or a new connection's first statement can wait out the whole busy timeout and get SQLITE_BUSY, as with mattn/go-sqlite3 and modernc.org/sqlite. The driver replaces it with its own busy handler (busy.go), which knows what locks this process's connections hold on the file. When another connection in the process holds the lock, the handler sleeps as long as SQLite's would, but wakes early when the lock clears. A connection blocked by a writer in the process wakes when that writer releases the write lock, and a writer blocked from committing by readers in the process wakes when the last reader lets go. A woken connection takes no place among the writers, so the scheduler decides whether it or the next writer runs first. When every core is busy, writers can win every time, so a connection that has waited half its busy timeout goes first: the driver holds the write lock for it until it runs.
A writer that holds its process's write lock and is still blocked is blocked by another process, which signals no one when it lets go. The writer retries every millisecond to catch the next pause between that process's commits or during a checkpoint, and gives up once its busy timeout passes on the clock, counting its retries too. It does the same when the blocker is in its own process but outside the driver's sight: readers waited on by PRAGMA wal_checkpoint(FULL), RESTART or TRUNCATE, or the connections that hold a file attached to it. On 4 linux cores with synchronous=FULL, 30 short transactions in one process beside another writing continuously from 64 goroutines waited 15 to 26 ms at the median and 0.08 to 0.19 s at most across 3 runs, compared to 0.23 to 1.03 s and 4.5 to 5.0 s before, when 2 of the 90 got database is locked. The busy process holds the lock 93% of the time and lets it go for about 40 µs between commits, so a writer retrying every millisecond gets in after tens of tries. During those runs, the busy process wrote 39 000 to 42 000 rows a second, compared to 39 000 to 49 000 alone: it lost the lock for 3 to 4% of the time, while the other held it and until its own writer, also retrying every millisecond, saw it free. If another process writes while this one checkpoints, it leaves frames the checkpoint did not copy, and this process then checkpoints once more so that its WAL still starts over (wal-growth.md). Without that, each commit made the WAL longer, slowing its sync and cutting the busy process to less than half its speed.
A connection that does not hold the write lock waits for another process the same way SQLite does. The wait ends when the call's context is done. On 4 linux cores with a 1 s busy timeout, 8 reading goroutines beside 8 writing ones used to get database is locked 4 to 11 times in 3 s and read 100 to 600 times a second. They now get no error and read 1 100 to 6 100 times a second, beside the same 1 300 writes a second. One writing goroutine beside the 8 readers used to write 400 times a second while they read 30 to 60 times. It now writes 360 times while they read 23 000 to 29 000, waiting for reads that did not get in before. In WAL mode, readers never wait for writers: use it when a program reads while it writes.
SQLite starts the WAL over from its first frame only when a writer finds every frame copied into the database and no reader on the WAL. While reads overlap, that moment never comes. Automatic checkpoints still copy frames, but the file keeps growing and reads slow down with it. On an Apple M4, four readers scanning a 2 MB table beside one writer left a 1.2 GB WAL after 5 seconds.
So when a connection releases the write lock, it checks the WAL length. Once the WAL passes _wal_limit (64 MiB by default, _wal_limit=0 for no limit), it runs a RESTART checkpoint. That checkpoint waits up to 100 ms for WAL readers to finish while new readers read only the database file, and the next writer starts the WAL over. Because it holds the write lock, other writers wait for it, and one whose busy_timeout is shorter than the wait can get SQLITE_BUSY, as behind any slow writer. In the same run with the limit, the WAL reached 80 MB once and 127 MB another time, since each try held off by readers lets it grow by a quarter of the limit (see below), with as many writes and reads. Median write time stayed 12 µs either way, and the longest write took 110 ms, the wait of one such try.
If readers do not finish in time, as with a read transaction held open, the next try waits until the WAL grows by another quarter of the limit. The wait is paid once in that much writing, not at each commit. So the limit is where the driver starts trying, not a length the WAL cannot pass. A read that never ends still lets the WAL grow, as in SQLite.
Enough overlapping short reads can hold off a try too. SQLite has four slots for WAL readers, each marked with how far its readers read, and a new reader can move a mark forward only while that slot is free. When no slot is ever free, new readers keep joining the slot whose mark is behind, so that slot does not empty during the wait. On an Apple M4, 64 goroutines that each read in a deferred transaction and retry as soon as it fails held off 1 to 5 of 13 to 22 tries in 10 seconds, and the WAL reached 80 to 96 MiB. Sixty goroutines reading with a single statement beside four writers held off none of 8. Holding new readers back during the try would let it through, but they would wait for the checkpoint and its sync, so the driver does not.
A replicated file follows the same rule in its replicator, which runs every checkpoint of that file (see Replication).
SQLite runs an automatic checkpoint after every commit that leaves the WAL at wal_autocheckpoint frames or more (1000 by default). With no readers, that happens once every 1000 frames: the checkpoint copies them all, and the next writer starts the WAL over. While reads overlap, the WAL stays above that mark, so every commit runs a checkpoint and syncs the WAL for the few frames readers let it copy. When syncs are slow, the writer spends most of its time there. On linux/amd64 (4 cores, a network disk whose sync takes about 1 ms), one writer beside three readers scanning a 2 MB table spent 13 of 20 seconds in 12,000 syncs.
So the driver runs automatic checkpoints for its connections. The connection releasing the write lock runs one each time the WAL grows by wal_autocheckpoint frames since the driver's last checkpoint. With no readers, that matches when SQLite runs its own. In the run above, the writer made 3.5 times as many writes (471,000 compared to 134,000 in 20 seconds) with 570 syncs, and 99% of writes took under 0.3 ms instead of 2.5 ms. Readers did 12% fewer scans (32,500 compared to 36,800), because more frames sit in the WAL for them to look through: a smaller wal_autocheckpoint gives back reads at the cost of writes. With synchronous=FULL, where every commit already syncs the WAL, writes are 10% higher. On an Apple M4, where a sync costs little, the numbers do not move.
What a program sees:
wal_autocheckpointkeeps its meaning in both the DSN (_pragma=wal_autocheckpoint(N)) and a connection PRAGMA: one checkpoint every N frames, and none with 0.PRAGMA wal_autocheckpointreads what was set, as before.- A checkpoint that cannot run, such as when its connection has an open query, does not count, so the next commit that finds one due tries again. The same holds for the second checkpoint after another process writes (One writer per file).
- A connection with an attached database uses SQLite's own automatic checkpoints until it detaches: SQLite covers every database on the connection, while the driver covers only the main one.
- Writers in other processes checkpoint as SQLite does, and a replicator runs all checkpoints for a replicated file.
When an fsync fails, Linux marks the unwritten pages clean. They still read back from memory and the next fsync succeeds, but once the kernel drops them, reads return what the disk holds. With synchronous=NORMAL, SQLite syncs the WAL only when it checkpoints. After that sync fails, the next checkpoint copies frames that may not be on disk into the database. SQLite's own VFS lets this happen, and the database is damaged once the pages are dropped.
So on linux and darwin, the first failed sync of a WAL stops it in the process:
- As long as no other process has the database open, the driver cuts the WAL at the first byte written since its last good sync. This removes frames that may not be on disk from both the file and memory. Writes and syncs on one WAL never overlap, so the cut never removes a commit made durable by an earlier sync. It also keeps frames a checkpoint may have already copied into the database (from another process, or from this one under
synchronous=OFF): without them, older frames left in the WAL would be read in place of newer database pages. - Every read, write, and sync on the WAL then fails, and no connection can open it. Connections in the process that already have the WAL open no longer read or write the database file either, so a running checkpoint copies nothing more.
database/sqldrops each connection to that database (main or attached) when taking it from or returning it to the pool (IsValid). Connections to other databases are untouched.- The WAL opens again once it is cut and no connection in the process has it open. The next connection, from any process, then rebuilds the WAL index from the frames on disk. Until then, the WAL index still counts the cut frames, so a process opening the database in the meantime finds it locked, waits, and gets an error after about ten seconds.
- While another process has the database open, the driver does not cut the WAL and keeps it stopped here. That process shares the WAL index, which still counts the frames, so it would write past a cut and read the gap as empty pages. Once it closes the database, the driver cuts the WAL if the WAL, its index, and the database are still as the failed sync left them. Otherwise, that process wrote or checkpointed in the meantime, no cut is safe anymore, and the WAL opens as is.
- When the cut itself fails, the WAL stays stopped in the process and each open retries the cut. When the process cannot read from the WAL index which frames a checkpoint copied, it does not cut, and the WAL stays stopped as long as the process runs.
- The replicator closes its connections at its next step and stages a full copy.
The cost: with synchronous=NORMAL, commits since the last good WAL sync are lost, as on a power loss. With synchronous=FULL, nothing reported committed is lost, since a commit whose sync failed never joined the WAL. Until the WAL opens again, every call on the database fails. A connection that is never taken from its pool or given back keeps it stopped: a sql.Conn or sql.Tx the program keeps open, or idle connections in another sql.DB on the same file that gets no calls. SetConnMaxIdleTime lets database/sql close those idle connections. On windows, SQLite's own behavior is kept.
Other processes are not stopped. A process that has the database open when the sync fails continues as with SQLite's own VFS: the frames that may not be on disk stay in the WAL, and it may still copy them into the database. This process stays stopped as long as the other has the database open. The same holds for a process that opens the database after a cut failed and this process closed it. So the protection is complete only when one process opens the database.
On linux and darwin, a failed database sync in WAL mode stops the WAL the same way, with nothing to cut. A checkpoint held back by an open read copies some frames into the database without syncing it, and later reads take those pages from the database instead of the WAL. When a later database sync fails, the kernel may drop those pages too, and the next sync succeeds. With SQLite's own VFS, the next checkpoint then counts every frame as copied, the next commit starts the WAL over on top of them, and a write reported committed is gone: reads see old rows or a damaged database. Stopping the WAL keeps every frame. When it opens again, the next connection rebuilds the WAL index from disk with none counted as copied, and its checkpoint copies every frame again. Nothing reported committed is lost, with synchronous FULL or NORMAL. Until the WAL opens again, calls on the database fail as above, and other processes are not stopped. On windows, SQLite's own behavior is kept here too.
The kernel writes those checkpointed pages to disk in the background, and whether that worked is known only at the next database sync. If that write fails and the kernel drops the pages, reads in this process may see the old content until then. The driver stops the database at the sync that reports the error, as PostgreSQL does.
In rollback journal modes (DELETE, TRUNCATE, PERSIST), a commit syncs the journal before writing the database. When that sync fails, SQLite rolls the transaction back by reading the journal and putting each page back into its cache. If the kernel dropped pages the sync could not write, those pages are missing from the journal, and SQLite's own VFS lets two things happen:
- Without the header or pages, SQLite finds nothing to restore, treats the rollback as done, and keeps the failed transaction's pages in its cache. The next commit writes them to the database, so a write reported as failed is there after all. If it made the file longer, the connection reads a malformed database until it closes.
- A
PERSISTjournal still holds an earlier transaction's journal past the end of the current one, and SQLite zeroes the first byte of that old header. Without that byte, the rollback continues into the old journal and undoes pages of a committed transaction.
So on linux and darwin, the first failed sync of a rollback journal cuts the journal and stops its open file:
- The driver cuts the journal at the first byte written since its last good sync. What remains is all that must be undone: SQLite writes a page to the database only after a good sync of the journal holding it, so the cut part covers no database page.
- Every read, write, truncate, sync, and size check on that open file then fails. The rollback fails, and SQLite drops its whole cache, as after any I/O error it cannot undo.
- SQLite then closes the journal and rolls back what remains of it at the next statement, as after a crash.
- With
locking_mode=EXCLUSIVE, SQLite keeps the journal open, sodatabase/sqldrops the connection when taking it from or returning it to the pool (IsValid), and the next connection rolls the journal back.
The cost: the write whose sync failed returns an error, and later writes go on. A sql.Conn or sql.Tx held open on a locking_mode=EXCLUSIVE connection fails every call until closed. The cut may not reach disk either, so a power loss before the next statement can bring back what was cut, just like any unsynced write. When the cut itself fails, the journal does not open again in the process until the cut succeeds: each open retries it, and every call on the database fails in the meantime. If another process wrote or replaced the journal since, it opens as is, and other processes are never stopped. On windows, SQLite's own behavior is kept.
A commit error does not always mean the write is absent. As its last step, after writing and syncing the database, a commit ends the journal and syncs it again in three cases: journal_mode=PERSIST, journal_mode=DELETE with locking_mode=EXCLUSIVE, and journal_mode=TRUNCATE with synchronous=FULL. When that sync fails, the commit returns an error even though the write is there. A transaction over several databases (ATTACH) returns no error then, because SQLite counts it as committed once the journal tying the databases together is deleted.
When a statement runs out of memory, fails to read or write a file, or finds the disk full, SQLite rolls back the whole transaction at once unless it can undo that statement alone. This also happens when an extension runs a failing statement inside a program's still-running statement. FTS5 reads its row count that way while inserting. When that read fails, the rollback comes first, and FTS5 still marks the count it failed to read (zero) as read. The connection's next insert into that table writes that count to the file, leaving the index out of sync with the table, and PRAGMA integrity_check reports a malformed inverted index. This is SQLite 3.54.1 as released, and the driver does not edit SQLite's C.
So once a connection gets SQLITE_NOMEM, SQLITE_IOERR or SQLITE_FULL (with any extended code) while preparing or running a statement, the driver runs no more statements on it:
database/sqldrops the connection when taking it from or returning it to the pool (IsValid). The replacement connection reads everything from the file.- Any statement, prepare, or transaction that still reaches it gets
driver.ErrBadConnbefore running, sodatabase/sqlruns it on another connection. In a multi-statementExec, a later statement gets a driver error instead, becausedatabase/sqlwould rerun the wholeExeceven though earlier statements already ran. The connection never leads a group commit batch. - A transaction the error left open continues to its end: SQLite undid only that one statement, as with any other error, so a program can make room after
SQLITE_FULLand keep going. The connection is dropped once the transaction ends.
The cost: each such error costs the pool one connection, and a held sql.Conn gets driver.ErrBadConn at its next call and is closed by database/sql. An interrupt (a context that ends) leaves no such state, and its connection stays. The same holds when a checkpoint run by the driver fails, since it runs no statement.
When many goroutines each write one row in autocommit mode, each pays for its own commit and waits in line because SQLite allows one writer at a time. The driver takes the autocommit DML of concurrent callers, runs it as one transaction, and commits once. The rules are in AGENTS.md: only autocommit DML on the main database, one SAVEPOINT per statement, each caller gets its own result, and each call returns only after the commit.
How it works (writer.go): when a statement arrives at the file's write lock while another connection holds it, it joins the file's queue instead of waiting. Before releasing the lock, the holding connection runs up to 256 queued statements on itself: BEGIN IMMEDIATE, each statement between SAVEPOINT and RELEASE, and COMMIT. Callers get their results only after COMMIT. A failing statement keeps whatever SQLite kept of it, as it would alone (nothing, or the rows before the failure for OR FAIL), and its caller gets the error after the commit. If a statement (even a failed one) leaves a deferred foreign key unresolved, ROLLBACK TO undoes it and its caller gets the error its own COMMIT would have given. No statement runs twice. When a failure ends the whole transaction (an interrupt from a context that ended, an IO error, or ON CONFLICT ROLLBACK), its caller gets that error, earlier statements in the batch (including failed ones) get SQLITE_ABORT_ROLLBACK instead, and later statements that never reached SQLite return to the queue.
A Go function may act outside the database, which no rollback undoes. So any statement calling a Go function not marked Innocuous (scalar, aggregate, or window) ends the batch: it commits right after that statement, and later statements wait for the next batch. Calling such a function marks the connection (markEffects), so the call is caught as it happens, even from a trigger. FTS5 writes an INSERT's terms to its index only at the next SAVEPOINT or at COMMIT. So once a virtual table takes part in the transaction (db->nVTrans), each statement gets an extra SAVEPOINT and RELEASE right after it, inside its own SAVEPOINT. A failure writing the index (a broken index or a full disk) then belongs to that statement rather than the next one, and undoes the statement, just as if it ran alone. An authorizer (goClassify in engine/os.c) classifies statements as they are prepared. It also sees statements SQLite prepares along the way, such as R*Tree preparing writes of its shadow tables on first use. What those statements do does not count as the caller's statement: they never mark it as a write of the main database, though they may still make it unmergeable, which is only slower. A trigger body is coded in its own Parse whose pToplevel is its statement, and it does count: a Parse is nested when the statement at its top has a pOuterParse.
If a caller's context ends before its turn, it gets the context's error and its statement never runs. After the batch, the lock goes to whichever arrived first: the next waiting connection or the first queued statement (which then runs on its own connection). Handing on the lock in arrival order means a statement no batch can take (because it belongs to another connector, or because releasing connections changed themselves) still gets its turn. With no other writer, a statement runs directly, so one writer pays nothing. Every rule, and who gets what error at each step, is in group-commit.md.
sequenceDiagram
participant A as goroutine A
participant B as goroutine B
participant C as goroutine C
participant L as the file's write lock
A->>L: Exec INSERT: the lock is free, A takes it
B->>L: Exec INSERT: the lock is held, B joins the queue
C->>L: Exec UPDATE: C joins the queue
Note over A: A's INSERT runs and commits
L->>A: before giving the lock back, A takes the queue
Note over A: BEGIN IMMEDIATE<br>SAVEPOINT, B's INSERT, RELEASE<br>SAVEPOINT, C's UPDATE, RELEASE<br>COMMIT
A-->>B: B's error, LastInsertId, RowsAffected
A-->>C: C's result
Note over A,C: each call returns only after the COMMIT
Which statements may join: the driver installs a C authorizer (goClassify in engine/os.c) that inspects each statement as it is prepared. A statement joins only when it writes to main database tables and touches nothing only its own connection has: no other schema (temp, attached), no write from a trigger (it may be a temporary trigger), no write to a writable Go module table, no read of any Go module table or of a table whose name starts with pragma_ (SQLite's pragma tables run their PRAGMA on the connection that runs the statement), no last_insert_rowid(), changes() or total_changes(), and nothing that is not DML. Only Exec merges, and a statement in a transaction never does. A schema change after preparation can make a statement unmergeable (a new trigger, or a table that became a Go table), and SQLite then prepares it again inside sqlite3_step before doing anything. On a connection running a batch, the authorizer refuses that new program if it is no longer mergeable: the statement fails having done nothing and goes back to run on its caller's connection. Any statement SQLite prepares again is reclassified before it next asks to merge.
Which connections may run each other's statements: only connections of one connector (the same DSN, so the same _pragma settings), and only while neither has changed itself since opening. A connection changes itself with a PRAGMA with an argument, ATTACH, DETACH, or a temporary table, view, index, or trigger, and the authorizer marks it as the statement is prepared. The few PRAGMAs with an argument that set nothing (those that only read a table or an index, optimize, and wal_checkpoint and table_list on the main database) do not count. So settings go in the DSN (_pragma), where every connection of the pool gets them and keeps merging. A read-only connection, one whose DSN turns defer_foreign_keys on (SQLite turns it off at the end of each transaction, so connections of one DSN can differ), one in a read-only transaction, and one with an unfinished table query never merge either (the open query keeps its read snapshot, which another connection would not have). From then on, the connection writes only on its own, using the file's write lock as before. A connection with any unfinished statement, even a query of no table such as SELECT 1, runs no statements for others: the context of its rows interrupts the connection when it ends, and SQLite keeps an interrupt until no statement runs on that connection, which would stop the batch. Functions, aggregates, collations and virtual table modules written in Go belong to the connector. A connector made with options of its own (NewConnector(dsn, opts...)) has a key no other connector shares, while connectors made after the same Register calls share one. So the connection running a merged statement always has the functions its caller has.
One thing differs from running alone: because a merged statement runs on another connection, changes() and total_changes() count it on the running connection instead of the caller's. LastInsertId, RowsAffected, and last_insert_rowid() on the caller's connection are still right.
On an Apple M4 (WAL, synchronous=NORMAL, one autocommit INSERT per call, bench/), the time per insert:
| Writers | mattn (cgo) | this driver |
|---|---|---|
| 1 | 6.1 µs | 6.2 µs |
| 8 | 6.7 µs | 3.1 µs |
| 64 | 9.6 µs | 1.2 µs |
More drivers and linux are in benchmarks.md.
A prototype in application code on mattn/go-sqlite3 (WAL, one writer goroutine taking up to 256 waiting callers), measured on an Apple M4:
| Writers | synchronous | One commit per write | Group commit | Gain |
|---|---|---|---|---|
| 1 | NORMAL | 133k writes/s | 88k writes/s | 0.7x |
| 16 | NORMAL | 88k | 197k | 2.2x |
| 256 | NORMAL | 94k | 359k | 3.8x |
| 16 | FULL, fullfsync | 213 | 2.0k | 9.5x |
| 256 | FULL, fullfsync | 150 | 34.8k | 232x |
Group commit pays off from about 16 concurrent writers up, most where commits wait for disk, and slows down a single writer because the queue adds a hop. That is why the driver writes directly when no one else is waiting. One commit per write is also unfair: some goroutines waited seconds and some got SQLITE_BUSY. A SAVEPOINT per statement halves the peak (adding two calls per statement in the prototype). A failed constraint in SQLite already undoes only its own statement, so where the SAVEPOINT is really needed has yet to be shown. It stays anyway because safety comes before speed. Each run took 3 seconds once, and runs of the same setup differed by up to 90%, so treat gains under 1.5x as noise.
The replica package copies a database to S3-compatible storage as it changes. How to use it and what it guarantees are in replication.md. It has four parts:
| Package | Job |
|---|---|
internal/replhook |
What the driver exposes only to the replicator: a file attached for replication, its write lock, and a callback whenever a writer releases that lock |
replica/internal/capture |
Copies each database change into a local staging folder as an LTX file and runs checkpoints |
replica/internal/s3 |
The S3 client: SigV4, PUT, multipart upload, ranged GET, LIST, DELETE, conditional PUT. No dependencies |
replica |
The API: uploads, compaction, snapshots, retention, restore |
Capture inside the driver. Litestream watches a database from outside: it reads the WAL every second, holds a long read transaction to block checkpoints from passing it, and guesses what other connections did from salts and the last page. Its open bugs that lose or damage data come from that guessing (replicating an uncommitted transaction, missing a WAL rewound by a power loss, or dropping rows after a checkpoint it did not run). Here the driver owns every connection to the file, so the replicator does not guess:
- An attached file runs no automatic checkpoints, and PRAGMAs that checkpoint or leave WAL mode return an error.
- The capturer reads new WAL frames up to the last commit frame, verifies salts and frame checksums as SQLite's recovery does, writes them as one LTX file, and syncs it before counting it as staged. Frames after the last commit are never read.
- Checkpoints run under the file's write lock after staging the WAL to its end, so no frame is copied into the database or overwritten before it is staged. Each time the WAL grows by 4000 frames, the writer releasing the lock stages and checkpoints, just as SQLite runs automatic checkpoints on the committing writer. Past that writer's
_wal_limit, the checkpoint waits for readers, as above. - If the WAL changed in a way the driver did not make (other salts, a shorter WAL, or unseen frames), another process wrote to it. The capturer stages a full copy of the database and reports it.
- A snapshot takes the write lock only to stage the WAL and open a read transaction, then reads the pages without stopping writers.
Upload from the staging folder. Writes never wait for the store. Each LTX file uploads once with If-None-Match: *, so a second replicator gets 412 and stops instead of overwriting the first. At start, the replicator checks where the replica ends and continues only if the staged files continue from there. Staging has a limit: past it, staging stops while checkpoints go on, and a full copy follows once the store is back, so a down store does not make the disk or the WAL grow without end.
Litestream's format. The replica stores LTX files (github.com/superfly/ltx) in Litestream's layout, so litestream restore also works, and the tests verify it gives the same bytes. LTX files carry whole-database checksums before and after each file. Litestream leaves those off, while this replicator turns them on, so a restore checks the database after every applied file, not only after the last.
Left out on purpose. Client-side encryption (litestream restore could not read the replica). Storage other than S3. Synchronous replication, where a commit returns once it is in the store: because the driver already calls the replicator whenever a writer releases the lock, this can come later, paid once per group commit batch. A fence that keeps a second machine out: S3 has none, see replication.md.
The queue package stores a message queue in database tables. How to use it and what it guarantees are in queue.md. It uses database/sql and SQL anyone could write, plus one hook the driver gives only to it (internal/queuehook): a per-file signal fired when a write marked for a queue ends.
- The mark. The queue adds a final argument of type
queuehook.Waketo statements that make a message ready (Publish, a failed handler, a message given back,Requeue). The driver strips it before binding arguments (CheckNamedValuereturnsdriver.ErrRemoveArgument) and notes on the connection that a queue waits for this write. In group commit, the mark goes with the request to the connection that runs it. - The signal. When a connection releases the write lock after a marked write, it fires the file's signal. A
Consumethat found nothing waits for whichever comes first: the signal, the time the next message comes due, or one second (for a message published by another process). The signal belongs to the file and outlives its connections, staying alive while a queue holds it or any connection to the file is open. Unmarked writes fire nothing, so other writes cost the same with aConsumewaiting as without. - Taking a message.
Consumeclaims up to a batch of ready messages with oneUPDATEthat holds them for a time and gives them a randomtokenthat no other hold has. The handler's result is written by the row'sid,token, and state, so a result applies only while that take still holds the message. A message whose hold ended is taken again by whicheverConsumecomes first. ThatUPDATE,Publish, and the writes that end a handler are all autocommit writes throughExec, so writes from many goroutines share commits (group commit). - When another write ends the batch. A queue write can roll back with its batch when another caller's statement fails in it, and then gets
SQLITE_ABORT_ROLLBACK(group-commit.md, rule 12). The queue does not pass that error on. Because each of its statements does the same whenever it runs, the queue runs the statement again in its own transaction. A transaction joins no batch, so no other caller can end it.PublishTxruns in the caller's transaction and is not run again: its error goes to the caller.
The engine is slower than the same C built by clang. On an Apple M4, work inside the engine takes up to 1.47 times as long, with a geometric mean of 1.21 times (see benchmarks.md). Part of that is the price of this route itself. liustack/beastjs, which compiles its C the same way, measured 11 to 13% for the same C and options, coming from passing arguments and results on the Go stack, keeping address-taken locals on the shadow stack, and a few extra instructions per call. Work to win some of it back follows what beastjs learned from the routes it tried and dropped:
- Nothing private to Go. No
go:linknameinto the runtime, no reliance on how Go uses a register, and nothing the Go team may change in a release. Otherwise each Go version would need rechecking, and one could break the driver. - The engine stays on the goroutine stack. Running it on a stack of its own, as cgo, wazero, and purego do, would turn a C fault into a process crash instead of a panic of one call.
- No gain below the noise. Any change that saves less than the 2 to 3% shift from where code lands in memory is not taken, however clean.
- The same bits on every target. The math functions stay without fused multiply-add, so every platform gives the same result.
- SQLite's C stays as released. Changes go in the generator,
engine/libcor the Go host.
beastjs keeps the same rules, with the reasons it learned them: Making the engine faster. Before trying an idea, check the list of what beastjs tried and did not do: What was tried and not done.
Before the two changes below, measurements compared SQLite against the same C built natively across the ten workloads of bench/native/engine.sql. On darwin/arm64, missing compiler builtins and libc cost nothing: the full 31% is lowering to Go assembly. On linux/amd64, missing builtins cost 6 points, musl compared to glibc costs 4 more, and lowering costs 17.
- Done.
memcmpcompares eight bytes at a time, cutting index-lookup workloads by 15 to 18%.strcspnhas its own path for two stop bytes, which LIKE uses to find the next place a match can start (a letter in uppercase and lowercase), cutting LIKE queries starting with%by 9 to 17%. Both are musl patches inengine/libc/patches/, and both return what musl returns. - Done. Compiling the C with a profile of training SQL tells the compiler where each function is hot, cutting 6 to 10% across the ten workloads (see The profile).
- Tried and not done. Building SQLite's C with compiler builtins on made the engine 3.7% slower on linux/amd64, even though native C gains 6% from them. Faster
sin,powandlogwere also left out: musl's take 6 to 8 ns more per call than glibc's, but another libm would have to give the same bits on every target.
make gen compiles the C with a profile (engine/pgo/profile.txt) showing how often each branch of each function was taken while running engine/pgo/train.sql. The compiler uses it to lay out each function: blocks that run stay together in a straight line, blocks that do not run move out of the way, and values stay in registers where code is hot.
Across the ten workloads of bench/native/engine.sql (none used in training), the engine takes 6.3% less time on an Apple M4 and 9.9% less on linux/amd64 (geometric mean), from 1% less for a large sort to 22% less for JSON on linux. None takes longer, and each gives the same result.
Three decisions ignore the profile because their cost depends on a program's data, which training cannot know:
- What is inlined.
make gencompiles twice. First, it compiles without the profile and records every call it inlined. Second, it compiles with the profile and inlines only those recorded calls. Left to itself, the profile inlines more into functions the training ran most, slowing the rest of the engine: beastjs measured 5 to 15% more time that way. - Size over speed. With a profile, the compiler optimizes code the training ran little or never for size instead of speed, and assumes loops run as many turns as in training. Both are turned off.
- Where a loop counts for its polls. The pass that adds the polls weighs each loop as it does without a profile.
Why it is safe: the profile changes where code is placed, not what it computes. The C, options, and libc stay the same, the post-link check still verifies every generated function against the compiler's code, and the same tests run. A function whose branches and loops changed since training compiles without its profile.
What it costs: make gen takes about 80 seconds per target instead of 50, generated files are 10 to 13% larger, and a binary is about 5% larger. A path the training never ran looks unused to the compiler, so a program running it may pay a small cost. So training covers every kind of work a program may do, and a check stops training if it runs fewer than 95% of the paths the ten workloads run (it runs all of them). With the profile, 17 small functions that prepare a statement are no longer inlined at one of their call sites.
What the training runs, how the check works and how to train again: engine/pgo/README.md. When to train again: upstream.md.
- cgo (mattn/go-sqlite3): needs a C compiler for every build and every target, and cross-compiling is hard. Not having to do this is the reason for the project.
- C translated to Go (modernc.org/sqlite, made with ccgo): no cgo, but slower than cgo: 1.3 to 1.4 times as long as cgo on a point read and 1.7 to 2.3 times on a join (see benchmarks.md). beastjs went this way for QuickJS before and left it for the same reason.
- WebAssembly (ncruces/go-sqlite3): SQLite compiled to wasm, which wasm2go translates to Go. No cgo, but the C passes through a second machine model on its way to the CPU.
- A shared library loaded with purego: no single static binary, the SQLite version depends on the system, and each call costs more.