{"guides":[],"hints":[{"hint":"Ask where a commit is written in WAL mode and when it reaches the main file.","lessonID":"sqlite.backups-maintenance","nuance":"Commits land in the -wal file and reach app.db only at a checkpoint, so the copy can lack recent transactions or be torn. VACUUM INTO reads one consistent snapshot through SQLite."},{"hint":"Compare what the second transaction already read with what is now committed.","lessonID":"sqlite.begin-immediate","nuance":"Its snapshot predates the other commit, so SQLite returns SQLITE_BUSY_SNAPSHOT at once without calling the busy handler. With BEGIN IMMEDIATE, the second would have waited at BEGIN and then read the new value."},{"hint":"Count how many SQLite connections a *sql.DB may hold, and ask which of them executed your statement.","lessonID":"sqlite.drivers-dsn","nuance":"foreign_keys is a per-connection setting. db.Exec ran it on one pooled connection; any other connection the pool opens starts with the default of OFF unless the driver applies the pragma from the DSN."},{"hint":"Ask what sql.Open actually does with the data source name before any statement runs.","lessonID":"sqlite.first-database","nuance":"sql.Open validates the driver name and stores the DSN. The first operation that needs a connection, such as PingContext, is where SQLite tries to open the file and reports a missing directory."},{"hint":"Check the pragma on the connection that ran the insert, not the schema text.","lessonID":"sqlite.foreign-keys","nuance":"The schema is fine; the connection never enabled foreign_keys. The pragma is per connection and ignored inside a transaction, so set it in the DSN and verify with PRAGMA foreign_keys."},{"hint":"Binding keeps the text out of the SQL statement. Ask who parses the bound value next.","lessonID":"sqlite.fts5-search","nuance":"The bound value reaches FTS5 intact and FTS5 parses it as a query, where + is not valid. Quoting each word turns it into a string token; unicode61 then reduces c++ to c."},{"hint":"An index needs a value to store per row. Where can the extracted value live?","lessonID":"sqlite.json-functions","nuance":"Add a generated column defined as doc ->> '$.kind' and index it, or index the expression itself. SQLite has no JSON column type, and json_valid only checks syntax."},{"hint":"The pool opened a second connection for the parallel query. What does a fresh connection to :memory: contain?","lessonID":"sqlite.memory-pool","nuance":"Every connection to :memory: gets a private database. Pin one connection, share a named memdb database, or use a temporary file; shared cache works too but brings table-level locking and SQLITE_LOCKED errors."},{"hint":"Look at what the runner does between BeginTx and Commit, and at what Rollback undoes.","lessonID":"sqlite.migrations-user-version","nuance":"SQLite DDL and the user_version write are transactional. Rolling back the failed step also discards the version bump, so the schema and its number always change together."},{"hint":"Follow the version number: what does the first save change, and which row can the second UPDATE still match?","lessonID":"sqlite.notes-repository","nuance":"The first save sets version to 2, so the second UPDATE ... WHERE version = 1 matches no row. The repository then finds the note still exists and returns ErrConflict instead of overwriting."},{"hint":"Evaluate NULL <> 'countess'. Is the result true, false or something else, and what does WHERE do with it?","lessonID":"sqlite.nulls-time","nuance":"Comparing NULL with anything yields NULL, and WHERE keeps only rows where the condition is true. Write nickname IS NOT 'countess' or add OR nickname IS NULL to include them."},{"hint":"Compare the values stored in the index with the values the WHERE clause asks about.","lessonID":"sqlite.query-plans","nuance":"The index stores email as written, not lower(email). Create an index on lower(email) and use that exact expression, or store a NOCASE or normalised column; statistics cannot make a non-matching index usable."},{"hint":"Without AUTOINCREMENT, the next rowid is derived from the rows that currently exist.","lessonID":"sqlite.rowid-keys","nuance":"Without AUTOINCREMENT the next rowid is normally max(rowid)+1 of the rows present now, so a deleted maximum is reused. AUTOINCREMENT stores the high-water mark in sqlite_sequence to prevent that."},{"hint":"Count how many connections the pool can open and ask what each one sees with :memory:.","lessonID":"sqlite.testing-temp-databases","nuance":"Each pooled connection to :memory: opens its own empty database, so a query on a second connection misses the migrated tables. A temp file per test is shared by the pool and isolated from other tests."},{"hint":"Think about how many rows RETURNING produces when the UPDATE matches nothing.","lessonID":"sqlite.transactions-returning","nuance":"No row is updated, so RETURNING yields no row and Scan returns sql.ErrNoRows. The function returns before the credit and the deferred Rollback leaves both balances untouched."},{"hint":"Affinity converts only when the conversion is lossless. Can \"abc\" become an integer without losing anything?","lessonID":"sqlite.type-affinity","nuance":"Ordinary tables keep \"abc\" as TEXT in an INTEGER column. Only STRICT tables reject it, with SQLITE_CONSTRAINT_DATATYPE, while still converting lossless values such as \"42\" to integers."},{"hint":"OR REPLACE resolves the conflict by removing something first. What does removing a parent do here?","lessonID":"sqlite.upsert","nuance":"REPLACE deletes the conflicting tag, so the cascade deletes its children, then inserts a new row with a new rowid. ON CONFLICT DO UPDATE changes the row in place and keeps both the id and the children."},{"hint":"Ask how many connections the pool has and which one ran that statement.","lessonID":"sqlite.wal-busy","nuance":"busy_timeout is per connection. The Exec reached one pooled connection; others opened later still have 0. Putting _pragma=busy_timeout(5000) in the DSN applies it to every connection the pool creates."},{"hint":"Window values exist only after filtering and grouping. Where can you filter on them?","lessonID":"sqlite.window-ctes","nuance":"Compute row_number() OVER (PARTITION BY region ORDER BY amount DESC) in a subquery or CTE and filter on it outside. A LIMIT applies to the whole result, not to each group."}],"id":"sqlite","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"sqlite.first-database","designGuide":{"cautions":["Configuration errors surface on first use unless you Ping.","Every pooled connection has its own settings and state."],"cost":"A single shared *sql.DB, a Ping at startup and the discipline of closing every Rows value.","family":"sqlite","flow":["sql.Open once","PingContext at startup","Exec and Query with ?","Close rows, check Err"],"ratings":[],"strengths":["One process, one file: no server to install or operate.","database/sql code stays the same across SQLite drivers."]},"hint":"Ask what sql.Open actually does with the data source name before any statement runs.","id":"sqlite.first-database","introduction":"SQLite is a library, not a server: your Go process opens a single file and runs the SQL engine in its own address space. database/sql supplies the pool, statements and transactions; a driver supplies the engine. This course uses the pure-Go modernc.org/sqlite driver for its runnable examples, and every program here works the same in a native Go environment. The next GopherForge update adds a SQLite project template whose Go program uses database/sql through the app's bundled gopherforge.app/sqlite driver (registered as sqlite, backed by the system SQLite on iPhone and iPad); databases a program writes under /sandbox are kept with the project; and a database browser per project shows tables, schema and rows, offers a SQL console, and imports and exports .sqlite and .db files through Files.","nuance":"sql.Open validates the driver name and stores the DSN. The first operation that needs a connection, such as PingContext, is where SQLite tries to open the file and reports a missing directory.","objective":"Open a file database through database/sql, see that sql.Open connects lazily, and run Exec, Query and QueryRow with placeholders and complete error handling.","question":"You call sql.Open(\"sqlite\", path) with a path inside a directory that does not exist. Where does the error appear?","references":["https://pkg.go.dev/database/sql","https://go.dev/doc/database/querying","https://pkg.go.dev/modernc.org/sqlite","https://www.sqlite.org/lang_expr.html#varparam"],"reviewAnswer":"Not at all: the first Ping or statement opens it","reviewPrompt":"When does sql.Open touch the file?","sections":[{"body":"sql.Open checks the driver name and remembers the data source name. It does not touch the disk, so a misspelt path or a read-only directory is reported by the first statement, not by Open. The *sql.DB it returns is a concurrency-safe pool that opens connections on demand and keeps idle ones for reuse; create it once at startup, share it, and Close it at shutdown. Call PingContext right after Open when you want configuration errors at startup instead of on the first request. With SQLite each pooled connection is a separate open of the same file with its own page cache, its own PRAGMA settings and its own transaction state, which is why later lessons care so much about how many connections exist.","title":"A database handle is a pool, not a connection"},{"body":"The program opens app.db in a temporary directory, shows that the file appears only once Ping opens a real connection, creates a table and inserts three rows with ? placeholders. Arguments always travel separately from the SQL text, so a title containing a quote cannot change the statement. LastInsertId returns the new rowid for each insert, RowsAffected reports how many rows an UPDATE touched, and a QueryRow that finds nothing reports sql.ErrNoRows from Scan.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\" // registers the driver name \"sqlite\"\n)\n\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"first-db\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"app.db\")\n\n\tdb, err := sql.Open(\"sqlite\", path)\n\tif err != nil {\n\t\tlog.Fatal(err) // only a bad driver name or DSN fails here\n\t}\n\tdefer db.Close()\n\tfmt.Println(\"after sql.Open, file exists:\", exists(path))\n\n\tif err := db.PingContext(ctx); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"after Ping, file exists:\", exists(path))\n\n\tvar version string\n\tif err := db.QueryRowContext(ctx, \"SELECT sqlite_version()\").Scan(&version); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"SQLite library major version:\", version[:1])\n\n\tif _, err := db.ExecContext(ctx, `CREATE TABLE books (\n\t\tid    INTEGER PRIMARY KEY,\n\t\ttitle TEXT NOT NULL,\n\t\tyear  INTEGER NOT NULL\n\t)`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbooks := []struct {\n\t\ttitle string\n\t\tyear  int\n\t}{{\"The Go Programming Language\", 2015}, {\"Concurrency in Go\", 2017}, {\"Learning Go\", 2021}}\n\tfor _, b := range books {\n\t\tres, err := db.ExecContext(ctx, \"INSERT INTO books (title, year) VALUES (?, ?)\", b.title, b.year)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tid, _ := res.LastInsertId()\n\t\tfmt.Printf(\"inserted id=%d %q\\n\", id, b.title)\n\t}\n\n\trows, err := db.QueryContext(ctx, \"SELECT id, title FROM books WHERE year >= ? ORDER BY year\", 2016)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tvar title string\n\t\tif err := rows.Scan(&id, &title); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"since 2016: %d %s\\n\", id, title)\n\t}\n\tif err := rows.Err(); err != nil { // an error that ended the loop early\n\t\tlog.Fatal(err)\n\t}\n\n\tvar title string\n\terr = db.QueryRowContext(ctx, \"SELECT title FROM books WHERE year = ?\", 1999).Scan(&title)\n\tfmt.Println(\"no book from 1999:\", errors.Is(err, sql.ErrNoRows))\n\n\tres, err := db.ExecContext(ctx, \"UPDATE books SET year = year + 1 WHERE year < ?\", 2020)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tn, _ := res.RowsAffected()\n\tfmt.Println(\"rows updated:\", n)\n}","language":"go","title":"Create, insert and read back","walkthrough":"The first two lines show the lazy open: false after sql.Open, true after Ping. The library version line prints only the major version, which is 3 for every SQLite in use today. The inserts receive ids 1, 2 and 3 because id is an INTEGER PRIMARY KEY. The query returns the two books from 2017 and 2021 in year order, the 1999 lookup reports sql.ErrNoRows, and the UPDATE touches the two books published before 2020."},{"body":"QueryContext borrows a connection from the pool and keeps it until the rows are closed. Always defer rows.Close() right after checking the error, read with rows.Next and rows.Scan, and check rows.Err() after the loop, because Next returns false both at the end and on a read error. A forgotten Close leaks a connection; with SQLite it can also keep a read transaction open, which stops a WAL checkpoint from resetting the log. QueryRowContext closes its rows for you inside Scan and turns an empty result into sql.ErrNoRows, which you test with errors.Is rather than by comparing message strings.","code":"rows, err := db.QueryContext(ctx, query, args...)\nif err != nil {\n\treturn err\n}\ndefer rows.Close()\nfor rows.Next() {\n\tif err := rows.Scan(&dest...); err != nil {\n\t\treturn err\n\t}\n}\nreturn rows.Err()","language":"go","title":"Rows hold a connection until you are done","walkthrough":"This is the shape of every multi-row read. The deferred Close runs even when Scan fails halfway, and the final rows.Err() distinguishes a complete result from one that a cancelled context or an I/O error cut short."},{"body":"SQLite accepts ? for positional parameters and also ?NNN, :name, @name and $name. database/sql passes sql.Named arguments to drivers that support names, which modernc.org/sqlite does. Placeholders stand only for values: table names, column names, ORDER BY directions and PRAGMA arguments cannot be bound and must come from a fixed allow-list in your code. Each Exec or Query with arguments prepares a statement on the borrowed connection; when the same statement runs very often, db.PrepareContext keeps it prepared per connection, but measure before adding that complexity.","title":"Placeholders and the statement cache"},{"body":"Every program in this course is a complete package main that runs natively with go run against modernc.org/sqlite, which is pure Go and needs no C compiler. The coming GopherForge update brings a SQLite project template to iPhone and iPad: its program uses the same database/sql calls through the bundled gopherforge.app/sqlite driver, registered under the driver name sqlite and backed by the system SQLite. Database files a program writes under /sandbox stay with the project, a per-project database browser (Project, then Databases) shows tables, schema, rows and a SQL console, and .sqlite and .db files can be imported and exported through Files. Until that update ships, run the examples in your own Go environment.","title":"Where this runs"}],"takeaway":"sql.Open only validates its arguments; Ping or the first statement opens a real SQLite connection. Share one *sql.DB, bind every value with placeholders, close rows, check rows.Err and treat sql.ErrNoRows as an expected outcome.","title":"Open a SQLite database from Go: database/sql, a driver and a file","unitID":"sqlite-foundations","wrongAnswers":["sql.Open returns it immediately","It never appears; SQLite creates the directory"]},{"conceptTag":"sqlite.drivers-dsn","designGuide":{"cautions":["DSN parameter names differ between drivers.","mattn and ncruces both register sqlite3 and cannot share a binary."],"cost":"One constructor that owns the DSN, plus a driver choice made consciously for your build and deployment targets.","family":"sqlite","flow":["Pick a driver","Build one DSN","Pragmas per connection","Ping at startup"],"ratings":[],"strengths":["Every connection is configured identically, including replacements.","Pure-Go drivers keep cross-compilation and static binaries simple."]},"hint":"Count how many SQLite connections a *sql.DB may hold, and ask which of them executed your statement.","id":"sqlite.drivers-dsn","introduction":"Three mature SQLite drivers exist for Go and they differ in how the C library reaches your binary: translated to Go, linked through cgo, or compiled to WebAssembly. Whichever you pick, most SQLite settings belong to a connection rather than to the file, and database/sql opens connections whenever it likes. A setting that is not in the data source name is a setting some of your connections do not have.","nuance":"foreign_keys is a per-connection setting. db.Exec ran it on one pooled connection; any other connection the pool opens starts with the default of OFF unless the driver applies the pragma from the DSN.","objective":"Compare modernc.org/sqlite, mattn/go-sqlite3 and ncruces/go-sqlite3, and use DSN parameters so that every pooled connection gets the same pragmas and transaction mode.","question":"You run db.Exec(\"PRAGMA foreign_keys = ON\") once after sql.Open. Why do some later inserts still accept orphan rows?","references":["https://pkg.go.dev/modernc.org/sqlite","https://github.com/mattn/go-sqlite3","https://github.com/ncruces/go-sqlite3","https://www.sqlite.org/pragma.html","https://www.sqlite.org/uri.html"],"reviewAnswer":"In the DSN, so every pooled connection runs it","reviewPrompt":"Where should foreign_keys(1) go?","sections":[{"body":"modernc.org/sqlite is the SQLite C source mechanically translated to Go. It needs no C toolchain, cross-compiles like any Go package with CGO_ENABLED=0, registers the driver name \"sqlite\", and ships with FTS5 and JSON enabled; the price is a larger binary, slower builds and somewhat lower raw speed than C on heavy workloads, on the platforms its generated code supports. github.com/mattn/go-sqlite3 wraps the real C amalgamation through cgo, registers \"sqlite3\", needs CGO_ENABLED=1 and a C compiler for every target, and enables some features such as FTS5 only through build tags. github.com/ncruces/go-sqlite3 runs SQLite compiled to WebAssembly inside the wazero runtime: no cgo, its database/sql driver lives in the driver subpackage, and the embed subpackage supplies the Wasm build. mattn and ncruces both register \"sqlite3\", so one binary cannot import both.","title":"Three drivers, three ways to ship the C library"},{"body":"The program first runs PRAGMA foreign_keys = ON with db.ExecContext on a plain path, then holds three connections at once and reads four settings on each. Only the connection that happened to execute the pragma has it. Then it opens a second database whose DSN carries _pragma parameters and _txlock=immediate: modernc.org/sqlite executes each _pragma (busy_timeout first, the rest in a fixed order) every time the pool opens a connection, so all three agree.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// settings reads the pragmas that matter on one specific connection.\nfunc settings(ctx context.Context, conn *sql.Conn) string {\n\tvar fk, busy, sync int\n\tvar journal string\n\tfor _, q := range []struct {\n\t\tsql  string\n\t\tdest any\n\t}{\n\t\t{\"PRAGMA foreign_keys\", &fk},\n\t\t{\"PRAGMA busy_timeout\", &busy},\n\t\t{\"PRAGMA journal_mode\", &journal},\n\t\t{\"PRAGMA synchronous\", &sync},\n\t} {\n\t\tif err := conn.QueryRowContext(ctx, q.sql).Scan(q.dest); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"foreign_keys=%d busy_timeout=%d journal_mode=%s synchronous=%d\", fk, busy, journal, sync)\n}\n\n// report holds three connections at once, so the pool must open three.\nfunc report(ctx context.Context, label string, db *sql.DB) {\n\tvar conns []*sql.Conn\n\tfor i := 0; i < 3; i++ {\n\t\tconn, err := db.Conn(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconns = append(conns, conn)\n\t\tfmt.Printf(\"%s conn %d: %s\\n\", label, i+1, settings(ctx, conn))\n\t}\n\tfor _, c := range conns {\n\t\tc.Close()\n\t}\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"dsn\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\t// 1. Plain path, then a PRAGMA through the pool: it lands on one connection.\n\tplain, err := sql.Open(\"sqlite\", filepath.Join(dir, \"plain.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif _, err := plain.ExecContext(ctx, \"PRAGMA foreign_keys = ON\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treport(ctx, \"db.Exec pragma\", plain)\n\tplain.Close()\n\n\t// 2. The same settings in the DSN: the driver runs them on every new connection.\n\tconst params = \"_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)\" +\n\t\t\"&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate\"\n\tdsn := \"file:\" + filepath.ToSlash(filepath.Join(dir, \"app.db\")) + \"?\" + params\n\tfmt.Println(\"DSN parameters:\", params)\n\n\tdb, err := sql.Open(\"sqlite\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\treport(ctx, \"DSN pragmas   \", db)\n\t// Closing a *sql.Conn returns it to the pool; at most two stay idle by default.\n\tfmt.Println(\"connections kept idle:\", db.Stats().Idle)\n}","language":"go","title":"A PRAGMA through the pool reaches one connection","walkthrough":"The first three lines show foreign_keys=1 on connection 1 and 0 on connections 2 and 3, all in rollback-journal mode (journal_mode=delete, synchronous=2 is FULL). With the DSN, every connection reports foreign_keys=1, busy_timeout=5000, journal_mode=wal and synchronous=1 (NORMAL). The last line shows that after the three *sql.Conn values are closed, the pool keeps two of them idle, its default MaxIdleConns."},{"body":"journal_mode=WAL is persistent: once one connection switches the file, the mode is stored in the database and later connections inherit it. foreign_keys, busy_timeout, synchronous, cache_size, temp_store and query_only are per connection and reset to their defaults on every new connection. user_version and application_id are stored in the file header. That is why the DSN is the right home for the per-connection group: a pool may close an idle connection after ConnMaxIdleTime and open a new one in the middle of a request, and that new connection must be configured before your first statement runs.","title":"Which settings live where"},{"body":"modernc.org/sqlite accepts a plain path or a file: URI, repeated _pragma=name(value) parameters, _txlock=deferred|immediate|exclusive for BeginTx, and _time_format=sqlite for how time.Time values are written; recent versions also accept mattn-style shorthands. mattn/go-sqlite3 uses keys such as _foreign_keys=1, _busy_timeout=5000, _journal_mode=WAL and _txlock=immediate. ncruces/go-sqlite3 uses file: URIs with _pragma and _txlock. Standard SQLite URI parameters such as mode=ro, mode=memory, cache=shared and immutable=1 are interpreted by SQLite itself. Keep the DSN in one constructor function so the parameters cannot drift between call sites.","code":"func OpenDB(path string) (*sql.DB, error) {\n\tdsn := \"file:\" + filepath.ToSlash(path) +\n\t\t\"?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)\" +\n\t\t\"&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate\"\n\tdb, err := sql.Open(\"sqlite\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}","language":"go","title":"DSN syntax per driver","walkthrough":"One function owns the data source name, so tests, commands and the server all open the database with identical settings. The Ping turns a malformed parameter or an unwritable directory into a startup error instead of a failure on the first request."},{"body":"Prefer modernc.org/sqlite or ncruces when you want plain go build, easy cross-compilation, static binaries and scratch containers; prefer mattn when you already have cgo in the build, need the C library's full speed or a C extension. Benchmark your own queries before deciding on speed alone, because for many services the time is spent in I/O and fsync, not in the SQL engine. The GopherForge app's coming gopherforge.app/sqlite driver also registers the name sqlite and follows modernc's _pragma parameters, so a database/sql program written against modernc reads the same. Other DSN parameters, such as _txlock, are driver-specific: check them against the driver you ship, and remember that pragmas issued as statements behave the same with every driver.","title":"Choosing in practice"}],"takeaway":"Pick the driver by how you build and ship: modernc for pure Go, mattn for cgo and C speed, ncruces for Wasm without cgo. Put every per-connection pragma and the transaction mode in the DSN, because the pool opens new connections on its own schedule.","title":"Choose a SQLite driver and configure every connection through the DSN","unitID":"sqlite-foundations","wrongAnswers":["The pragma needs a COMMIT before it applies","foreign_keys only applies to tables created after it"]},{"conceptTag":"sqlite.memory-pool","designGuide":{"cautions":["A pool silently opens new, empty :memory: databases.","Shared cache brings table locks and SQLITE_LOCKED."],"cost":"A conscious choice per use: one pinned connection, a memdb name, or a temporary directory cleaned up after the run.","family":"sqlite","flow":["Need concurrency?","Yes: temporary file","No: :memory: + 1 conn","Shared RAM: vfs=memdb"],"ratings":[],"strengths":["In-memory databases are fast and leave nothing behind.","A temporary file gives tests production behaviour."]},"hint":"The pool opened a second connection for the parallel query. What does a fresh connection to :memory: contain?","id":"sqlite.memory-pool","introduction":"The filename :memory: does not name one database; it asks SQLite for a new, private, empty database for this connection. database/sql happily opens a second connection when two queries overlap, and that connection sees nothing the first one created. The usual symptom is a test that passes alone and fails with \"no such table\" as soon as something runs concurrently.","nuance":"Every connection to :memory: gets a private database. Pin one connection, share a named memdb database, or use a temporary file; shared cache works too but brings table-level locking and SQLITE_LOCKED errors.","objective":"Explain why an in-memory database vanishes between pooled connections and choose between a single connection, the memdb VFS, shared cache and a temporary file.","question":"A test opens sql.Open(\"sqlite\", \":memory:\"), creates a table, then runs two queries in parallel goroutines. One fails with \"no such table\". Why?","references":["https://www.sqlite.org/inmemorydb.html","https://www.sqlite.org/sharedcache.html","https://go.dev/doc/database/manage-connections","https://pkg.go.dev/database/sql#DB.SetMaxOpenConns"],"reviewAnswer":"Its own new, empty database","reviewPrompt":"What does each :memory: conn see?","sections":[{"body":"An in-memory database lives inside one sqlite3 connection object and is freed when that connection closes. The *sql.DB pool may open a connection for any statement, close idle ones after ConnMaxIdleTime or ConnMaxLifetime, and open again later. So with \":memory:\" every new connection starts from an empty schema, and data can also vanish when the last connection holding it is closed by the pool. A temporary file has none of these problems because every connection opens the same file.","title":"Why the table disappears"},{"body":"The program pins two connections from each pool, creates a table on the first and counts rows on the second. Plain :memory: fails on the second connection. MaxOpenConns(1) avoids the problem by never having a second connection. The memdb VFS with a name that starts with a slash shares one in-memory database among all connections of the process, as does shared cache with mode=memory. A temporary file behaves the way production does.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// twoConnections creates a table on one pooled connection and reads it from another.\nfunc twoConnections(ctx context.Context, label string, db *sql.DB) {\n\ta, err := db.Conn(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer a.Close()\n\tb, err := db.Conn(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer b.Close()\n\tif _, err := a.ExecContext(ctx, \"CREATE TABLE IF NOT EXISTS t (v INTEGER); INSERT INTO t VALUES (1)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar n int\n\tif err := b.QueryRowContext(ctx, \"SELECT count(*) FROM t\").Scan(&n); err != nil {\n\t\tfmt.Printf(\"%-22s second connection: %v\\n\", label, err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%-22s second connection sees %d row(s)\\n\", label, n)\n}\n\nfunc open(dsn string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}\n\nfunc main() {\n\tctx := context.Background()\n\n\t// Every connection to \":memory:\" is a brand-new, empty database.\n\tmem := open(\":memory:\")\n\ttwoConnections(ctx, \":memory:\", mem)\n\tmem.Close()\n\n\t// One connection: the pool can never hand out a second, empty database.\n\tsingle := open(\":memory:\")\n\tsingle.SetMaxOpenConns(1)\n\tfor i := 0; i < 2; i++ {\n\t\tif _, err := single.ExecContext(ctx, \"CREATE TABLE IF NOT EXISTS t (v INTEGER); INSERT INTO t VALUES (1)\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tvar n int\n\tif err := single.QueryRowContext(ctx, \"SELECT count(*) FROM t\").Scan(&n); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"%-22s every statement sees %d row(s), open=%d\\n\", \"MaxOpenConns(1)\", n, single.Stats().OpenConnections)\n\tsingle.Close()\n\n\t// Named in-memory database in the memdb VFS: shared by connections of this process.\n\tmemdb := open(\"file:/lesson?vfs=memdb\")\n\ttwoConnections(ctx, \"vfs=memdb\", memdb)\n\tmemdb.Close()\n\n\t// Shared cache also works, with table-level locks you rarely want.\n\tshared := open(\"file:lesson?mode=memory&cache=shared\")\n\ttwoConnections(ctx, \"cache=shared\", shared)\n\tshared.Close()\n\n\t// A temporary file behaves exactly like production.\n\tdir, err := os.MkdirTemp(\"\", \"pool\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tfile := open(filepath.Join(dir, \"test.db\"))\n\ttwoConnections(ctx, \"temporary file\", file)\n\tfile.Close()\n}","language":"go","title":"Five ways to open an in-memory or test database","walkthrough":"The :memory: line reports \"no such table: t\" from the second connection, SQLite result code 1. With MaxOpenConns(1) the two CREATE IF NOT EXISTS plus INSERT statements run on the one connection, so the count is 2 and OpenConnections is 1. vfs=memdb, cache=shared and the temporary file each let the second connection see the row the first inserted."},{"body":"A single connection serializes everything: while a Rows value is open, any other statement on the same *sql.DB waits for the connection, and a goroutine that holds rows while issuing a second query on the same pool deadlocks itself. Idle closing still applies unless you keep MaxIdleConns at 1 or more and leave ConnMaxIdleTime and ConnMaxLifetime at zero, which are the defaults. For one-off tools and unit tests of pure SQL this is fine; for anything with concurrency use a file.","title":"SetMaxOpenConns(1) and its cost"},{"body":"cache=shared makes connections share one page cache and replaces file locking with table-level locks. Readers and writers on the same table then fail with SQLITE_LOCKED (code 6) rather than waiting, and busy_timeout does not help with those. The SQLite documentation discourages shared cache for most uses and recommends WAL mode instead. If you need an in-memory database that several connections share, the memdb VFS (file:/name?vfs=memdb) uses normal locking; for tests, a file under t.TempDir() is usually simplest and exercises exactly the code paths production uses, including WAL and busy handling.","title":"Shared cache is a legacy mode"},{"body":"Use a temporary file for integration tests and for anything that runs goroutines against the database. Use \":memory:\" with SetMaxOpenConns(1) for small, sequential programs such as most examples in this course. Use memdb when you truly need a shared in-memory database, for example a cache rebuilt at startup, and remember it is gone when the last connection closes. In the coming GopherForge SQLite template, a database the program writes to a file under /sandbox is kept with the project, while an in-memory database lasts only for one run.","title":"What to use where"}],"takeaway":"Each connection to :memory: is a new empty database. Pin one connection with SetMaxOpenConns(1) for sequential programs, use file:/name?vfs=memdb for a shared in-memory database, avoid shared cache, and prefer a temporary file whenever concurrency is involved.","title":":memory: is per connection: the pool, SetMaxOpenConns(1), memdb and shared cache","unitID":"sqlite-foundations","wrongAnswers":["CREATE TABLE is not committed until db.Close","In-memory databases do not support parallel reads"]},{"conceptTag":"sqlite.type-affinity","designGuide":{"cautions":["Ordinary tables accept any value in any column.","STRICT schemas need SQLite 3.37 or newer to read."],"cost":"A STRICT keyword and a few CHECK constraints per table; existing tables need a rebuild to adopt them.","family":"sqlite","flow":["Declare STRICT table","Pick INT/REAL/TEXT/BLOB","Add CHECK constraints","Scan into exact types"],"ratings":[],"strengths":["STRICT turns silent type drift into insert-time errors.","Affinity still converts lossless input such as \"42\"."]},"hint":"Affinity converts only when the conversion is lossless. Can \"abc\" become an integer without losing anything?","id":"sqlite.type-affinity","introduction":"In most databases a column has a type and every value in it has that type. In SQLite a value carries its own storage class (NULL, INTEGER, REAL, TEXT or BLOB) and the column only has an affinity, a preference applied when a conversion is lossless. VARCHAR(3) does not limit length and a column named INTEGER can hold the word abc. STRICT tables, available since SQLite 3.37, restore the rules you probably expected.","nuance":"Ordinary tables keep \"abc\" as TEXT in an INTEGER column. Only STRICT tables reject it, with SQLITE_CONSTRAINT_DATATYPE, while still converting lossless values such as \"42\" to integers.","objective":"Predict the storage class SQLite gives each value from a column's declared type, see what Go receives when scanning into any, and use STRICT tables to reject values that do not fit.","question":"In an ordinary (non-STRICT) table, what happens when you insert the text \"abc\" into a column declared INTEGER?","references":["https://www.sqlite.org/datatype3.html","https://www.sqlite.org/stricttables.html","https://www.sqlite.org/flextypegood.html","https://pkg.go.dev/database/sql#Rows.Scan"],"reviewAnswer":"No: TEXT affinity, length ignored; add a CHECK","reviewPrompt":"Does VARCHAR(3) limit length?","sections":[{"body":"SQLite derives an affinity from the declared type by substring rules: a type containing INT has INTEGER affinity; CHAR, CLOB or TEXT gives TEXT; BLOB or no type gives BLOB (also called none); REAL, FLOA or DOUB gives REAL; anything else, such as NUMERIC, DECIMAL, BOOLEAN or DATETIME, gives NUMERIC. So VARCHAR(255) is TEXT affinity with no length limit, BOOLEAN stores 0 and 1 as integers, and DATETIME stores whatever you give it. Lengths and precisions in parentheses are parsed and ignored.","title":"Five affinities from the declared type"},{"body":"The program inserts the same six Go values into five columns of an ordinary table and prints typeof() for each, plus the Go type database/sql returns when scanning the INTEGER column into any. A second table is declared STRICT, where the declared type must be INT, INTEGER, REAL, TEXT, BLOB or ANY and a value that cannot be converted losslessly is a constraint error.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\tdb, err := sql.Open(\"sqlite\", \":memory:\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tdb.SetMaxOpenConns(1) // one in-memory database for the whole program\n\n\tif _, err := db.ExecContext(ctx, `\n\t\tCREATE TABLE loose (n INTEGER, r REAL, t TEXT, code VARCHAR(3), x);\n\t\tCREATE TABLE strict (n INTEGER, t TEXT, x ANY) STRICT;`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Affinity converts when it can do so losslessly; otherwise the value is kept as given.\n\tinputs := []struct {\n\t\tlabel string\n\t\tv     any\n\t}{{`\"42\"`, \"42\"}, {`\"4.0\"`, \"4.0\"}, {\"7.5\", 7.5}, {`\"abc\"`, \"abc\"}, {\"int 10\", 10}, {\"[]byte\", []byte{0xCA, 0xFE}}}\n\tfor _, in := range inputs {\n\t\tv := in.v\n\t\tif _, err := db.ExecContext(ctx, \"INSERT INTO loose (n, r, t, code, x) VALUES (?, ?, ?, ?, ?)\", v, v, v, v, v); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\trows, err := db.QueryContext(ctx, \"SELECT typeof(n), typeof(r), typeof(t), typeof(code), typeof(x), n FROM loose\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"input     INTEGER  REAL     TEXT     VARCHAR  none     Go value in n\")\n\tfor i := 0; rows.Next(); i++ {\n\t\tvar tn, tr, tt, tc, tx string\n\t\tvar n any\n\t\tif err := rows.Scan(&tn, &tr, &tt, &tc, &tx, &n); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"%-9s %-8s %-8s %-8s %-8s %-8s %T\\n\", inputs[i].label, tn, tr, tt, tc, tx, n)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows.Close()\n\n\tvar long string\n\tif _, err := db.ExecContext(ctx, \"INSERT INTO loose (code) VALUES (?)\", \"far longer than three\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := db.QueryRowContext(ctx, \"SELECT code FROM loose WHERE length(code) > 3\").Scan(&long); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"VARCHAR(3) kept %d characters\\n\", len(long))\n\n\t// STRICT tables reject values that cannot be converted losslessly.\n\tfor _, v := range []any{\"42\", \"abc\", 4.0, 4.5} {\n\t\t_, err := db.ExecContext(ctx, \"INSERT INTO strict (n) VALUES (?)\", v)\n\t\tfmt.Printf(\"STRICT INTEGER <- %T %v: %v\\n\", v, v, errText(err))\n\t}\n\tvar stored string\n\tif err := db.QueryRowContext(ctx, \"SELECT group_concat(typeof(n) || ':' || n, ' ') FROM strict\").Scan(&stored); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"STRICT rows:\", stored)\n\t_, err = db.ExecContext(ctx, \"CREATE TABLE bad (created DATETIME) STRICT\")\n\tfmt.Println(\"STRICT with DATETIME:\", errText(err))\n}\n\nfunc errText(err error) string {\n\tif err == nil {\n\t\treturn \"ok\"\n\t}\n\treturn err.Error()\n}","language":"go","title":"Watch the conversions","walkthrough":"The text \"42\" and \"4.0\" become integers in the INTEGER column, real in the REAL column, and stay text in the TEXT and untyped columns. 7.5 stays real in INTEGER because converting it would lose the fraction, and \"abc\" stays text there. Scanning into any returns int64, float64, string or []uint8 according to the stored class, row by row. VARCHAR(3) kept 21 characters. In the STRICT table \"42\" and 4.0 are converted and stored as integers, while \"abc\" and 4.5 fail with extended code 3091, SQLITE_CONSTRAINT_DATATYPE, and DATETIME is not an allowed type at all."},{"body":"Because the storage class can vary from row to row, a scan target must accept every class the column can actually contain. Scanning into int64 works for INTEGER values and for text that parses as an integer, and fails for \"abc\"; scanning into string accepts most classes; scanning into any exposes the stored class directly. With ordinary tables, the only way to know is to control every writer. Comparisons also follow storage classes: an INTEGER is always less than any TEXT, so a column that mixes \"10\" and 9 sorts in surprising ways.","title":"What Go code sees"},{"body":"Declare new tables STRICT unless you have a reason not to, and use CHECK constraints for the rules affinity never enforced: length(code) <= 3, flag IN (0, 1), or a time format. A STRICT table can still have an ANY column for genuinely dynamic data. Existing tables cannot be switched to STRICT with ALTER TABLE; they are rebuilt with the copy-and-rename procedure from the migrations lesson. Tools and older SQLite versions before 3.37 cannot read a schema that uses STRICT, which matters if you hand database files to other programs.","code":"CREATE TABLE products (\n  id     INTEGER PRIMARY KEY,\n  code   TEXT NOT NULL CHECK (length(code) <= 12),\n  price  INTEGER NOT NULL CHECK (price >= 0), -- cents\n  active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),\n  extra  ANY\n) STRICT;","language":"sql","title":"Make the schema say what it means","walkthrough":"STRICT rejects text in price and active, the CHECK constraints add the length, range and boolean rules affinity never had, money is stored as integer cents rather than REAL, and the ANY column keeps one deliberately dynamic field."}],"takeaway":"SQLite values carry their own type; columns only have an affinity that converts losslessly when it can. Declared lengths are ignored, so add CHECK constraints, and prefer STRICT tables so that wrong types fail at insert time instead of surfacing in a later Scan.","title":"Type affinity, dynamic typing and STRICT tables","unitID":"sqlite-foundations","wrongAnswers":["The insert fails with a datatype mismatch","SQLite stores 0 because the text is not a number"]},{"conceptTag":"sqlite.rowid-keys","designGuide":{"cautions":["INT PRIMARY KEY silently adds a second key.","AUTOINCREMENT costs a write and is still not gapless."],"cost":"Choosing the key declaration deliberately per table; changing it later means rebuilding the table.","family":"sqlite","flow":["Integer surrogate key?","INTEGER PRIMARY KEY","Ids leak? AUTOINCREMENT","Composite: WITHOUT ROWID"],"ratings":[],"strengths":["The rowid alias makes key lookups a single B-tree search.","RETURNING reports keys for any table shape."]},"hint":"Without AUTOINCREMENT, the next rowid is derived from the rows that currently exist.","id":"sqlite.rowid-keys","introduction":"Almost every SQLite table is a B-tree keyed by a hidden 64-bit integer, the rowid. Declaring a column exactly INTEGER PRIMARY KEY makes it that key, which is fast and is what LastInsertId returns. A small spelling difference, INT instead of INTEGER, gives you a second, separate key, and AUTOINCREMENT changes how ids are reused at a cost most tables do not need.","nuance":"Without AUTOINCREMENT the next rowid is normally max(rowid)+1 of the rows present now, so a deleted maximum is reused. AUTOINCREMENT stores the high-water mark in sqlite_sequence to prevent that.","objective":"Recognize when a primary key is an alias for the rowid, decide whether AUTOINCREMENT is worth its cost, and know when a WITHOUT ROWID table fits.","question":"A table uses id INTEGER PRIMARY KEY without AUTOINCREMENT. You delete the row with the largest id and insert a new row. Which id can it receive?","references":["https://www.sqlite.org/lang_createtable.html#rowid","https://www.sqlite.org/autoinc.html","https://www.sqlite.org/withoutrowid.html","https://www.sqlite.org/lang_returning.html"],"reviewAnswer":"No: only the exact type INTEGER PRIMARY KEY is","reviewPrompt":"Is INT PRIMARY KEY a rowid alias?","sections":[{"body":"A column declared with the type INTEGER and PRIMARY KEY becomes an alias for the rowid: the value is the B-tree key, lookups by it need no separate index, and inserting without a value picks one for you. Any other primary key, including INT PRIMARY KEY, BIGINT PRIMARY KEY or a composite key, is an ordinary unique index next to the hidden rowid. Without AUTOINCREMENT the new rowid is normally one more than the largest rowid in the table, so after deleting the newest row its id can be handed out again.","title":"The rowid and its alias"},{"body":"The program creates a table with INTEGER PRIMARY KEY, one with AUTOINCREMENT, one with INT PRIMARY KEY and a WITHOUT ROWID table with a composite key. It deletes the newest row and inserts again, inspects sqlite_sequence, inserts explicit ids, and uses RETURNING to read back a composite key that LastInsertId cannot describe.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nvar ctx = context.Background()\n\nfunc must(db *sql.DB, query string, args ...any) sql.Result {\n\tres, err := db.ExecContext(ctx, query, args...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res\n}\n\nfunc list(db *sql.DB, query string) string {\n\tvar s sql.NullString\n\tif err := db.QueryRowContext(ctx, query).Scan(&s); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn s.String\n}\n\nfunc main() {\n\tdb, err := sql.Open(\"sqlite\", \":memory:\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tdb.SetMaxOpenConns(1)\n\n\tmust(db, `\n\t\tCREATE TABLE plain (id INTEGER PRIMARY KEY, name TEXT);\n\t\tCREATE TABLE counted (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);\n\t\tCREATE TABLE intkey (id INT PRIMARY KEY, name TEXT);\n\t\tCREATE TABLE members (team TEXT, user TEXT, role TEXT, PRIMARY KEY (team, user)) WITHOUT ROWID;`)\n\n\t// INTEGER PRIMARY KEY is the rowid: id and rowid are the same column.\n\tfor _, table := range []string{\"plain\", \"counted\"} {\n\t\tfor _, name := range []string{\"ada\", \"brian\", \"carol\"} {\n\t\t\tmust(db, \"INSERT INTO \"+table+\" (name) VALUES (?)\", name)\n\t\t}\n\t\tmust(db, \"DELETE FROM \"+table+\" WHERE id = 3\")\n\t\tres := must(db, \"INSERT INTO \"+table+\" (name) VALUES ('dave')\")\n\t\tid, _ := res.LastInsertId()\n\t\tfmt.Printf(\"%-8s after deleting id 3, the next insert gets id %d; rows: %s\\n\",\n\t\t\ttable, id, list(db, \"SELECT group_concat(id || '=' || name, ' ') FROM \"+table))\n\t}\n\tfmt.Println(\"sqlite_sequence:\", list(db, \"SELECT group_concat(name || '=' || seq) FROM sqlite_sequence\"))\n\tfmt.Println(\"plain: id equals rowid for every row:\",\n\t\tlist(db, \"SELECT CASE WHEN count(*) = sum(id = rowid) THEN 'true' ELSE 'false' END FROM plain\"))\n\n\t// INT PRIMARY KEY is not an alias: the table has a separate hidden rowid.\n\tmust(db, \"INSERT INTO intkey (id, name) VALUES (100, 'eve'), (200, 'frank')\")\n\tfmt.Println(\"INT PRIMARY KEY (id:rowid):\", list(db, \"SELECT group_concat(id || ':' || rowid, ' ') FROM intkey\"))\n\n\t// An explicit id is accepted; without AUTOINCREMENT the next one is max(rowid)+1.\n\tmust(db, \"INSERT INTO plain (id, name) VALUES (1000, 'grace')\")\n\tres := must(db, \"INSERT INTO plain (name) VALUES ('heidi')\")\n\tid, _ := res.LastInsertId()\n\tfmt.Println(\"plain after an explicit id 1000, next id:\", id)\n\n\t// RETURNING reports the key directly, also for WITHOUT ROWID tables.\n\tvar team, user string\n\tif err := db.QueryRowContext(ctx,\n\t\t\"INSERT INTO members (team, user, role) VALUES ('core', 'ada', 'owner') RETURNING team, user\").Scan(&team, &user); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"WITHOUT ROWID key: (%s, %s)\\n\", team, user)\n\t_, err = db.ExecContext(ctx, \"INSERT INTO members (team, user, role) VALUES ('core', 'ada', 'viewer')\")\n\tfmt.Println(\"duplicate composite key:\", err)\n\tfmt.Println(\"tables without rowid:\", list(db, \"SELECT group_concat(name) FROM pragma_table_list WHERE wr = 1\"))\n}","language":"go","title":"Four tables side by side","walkthrough":"In plain, deleting id 3 and inserting again reuses 3; in counted, AUTOINCREMENT remembers 3 in sqlite_sequence and hands out 4. id equals rowid for every row of plain. The INT PRIMARY KEY table stores ids 100 and 200 with hidden rowids 1 and 2. After an explicit id 1000 the next automatic id is 1001. The WITHOUT ROWID insert returns its key through RETURNING, a duplicate key fails with extended code 1555 (SQLITE_CONSTRAINT_PRIMARYKEY), and pragma_table_list marks members as a WITHOUT ROWID table."},{"body":"AUTOINCREMENT guarantees that an id is never reused, even after the row with the largest id is deleted. It does so by keeping the high-water mark in the internal sqlite_sequence table and updating it on every insert, which costs extra work and an extra write. Use it when ids escape into the world and reuse would be a bug: an id printed on an invoice, cached by clients or referenced by another system that might not see the delete. For internal keys that only appear in foreign keys with ON DELETE handling, plain INTEGER PRIMARY KEY is enough and faster. Neither variant promises gapless ids; a rolled-back insert still consumes an AUTOINCREMENT value.","title":"When AUTOINCREMENT is worth it"},{"body":"A WITHOUT ROWID table stores rows in a B-tree keyed by its declared primary key, so a lookup by that key reads one tree instead of an index and then the table. It suits tables with a non-integer or composite primary key and small rows, such as memberships, tag links and key-value settings. It requires a PRIMARY KEY, does not support AUTOINCREMENT, and LastInsertId has no meaning for it, so use RETURNING or the key you inserted. With large rows, an ordinary rowid table is usually better. Do not use it for an INTEGER PRIMARY KEY table: that is already keyed by the rowid.","title":"WITHOUT ROWID tables"},{"body":"Result.LastInsertId returns the rowid of the most recent successful insert on the connection that ran your statement, which database/sql hands back with the Result; it is reliable for single-row inserts into rowid tables. For multi-row inserts, upserts or WITHOUT ROWID tables, prefer INSERT ... RETURNING id, which reports exactly the rows the statement wrote. Scan rowids into int64: they are signed 64-bit integers, and if the largest possible rowid is ever in use, a table without AUTOINCREMENT gets a randomly chosen unused rowid while an AUTOINCREMENT table fails with SQLITE_FULL.","title":"Ids in Go"}],"takeaway":"Spell integer keys exactly INTEGER PRIMARY KEY to get the rowid alias. Add AUTOINCREMENT only when an id must never be reused, use WITHOUT ROWID for small rows with composite or text keys, and read generated keys with RETURNING when LastInsertId cannot describe them.","title":"INTEGER PRIMARY KEY, rowid, AUTOINCREMENT and WITHOUT ROWID","unitID":"sqlite-foundations","wrongAnswers":["Always a new id, larger than any ever used","The smallest free id, starting from 1"]},{"conceptTag":"sqlite.nulls-time","designGuide":{"cautions":["Driver default time formats differ and may not parse in SQL.","NOT IN with a NULL in the list matches nothing."],"cost":"A layout constant with two conversion functions, and Null types or pointers wherever the schema allows NULL.","family":"sqlite","flow":["Mark optional columns","Scan into Null or *T","Store UTC, one format","Query with IS, coalesce"],"ratings":[],"strengths":["Missing values stay distinguishable from zero values.","Fixed-width UTC text and Unix integers sort and index well."]},"hint":"Evaluate NULL <> 'countess'. Is the result true, false or something else, and what does WHERE do with it?","id":"sqlite.nulls-time","introduction":"Two things trip up nearly every Go program that talks to SQLite: a NULL arriving in a plain string, and time values stored in whatever format the driver happened to choose. SQLite has no date type, so the format is your decision. Make both explicit in the schema and in the scan targets and the surprises go away.","nuance":"Comparing NULL with anything yields NULL, and WHERE keeps only rows where the condition is true. Write nickname IS NOT 'countess' or add OR nickname IS NULL to include them.","objective":"Scan nullable columns with sql.NullString, sql.Null[T] and pointers, write NULL-aware SQL, and store times in a format that sorts and that SQLite's date functions understand.","question":"Why does WHERE nickname <> 'countess' skip rows whose nickname is NULL?","references":["https://pkg.go.dev/database/sql#Null","https://www.sqlite.org/nulls.html","https://www.sqlite.org/lang_datefunc.html","https://pkg.go.dev/modernc.org/sqlite"],"reviewAnswer":"Error: use sql.NullString, sql.Null[T] or a pointer","reviewPrompt":"Scan NULL into a string?","sections":[{"body":"database/sql refuses to scan NULL into string, int64 or bool and returns an error naming the column. For nullable columns, scan into sql.NullString, sql.NullInt64, sql.NullTime and friends, the generic sql.Null[T] added in Go 1.22, or a pointer such as *int64 that stays nil for NULL. Writing works the other way: a nil argument or a Null value with Valid false stores NULL. Pick one convention per codebase; pointers read well in structs that become JSON, Null types make the validity check explicit.","title":"NULL in, Go value out"},{"body":"The program stores a joined time as fixed-width UTC text and a last-seen time as Unix seconds, inserts one complete and one sparse row, and reads them back with Null types and a pointer. It then shows NULL comparisons, SQLite's date functions reading both formats, and what modernc.org/sqlite writes when you pass a time.Time directly, with and without _time_format=sqlite.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// One fixed-width UTC layout: text comparison then matches time order.\nconst layout = \"2006-01-02T15:04:05.000Z\"\n\nfunc main() {\n\tctx := context.Background()\n\tdb, err := sql.Open(\"sqlite\", \":memory:\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tdb.SetMaxOpenConns(1)\n\n\tif _, err := db.ExecContext(ctx, `CREATE TABLE users (\n\t\tid        INTEGER PRIMARY KEY,\n\t\tname      TEXT NOT NULL,\n\t\tnickname  TEXT,             -- optional\n\t\tscore     INTEGER,          -- optional\n\t\tjoined_at TEXT NOT NULL,    -- UTC, fixed-width text\n\t\tseen_unix INTEGER           -- optional, Unix seconds\n\t)`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tjoined := time.Date(2026, 3, 1, 9, 30, 0, 0, time.FixedZone(\"CET\", 3600))\n\tseen := time.Date(2026, 11, 29, 18, 0, 0, 0, time.UTC)\n\tinsert := \"INSERT INTO users (name, nickname, score, joined_at, seen_unix) VALUES (?, ?, ?, ?, ?)\"\n\t// A nil interface or an invalid sql.Null value is stored as NULL.\n\tif _, err := db.ExecContext(ctx, insert, \"Ada\", \"countess\", 42, joined.UTC().Format(layout), seen.Unix()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif _, err := db.ExecContext(ctx, insert, \"Brian\", nil, sql.Null[int64]{}, joined.Add(time.Hour).UTC().Format(layout), sql.NullInt64{}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Scanning NULL into a plain string is an error, not an empty string.\n\tvar nick string\n\terr = db.QueryRowContext(ctx, \"SELECT nickname FROM users WHERE name = 'Brian'\").Scan(&nick)\n\tfmt.Println(\"plain string:\", err)\n\n\trows, err := db.QueryContext(ctx, \"SELECT name, nickname, score, joined_at, seen_unix FROM users ORDER BY joined_at\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar name, joinedText string\n\t\tvar nickname sql.NullString\n\t\tvar score sql.Null[int64]\n\t\tvar seenUnix *int64 // a pointer is nil for NULL\n\t\tif err := rows.Scan(&name, &nickname, &score, &joinedText, &seenUnix); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tjoinedAt, err := time.Parse(layout, joinedText)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tseenText := \"never\"\n\t\tif seenUnix != nil {\n\t\t\tseenText = time.Unix(*seenUnix, 0).UTC().Format(time.RFC3339)\n\t\t}\n\t\tfmt.Printf(\"%s nickname=%q valid=%t score=%d valid=%t joined=%s seen=%s\\n\",\n\t\t\tname, nickname.String, nickname.Valid, score.V, score.Valid, joinedAt.Format(time.RFC3339), seenText)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// NULL is not equal to anything, including NULL; use IS, IS NOT, COALESCE.\n\tvar eq, is sql.NullBool\n\tvar label string\n\tif err := db.QueryRowContext(ctx,\n\t\t\"SELECT NULL = NULL, NULL IS NULL, coalesce((SELECT nickname FROM users WHERE name = 'Brian'), '(none)')\").Scan(&eq, &is, &label); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"NULL = NULL valid=%t, NULL IS NULL=%t, coalesce=%s\\n\", eq.Valid, is.Bool, label)\n\tvar missing int\n\tif err := db.QueryRowContext(ctx, \"SELECT count(*) FROM users WHERE nickname <> 'countess'\").Scan(&missing); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"rows where nickname <> 'countess':\", missing)\n\n\t// SQLite's date functions read both storage forms.\n\tvar day, fromUnix string\n\tif err := db.QueryRowContext(ctx,\n\t\t\"SELECT date(joined_at), datetime(seen_unix, 'unixepoch') FROM users WHERE name = 'Ada'\").Scan(&day, &fromUnix); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"date(joined_at):\", day, \"| datetime(seen_unix, 'unixepoch'):\", fromUnix)\n\n\t// Passing a time.Time directly lets the driver choose the text format.\n\tfor _, dsn := range []string{\":memory:\", \":memory:?_time_format=sqlite\"} {\n\t\ttdb, err := sql.Open(\"sqlite\", dsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvar stored string\n\t\tvar day sql.NullString\n\t\tif err := tdb.QueryRowContext(ctx, \"SELECT CAST(? AS TEXT), date(?)\", joined, joined).Scan(&stored, &day); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"%-28s time.Time stored as %q, date() valid=%t\\n\", dsn, stored, day.Valid)\n\t\ttdb.Close()\n\t}\n}","language":"go","title":"A table with optional columns and two time formats","walkthrough":"The first line is the error database/sql returns for NULL into string. Ada has every value; Brian has invalid Null values and a nil pointer, printed as never. The joined time 09:30 in CET is stored and printed as 08:30Z. NULL = NULL is itself NULL (valid=false), and nickname <> 'countess' matches 0 rows because the comparison with Brian's NULL is unknown. date() and datetime(..., 'unixepoch') read both formats. Passed as time.Time, the driver writes Go's String format, which date() cannot parse; with _time_format=sqlite it writes 2026-03-01 09:30:00+01:00, which it can."},{"body":"Any comparison with NULL yields NULL, which WHERE treats as false. That is why nickname <> 'countess' skips rows whose nickname is NULL, and why NOT IN with a subquery that returns a NULL matches nothing. Use IS NULL and IS NOT NULL, the null-safe IS and IS NOT comparisons (a IS b is true when both are NULL), coalesce(x, default) for display and ifnull or nullif where they read better. Aggregates skip NULLs: count(col) counts non-NULL values while count(*) counts rows, and avg ignores missing scores rather than treating them as zero.","title":"Three-valued logic in SQL"},{"body":"Store instants in UTC, in one format per column, and document it in the schema. Unix seconds or milliseconds in an INTEGER column are compact, compare as numbers and work with datetime(x, 'unixepoch') or unixepoch(). ISO 8601 text such as 2026-03-01T08:30:00.000Z is readable in any browser and sorts correctly only if every value has the same width and zone: time.RFC3339Nano drops trailing zeros, so 08:30:00.5Z and 08:30:00.25Z sort in the wrong order. Format and parse in Go with one layout constant rather than relying on the driver default, which differs between drivers. Keep calendar dates, such as a birthday, as YYYY-MM-DD text without a zone.","code":"const layout = \"2006-01-02T15:04:05.000Z\" // fixed width, always UTC\n\nfunc toDB(t time.Time) string { return t.UTC().Format(layout) }\n\nfunc fromDB(s string) (time.Time, error) { return time.Parse(layout, s) }","language":"go","title":"Choosing a time representation","walkthrough":"Two small functions own the conversion in both directions. Because the layout always has three fractional digits and the literal Z, string order equals time order, so ORDER BY joined_at and range queries with >= and < work on the text column and can use an index."}],"takeaway":"Scan nullable columns into sql.Null types or pointers, write NULL-aware SQL with IS and coalesce, and store times in UTC in one explicit format per column, either Unix integers or fixed-width ISO 8601 text, converted by your own code rather than the driver default.","title":"NULLs and time values: sql.Null, pointers, COALESCE and a time format you choose","unitID":"sqlite-foundations","wrongAnswers":["SQLite converts NULL to an empty string first","Indexes do not store NULL values"]},{"conceptTag":"sqlite.foreign-keys","designGuide":{"cautions":["Any connection without the pragma writes orphans.","The pragma is silently ignored inside a transaction."],"cost":"One DSN parameter, an index per foreign key and a one-time foreign_key_check on existing data.","family":"sqlite","flow":["Declare REFERENCES","Index the child column","foreign_keys(1) in DSN","foreign_key_check data"],"ratings":[],"strengths":["The database, not every code path, guards references.","CASCADE and SET NULL keep related rows consistent."]},"hint":"Check the pragma on the connection that ran the insert, not the schema text.","id":"sqlite.foreign-keys","introduction":"SQLite parses and stores every REFERENCES clause, and then, for backward compatibility, ignores it unless the connection has run PRAGMA foreign_keys = ON. The setting is not stored in the file and must be enabled on every connection, so a database written by a tool or a forgotten code path can already contain orphans.","nuance":"The schema is fine; the connection never enabled foreign_keys. The pragma is per connection and ignored inside a transaction, so set it in the DSN and verify with PRAGMA foreign_keys.","objective":"Show that REFERENCES clauses are not enforced by default, enable enforcement for every connection through the DSN, use ON DELETE CASCADE and find existing violations with foreign_key_check.","question":"Your schema declares REFERENCES authors(id), yet an insert with a missing author succeeds. What is the most likely cause?","references":["https://www.sqlite.org/foreignkeys.html","https://www.sqlite.org/pragma.html#pragma_foreign_keys","https://www.sqlite.org/pragma.html#pragma_foreign_key_check","https://www.sqlite.org/rescode.html#constraint_foreignkey"],"reviewAnswer":"OFF, and it must be enabled on every connection","reviewPrompt":"Default PRAGMA foreign_keys?","sections":[{"body":"Foreign key enforcement was added to SQLite long after many applications depended on it being absent, so the default stayed OFF and remains so unless SQLite is compiled with a different default. PRAGMA foreign_keys = ON affects only the connection that runs it, lasts until that connection closes, and is a no-op inside an open transaction. With database/sql the dependable place is the DSN, so the driver turns it on for each connection the pool opens.","title":"Off by default, per connection"},{"body":"The program creates authors and books with ON DELETE CASCADE, then inserts a book for a missing author through a default connection and through one opened with _pragma=foreign_keys(1). It uses pragma_foreign_key_check to find the orphan, errors.As to read the extended result code, and finally tries to turn enforcement off inside a transaction.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"modernc.org/sqlite\"\n\tsqlite3 \"modernc.org/sqlite/lib\"\n)\n\nvar ctx = context.Background()\n\nconst schema = `\nCREATE TABLE authors (\n\tid   INTEGER PRIMARY KEY,\n\tname TEXT NOT NULL\n);\nCREATE TABLE books (\n\tid        INTEGER PRIMARY KEY,\n\tauthor_id INTEGER NOT NULL REFERENCES authors (id) ON DELETE CASCADE,\n\ttitle     TEXT NOT NULL\n);\nCREATE INDEX books_author ON books (author_id); -- the child side needs its own index\nINSERT INTO authors (id, name) VALUES (1, 'Kernighan');\nINSERT INTO books (author_id, title) VALUES (1, 'The Go Programming Language');`\n\nfunc open(path, params string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+filepath.ToSlash(path)+params)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}\n\nfunc count(db *sql.DB, query string) int {\n\tvar n int\n\tif err := db.QueryRowContext(ctx, query).Scan(&n); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn n\n}\n\nfunc describe(err error) string {\n\tvar se *sqlite.Error\n\tif errors.As(err, &se) {\n\t\treturn fmt.Sprintf(\"rejected, code %d (SQLITE_CONSTRAINT_FOREIGNKEY=%d)\", se.Code(), sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY)\n\t}\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn \"accepted\"\n}\n\nfunc main() {\n\tdir, err := os.MkdirTemp(\"\", \"fk\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"library.db\")\n\n\t// Default connection: the REFERENCES clause is parsed and stored, but not enforced.\n\tloose := open(path, \"\")\n\tif _, err := loose.ExecContext(ctx, schema); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"default PRAGMA foreign_keys =\", count(loose, \"PRAGMA foreign_keys\"))\n\t_, err = loose.ExecContext(ctx, \"INSERT INTO books (author_id, title) VALUES (99, 'Orphan')\")\n\tfmt.Println(\"default: book for missing author 99:\", describe(err))\n\tfmt.Println(\"default: orphans found by foreign_key_check:\", count(loose, \"SELECT count(*) FROM pragma_foreign_key_check('books')\"))\n\tif _, err := loose.ExecContext(ctx, \"DELETE FROM books WHERE author_id = 99\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tloose.Close()\n\n\t// Enforcing connection: the driver runs PRAGMA foreign_keys = ON on every new connection.\n\tdb := open(path, \"?_pragma=foreign_keys(1)\")\n\tdefer db.Close()\n\tfmt.Println(\"DSN PRAGMA foreign_keys =\", count(db, \"PRAGMA foreign_keys\"))\n\t_, err = db.ExecContext(ctx, \"INSERT INTO books (author_id, title) VALUES (99, 'Orphan')\")\n\tfmt.Println(\"enforced: book for missing author 99:\", describe(err))\n\t_, err = db.ExecContext(ctx, \"UPDATE authors SET id = 2 WHERE id = 1\")\n\tfmt.Println(\"enforced: change a referenced key:\", describe(err))\n\tif _, err := db.ExecContext(ctx, \"DELETE FROM authors WHERE id = 1\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"enforced: books left after deleting author 1 (ON DELETE CASCADE):\", count(db, \"SELECT count(*) FROM books\"))\n\n\t// Inside a transaction the pragma is a silent no-op.\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif _, err := tx.ExecContext(ctx, \"PRAGMA foreign_keys = OFF\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar inTx int\n\tif err := tx.QueryRowContext(ctx, \"PRAGMA foreign_keys\").Scan(&inTx); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"PRAGMA foreign_keys = OFF inside a transaction leaves it at\", inTx)\n\tif err := tx.Rollback(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Same file, two kinds of connection","walkthrough":"The default connection reports foreign_keys 0, accepts the orphan and foreign_key_check finds one violation. After deleting it, the DSN connection reports 1, rejects the orphan and an update of a referenced key with extended code 787, SQLITE_CONSTRAINT_FOREIGNKEY, and deleting author 1 cascades to the book. The last line shows the pragma left at 1 because it ran inside a transaction."},{"body":"ON DELETE and ON UPDATE accept NO ACTION (the default), RESTRICT, SET NULL, SET DEFAULT and CASCADE. NO ACTION is checked at the end of the statement, RESTRICT immediately; DEFERRABLE INITIALLY DEFERRED moves the check to COMMIT, which helps when inserting rows that reference each other. SQLite does not create an index on the child column for you. Without books(author_id) indexed, every delete of an author scans the whole books table to find children, so add the index in the same migration as the constraint.","title":"Actions and indexes"},{"body":"Before enabling enforcement on data that was written without it, run PRAGMA foreign_key_check: it lists every row whose reference has no parent, with the table, rowid and constraint, and changes nothing. Fix or delete those rows in a migration, then enable the pragma in the DSN. Table rebuilds during migrations are the one time you deliberately switch enforcement off, outside the transaction, followed by foreign_key_check before committing, as the documented ALTER TABLE procedure describes.","code":"SELECT \"table\", rowid, parent, fkid FROM pragma_foreign_key_check;\n-- books | 7 | authors | 0  means books row 7 references a missing author","language":"sql","title":"Turning it on for an existing database","walkthrough":"The table-valued form of the pragma can be filtered and joined like a table. An empty result means every reference has a parent and enforcement can be enabled without breaking existing writes."}],"takeaway":"Foreign keys in SQLite are enforced only on connections that ran PRAGMA foreign_keys = ON, outside a transaction. Put it in the DSN, index every child column, choose ON DELETE actions deliberately and run foreign_key_check before relying on existing data.","title":"Foreign keys are off until each connection turns them on","unitID":"sqlite-foundations","wrongAnswers":["REFERENCES needs ON DELETE CASCADE to be enforced","Foreign keys only work in STRICT tables"]},{"conceptTag":"sqlite.transactions-returning","designGuide":{"cautions":["Statements on db instead of tx escape the transaction.","A long transaction holds the single write lock."],"cost":"One pinned connection per transaction and an error-mapping function; the discipline is keeping slow work outside the transaction.","family":"sqlite","flow":["BeginTx with request ctx","defer tx.Rollback()","Writes with RETURNING","Commit and map codes"],"ratings":[],"strengths":["Constraints enforce invariants even if application code has a bug.","RETURNING removes a second query and its race."]},"hint":"Think about how many rows RETURNING produces when the UPDATE matches nothing.","id":"sqlite.transactions-returning","introduction":"A transfer that debits one account and fails to credit the other is worse than no transfer at all. A transaction makes the two updates one unit: SQLite commits both or neither, even if the process dies halfway. RETURNING, available since SQLite 3.35, lets an INSERT or UPDATE report the values it produced, so you learn the new id, a default or the updated balance without a second query that could see a different state.","nuance":"No row is updated, so RETURNING yields no row and Scan returns sql.ErrNoRows. The function returns before the credit and the deferred Rollback leaves both balances untouched.","objective":"Group related writes in a database/sql transaction that always rolls back on failure, read generated values with RETURNING, and classify a constraint failure by its extended SQLite result code.","question":"A transfer debits with UPDATE ... RETURNING balance read through QueryRowContext. What happens when the source account does not exist?","references":["https://go.dev/doc/database/execute-transactions","https://www.sqlite.org/lang_transaction.html","https://www.sqlite.org/lang_returning.html","https://www.sqlite.org/rescode.html"],"reviewAnswer":"It undoes partial work on every early return","reviewPrompt":"Why defer tx.Rollback()?","sections":[{"body":"db.BeginTx borrows one connection from the pool and pins it to the *sql.Tx until Commit or Rollback; every statement must go through tx, not db, or it runs on a different connection outside the transaction. The idiom is to defer tx.Rollback() immediately after BeginTx. On every early return the deferred call undoes the partial work; after a successful Commit it returns sql.ErrTxDone and changes nothing, so it is safe to ignore. A failed statement, such as a constraint violation, undoes only that statement: the transaction stays open with the earlier writes, and a Commit at that point would keep them. The deferred Rollback is what discards them and returns the connection to the pool in a clean state.","code":"tx, err := db.BeginTx(ctx, nil)\nif err != nil {\n\treturn err\n}\ndefer tx.Rollback() // no-op once Commit has succeeded\n\nif _, err := tx.ExecContext(ctx, debit, amount, from); err != nil {\n\treturn err // the deferred Rollback undoes nothing committed\n}\nif _, err := tx.ExecContext(ctx, credit, amount, to); err != nil {\n\treturn err // the debit is undone too\n}\nreturn tx.Commit()","language":"go","title":"BeginTx, defer Rollback, Commit","walkthrough":"Both writes go through tx, so they share one connection and one transaction. Any error returns before Commit and the deferred Rollback discards the debit; only the final Commit makes the pair visible to other connections."},{"body":"The program stores balances with CHECK (balance >= 0), so the database itself refuses an overdraft. Accounts are opened with INSERT ... RETURNING id, opened, which returns the generated rowid and the column default in the same statement. The debit is UPDATE ... RETURNING balance read with QueryRowContext: when the WHERE clause matches no row, RETURNING produces no row and Scan reports sql.ErrNoRows, so an unknown account fails loudly instead of silently crediting money that was never debited.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"modernc.org/sqlite\"\n\tsqlite3 \"modernc.org/sqlite/lib\"\n)\n\n// transfer moves amount between two accounts atomically: both updates commit or neither does.\nfunc transfer(ctx context.Context, db *sql.DB, from, to string, amount int) error {\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback() // a no-op after a successful Commit\n\n\tvar left int\n\tif err := tx.QueryRowContext(ctx,\n\t\t\"UPDATE accounts SET balance = balance - ? WHERE name = ? RETURNING balance\",\n\t\tamount, from).Scan(&left); err != nil {\n\t\treturn fmt.Errorf(\"debit %s: %w\", from, err)\n\t}\n\tif _, err := tx.ExecContext(ctx,\n\t\t\"UPDATE accounts SET balance = balance + ? WHERE name = ?\", amount, to); err != nil {\n\t\treturn fmt.Errorf(\"credit %s: %w\", to, err)\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"moved %d from %s to %s, %s now has %d\\n\", amount, from, to, from, left)\n\treturn nil\n}\n\nfunc balances(ctx context.Context, db *sql.DB) string {\n\trows, err := db.QueryContext(ctx, \"SELECT name, balance FROM accounts ORDER BY name\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tvar out []string\n\tfor rows.Next() {\n\t\tvar name string\n\t\tvar balance int\n\t\tif err := rows.Scan(&name, &balance); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tout = append(out, fmt.Sprintf(\"%s=%d\", name, balance))\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn strings.Join(out, \" \")\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"tx\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", filepath.Join(dir, \"bank.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tif _, err := db.ExecContext(ctx, `CREATE TABLE accounts (\n\t\tid      INTEGER PRIMARY KEY,\n\t\tname    TEXT NOT NULL UNIQUE,\n\t\tbalance INTEGER NOT NULL CHECK (balance >= 0),\n\t\topened  TEXT NOT NULL DEFAULT 'day-1'\n\t)`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// RETURNING hands back generated values from the same statement.\n\tfor _, name := range []string{\"alice\", \"bob\"} {\n\t\tvar id int64\n\t\tvar opened string\n\t\tif err := db.QueryRowContext(ctx,\n\t\t\t\"INSERT INTO accounts (name, balance) VALUES (?, 100) RETURNING id, opened\",\n\t\t\tname).Scan(&id, &opened); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"opened %s: id=%d opened=%s\\n\", name, id, opened)\n\t}\n\n\tif err := transfer(ctx, db, \"alice\", \"bob\", 30); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"after first transfer:\", balances(ctx, db))\n\n\terr = transfer(ctx, db, \"alice\", \"bob\", 500)\n\tfmt.Println(\"second transfer failed:\", err)\n\tvar se *sqlite.Error\n\tif errors.As(err, &se) {\n\t\tfmt.Println(\"extended code:\", se.Code(), \"is CHECK:\", se.Code() == sqlite3.SQLITE_CONSTRAINT_CHECK,\n\t\t\t\"primary code:\", se.Code()&0xff)\n\t}\n\tfmt.Println(\"after failed transfer:\", balances(ctx, db))\n\n\terr = transfer(ctx, db, \"carol\", \"bob\", 10)\n\tfmt.Println(\"unknown account:\", errors.Is(err, sql.ErrNoRows))\n\tfmt.Println(\"after unknown account:\", balances(ctx, db))\n}","language":"go","title":"A transfer with a CHECK constraint and RETURNING","walkthrough":"alice and bob receive ids 1 and 2 and the default opened value day-1. The first transfer moves 30 and the RETURNING clause reports alice at 70. The second asks for 500; the CHECK fails with extended code 275, SQLITE_CONSTRAINT_CHECK, whose low byte is 19, SQLITE_CONSTRAINT, and the balances stay 70 and 130. The transfer from carol fails with sql.ErrNoRows before any credit is written."},{"body":"modernc.org/sqlite returns *sqlite.Error, whose Code method gives the extended result code, and modernc.org/sqlite/lib defines the constants. The low eight bits are the primary code: 19 is SQLITE_CONSTRAINT for every constraint, and the extended codes tell them apart, such as 2067 for UNIQUE, 1555 for PRIMARY KEY, 787 for FOREIGN KEY, 1299 for NOT NULL and 275 for CHECK. Map those to your own domain errors in the repository layer, for example a UNIQUE violation on email to ErrEmailTaken, so handlers never parse driver text. Other drivers expose the same numbers through their own error types, which is another reason to keep this mapping in one place.","title":"Classify errors by code, not by message"},{"body":"RETURNING works on INSERT, UPDATE and DELETE, and an UPSERT can return the row it inserted or updated. It reports each row as the statement wrote it, including defaults and generated rowids. SQLite documents its limits: it is available only on top-level statements, not inside triggers; it cannot contain aggregate or window functions; the order of rows from a multi-row statement is arbitrary; and it reports only rows the statement itself changed, not changes made by triggers or foreign key actions. SQLite performs all the changes on the first step and buffers the returned rows, but the Rows value still holds the transaction's connection, so read and close it before the next statement. Run such statements with Query or QueryRow, not Exec, when you want the values.","title":"What RETURNING can and cannot do"},{"body":"A write transaction in SQLite holds the database-wide write lock from its first write until Commit. Do the slow work, such as calling another service, hashing a password or rendering a template, before BeginTx, and do only SQL inside it. Pass the request context to BeginTx: database/sql rolls the transaction back if that context is cancelled before Commit, so an abandoned request cannot keep the lock. Never wait for user input or a network reply while a transaction is open, and never mix tx and db statements in the same unit of work.","title":"Keep transactions short"}],"takeaway":"Run related writes on one *sql.Tx with a deferred Rollback and a final Commit, let constraints enforce invariants, use RETURNING to read generated values and to detect a missing row, and classify failures by extended result code.","title":"Transactions and RETURNING: all-or-nothing changes that hand back what they wrote","unitID":"sqlite-data","wrongAnswers":["Scan reads a zero balance and the credit proceeds","SQLite raises SQLITE_CONSTRAINT_CHECK"]},{"conceptTag":"sqlite.upsert","designGuide":{"cautions":["INSERT OR REPLACE changes rowids and cascades deletes.","INSERT ... SELECT needs a WHERE before ON CONFLICT."],"cost":"A unique index on the conflict target and a clear rule for merging duplicate keys within one batch.","family":"sqlite","flow":["Unique key as target","ON CONFLICT DO UPDATE","excluded.col for new value","RETURNING the result"],"ratings":[],"strengths":["One atomic statement replaces a racy read-then-write.","RETURNING tells you whether you inserted or updated."]},"hint":"OR REPLACE resolves the conflict by removing something first. What does removing a parent do here?","id":"sqlite.upsert","introduction":"Insert this row, or update the one that is already there is one of the most common writes in an application. Doing it as SELECT-then-INSERT in Go is a race; SQLite does it atomically with the UPSERT clause, ON CONFLICT, added in 3.24. The older INSERT OR REPLACE looks similar but is a different operation: it deletes the conflicting row and inserts a new one, which quietly changes ids and can cascade into child tables.","nuance":"REPLACE deletes the conflicting tag, so the cascade deletes its children, then inserts a new row with a new rowid. ON CONFLICT DO UPDATE changes the row in place and keeps both the id and the children.","objective":"Write ON CONFLICT DO UPDATE and DO NOTHING statements that use excluded values and RETURNING, and explain why INSERT OR REPLACE changes rowids and fires cascading deletes.","question":"A tags row has child rows with ON DELETE CASCADE. You rewrite its color with INSERT OR REPLACE using the same unique name. What happens to the children?","references":["https://www.sqlite.org/lang_upsert.html","https://www.sqlite.org/lang_conflict.html","https://www.sqlite.org/lang_returning.html","https://www.sqlite.org/foreignkeys.html"],"reviewAnswer":"Deletes the existing row, then inserts a new one","reviewPrompt":"What does OR REPLACE do?","sections":[{"body":"ON CONFLICT (columns) names a UNIQUE or PRIMARY KEY constraint, and the clause runs only when the insert would violate that constraint. DO UPDATE SET then modifies the existing row; inside it, a bare column name is the stored value and excluded.column is the value the INSERT tried to write. A WHERE clause after DO UPDATE SET can skip the update, for example to keep the newer of two timestamps. DO NOTHING skips the row entirely. The conflict target must match an actual unique index; a column without one is an error, which is good, because it means the statement cannot silently stop deduplicating.","code":"INSERT INTO page_views (path, views, last) VALUES (?, 1, ?)\nON CONFLICT (path) DO UPDATE\n  SET views = views + excluded.views,\n      last  = excluded.last\n  WHERE excluded.last > last\nRETURNING views;","language":"sql","title":"The shape of an UPSERT","walkthrough":"views on the right is the stored count and excluded.views is the 1 being inserted. The optional WHERE keeps an out-of-order, older visit from overwriting last. RETURNING reports the count after the insert or the update."},{"body":"The program runs four cases against one file database opened with foreign keys on. A page-view counter inserts each path once and increments it afterwards, returning the new total. An email claim uses DO NOTHING with RETURNING, so a conflict produces no row. A tag is rewritten first with INSERT OR REPLACE and then with ON CONFLICT DO UPDATE, and the child table shows the difference. Last, rows are merged from a staging table with INSERT ... SELECT.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nfunc must(_ sql.Result, err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc count(ctx context.Context, db *sql.DB, query string) int {\n\tvar n int\n\tif err := db.QueryRowContext(ctx, query).Scan(&n); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn n\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"upsert\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+filepath.Join(dir, \"app.db\")+\"?_pragma=foreign_keys(1)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tmust(db.ExecContext(ctx, `CREATE TABLE page_views (\n\t\tpath  TEXT PRIMARY KEY,\n\t\tviews INTEGER NOT NULL,\n\t\tlast  TEXT NOT NULL\n\t)`))\n\n\t// 1. Counter: insert the first time, add to the stored value afterwards.\n\thit := `INSERT INTO page_views (path, views, last) VALUES (?, 1, ?)\n\t\tON CONFLICT (path) DO UPDATE SET views = views + excluded.views, last = excluded.last\n\t\tRETURNING views`\n\tfor i, path := range []string{\"/\", \"/docs\", \"/\", \"/\", \"/docs\"} {\n\t\tvar views int\n\t\tif err := db.QueryRowContext(ctx, hit, path, fmt.Sprintf(\"t%d\", i+1)).Scan(&views); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"hit %-5s -> views=%d\\n\", path, views)\n\t}\n\tvar last string\n\tif err := db.QueryRowContext(ctx, \"SELECT last FROM page_views WHERE path = '/'\").Scan(&last); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"last visit of / :\", last)\n\n\t// 2. Insert-if-absent: DO NOTHING plus RETURNING yields no row on conflict.\n\tmust(db.ExecContext(ctx, \"CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE)\"))\n\tclaim := \"INSERT INTO users (email) VALUES (?) ON CONFLICT (email) DO NOTHING RETURNING id\"\n\tfor _, email := range []string{\"ann@example.com\", \"ann@example.com\"} {\n\t\tvar id int64\n\t\terr := db.QueryRowContext(ctx, claim, email).Scan(&id)\n\t\tswitch {\n\t\tcase errors.Is(err, sql.ErrNoRows):\n\t\t\tfmt.Println(\"claim\", email, \"-> already taken\")\n\t\tcase err != nil:\n\t\t\tlog.Fatal(err)\n\t\tdefault:\n\t\t\tfmt.Println(\"claim\", email, \"-> new id\", id)\n\t\t}\n\t}\n\n\t// 3. INSERT OR REPLACE deletes the old row first: new rowid, cascades fire.\n\tmust(db.ExecContext(ctx, `CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, color TEXT)`))\n\tmust(db.ExecContext(ctx, `CREATE TABLE post_tags (\n\t\tpost   INTEGER NOT NULL,\n\t\ttag_id INTEGER NOT NULL REFERENCES tags (id) ON DELETE CASCADE\n\t)`))\n\tmust(db.ExecContext(ctx, \"INSERT INTO tags (name, color) VALUES ('go', 'blue')\"))\n\tmust(db.ExecContext(ctx, \"INSERT INTO post_tags VALUES (1, 1), (2, 1)\"))\n\n\tmust(db.ExecContext(ctx, \"INSERT OR REPLACE INTO tags (name, color) VALUES ('go', 'cyan')\"))\n\tvar id int64\n\tif err := db.QueryRowContext(ctx, \"SELECT id FROM tags WHERE name = 'go'\").Scan(&id); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"after OR REPLACE: tag id=%d, post_tags rows=%d\\n\", id, count(ctx, db, \"SELECT count(*) FROM post_tags\"))\n\n\tmust(db.ExecContext(ctx, \"INSERT INTO post_tags VALUES (1, ?), (2, ?)\", id, id))\n\tmust(db.ExecContext(ctx, `INSERT INTO tags (name, color) VALUES ('go', 'teal')\n\t\tON CONFLICT (name) DO UPDATE SET color = excluded.color`))\n\tif err := db.QueryRowContext(ctx, \"SELECT id FROM tags WHERE name = 'go'\").Scan(&id); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"after DO UPDATE: tag id=%d, post_tags rows=%d\\n\", id, count(ctx, db, \"SELECT count(*) FROM post_tags\"))\n\n\t// 4. INSERT ... SELECT needs a WHERE clause before ON CONFLICT.\n\tmust(db.ExecContext(ctx, \"CREATE TABLE incoming (path TEXT, views INTEGER)\"))\n\tmust(db.ExecContext(ctx, \"INSERT INTO incoming VALUES ('/', 10), ('/new', 4)\"))\n\t_, err = db.ExecContext(ctx, `INSERT INTO page_views (path, views, last)\n\t\tSELECT path, views, 'import' FROM incoming\n\t\tON CONFLICT (path) DO UPDATE SET views = views + excluded.views`)\n\tfmt.Println(\"without WHERE, a parse error:\", err != nil)\n\tmust(db.ExecContext(ctx, `INSERT INTO page_views (path, views, last)\n\t\tSELECT path, views, 'import' FROM incoming WHERE true\n\t\tON CONFLICT (path) DO UPDATE SET views = views + excluded.views`))\n\trows, err := db.QueryContext(ctx, \"SELECT path, views FROM page_views ORDER BY path\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar path string\n\t\tvar views int\n\t\tif err := rows.Scan(&path, &views); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"merged %-5s views=%d\\n\", path, views)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"Counters, claims, replace and merge","walkthrough":"The counter reaches 3 for / and 2 for /docs, and last records the fourth visit, t4. The second claim of ann@example.com hits the conflict, RETURNING yields nothing and Scan reports sql.ErrNoRows. INSERT OR REPLACE gives the go tag a new id, 2, and the cascade deletes both post_tags rows; the DO UPDATE afterwards keeps id 2 and both new links. The merge without WHERE fails to parse; with WHERE true, / grows from 3 to 13 and /new is inserted with 4."},{"body":"Insert-if-absent is DO NOTHING. Adding RETURNING id tells you which case happened: one row means you created it, no row means it already existed, which database/sql reports as sql.ErrNoRows from QueryRow. If you also need the existing id, either follow up with a SELECT in the same transaction or use a no-op DO UPDATE such as SET email = excluded.email, which makes RETURNING report the existing row. Note that DO NOTHING applies only to the named conflict target; a different constraint, such as a CHECK or another UNIQUE index, still raises its error.","title":"DO NOTHING with RETURNING"},{"body":"OR REPLACE is a conflict resolution algorithm, not an update. When a uniqueness constraint fails, SQLite deletes the existing row and inserts the new one. Columns you did not list receive their defaults rather than keeping their old values, an INTEGER PRIMARY KEY that you did not supply gets a new rowid, and with foreign keys enabled the delete performs ON DELETE actions, which is why the link rows vanished in the program. Delete triggers fire only when recursive_triggers is on. Prefer ON CONFLICT DO UPDATE whenever existing rows have identity, children or columns you mean to keep.","title":"INSERT OR REPLACE is delete plus insert"},{"body":"When the rows come from a SELECT, the parser cannot tell whether ON starts a join constraint or the upsert clause, so INSERT ... SELECT ... FROM t ON CONFLICT fails with a syntax error near DO. The documented fix is to give the SELECT a WHERE clause, even WHERE true. Also remember that an UPSERT handles conflicts one row at a time: if two rows of the same batch share a key, the second one updates the row the first one inserted, so define what merging means for duplicates inside the batch as well as against existing rows.","title":"INSERT ... SELECT needs WHERE before ON CONFLICT"}],"takeaway":"Use ON CONFLICT (key) DO UPDATE with excluded.column for atomic insert-or-update, DO NOTHING with RETURNING to learn whether you created the row, WHERE true for INSERT ... SELECT, and avoid INSERT OR REPLACE when rows have identity or children.","title":"UPSERT with ON CONFLICT: counters, insert-if-absent and why INSERT OR REPLACE deletes rows","unitID":"sqlite-data","wrongAnswers":["They keep pointing at the updated tag","The statement fails with a FOREIGN KEY error"]},{"conceptTag":"sqlite.wal-busy","designGuide":{"cautions":["Still a single writer; WAL does not add write concurrency.","Needs a local file system; -wal and -shm travel with the file."],"cost":"Two side files, periodic checkpoints and a DSN that configures every connection; long readers can make the log grow.","family":"sqlite","flow":["journal_mode=WAL once","busy_timeout in DSN","synchronous per need","Close readers promptly"],"ratings":[],"strengths":["Readers never block the writer and the writer never blocks readers.","Lock conflicts become bounded waits instead of errors."]},"hint":"Ask how many connections the pool has and which one ran that statement.","id":"sqlite.wal-busy","introduction":"In SQLite's default rollback-journal mode a writer must wait for readers to finish and readers wait while a writer commits. Write-ahead logging changes that: writers append to a separate -wal file, readers keep reading a consistent snapshot, and the two no longer block each other. There is still exactly one writer at a time, so a second writer either fails at once with SQLITE_BUSY or, with busy_timeout, waits its turn.","nuance":"busy_timeout is per connection. The Exec reached one pooled connection; others opened later still have 0. Putting _pragma=busy_timeout(5000) in the DSN applies it to every connection the pool creates.","objective":"Switch a database to write-ahead logging, explain which settings persist in the file and which are per connection, and turn SQLITE_BUSY into a bounded wait with busy_timeout.","question":"You run db.Exec(\"PRAGMA busy_timeout = 5000\") once at startup on a pool. Why do some requests still fail at once with SQLITE_BUSY?","references":["https://www.sqlite.org/wal.html","https://www.sqlite.org/pragma.html#pragma_synchronous","https://www.sqlite.org/c3ref/busy_timeout.html","https://www.sqlite.org/rescode.html#busy"],"reviewAnswer":"journal_mode=WAL; busy_timeout and synchronous do not","reviewPrompt":"Which PRAGMA persists in the file?","sections":[{"body":"PRAGMA journal_mode=WAL is persistent: once set, the database stays in WAL mode for every later connection and process until another journal mode is chosen. Almost everything else you configure is per connection and lasts only as long as that connection: busy_timeout, synchronous, foreign_keys, cache_size and query_only. With a pool you therefore set them in the DSN, which modernc.org/sqlite applies to every new connection, rather than with a one-off db.Exec that reaches only one of the pooled connections.","code":"dsn := \"file:\" + path +\n\t\"?_pragma=busy_timeout(5000)\" +\n\t\"&_pragma=journal_mode(WAL)\" +\n\t\"&_pragma=synchronous(NORMAL)\"\ndb, err := sql.Open(\"sqlite\", dsn)","language":"go","title":"Settings that live in the file and settings that do not","walkthrough":"Each _pragma runs on every connection the pool opens, busy_timeout first. journal_mode(WAL) is idempotent once the file is in WAL mode, and synchronous(NORMAL) must be repeated per connection because it is not stored in the file."},{"body":"The program opens an application pool with WAL, NORMAL and a five-second busy timeout, writes a row and checks the side files. A second pool with no parameters shows what persisted. A read transaction on that pool then watches a writer commit, and finally one connection holds the write lock with BEGIN IMMEDIATE while two other pools try to insert: one with busy_timeout 0 and one with 2000 ms, released by a goroutine after 100 ms.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"modernc.org/sqlite\"\n)\n\nfunc open(path, params string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+path+params)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}\n\nfunc scalar[T any](ctx context.Context, q interface {\n\tQueryRowContext(context.Context, string, ...any) *sql.Row\n}, query string) T {\n\tvar v T\n\tif err := q.QueryRowContext(ctx, query).Scan(&v); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn v\n}\n\nfunc exists(path string) bool { _, err := os.Stat(path); return err == nil }\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"wal\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"app.db\")\n\n\t// The application pool: WAL, NORMAL sync and a 5 s busy timeout on every connection.\n\tapp := open(path, \"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)\")\n\tdefer app.Close()\n\tfmt.Println(\"journal_mode:\", scalar[string](ctx, app, \"PRAGMA journal_mode\"))\n\tif _, err := app.ExecContext(ctx, \"CREATE TABLE events (id INTEGER PRIMARY KEY, name TEXT)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif _, err := app.ExecContext(ctx, \"INSERT INTO events (name) VALUES ('boot')\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"-wal and -shm files exist:\", exists(path+\"-wal\"), exists(path+\"-shm\"))\n\n\t// A pool with no parameters: journal_mode is stored in the file, synchronous is not.\n\tplain := open(path, \"\")\n\tdefer plain.Close()\n\tfmt.Println(\"plain pool journal_mode:\", scalar[string](ctx, plain, \"PRAGMA journal_mode\"))\n\tfmt.Println(\"synchronous app/plain:\", scalar[int](ctx, app, \"PRAGMA synchronous\"), scalar[int](ctx, plain, \"PRAGMA synchronous\"))\n\n\t// Readers keep a snapshot; the writer does not wait for them.\n\treader, err := plain.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"reader sees rows:\", scalar[int](ctx, reader, \"SELECT count(*) FROM events\"))\n\tif _, err := app.ExecContext(ctx, \"INSERT INTO events (name) VALUES ('login')\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"writer committed while the reader was open\")\n\tfmt.Println(\"reader still sees rows:\", scalar[int](ctx, reader, \"SELECT count(*) FROM events\"))\n\tif err := reader.Commit(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"a new read sees rows:\", scalar[int](ctx, plain, \"SELECT count(*) FROM events\"))\n\n\t// Writers do wait for each other. Hold the write lock on one connection.\n\tholder, err := app.Conn(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer holder.Close()\n\tif _, err := holder.ExecContext(ctx, \"BEGIN IMMEDIATE\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\timpatient := open(path, \"?_pragma=busy_timeout(0)\")\n\tdefer impatient.Close()\n\t_, err = impatient.ExecContext(ctx, \"INSERT INTO events (name) VALUES ('impatient')\")\n\tvar se *sqlite.Error\n\tif errors.As(err, &se) {\n\t\tfmt.Printf(\"busy_timeout=0: code %d, %v\\n\", se.Code(), err)\n\t}\n\n\trelease := make(chan struct{})\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tif _, err := holder.ExecContext(ctx, \"COMMIT\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tclose(release)\n\t}()\n\tpatient := open(path, \"?_pragma=busy_timeout(2000)\")\n\tdefer patient.Close()\n\tstart := time.Now()\n\t_, err = patient.ExecContext(ctx, \"INSERT INTO events (name) VALUES ('patient')\")\n\twaited := time.Since(start)\n\t<-release\n\tfmt.Println(\"busy_timeout=2000: err =\", err, \"| waited at least 80ms:\", waited >= 80*time.Millisecond)\n\tfmt.Println(\"rows now:\", scalar[int](ctx, app, \"SELECT count(*) FROM events\"))\n}","language":"go","title":"Snapshots, persistence and lock waits in one program","walkthrough":"journal_mode reports wal and both app.db-wal and app.db-shm exist. The plain pool also reports wal, but synchronous is 1 (NORMAL) on the app pool and 2 (FULL, the default) on the plain one. The reader sees 1 row, the writer commits without waiting, the reader still sees 1, and a fresh read sees 2. With busy_timeout 0 the insert fails at once with code 5, SQLITE_BUSY; with 2000 ms it waits until the holder commits, succeeds, and the table ends with 3 rows."},{"body":"A reader in WAL mode sees the database as of the moment its read transaction started and keeps that snapshot until it ends, while a writer appends new page versions to the -wal file. A checkpoint copies those pages back into the main file; SQLite runs one automatically when the log passes about 1000 pages. A reader that never finishes stops the checkpoint from reaching the end of the log, so the -wal file keeps growing, which is one more reason to close rows promptly. WAL needs shared memory through the -shm file, so every process using the database must be on the same host; it does not work on network file systems. The database, -wal and -shm belong together: copy a live database with VACUUM INTO or the backup API, not by copying the main file.","title":"What WAL changes and what it costs"},{"body":"synchronous controls how often SQLite waits for the disk with fsync. FULL syncs the log on every commit. In WAL mode NORMAL syncs only at checkpoints, and the SQLite documentation states that the database stays consistent and uncorrupted: an application crash loses nothing that was committed, but a power failure or operating system crash may roll back the most recent transactions. That is the usual choice for application databases where a few seconds of lost writes after a power cut is acceptable. Keep FULL when every acknowledged commit must survive power loss, such as a ledger that has already told a client yes.","title":"synchronous=NORMAL in WAL mode"},{"body":"When a connection needs a lock another connection holds, SQLite calls its busy handler. With busy_timeout 0, the default, there is no handler and the statement fails immediately with SQLITE_BUSY, code 5, reported by modernc.org/sqlite as database is locked. busy_timeout(ms) installs a handler that sleeps and retries until the lock frees or the time runs out. Five seconds is a common starting point for services. Set it in the DSN so that every pooled connection has it, and still handle SQLITE_BUSY: under sustained write load a timeout can expire, and some conflicts, covered in the next lesson, are reported without waiting at all.","title":"busy_timeout turns a lock conflict into a bounded wait"}],"takeaway":"Set journal_mode=WAL once, and busy_timeout and synchronous on every connection through the DSN. WAL lets readers and the single writer proceed together, NORMAL trades the last commits on power loss for speed, and busy_timeout makes writers queue instead of failing.","title":"WAL mode, synchronous and busy_timeout: readers that never wait and writers that queue","unitID":"sqlite-data","wrongAnswers":["busy_timeout only applies to read transactions","WAL mode ignores busy_timeout"]},{"conceptTag":"sqlite.begin-immediate","designGuide":{"cautions":["Immediate transactions hold the write lock from the start.","Other processes or deferred code can still return SQLITE_BUSY."],"cost":"Two *sql.DB values and a retry helper; every write path must use the writer pool.","family":"sqlite","flow":["_txlock=immediate","Writer pool of one","query_only reader pool","Retry whole tx on BUSY"],"ratings":[],"strengths":["Read-modify-write transactions become exact under concurrency.","Writers queue in Go where context deadlines apply."]},"hint":"Compare what the second transaction already read with what is now committed.","id":"sqlite.begin-immediate","introduction":"A plain BEGIN in SQLite is deferred: it takes no lock until the first statement, starts as a read transaction and tries to upgrade to a write transaction at the first write. If another connection committed in between, the reader's snapshot is stale and cannot be upgraded. SQLite reports that immediately as SQLITE_BUSY_SNAPSHOT, extended code 517, without calling the busy handler, so the busy_timeout from the previous lesson does nothing for it. Starting write transactions with BEGIN IMMEDIATE avoids the problem entirely.","nuance":"Its snapshot predates the other commit, so SQLite returns SQLITE_BUSY_SNAPSHOT at once without calling the busy handler. With BEGIN IMMEDIATE, the second would have waited at BEGIN and then read the new value.","objective":"Explain why a deferred transaction that reads and then writes can fail with SQLITE_BUSY_SNAPSHOT regardless of busy_timeout, and prevent it with BEGIN IMMEDIATE through _txlock and a single-writer pool.","question":"Two deferred transactions read a counter; one commits an update, then the other tries to update. With busy_timeout set to 5 s, what does the second get?","references":["https://www.sqlite.org/lang_transaction.html","https://www.sqlite.org/rescode.html#busy_snapshot","https://www.sqlite.org/wal.html","https://pkg.go.dev/modernc.org/sqlite"],"reviewAnswer":"A stale snapshot cannot become current by waiting","reviewPrompt":"Why does busy_timeout miss 517?","sections":[{"body":"In WAL mode a read transaction pins a snapshot. To write, a connection must hold the write lock and be reading the latest version of the database. If another writer committed after the snapshot was taken, waiting for the lock would not make the snapshot current, because the values the transaction already read may be out of date. SQLite therefore fails the write at once with SQLITE_BUSY_SNAPSHOT. The only correct response is to roll back and run the whole transaction again, including its reads. In rollback-journal mode the same read-then-write pattern can deadlock two connections, and SQLite returns SQLITE_BUSY without invoking the busy handler for the same reason.","title":"Why waiting cannot help a stale snapshot"},{"body":"The program first reproduces the failure deterministically with two pinned connections running raw BEGIN statements: A reads, B reads, writes and commits, then A tries to write. It then runs a read-modify-write counter from eight goroutines on a pool opened with _txlock=immediate, so every BeginTx issues BEGIN IMMEDIATE. Finally it splits work into a writer pool limited to one connection and a reader pool opened with query_only.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\t\"modernc.org/sqlite\"\n\tsqlite3 \"modernc.org/sqlite/lib\"\n)\n\nconst common = \"&_pragma=busy_timeout(1000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)\"\n\nfunc open(path, params string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+path+\"?\"+params+common)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}\n\nfunc code(err error) int {\n\tvar se *sqlite.Error\n\tif errors.As(err, &se) {\n\t\treturn se.Code()\n\t}\n\treturn 0\n}\n\nfunc exec(ctx context.Context, c *sql.Conn, query string) error {\n\t_, err := c.ExecContext(ctx, query)\n\treturn err\n}\n\n// increment is a read-modify-write in Go: read n, compute, write it back.\nfunc increment(ctx context.Context, db *sql.DB) error {\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\tvar n int\n\tif err := tx.QueryRowContext(ctx, \"SELECT n FROM counter\").Scan(&n); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tx.ExecContext(ctx, \"UPDATE counter SET n = ?\", n+1); err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"immediate\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"app.db\")\n\n\tdeferred := open(path, \"_txlock=deferred\")\n\tdefer deferred.Close()\n\tif _, err := deferred.ExecContext(ctx, \"CREATE TABLE counter (n INTEGER NOT NULL); INSERT INTO counter VALUES (0)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Two deferred transactions both read, then both try to write.\n\ta, _ := deferred.Conn(ctx)\n\tb, _ := deferred.Conn(ctx)\n\tdefer a.Close()\n\tdefer b.Close()\n\tvar n int\n\t_ = exec(ctx, a, \"BEGIN\")\n\t_ = a.QueryRowContext(ctx, \"SELECT n FROM counter\").Scan(&n)\n\tfmt.Println(\"A read n =\", n)\n\t_ = exec(ctx, b, \"BEGIN\")\n\t_ = b.QueryRowContext(ctx, \"SELECT n FROM counter\").Scan(&n)\n\tfmt.Println(\"B read n =\", n)\n\tfmt.Println(\"B update:\", exec(ctx, b, \"UPDATE counter SET n = 1\"), \"| B commit:\", exec(ctx, b, \"COMMIT\"))\n\tstart := time.Now()\n\terr = exec(ctx, a, \"UPDATE counter SET n = 1\")\n\tfmt.Printf(\"A update: code %d, BUSY_SNAPSHOT=%v, waited for the busy timeout=%v\\n\",\n\t\tcode(err), code(err) == sqlite3.SQLITE_BUSY_SNAPSHOT, time.Since(start) >= 900*time.Millisecond)\n\tfmt.Println(\"A must roll back and start over:\", exec(ctx, a, \"ROLLBACK\") == nil)\n\ta.Close()\n\tb.Close()\n\n\t// The same read-modify-write from 8 goroutines, with BEGIN IMMEDIATE.\n\timmediate := open(path, \"_txlock=immediate\")\n\tdefer immediate.Close()\n\tif _, err := immediate.ExecContext(ctx, \"UPDATE counter SET n = 0\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tfailures := 0\n\tfor range 8 {\n\t\twg.Go(func() {\n\t\t\tfor range 25 {\n\t\t\t\tif err := increment(ctx, immediate); err != nil {\n\t\t\t\t\tmu.Lock()\n\t\t\t\t\tfailures++\n\t\t\t\t\tmu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\t_ = immediate.QueryRowContext(ctx, \"SELECT n FROM counter\").Scan(&n)\n\tfmt.Printf(\"immediate: 200 increments -> n=%d, failures=%d\\n\", n, failures)\n\n\t// One writer connection, a separate read-only pool for queries.\n\twriter := open(path, \"_txlock=immediate\")\n\twriter.SetMaxOpenConns(1)\n\tdefer writer.Close()\n\treaders := open(path, \"_pragma=query_only(1)\")\n\treaders.SetMaxOpenConns(4)\n\tdefer readers.Close()\n\tif err := increment(ctx, writer); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t_ = readers.QueryRowContext(ctx, \"SELECT n FROM counter\").Scan(&n)\n\tfmt.Println(\"reader pool sees n =\", n)\n\t_, err = readers.ExecContext(ctx, \"UPDATE counter SET n = 0\")\n\tfmt.Printf(\"reader pool write: code %d (%v)\\n\", code(err), err)\n}","language":"go","title":"The failure, the fix, and a read-only pool","walkthrough":"A and B both read n = 0. B updates and commits without error. A's update fails with code 517, SQLITE_BUSY_SNAPSHOT, without waiting for the one-second busy timeout, and A can only roll back. With BEGIN IMMEDIATE, 8 goroutines times 25 increments end at exactly n=200 with no failures, because each transaction takes the write lock before it reads. The reader pool sees 201 after the writer's increment, and its write attempt fails with code 8, SQLITE_READONLY."},{"body":"BEGIN IMMEDIATE takes the write lock at the start of the transaction. If another writer holds it, the begin itself waits under busy_timeout, which is exactly where waiting is safe, because nothing has been read yet. modernc.org/sqlite and mattn/go-sqlite3 both accept _txlock=immediate in the DSN to make BeginTx issue BEGIN IMMEDIATE, and ncruces/go-sqlite3 has the same option. In modernc.org/sqlite a BeginTx with sql.TxOptions{ReadOnly: true} still issues a plain deferred BEGIN on such a pool, so read-only transactions do not queue for the write lock. The read-only flag does not make the connection refuse writes; query_only does.","code":"writer, _ := sql.Open(\"sqlite\", \"file:\"+path+\n\t\"?_txlock=immediate&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)\")\nwriter.SetMaxOpenConns(1) // one writer, so writes queue in Go, not in SQLite\n\nreaders, _ := sql.Open(\"sqlite\", \"file:\"+path+\n\t\"?_pragma=query_only(1)&_pragma=busy_timeout(5000)\")\nreaders.SetMaxOpenConns(4)","language":"go","title":"Make write transactions immediate","walkthrough":"All writes go through the writer pool, whose single connection makes database/sql queue concurrent writers in Go instead of letting them contend for SQLite's lock. The reader pool serves queries in parallel under WAL and refuses accidental writes with SQLITE_READONLY."},{"body":"SQLite permits one writer at a time no matter how many connections you open, so a large pool of writers only creates contention. A common service layout is a writer *sql.DB with SetMaxOpenConns(1) and immediate transactions, and a reader *sql.DB with several connections and query_only. A request waiting for the writer then waits on database/sql's pool, where the context deadline applies, rather than sleeping in the busy handler. Keep transactions on the writer short; one slow transaction delays every write behind it.","title":"One writer pool and one reader pool"},{"body":"Immediate transactions remove SQLITE_BUSY_SNAPSHOT from your own write paths, but SQLITE_BUSY can still appear when busy_timeout expires, when another process writes to the same file, or when a deferred transaction from code you do not control upgrades. Treat code 5 and its extended forms, such as 517, as retryable: roll back, wait briefly with jitter, and run the whole function again, reads included, a bounded number of times. Never retry only the failing statement inside the same transaction.","title":"Still be ready to retry"}],"takeaway":"A deferred transaction that reads then writes can fail with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot fix. Begin write transactions with BEGIN IMMEDIATE via _txlock=immediate, route writes through a one-connection pool, read from a query_only pool and retry whole transactions.","title":"BEGIN IMMEDIATE and one writer: avoid SQLITE_BUSY_SNAPSHOT that no timeout can fix","unitID":"sqlite-data","wrongAnswers":["It waits up to 5 s and then succeeds","It succeeds and overwrites the first update"]},{"conceptTag":"sqlite.json-functions","designGuide":{"cautions":["Constraints apply to columns, not to fields inside a document.","-> returns JSON text, so comparisons with strings can surprise."],"cost":"Parsing on every unindexed read; one generated column and index per field you filter on.","family":"sqlite","flow":["TEXT with json_valid","->> for scalar values","json_each for arrays","Index generated columns"],"ratings":[],"strengths":["Flexible payloads without a migration per optional field.","Hot paths become indexed columns without duplicating data."]},"hint":"An index needs a value to store per row. Where can the extracted value live?","id":"sqlite.json-functions","introduction":"SQLite has no separate JSON column type, but its JSON functions, built into the core library since 3.38, read and edit JSON stored as TEXT. That makes it practical to keep a flexible payload next to ordinary columns: validate it on write, query into it with path expressions, and promote the fields you filter on into generated columns that can be indexed like any other.","nuance":"Add a generated column defined as doc ->> '$.kind' and index it, or index the expression itself. SQLite has no JSON column type, and json_valid only checks syntax.","objective":"Store JSON documents with a validity check, query paths with json_extract, -> and ->>, expand arrays with json_each and index a field through a generated column.","question":"A query filters on doc ->> '$.kind' over a million rows and is slow. What lets SQLite use an index for it?","references":["https://www.sqlite.org/json1.html","https://www.sqlite.org/gencol.html","https://www.sqlite.org/expridx.html","https://pkg.go.dev/encoding/json"],"reviewAnswer":"JSON text with quotes; ->> returns the SQL value","reviewPrompt":"What does -> return for a string?","sections":[{"body":"json_extract(doc, '$.user.plan') returns an SQL value: text for a JSON string, integer or real for a number, and JSON text for an object or array. The -> operator, added in 3.38 with syntax borrowed from PostgreSQL and MySQL, always returns JSON text, so a string comes back with its quotes. ->> returns an SQL value like json_extract. Use ->> or json_extract when you compare or display a scalar, and -> when you pass a fragment on to another JSON function. Paths start at $, use .key for members and [n] for array elements, and [#-1] counts from the end.","title":"Three ways to read a path"},{"body":"The program stores events as JSON text with CHECK (json_valid(doc)), so malformed documents are rejected at write time. A VIRTUAL generated column, kind, is defined as doc ->> '$.kind' and indexed. It then reads one document three ways, groups by a path, expands the tags array with json_each, asks the planner how it finds a kind, decodes a document into a Go struct and edits one in SQL with json_set.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\ntype Event struct {\n\tKind string `json:\"kind\"`\n\tUser struct {\n\t\tID   int    `json:\"id\"`\n\t\tPlan string `json:\"plan\"`\n\t} `json:\"user\"`\n\tTags []string `json:\"tags\"`\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"json\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", filepath.Join(dir, \"app.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tif _, err := db.ExecContext(ctx, `CREATE TABLE events (\n\t\tid   INTEGER PRIMARY KEY,\n\t\tdoc  TEXT NOT NULL CHECK (json_valid(doc)),\n\t\tkind TEXT GENERATED ALWAYS AS (doc ->> '$.kind') VIRTUAL\n\t);\n\tCREATE INDEX events_kind ON events (kind)`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdocs := []string{\n\t\t`{\"kind\":\"signup\",\"user\":{\"id\":7,\"plan\":\"free\"},\"tags\":[\"web\",\"eu\"]}`,\n\t\t`{\"kind\":\"upgrade\",\"user\":{\"id\":7,\"plan\":\"pro\"},\"tags\":[\"web\"]}`,\n\t\t`{\"kind\":\"signup\",\"user\":{\"id\":9,\"plan\":\"free\"},\"tags\":[\"ios\"]}`,\n\t}\n\tfor _, d := range docs {\n\t\tif _, err := db.ExecContext(ctx, \"INSERT INTO events (doc) VALUES (?)\", d); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\t_, err = db.ExecContext(ctx, \"INSERT INTO events (doc) VALUES (?)\", `{\"kind\":`)\n\tfmt.Println(\"invalid JSON rejected:\", err != nil)\n\n\t// -> returns JSON text, ->> returns an SQL value; json_extract returns an SQL value too.\n\tvar arrow, arrow2, extract string\n\tvar arrowType, arrow2Type string\n\tif err := db.QueryRowContext(ctx, `SELECT doc -> '$.user.plan', typeof(doc -> '$.user.id'),\n\t\tdoc ->> '$.user.plan', typeof(doc ->> '$.user.id'), json_extract(doc, '$.tags[0]')\n\t\tFROM events WHERE id = 1`).Scan(&arrow, &arrowType, &arrow2, &arrow2Type, &extract); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"->  plan=%s id is %s\\n\", arrow, arrowType)\n\tfmt.Printf(\"->> plan=%s id is %s\\n\", arrow2, arrow2Type)\n\tfmt.Println(\"json_extract first tag:\", extract)\n\n\t// Filter and group on JSON paths.\n\trows, err := db.QueryContext(ctx, `SELECT kind, count(*), group_concat(DISTINCT doc ->> '$.user.id')\n\t\tFROM events GROUP BY kind ORDER BY kind`)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor rows.Next() {\n\t\tvar kind, users string\n\t\tvar n int\n\t\tif err := rows.Scan(&kind, &n, &users); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"kind=%s events=%d users=%s\\n\", kind, n, users)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows.Close()\n\n\t// json_each turns an array into rows.\n\trows, err = db.QueryContext(ctx, `SELECT t.value, count(*) FROM events, json_each(events.doc, '$.tags') AS t\n\t\tGROUP BY t.value ORDER BY count(*) DESC, t.value`)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor rows.Next() {\n\t\tvar tag string\n\t\tvar n int\n\t\tif err := rows.Scan(&tag, &n); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"tag %s: %d\\n\", tag, n)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows.Close()\n\n\t// The generated column's index serves the lookup.\n\tvar plan string\n\tif err := db.QueryRowContext(ctx, \"EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'upgrade'\").\n\t\tScan(new(int), new(int), new(int), &plan); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"plan:\", plan)\n\n\t// Decode a whole document in Go when you need the structure.\n\tvar raw string\n\tif err := db.QueryRowContext(ctx, \"SELECT doc FROM events WHERE kind = 'upgrade'\").Scan(&raw); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar e Event\n\tif err := json.Unmarshal([]byte(raw), &e); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"decoded: %s by user %d on %s\\n\", e.Kind, e.User.ID, e.User.Plan)\n\n\t// json_set edits in SQL; the CHECK still holds.\n\tif _, err := db.ExecContext(ctx, `UPDATE events SET doc = json_set(doc, '$.user.plan', 'team') WHERE id = 2`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := db.QueryRowContext(ctx, \"SELECT doc FROM events WHERE id = 2\").Scan(&raw); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"after json_set:\", raw)\n}","language":"go","title":"Events with a JSON payload","walkthrough":"The truncated document is rejected by the CHECK. -> returns \"free\" with quotes and its id is text, while ->> returns free and an integer. Grouping finds two signups by users 7 and 9 and one upgrade by user 7. json_each counts web twice and eu and ios once. The plan line shows SEARCH events USING INDEX events_kind, so the lookup uses the index on the generated column. json_set changes the plan to team in place."},{"body":"A query that filters on doc ->> '$.kind' must parse every document unless an index exists. A generated column names the expression once; VIRTUAL computes it on read and costs no storage, STORED computes it on write. An index on the generated column stores the extracted values, and queries that filter on the column use it, as the plan shows. You can also create an index directly on the expression, but then queries must repeat the expression exactly. Generated columns can be added to an existing table with ALTER TABLE ADD COLUMN only when they are VIRTUAL.","code":"ALTER TABLE events ADD COLUMN user_id INTEGER\n  GENERATED ALWAYS AS (doc ->> '$.user.id') VIRTUAL;\nCREATE INDEX events_user ON events (user_id);\n\nSELECT id FROM events WHERE user_id = ?;","language":"sql","title":"Index a JSON field through a generated column","walkthrough":"The new column costs nothing per row because it is VIRTUAL, the index stores each user id once, and the query filters on the column name rather than repeating the path expression."},{"body":"json_each is a table-valued function: joined to a table, it returns one row per array element or object member with key, value, type and path columns, which turns tag lists into something you can GROUP BY. json_set, json_insert, json_replace and json_remove return a modified copy of a document, so an UPDATE can change one field without a round trip through Go. Since 3.45 SQLite also supports JSONB, a binary encoding stored as a BLOB and produced by jsonb() and the jsonb_ variants of the functions; it saves reparsing on every read, but it is an SQLite-internal format, so keep TEXT when other programs read the column.","title":"json_each, json_set and JSONB"},{"body":"Marshal documents with encoding/json and bind them as string parameters; scan them back as string or []byte and unmarshal when you need the whole structure. Keep the fields that drive queries, joins and constraints as real columns or generated columns, and the rest in the document. A JSON column is a convenience for optional, evolving data, not a replacement for a schema: NOT NULL, UNIQUE and foreign keys only apply to columns, and json_valid in a CHECK is the minimum validation to add.","title":"Where Go fits"}],"takeaway":"Store JSON as TEXT with CHECK (json_valid(doc)), read scalars with ->> or json_extract and fragments with ->, expand arrays with json_each, and index the fields you filter on through generated columns.","title":"JSON in SQLite: json_extract, -> and ->>, json_each and indexed generated columns","unitID":"sqlite-data","wrongAnswers":["Switching the column type to JSON","Calling json_valid in the WHERE clause"]},{"conceptTag":"sqlite.window-ctes","designGuide":{"cautions":["Ties make row_number arbitrary without a tie-breaker.","Recursive CTEs on cyclic data need a depth bound."],"cost":"Sorting per partition; an index matching PARTITION BY and ORDER BY avoids a temporary sort.","family":"sqlite","flow":["PARTITION BY the group","ORDER BY inside OVER","Filter in an outer query","Recurse with a stop rule"],"ratings":[],"strengths":["Per-row results with group context in a single query.","Generated series and tree walks need no extra tables."]},"hint":"Window values exist only after filtering and grouping. Where can you filter on them?","id":"sqlite.window-ctes","introduction":"Reports often need a value that depends on neighbouring rows: a running total, the change since yesterday, the best two days per region. Window functions, in SQLite since 3.25, compute those without collapsing rows the way GROUP BY does. Common table expressions name intermediate results, and WITH RECURSIVE can generate rows, such as every day in a range or every reply in a thread, that are not stored anywhere.","nuance":"Compute row_number() OVER (PARTITION BY region ORDER BY amount DESC) in a subquery or CTE and filter on it outside. A LIMIT applies to the whole result, not to each group.","objective":"Compute running totals, differences and shares with window functions, select the top rows per group with row_number, and walk series and trees with recursive common table expressions.","question":"You need the two largest sales per region. Which query shape works in SQLite?","references":["https://www.sqlite.org/windowfunctions.html","https://www.sqlite.org/lang_with.html","https://www.sqlite.org/lang_datefunc.html","https://go.dev/doc/database/querying"],"reviewAnswer":"WHERE runs before window functions are computed","reviewPrompt":"Why wrap row_number in a subquery?","sections":[{"body":"A window function is an aggregate or ranking function followed by OVER. PARTITION BY splits rows into groups that are computed independently, and ORDER BY inside OVER defines the order within each group. With an ORDER BY, an aggregate like sum uses a frame that runs from the start of the partition to the current row and its peers, which is a running total; without one, it covers the whole partition, which gives a group total on every row. lag and lead read a value from the previous or next row and return NULL at the edges, and row_number, rank and dense_rank number rows.","title":"OVER, PARTITION BY and ORDER BY"},{"body":"The program uses a :memory: database with SetMaxOpenConns(1), because an in-memory database belongs to the single connection that created it. It computes a running total and day-over-day change per region, the best two days per region, each day's share of its region total, a daily series with zero for missing days, and an indented comment thread. A small helper scans every column as sql.NullString so NULLs print visibly.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nfunc show(ctx context.Context, db *sql.DB, title, query string) {\n\trows, err := db.QueryContext(ctx, query)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tcols, _ := rows.Columns()\n\tfmt.Println(\"--\", title)\n\tfor rows.Next() {\n\t\tvals := make([]sql.NullString, len(cols))\n\t\tptrs := make([]any, len(cols))\n\t\tfor i := range vals {\n\t\t\tptrs[i] = &vals[i]\n\t\t}\n\t\tif err := rows.Scan(ptrs...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tout := make([]string, len(cols))\n\t\tfor i, v := range vals {\n\t\t\tout[i] = cols[i] + \"=\" + v.String\n\t\t\tif !v.Valid {\n\t\t\t\tout[i] = cols[i] + \"=NULL\"\n\t\t\t}\n\t\t}\n\t\tfmt.Println(strings.Join(out, \" \"))\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\tctx := context.Background()\n\t// One connection: a :memory: database lives only on the connection that created it.\n\tdb, err := sql.Open(\"sqlite\", \":memory:\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb.SetMaxOpenConns(1)\n\tdefer db.Close()\n\n\tif _, err := db.ExecContext(ctx, `\n\tCREATE TABLE sales (day TEXT, region TEXT, amount INTEGER);\n\tINSERT INTO sales VALUES\n\t\t('2026-11-01', 'eu', 120), ('2026-11-01', 'us', 200),\n\t\t('2026-11-02', 'eu',  80), ('2026-11-02', 'us', 150),\n\t\t('2026-11-03', 'eu', 160), ('2026-11-03', 'us', 210),\n\t\t('2026-11-04', 'eu',  90);\n\tCREATE TABLE comments (id INTEGER PRIMARY KEY, parent INTEGER REFERENCES comments, body TEXT);\n\tINSERT INTO comments VALUES\n\t\t(1, NULL, 'Ship it?'), (2, 1, 'Tests first'), (3, 2, 'They pass'),\n\t\t(4, 1, 'Docs too'), (5, NULL, 'Unrelated thread');`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tshow(ctx, db, \"running total and change per region\", `\n\tSELECT region, day, amount,\n\t\t   sum(amount) OVER (PARTITION BY region ORDER BY day) AS running,\n\t\t   amount - lag(amount) OVER (PARTITION BY region ORDER BY day) AS change\n\tFROM sales ORDER BY region, day`)\n\n\tshow(ctx, db, \"best two days per region\", `\n\tSELECT region, day, amount FROM (\n\t\tSELECT *, row_number() OVER (PARTITION BY region ORDER BY amount DESC) AS rank\n\t\tFROM sales)\n\tWHERE rank <= 2 ORDER BY region, rank`)\n\n\tshow(ctx, db, \"share of the region total\", `\n\tSELECT region, day, round(100.0 * amount / sum(amount) OVER (PARTITION BY region), 1) AS pct\n\tFROM sales WHERE region = 'eu' ORDER BY day`)\n\n\tshow(ctx, db, \"every day in the range, with zero for gaps\", `\n\tWITH RECURSIVE days(day) AS (\n\t\tSELECT '2026-10-31'\n\t\tUNION ALL\n\t\tSELECT date(day, '+1 day') FROM days WHERE day < '2026-11-04')\n\tSELECT days.day, coalesce(sum(s.amount), 0) AS total\n\tFROM days LEFT JOIN sales AS s ON s.day = days.day AND s.region = 'eu'\n\tGROUP BY days.day ORDER BY days.day`)\n\n\tshow(ctx, db, \"thread under comment 1\", `\n\tWITH RECURSIVE thread(id, depth, path) AS (\n\t\tSELECT id, 0, printf('%03d', id) FROM comments WHERE id = 1\n\t\tUNION ALL\n\t\tSELECT c.id, t.depth + 1, t.path || '/' || printf('%03d', c.id)\n\t\tFROM comments AS c JOIN thread AS t ON c.parent = t.id)\n\tSELECT printf('%*s', depth * 2, '') || body AS line FROM thread\n\tJOIN comments USING (id) ORDER BY path`)\n}","language":"go","title":"Sales reports and a comment thread","walkthrough":"For eu the running total grows 120, 200, 360, 450 and change starts as NULL, then -40, 80 and -70. row_number keeps 2026-11-03 and 2026-11-01 for both regions. The eu shares are 26.7, 17.8, 35.6 and 20 percent. The recursive series adds 2026-10-31 with a total of 0 through the LEFT JOIN. The thread lists comment 1, its replies 2 and 4, and reply 3 under 2, indented by depth, while thread 5 is not reached."},{"body":"Window functions cannot appear in WHERE, because WHERE runs before windows are computed. Compute row_number() OVER (PARTITION BY region ORDER BY amount DESC) in a subquery or CTE, then filter on it outside. row_number breaks ties arbitrarily unless the ORDER BY makes rows unique, so add a tie-breaker such as day; use rank if tied rows should all be kept. The same structure gives latest row per key, first event per user and deduplication by keeping row number 1.","code":"WITH ranked AS (\n  SELECT *, row_number() OVER (\n    PARTITION BY region ORDER BY amount DESC, day) AS rn\n  FROM sales)\nSELECT region, day, amount FROM ranked WHERE rn <= 2;","language":"sql","title":"Top N per group","walkthrough":"The CTE numbers each region's days from the highest amount down, using day to break ties deterministically, and the outer query keeps the first two per region."},{"body":"A recursive CTE has an initial SELECT, UNION ALL, and a recursive SELECT that refers to the CTE itself. SQLite runs the recursive part on each new batch of rows until it produces none, so it needs a terminating condition such as day < '2026-11-04' or a join that runs out of children. Carrying a depth and a path column lets you indent and order a tree; zero-padding the ids in the path, as printf('%03d') does, keeps text ordering correct. Add a LIMIT or a depth bound when data could contain a cycle, because UNION ALL does not stop on repeated rows.","title":"WITH RECURSIVE"},{"body":"Window functions and CTEs are ordinary SQL to database/sql: scan the columns as usual. Columns such as lag that can be NULL need sql.NullInt64 or a pointer, and computed columns have the types SQLite produced, so round(...) returns a REAL and 20.0 prints as 20 through a string scan. Push the computation into SQL when it reduces the rows sent to Go, and keep business rules that need testing and explanation in Go when the SQL would become opaque.","title":"Reading results in Go"}],"takeaway":"Use OVER (PARTITION BY ... ORDER BY ...) for running totals, lag for differences and row_number in a subquery for top N per group, and WITH RECURSIVE with a clear stop condition for series and trees.","title":"Window functions and CTEs: running totals, top N per group and recursive queries","unitID":"sqlite-data","wrongAnswers":["WHERE row_number() OVER (...) <= 2 directly","GROUP BY region with LIMIT 2"]},{"conceptTag":"sqlite.query-plans","designGuide":{"cautions":["Every index slows writes and takes space.","Plan wording changes between SQLite versions."],"cost":"A few minutes per query and representative data; indexes add write and storage cost.","family":"sqlite","flow":["EXPLAIN QUERY PLAN","Find SCAN and TEMP B-TREE","Index equality then order","PRAGMA optimize"],"ratings":[],"strengths":["Plans are cheap to read and catch slow queries before production.","Covering indexes answer queries without touching the table."]},"hint":"Compare the values stored in the index with the values the WHERE clause asks about.","id":"sqlite.query-plans","introduction":"An SQLite query that is fast on a hundred rows can scan the whole table on a million. EXPLAIN QUERY PLAN tells you how the planner will run a statement before you discover it in production: whether it scans or searches, which index it uses, whether it can answer from the index alone, and whether it needs a temporary B-tree to sort. Reading it takes a few minutes to learn and pays off on every query you write.","nuance":"The index stores email as written, not lower(email). Create an index on lower(email) and use that exact expression, or store a NOCASE or normalised column; statistics cannot make a non-matching index usable.","objective":"Read EXPLAIN QUERY PLAN output from Go, add indexes that turn scans into searches and remove temporary sorts, use expression indexes for computed filters, and keep statistics fresh with ANALYZE and PRAGMA optimize.","question":"customers has an index on email, yet WHERE lower(email) = ? shows SCAN customers. What fixes it?","references":["https://www.sqlite.org/eqp.html","https://www.sqlite.org/queryplanner.html","https://www.sqlite.org/expridx.html","https://www.sqlite.org/lang_analyze.html","https://www.sqlite.org/pragma.html#pragma_optimize"],"reviewAnswer":"Every needed column is in the index; table not read","reviewPrompt":"What does COVERING INDEX mean?","sections":[{"body":"EXPLAIN QUERY PLAN returns rows with id, parent, an unused column and a detail text; the detail is what you read. SCAN table means every row is visited. SEARCH table USING INDEX name (col=?) means the index narrows the rows first. COVERING INDEX means every column the query needs is in the index, so the table itself is never read. USE TEMP B-TREE FOR ORDER BY or GROUP BY means SQLite must sort the results itself. The exact wording can change between SQLite versions, so tests should not assert full plan strings unless the library version is pinned, as it is here.","title":"The words in a plan"},{"body":"The program fills a file database with 200 customers and 5000 orders in one transaction, then prints the plan of the same queries before and after adding indexes. It also tries a filter on lower(email), adds an expression index for it, runs ANALYZE and reads sqlite_stat1, and finishes with PRAGMA optimize. The plan helper joins every detail row so multi-step plans fit on one line.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// plan returns the detail column of every EXPLAIN QUERY PLAN row.\nfunc plan(ctx context.Context, db *sql.DB, query string) string {\n\trows, err := db.QueryContext(ctx, \"EXPLAIN QUERY PLAN \"+query)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tvar steps []string\n\tfor rows.Next() {\n\t\tvar id, parent, unused int\n\t\tvar detail string\n\t\tif err := rows.Scan(&id, &parent, &unused, &detail); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tsteps = append(steps, detail)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn strings.Join(steps, \" | \")\n}\n\nfunc exec(ctx context.Context, db *sql.DB, query string, args ...any) {\n\tif _, err := db.ExecContext(ctx, query, args...); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"plans\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", filepath.Join(dir, \"shop.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\texec(ctx, db, `CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL);\n\t\tCREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, placed TEXT NOT NULL, total INTEGER NOT NULL)`)\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor c := 1; c <= 200; c++ {\n\t\tif _, err := tx.ExecContext(ctx, \"INSERT INTO customers VALUES (?, ?)\", c, fmt.Sprintf(\"User%d@Example.com\", c)); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tfor o := 1; o <= 5000; o++ {\n\t\tif _, err := tx.ExecContext(ctx, \"INSERT INTO orders (customer_id, placed, total) VALUES (?, ?, ?)\",\n\t\t\to%200+1, fmt.Sprintf(\"2026-%02d-%02d\", o%12+1, o%28+1), o%97*10); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbyCustomer := \"SELECT id, total FROM orders WHERE customer_id = 42\"\n\tfmt.Println(\"1 no index:       \", plan(ctx, db, byCustomer))\n\texec(ctx, db, \"CREATE INDEX orders_customer ON orders (customer_id)\")\n\tfmt.Println(\"2 with index:     \", plan(ctx, db, byCustomer))\n\tfmt.Println(\"3 index only:     \", plan(ctx, db, \"SELECT count(*) FROM orders WHERE customer_id = 42\"))\n\n\trecent := \"SELECT id, placed FROM orders WHERE customer_id = 42 ORDER BY placed DESC LIMIT 5\"\n\tfmt.Println(\"4 sort needed:    \", plan(ctx, db, recent))\n\texec(ctx, db, \"CREATE INDEX orders_customer_placed ON orders (customer_id, placed)\")\n\tfmt.Println(\"5 sorted by index:\", plan(ctx, db, recent))\n\n\texec(ctx, db, \"CREATE INDEX customers_email ON customers (email)\")\n\tbyEmail := \"SELECT id FROM customers WHERE lower(email) = 'user7@example.com'\"\n\tfmt.Println(\"6 lower(email):   \", plan(ctx, db, byEmail))\n\texec(ctx, db, \"CREATE INDEX customers_email_lower ON customers (lower(email))\")\n\tfmt.Println(\"7 expression idx: \", plan(ctx, db, byEmail))\n\n\tvar id int\n\tif err := db.QueryRowContext(ctx, byEmail).Scan(&id); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"found customer\", id)\n\n\texec(ctx, db, \"ANALYZE\")\n\trows, err := db.QueryContext(ctx, \"SELECT idx, stat FROM sqlite_stat1 WHERE tbl = 'orders' ORDER BY idx\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor rows.Next() {\n\t\tvar idx, stat string\n\t\tif err := rows.Scan(&idx, &stat); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"sqlite_stat1 %s: %s\\n\", idx, stat)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows.Close()\n\tfmt.Println(\"8 after ANALYZE:  \", plan(ctx, db, byCustomer))\n\texec(ctx, db, \"PRAGMA optimize\")\n\tfmt.Println(\"PRAGMA optimize ran\")\n}","language":"go","title":"From scans to searches","walkthrough":"Without an index the lookup is SCAN orders. After orders_customer it is a SEARCH on customer_id=?, and count(*) uses the COVERING INDEX. Ordering by placed adds USE TEMP B-TREE FOR ORDER BY until the index on (customer_id, placed) serves both the filter and the order. lower(email) scans customers despite the email index; the expression index turns it into a search. ANALYZE records 5000 rows and about 25 per customer."},{"body":"A composite index is sorted by its first column, then the second, and so on. Equality columns go first, then the column used for range or ORDER BY, so (customer_id, placed) serves WHERE customer_id = ? ORDER BY placed DESC without a sort; SQLite can walk an index backwards for DESC. Every index entry also carries the rowid, which is why that query became covering: it needed only id and placed. Each index costs space and slows every insert, update and delete on the table, so add the ones your real queries need and drop indexes that a wider one already covers, such as orders_customer once the composite exists.","title":"Design indexes for the query, left to right"},{"body":"An index on email stores the values as written; lower(email) = ? asks about different values, so the planner cannot use it and scans. Either store a normalised column, declare the column with COLLATE NOCASE and compare without the function, or create an index on the exact expression, which SQLite has supported since 3.9. The query must use the same expression as the index for the planner to match it. The same rule applies to date(created) or substr(code, 1, 3): wrap the column in a function and the plain index no longer helps.","code":"CREATE INDEX customers_email_lower ON customers (lower(email));\nSELECT id FROM customers WHERE lower(email) = ?; -- SEARCH ... (<expr>=?)\n\n-- or normalise on write and compare the column directly\nCREATE TABLE accounts (email TEXT NOT NULL COLLATE NOCASE UNIQUE);","language":"sql","title":"Functions on columns and expression indexes","walkthrough":"The expression index stores lower(email) for each row, so a query using the same expression becomes a SEARCH. A NOCASE column compares case-insensitively for ASCII letters and its UNIQUE index enforces that rule too."},{"body":"ANALYZE reads each index and stores the results in sqlite_stat1: the row count, then the average number of rows per distinct prefix of the index, which is how 5000 25 says about 25 orders per customer. The planner uses those numbers to choose between indexes when more than one could apply. PRAGMA optimize analyses only what looks stale and is usually quick. The SQLite documentation recommends running it just before closing each short-lived connection; for long-lived connections, run PRAGMA optimize=0x10002 when the connection opens and PRAGMA optimize periodically, for example daily; and always after schema changes, especially CREATE INDEX. Check plans again after adding data in bulk.","title":"ANALYZE, sqlite_stat1 and PRAGMA optimize"},{"body":"For each query that runs on a request path, run EXPLAIN QUERY PLAN against a database with realistic data and look for SCAN on large tables and TEMP B-TREE on hot paths. A small Go test can assert that critical queries do not SCAN, as long as it pins the SQLite library version through go.mod. Measure with real sizes before adding indexes for everything, and remember that a SCAN of a ten-row lookup table is perfectly fine.","title":"Make plans part of review"}],"takeaway":"Read EXPLAIN QUERY PLAN for every hot query: turn SCAN into SEARCH with indexes ordered equality first, remove TEMP B-TREE sorts with the right composite index, match function filters with expression indexes and keep statistics current with PRAGMA optimize.","title":"Read EXPLAIN QUERY PLAN: SCAN, SEARCH, covering indexes, sorts and ANALYZE","unitID":"sqlite-data","wrongAnswers":["Running ANALYZE so the planner trusts the index","Adding ORDER BY email to the query"]},{"conceptTag":"sqlite.migrations-user-version","designGuide":{"cautions":["ALTER TABLE is limited; many changes need a rebuild.","foreign_keys cannot be toggled inside a transaction."],"cost":"A slice of SQL strings, one transaction per step and the discipline of never editing a shipped migration.","family":"sqlite","flow":["Read user_version","Refuse newer schemas","Step + bump in one tx","Repeat until current"],"ratings":[],"strengths":["The version travels inside every copy of the file.","A failed step leaves schema and version consistent."]},"hint":"Look at what the runner does between BeginTx and Commit, and at what Rollback undoes.","id":"sqlite.migrations-user-version","introduction":"A SQLite file outlives the binary that created it: users keep it, copy it and open it with the next release. A migration runner must know which schema the file has and move it forward exactly once per step. SQLite gives every database a 32-bit integer in its header, PRAGMA user_version, that the library never touches. Store the schema version there and change it in the same transaction as the schema itself, because SQLite DDL is transactional.","nuance":"SQLite DDL and the user_version write are transactional. Rolling back the failed step also discards the version bump, so the schema and its number always change together.","objective":"Apply append-only migrations that record their version in PRAGMA user_version inside the same transaction, skip applied steps, roll back a failing step and refuse a newer schema.","question":"A migration step fails halfway. Why does PRAGMA user_version still show the previous version afterwards?","references":["https://www.sqlite.org/pragma.html#pragma_user_version","https://www.sqlite.org/lang_altertable.html","https://www.sqlite.org/fileformat2.html#database_header","https://go.dev/doc/database/execute-transactions"],"reviewAnswer":"Inside the same transaction as the migration step","reviewPrompt":"Where is the version bumped?","sections":[{"body":"PRAGMA user_version reads and writes four bytes at offset 60 of the database header. A new file reports 0. Nothing else uses the value, so it is yours to define: here it means how many migrations from an append-only slice have been applied. Because CREATE TABLE, ALTER TABLE and the user_version write are all part of the transaction, a crash or an error halfway through a step leaves the old schema and the old number together, never a new table with an old version. Unlike a schema_migrations table, the header value travels with every copy and every backup and costs no extra schema object.","title":"The version lives in the file header"},{"body":"migrate reads the version, refuses a file whose version is higher than the number of migrations it knows, and then applies each pending step in its own transaction together with PRAGMA user_version = v+1. PRAGMA arguments cannot be bound as ? parameters, so the statement is built with fmt.Sprintf from an int the program computed, never from input. The program simulates an older release that knows two migrations, a newer release that knows three, a second run, a broken fourth migration, a DROP COLUMN, and the old release opening the upgraded file.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// Migrations are append-only: index i moves the schema from version i to i+1.\n// Never edit or reorder a migration that has shipped.\nvar migrations = []string{\n\t// 1: the first schema.\n\t`CREATE TABLE notes (\n\t\tid    INTEGER PRIMARY KEY,\n\t\ttitle TEXT NOT NULL,\n\t\tbody  TEXT NOT NULL DEFAULT ''\n\t)`,\n\t// 2: a nullable column with a constant default is a cheap ALTER.\n\t`ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0`,\n\t// 3: an index is just another schema object.\n\t`CREATE INDEX notes_pinned ON notes (pinned, id)`,\n}\n\nfunc userVersion(ctx context.Context, q interface {\n\tQueryRowContext(context.Context, string, ...any) *sql.Row\n}) (int, error) {\n\tvar v int\n\terr := q.QueryRowContext(ctx, \"PRAGMA user_version\").Scan(&v)\n\treturn v, err\n}\n\n// migrate applies every pending migration, each in its own transaction that\n// also records the new version, so a crash leaves a consistent schema.\nfunc migrate(ctx context.Context, db *sql.DB, steps []string) (applied int, err error) {\n\tcurrent, err := userVersion(ctx, db)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif current > len(steps) {\n\t\treturn 0, fmt.Errorf(\"database schema version %d is newer than this program (%d)\", current, len(steps))\n\t}\n\tfor v := current; v < len(steps); v++ {\n\t\ttx, err := db.BeginTx(ctx, nil)\n\t\tif err != nil {\n\t\t\treturn applied, err\n\t\t}\n\t\tif _, err := tx.ExecContext(ctx, steps[v]); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn applied, fmt.Errorf(\"migration %d: %w\", v+1, err)\n\t\t}\n\t\t// PRAGMA arguments cannot be bound; v+1 is an int we computed, not input.\n\t\tif _, err := tx.ExecContext(ctx, fmt.Sprintf(\"PRAGMA user_version = %d\", v+1)); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn applied, err\n\t\t}\n\t\tif err := tx.Commit(); err != nil {\n\t\t\treturn applied, err\n\t\t}\n\t\tapplied++\n\t}\n\treturn applied, nil\n}\n\nfunc columns(ctx context.Context, db *sql.DB) string {\n\trows, err := db.QueryContext(ctx, \"SELECT name FROM pragma_table_info('notes') ORDER BY cid\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\tvar names []string\n\tfor rows.Next() {\n\t\tvar n string\n\t\tif err := rows.Scan(&n); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tnames = append(names, n)\n\t}\n\treturn strings.Join(names, \", \")\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"migrations\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", filepath.Join(dir, \"app.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tv, _ := userVersion(ctx, db)\n\tfmt.Println(\"new file, user_version:\", v)\n\n\t// An older release knew only the first two migrations.\n\tn, err := migrate(ctx, db, migrations[:2])\n\tfmt.Println(\"old release applied:\", n, \"err:\", err)\n\tif _, err := db.ExecContext(ctx, \"INSERT INTO notes (title) VALUES ('kept across upgrades')\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tn, err = migrate(ctx, db, migrations)\n\tv, _ = userVersion(ctx, db)\n\tfmt.Println(\"new release applied:\", n, \"err:\", err, \"version:\", v)\n\tn, err = migrate(ctx, db, migrations)\n\tfmt.Println(\"second run applied:\", n, \"err:\", err)\n\tfmt.Println(\"columns:\", columns(ctx, db))\n\n\t// A broken migration rolls back together with its version bump.\n\tbroken := append(append([]string{}, migrations...), \"ALTER TABLE notes ADD COLUMN created TEXT DEFAULT CURRENT_TIMESTAMP\")\n\tn, err = migrate(ctx, db, broken)\n\tv, _ = userVersion(ctx, db)\n\tfmt.Println(\"broken migration applied:\", n, \"version still:\", v)\n\tfmt.Println(\"error:\", err)\n\n\t// DROP COLUMN exists since SQLite 3.35 for columns nothing else depends on.\n\tdropped := append(append([]string{}, migrations...), \"ALTER TABLE notes DROP COLUMN body\")\n\tn, err = migrate(ctx, db, dropped)\n\tfmt.Println(\"drop column applied:\", n, \"err:\", err)\n\tfmt.Println(\"columns:\", columns(ctx, db))\n\n\t// An older binary must refuse a schema it does not know.\n\t_, err = migrate(ctx, db, migrations[:2])\n\tfmt.Println(\"old release now:\", err)\n\n\tvar title string\n\tdb.QueryRowContext(ctx, \"SELECT title FROM notes\").Scan(&title)\n\tfmt.Println(\"data survived:\", title)\n}","language":"go","title":"An idempotent runner","walkthrough":"The old release applies two steps and the row it inserts survives every later upgrade. The new release applies only the third step and reports version 3; a second run applies nothing. The broken step fails with \"Cannot add a column with non-constant default\" and the version stays 3 because the bump rolled back with it. DROP COLUMN body succeeds and the columns become id, title, pinned. The old release then refuses version 4 instead of writing to a schema it does not understand."},{"body":"SQLite supports a small ALTER TABLE: RENAME TO, RENAME COLUMN, ADD COLUMN and, since 3.35, DROP COLUMN. ADD COLUMN cannot add a PRIMARY KEY or UNIQUE column, cannot use a non-constant default such as CURRENT_TIMESTAMP, and needs a default when it is NOT NULL. DROP COLUMN fails when the column is part of an index, a primary key, a unique or foreign key constraint, or is used by a view, trigger, generated column or CHECK. Adding an index, a view or a trigger is an ordinary CREATE statement and needs no special care.","title":"What ALTER TABLE can and cannot do"},{"body":"Changing a column type, adding a CHECK or a foreign key, or making a table STRICT means creating a new table, copying the rows, dropping the old one and renaming the new one, the procedure the SQLite documentation lists step by step. Turn foreign keys off first, because dropping a referenced parent with enforcement on would delete or reject child rows, and run PRAGMA foreign_key_check before committing. PRAGMA foreign_keys is a no-op inside a transaction, so such a migration needs a runner hook that sets it on the same connection before BEGIN.","code":"-- Outside any transaction, on the one connection that runs the migration:\nPRAGMA foreign_keys = OFF;\nBEGIN IMMEDIATE;\nCREATE TABLE notes_new (\n    id     INTEGER PRIMARY KEY,\n    title  TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n    pinned INTEGER NOT NULL DEFAULT 0\n) STRICT;\nINSERT INTO notes_new (id, title, pinned) SELECT id, title, pinned FROM notes;\nDROP TABLE notes;\nALTER TABLE notes_new RENAME TO notes;\nCREATE INDEX notes_pinned ON notes (pinned, id);  -- indexes, triggers and views again\nPRAGMA foreign_key_check;                         -- must return no rows\nPRAGMA user_version = 5;\nCOMMIT;\nPRAGMA foreign_keys = ON;","language":"sql","title":"Every other change is a table rebuild","walkthrough":"The new table carries the new constraint, the copy keeps ids, and the rename puts it in place. Indexes and triggers on the old table are dropped with it and must be created again. foreign_key_check returns one row per violation; an empty result is the condition for COMMIT. The version bump is part of the same transaction."},{"body":"Never edit, reorder or delete a migration that has shipped: some file somewhere is at that version. Keep each step small and data-preserving, test the runner against a copy of a real old database, and take a VACUUM INTO backup before a rebuild. Run migrations once at startup through the same pool the program uses, before serving traffic. This runner reads the version before it begins each step, which is fine for one process; if two processes can start at the same moment, re-read user_version inside a BEGIN IMMEDIATE transaction (for example with _txlock=immediate) so the second waits on busy_timeout, sees the new version and applies nothing. Refusing a newer schema is what makes a rollback of the binary safe.","title":"Rules that keep migrations safe"}],"takeaway":"Keep migrations as an append-only list, store the applied count in PRAGMA user_version, and bump it inside the same transaction as the step. Use ALTER TABLE where it is allowed, rebuild the table for everything else, and refuse schemas newer than the code.","title":"Migrate a schema with PRAGMA user_version: ordered steps, one transaction each","unitID":"sqlite-project","wrongAnswers":["SQLite resets user_version after every error","user_version is only written when the file is closed"]},{"conceptTag":"sqlite.fts5-search","designGuide":{"cautions":["The index can be as large as the text.","Raw user input is parsed as query syntax."],"cost":"One virtual table, three triggers, a quoting function and extra write work on every change to the content table.","family":"sqlite","flow":["Content table + fts5","Triggers keep in sync","MATCH quoted terms","ORDER BY rank"],"ratings":[],"strengths":["Ranked word search without a separate search server.","External content keeps the text in one place."]},"hint":"Binding keeps the text out of the SQL statement. Ask who parses the bound value next.","id":"sqlite.fts5-search","introduction":"LIKE '%word%' reads every row and knows nothing about words, prefixes or relevance. FTS5 is SQLite's full-text engine: a virtual table that maintains an inverted index of tokens and answers MATCH queries with a bm25 rank. modernc.org/sqlite ships with FTS5 compiled in. The index can store its own copy of the text or point at an ordinary table you already have; the second option, external content, keeps one source of truth but makes keeping the index in sync your job.","nuance":"The bound value reaches FTS5 intact and FTS5 parses it as a query, where + is not valid. Quoting each word turns it into a string token; unicode61 then reduces c++ to c.","objective":"Index a table with an external-content FTS5 table kept in sync by triggers, query it with prefixes, phrases, operators and column filters, rank with bm25, and quote user input.","question":"A search box binds the user text to WHERE docs_fts MATCH ?. A user types c++ and the query fails. Why?","references":["https://www.sqlite.org/fts5.html","https://www.sqlite.org/fts5.html#external_content_tables","https://www.sqlite.org/fts5.html#full_text_query_syntax","https://pkg.go.dev/modernc.org/sqlite"],"reviewAnswer":"MATCH input is FTS5 syntax, not plain text","reviewPrompt":"Why quote user words for MATCH?","sections":[{"body":"CREATE VIRTUAL TABLE docs_fts USING fts5(title, body, content='docs', content_rowid='id') creates an index whose rowid is docs.id and whose column values are read from docs when FTS5 needs them, for highlight and snippet. The index does not watch docs: three triggers do the work. After INSERT they add the new row; after DELETE they insert the special 'delete' command with the old values; after UPDATE they do both. The delete command must receive exactly the values that were indexed, which is why the triggers use old.title and old.body. If the two ever drift, INSERT INTO docs_fts(docs_fts) VALUES('rebuild') regenerates the index from the content table.","title":"Content table plus index"},{"body":"The program indexes five short documents and runs a series of MATCH queries through one search function that joins the index back to docs and orders by rank, FTS5's hidden column that equals bm25() and sorts best matches first. highlight(docs_fts, 0, '[', ']') marks matched tokens in the title column; snippet picks the best short fragment of the body. It then updates a row, tries raw user input that is not valid FTS5 syntax, and finishes with the integrity-check command.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nconst schema = `\nCREATE TABLE docs (\n\tid    INTEGER PRIMARY KEY,\n\ttitle TEXT NOT NULL,\n\tbody  TEXT NOT NULL\n);\n-- External content: the index stores tokens, docs stores the text.\nCREATE VIRTUAL TABLE docs_fts USING fts5(\n\ttitle, body,\n\tcontent='docs', content_rowid='id',\n\ttokenize='unicode61'\n);\nCREATE TRIGGER docs_ai AFTER INSERT ON docs BEGIN\n\tINSERT INTO docs_fts (rowid, title, body) VALUES (new.id, new.title, new.body);\nEND;\nCREATE TRIGGER docs_ad AFTER DELETE ON docs BEGIN\n\tINSERT INTO docs_fts (docs_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);\nEND;\nCREATE TRIGGER docs_au AFTER UPDATE ON docs BEGIN\n\tINSERT INTO docs_fts (docs_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);\n\tINSERT INTO docs_fts (rowid, title, body) VALUES (new.id, new.title, new.body);\nEND;`\n\nvar docs = [][2]string{\n\t{\"Goroutines and channels\", \"A goroutine is a lightweight thread; channels connect goroutines.\"},\n\t{\"Context cancellation\", \"Pass a context to stop goroutines when a request is cancelled.\"},\n\t{\"SQLite in Go\", \"Use database/sql with a SQLite driver; SQLite stores the database in one file.\"},\n\t{\"Error handling\", \"Wrap errors with context and check them with errors.Is.\"},\n\t{\"Building C++ bindings\", \"cgo lets Go call C and C++ code, at the cost of cross-compilation.\"},\n}\n\nfunc search(ctx context.Context, db *sql.DB, query string) ([]string, error) {\n\trows, err := db.QueryContext(ctx, `\n\t\tSELECT d.id, highlight(docs_fts, 0, '[', ']')\n\t\tFROM docs_fts JOIN docs d ON d.id = docs_fts.rowid\n\t\tWHERE docs_fts MATCH ?\n\t\tORDER BY rank`, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar out []string\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar title string\n\t\tif err := rows.Scan(&id, &title); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout = append(out, fmt.Sprintf(\"%d %s\", id, title))\n\t}\n\treturn out, rows.Err()\n}\n\n// phrase turns arbitrary user input into FTS5 string tokens: each word is\n// wrapped in double quotes, with embedded quotes doubled, so operators and\n// punctuation lose their meaning. Adjacent quoted words are ANDed together.\nfunc phrase(input string) string {\n\tvar parts []string\n\tfor _, w := range strings.Fields(input) {\n\t\tparts = append(parts, `\"`+strings.ReplaceAll(w, `\"`, `\"\"`)+`\"`)\n\t}\n\treturn strings.Join(parts, \" \")\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"fts5\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tdb, err := sql.Open(\"sqlite\", filepath.Join(dir, \"app.db\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tif _, err := db.ExecContext(ctx, schema); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, d := range docs {\n\t\tif _, err := db.ExecContext(ctx, \"INSERT INTO docs (title, body) VALUES (?, ?)\", d[0], d[1]); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfor _, q := range []string{\n\t\t\"goroutine*\",             // prefix\n\t\t`\"one file\"`,             // phrase\n\t\t\"goroutines NOT context\", // boolean operators are upper case\n\t\t\"errors OR cgo\",\n\t\t\"title:sqlite\", // column filter\n\t\t\"context\",      // ranked by bm25, best match first\n\t} {\n\t\thits, err := search(ctx, db, q)\n\t\tfmt.Printf(\"%-26s -> %v %v\\n\", q, hits, err)\n\t}\n\n\tvar snippet string\n\tif err := db.QueryRowContext(ctx, `\n\t\tSELECT snippet(docs_fts, 1, '<b>', '</b>', '...', 6)\n\t\tFROM docs_fts WHERE docs_fts MATCH 'driver'`).Scan(&snippet); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"snippet:\", snippet)\n\n\t// The trigger keeps the index in step with an UPDATE.\n\tif _, err := db.ExecContext(ctx, \"UPDATE docs SET title = 'Errors and panics' WHERE id = 4\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thits, _ := search(ctx, db, \"panics\")\n\tfmt.Println(\"after update, panics ->\", hits)\n\n\tfor _, raw := range []string{\"c++\", `\"unbalanced`, \"AND\"} {\n\t\t_, err := search(ctx, db, raw)\n\t\tfmt.Printf(\"raw %-12q -> %v\\n\", raw, err)\n\t\thits, err := search(ctx, db, phrase(raw))\n\t\tfmt.Printf(\"quoted %-9s -> %v %v\\n\", phrase(raw), hits, err)\n\t}\n\n\t// rank = 1 also compares the index with the external content table.\n\tintegrity := \"ok\"\n\tif _, err := db.ExecContext(ctx, \"INSERT INTO docs_fts (docs_fts, rank) VALUES ('integrity-check', 1)\"); err != nil {\n\t\tintegrity = err.Error()\n\t}\n\tfmt.Println(\"index integrity-check:\", integrity)\n}","language":"go","title":"Querying, ranking and highlighting","walkthrough":"goroutine* is a prefix query and finds documents 1 and 2, the second only through goroutines in its body, so its title has no marks. \"one file\" is a phrase and finds document 3. NOT, OR and title: work as operators and a column filter. The snippet line shows six tokens around driver with an ellipsis. After the UPDATE the trigger has reindexed document 4, so panics finds it. Raw c++, an unbalanced quote and a bare AND are syntax errors; quoted, they search for c, unbalanced and and. integrity-check reports ok."},{"body":"The string passed to MATCH is parsed as FTS5 query syntax: double quotes delimit strings, * is a prefix, : selects a column, parentheses group, and the upper-case words AND, OR, NOT and NEAR are operators. A search box that passes text straight through turns c++ into an error, AND into a syntax error and title:secret into a column query. Binding with ? prevents SQL injection, not FTS5 syntax errors. The phrase helper wraps each whitespace-separated word in double quotes and doubles embedded quotes, so every word becomes a literal string and the words are implicitly ANDed. Offer operators only through explicit controls in your UI.","code":"func phrase(input string) string {\n\tvar parts []string\n\tfor _, w := range strings.Fields(input) {\n\t\tparts = append(parts, `\"`+strings.ReplaceAll(w, `\"`, `\"\"`)+`\"`)\n\t}\n\treturn strings.Join(parts, \" \")\n}","language":"go","title":"User input is a query language","walkthrough":"Quoted, c++ becomes the string \"c++\", which the unicode61 tokenizer splits on punctuation into the single token c; that is why it matches document 5 by its C. An empty input produces an empty string, which you should treat as no search rather than pass to MATCH."},{"body":"The default unicode61 tokenizer folds case, removes diacritics, and treats every character that is not a letter or digit as a separator, so c++, C and c are the same token. It does not stem: writer does not match writers unless you search writer*. tokenize='porter unicode61' adds English stemming, and the trigram tokenizer supports substring matching and LIKE acceleration at the cost of a much larger index. The tokenizer is fixed when the table is created; changing it means dropping and rebuilding the index in a migration.","title":"Tokenizers decide what a word is"},{"body":"An FTS5 index is often as large as the text it indexes, and every write to the content table now also writes index segments through the triggers. FTS5 merges segments automatically; after a bulk load, INSERT INTO docs_fts(docs_fts) VALUES('optimize') merges them into one. bm25 weights every column equally unless you pass weights, as in ORDER BY bm25(docs_fts, 10.0, 1.0) to favour titles. Keep the triggers, the FTS table and the content table in the same migration, and run the integrity-check with rank 1 in tests: it compares the index with the content table and reports drift.","title":"Costs and operational notes"}],"takeaway":"Use an external-content FTS5 table with insert, delete and update triggers so the text lives once. Order by rank, decorate with highlight and snippet, and quote every user word as an FTS5 string, because MATCH input is a query language of its own.","title":"Full-text search with FTS5: an external-content index, ranking and safe queries","unitID":"sqlite-project","wrongAnswers":["Binding with ? does not escape the plus signs for SQL","FTS5 cannot index punctuation in content"]},{"conceptTag":"sqlite.backups-maintenance","designGuide":{"cautions":["File copies of an open database can be torn.","VACUUM needs free space and holds the write lock."],"cost":"Disk space for one extra copy, a scheduled backup job and an occasional maintenance window for VACUUM.","family":"sqlite","flow":["VACUUM INTO temp path","integrity_check the copy","Rename into place","optimize on close"],"ratings":[],"strengths":["Consistent online backups with one SQL statement.","The copy is compacted and self-contained."]},"hint":"Ask where a commit is written in WAL mode and when it reaches the main file.","id":"sqlite.backups-maintenance","introduction":"A SQLite database is a file, which makes it tempting to back it up with cp. In WAL mode the committed state is split between app.db and app.db-wal, and a writer can change either while you copy. SQLite provides safe ways to produce a consistent snapshot while the program keeps running, and a few maintenance commands that keep the file compact and the query planner well informed.","nuance":"Commits land in the -wal file and reach app.db only at a checkpoint, so the copy can lack recent transactions or be torn. VACUUM INTO reads one consistent snapshot through SQLite.","objective":"Take a consistent backup of a WAL database with VACUUM INTO, verify the copy, reclaim free pages, truncate the WAL with a checkpoint and keep planner statistics current.","question":"A service runs in WAL mode and a nightly job copies app.db with cp. What can the backup be missing?","references":["https://www.sqlite.org/lang_vacuum.html","https://www.sqlite.org/backup.html","https://www.sqlite.org/wal.html","https://www.sqlite.org/pragma.html#pragma_optimize","https://www.sqlite.org/howtocorrupt.html"],"reviewAnswer":"VACUUM INTO a new path, then verify the copy","reviewPrompt":"Safe backup of a live WAL file?","sections":[{"body":"In WAL mode new commits are appended to the -wal file and only moved into the main file by a checkpoint. Copying app.db alone can lose every commit since the last checkpoint; copying app.db and app.db-wal one after another can capture them from different moments, and a write between the two reads can tear a page. Even in rollback-journal mode a copy taken during a write can be corrupt. File-level copies are safe only when no connection has the database open. Inside the program, use VACUUM INTO or the online backup API, both of which read through a transaction and produce a single, self-contained file.","title":"Why copying the file is unsafe"},{"body":"The program writes 2000 rows to a WAL database, backs it up with VACUUM INTO and a bound path, opens the copy read-only and checks it. It then deletes two thirds of the rows and compares page_count and freelist_count before and after VACUUM, truncates the WAL with a checkpoint, and finishes with ANALYZE and PRAGMA optimize.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\nfunc one[T any](ctx context.Context, db *sql.DB, query string, args ...any) T {\n\tvar v T\n\tif err := db.QueryRowContext(ctx, query, args...).Scan(&v); err != nil {\n\t\tlog.Fatalf(\"%s: %v\", query, err)\n\t}\n\treturn v\n}\n\nfunc pages(ctx context.Context, db *sql.DB) string {\n\treturn fmt.Sprintf(\"page_count=%d freelist_count=%d\",\n\t\tone[int](ctx, db, \"PRAGMA page_count\"), one[int](ctx, db, \"PRAGMA freelist_count\"))\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"backup\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tlive := filepath.Join(dir, \"live.db\")\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+live+\"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\tdb.SetMaxOpenConns(1) // keep the walkthrough on one connection\n\n\tif _, err := db.ExecContext(ctx, `CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, payload TEXT NOT NULL);\n\t\tCREATE INDEX events_kind ON events (kind)`); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := range 2000 {\n\t\tkind := []string{\"click\", \"view\", \"buy\"}[i%3]\n\t\tif _, err := tx.ExecContext(ctx, \"INSERT INTO events (kind, payload) VALUES (?, ?)\", kind, strings.Repeat(\"x\", 200)); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"journal_mode:\", one[string](ctx, db, \"PRAGMA journal_mode\"))\n\tinfo, _ := os.Stat(live + \"-wal\")\n\tfmt.Println(\"WAL file holds committed pages:\", info.Size() > 0)\n\n\t// VACUUM INTO writes a consistent, compacted copy from a read transaction.\n\t// The target is an ordinary bound value and must not exist yet.\n\tbackup := filepath.Join(dir, \"backup.db\")\n\tif _, err := db.ExecContext(ctx, \"VACUUM INTO ?\", backup); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t_, err = db.ExecContext(ctx, \"VACUUM INTO ?\", backup)\n\tfmt.Println(\"second VACUUM INTO same file:\", err)\n\n\tcopyDB, err := sql.Open(\"sqlite\", \"file:\"+backup+\"?mode=ro\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"backup integrity_check:\", one[string](ctx, copyDB, \"PRAGMA integrity_check\"))\n\tfmt.Println(\"backup rows:\", one[int](ctx, copyDB, \"SELECT count(*) FROM events\"))\n\tfmt.Println(\"backup journal_mode:\", one[string](ctx, copyDB, \"PRAGMA journal_mode\"))\n\tcopyDB.Close()\n\n\t// Deleting rows frees pages but does not shrink the file.\n\tfmt.Println(\"before delete:\", pages(ctx, db))\n\tif _, err := db.ExecContext(ctx, \"DELETE FROM events WHERE kind <> 'buy'\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"after delete: \", pages(ctx, db))\n\tif _, err := db.ExecContext(ctx, \"VACUUM\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"after VACUUM: \", pages(ctx, db))\n\n\t// Move WAL content into the main file and truncate the log to zero bytes.\n\tvar busy, logFrames, checkpointed int\n\tif err := db.QueryRowContext(ctx, \"PRAGMA wal_checkpoint(TRUNCATE)\").Scan(&busy, &logFrames, &checkpointed); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tinfo, _ = os.Stat(live + \"-wal\")\n\tfmt.Println(\"checkpoint busy:\", busy, \"WAL size after TRUNCATE:\", info.Size())\n\n\t// Statistics for the planner, then the routine maintenance call for close.\n\tif _, err := db.ExecContext(ctx, \"ANALYZE\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"sqlite_stat1 rows:\", one[int](ctx, db, \"SELECT count(*) FROM sqlite_stat1\"))\n\tif _, err := db.ExecContext(ctx, \"PRAGMA optimize\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"PRAGMA optimize: done\")\n}","language":"go","title":"Snapshot, verify, compact, checkpoint","walkthrough":"The WAL file is non-empty after the inserts, so the latest commits are not in live.db yet; VACUUM INTO still captures them. A second VACUUM INTO the same name fails with \"output file already exists\". The copy passes integrity_check, has all 2000 rows and uses journal_mode delete. Deleting rows leaves page_count at 116 with 68 free pages; VACUUM shrinks it to 41 pages. The TRUNCATE checkpoint reports busy 0 and a zero-byte WAL, and ANALYZE writes one sqlite_stat1 row for the events_kind index."},{"body":"VACUUM INTO 'file' builds a new, defragmented database from a read transaction on the source, so writers on other connections continue and the copy reflects exactly one committed moment. The argument is an expression, so a ? placeholder carries the path safely. The target must not exist; write to a temporary name and rename it into place so a crash never leaves a half-written file under the final name. The copy is in rollback-journal mode, contains no WAL, and can be opened, verified or shipped on its own. For very large databases, the online backup API copies incrementally and can yield between steps. In the coming GopherForge SQLite template, the app's driver keeps programs inside /sandbox and refuses VACUUM INTO and ATTACH; copy a project database with the database browser's export through Files instead.","code":"// backupTo writes a consistent snapshot next to the live file, then renames it\n// into place, so a crash never leaves a half-written backup under the final name.\nfunc backupTo(ctx context.Context, db *sql.DB, dest string) error {\n\ttmp := dest + \".partial\"\n\tos.Remove(tmp) // VACUUM INTO refuses an existing file\n\tif _, err := db.ExecContext(ctx, \"VACUUM INTO ?\", tmp); err != nil {\n\t\treturn err\n\t}\n\treturn os.Rename(tmp, dest)\n}","language":"go","title":"VACUUM INTO as a backup","walkthrough":"The helper removes a stale partial file, writes the snapshot under a temporary name and renames it. A rename within one directory replaces the old backup atomically on the same file system, so readers of dest see either the previous backup or the complete new one."},{"body":"DELETE marks pages as free and keeps them for later inserts; the file does not shrink. PRAGMA freelist_count shows how many are free. VACUUM rewrites the whole database into a new file, which needs up to twice the space, holds the write lock for the duration and can renumber rowids of tables without an INTEGER PRIMARY KEY. Run it in a maintenance window when free pages are a large share of the file, not on every start. auto_vacuum=INCREMENTAL, set before the first table is created, lets PRAGMA incremental_vacuum return free pages in small batches instead.","title":"Free pages, VACUUM and auto_vacuum"},{"body":"SQLite checkpoints automatically when the WAL reaches about 1000 pages, but a long-lived reader can prevent the log from being reset and it keeps growing. PRAGMA wal_checkpoint(TRUNCATE) copies everything into the main file and truncates the log to zero bytes when no reader blocks it; its first result column is 1 when it could not finish. ANALYZE stores index statistics in sqlite_stat1 so the planner can choose between indexes. PRAGMA optimize runs ANALYZE only where it looks useful and is cheap; the SQLite documentation recommends calling it before closing short-lived connections and periodically in long-running ones.","title":"Checkpoints and planner statistics"}],"takeaway":"Never copy a live database file. Back up with VACUUM INTO a new path or the online backup API, verify the copy with integrity_check, VACUUM only when free pages matter, truncate the WAL with a checkpoint and let PRAGMA optimize maintain statistics.","title":"Back up and maintain a live database: VACUUM INTO, checkpoints, VACUUM and ANALYZE","unitID":"sqlite-project","wrongAnswers":["Nothing, because WAL makes the main file always current","Only the indexes, which SQLite rebuilds on open"]},{"conceptTag":"sqlite.testing-temp-databases","designGuide":{"cautions":["Schema setup cost grows with the migration list.",":memory: with a pool silently splits databases."],"cost":"A ten-line helper and a few milliseconds of disk work per test; a migrated template file once the schema grows.","family":"sqlite","flow":["t.TempDir per test","Open with prod DSN","Migrate, register Cleanup","Run cases in parallel"],"ratings":[],"strengths":["Tests use the real engine, schema and constraints.","Isolated files make t.Parallel safe."]},"hint":"Count how many connections the pool can open and ask what each one sees with :memory:.","id":"sqlite.testing-temp-databases","introduction":"Because SQLite is a library, tests can use the real engine with the real schema instead of a mock, and still run in milliseconds. The question is isolation: tests that share one database see each other's rows, and an in-memory database interacts badly with the connection pool. A helper that gives every test its own migrated file in a temporary directory solves both and keeps the tests safe to run in parallel.","nuance":"Each pooled connection to :memory: opens its own empty database, so a query on a second connection misses the migrated tables. A temp file per test is shared by the pool and isolated from other tests.","objective":"Write a test helper that opens a migrated file database in t.TempDir, registers cleanup, and lets table-driven and parallel tests run against isolated databases.","question":"Tests share one *sql.DB opened on \":memory:\" and sometimes fail with \"no such table\". What is the cause?","references":["https://pkg.go.dev/testing#T.TempDir","https://pkg.go.dev/testing#T.Cleanup","https://pkg.go.dev/testing#T.Parallel","https://www.sqlite.org/inmemorydb.html"],"reviewAnswer":"Each test gets its own migrated file in t.TempDir","reviewPrompt":"Isolation for parallel DB tests?","sections":[{"body":"newTestDB takes a small interface with Helper, TempDir, Cleanup and Fatalf, which *testing.T and *testing.B satisfy. It creates the file inside t.TempDir(), opens it with the same DSN options as production, registers db.Close with t.Cleanup and applies the schema, failing the test with Fatalf on any error. Helper makes failures point at the calling test line. Cleanup functions run last-registered first, so the pool is closed before the testing package removes the temporary directory, which matters on systems that cannot delete open files.","title":"The helper owns setup and teardown"},{"body":"The program cannot import a test binary, so it runs the same helper with a tiny fake that implements the interface, records cleanups and turns Fatalf into a reported failure. Each case opens an account, withdraws and checks the balance; the CHECK constraint is part of the behaviour under test. A fourth test fails on purpose to show the reporting. At the end the program confirms that each case had its own directory and that cleanup removed every one.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// TB is the part of testing.TB the helper needs. *testing.T and *testing.B\n// satisfy it, and so does the small runner in main.\ntype TB interface {\n\tHelper()\n\tTempDir() string\n\tCleanup(func())\n\tFatalf(format string, args ...any)\n}\n\nconst schema = `CREATE TABLE accounts (\n\tid      INTEGER PRIMARY KEY,\n\towner   TEXT NOT NULL UNIQUE,\n\tbalance INTEGER NOT NULL CHECK (balance >= 0)\n)`\n\n// newTestDB opens a fresh, migrated file database that belongs to one test.\n// The file lives in the test's temporary directory and disappears with it.\nfunc newTestDB(t TB) *sql.DB {\n\tt.Helper()\n\tpath := filepath.Join(t.TempDir(), \"test.db\")\n\tdb, err := sql.Open(\"sqlite\", \"file:\"+path+\"?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)\")\n\tif err != nil {\n\t\tt.Fatalf(\"open: %v\", err)\n\t}\n\tt.Cleanup(func() { db.Close() }) // registered after TempDir, so it runs first\n\tif _, err := db.Exec(schema); err != nil {\n\t\tt.Fatalf(\"migrate: %v\", err)\n\t}\n\treturn db\n}\n\n// Code under test.\nfunc open(ctx context.Context, db *sql.DB, owner string, deposit int) error {\n\t_, err := db.ExecContext(ctx, \"INSERT INTO accounts (owner, balance) VALUES (?, ?)\", owner, deposit)\n\treturn err\n}\n\nfunc withdraw(ctx context.Context, db *sql.DB, owner string, amount int) error {\n\tres, err := db.ExecContext(ctx, \"UPDATE accounts SET balance = balance - ? WHERE owner = ?\", amount, owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n, _ := res.RowsAffected(); n == 0 {\n\t\treturn errors.New(\"no such account\")\n\t}\n\treturn nil\n}\n\n// fakeT is a minimal stand-in for *testing.T so this program runs with go run.\ntype fakeT struct {\n\tname     string\n\tdir      string\n\tcleanups []func()\n\tfailed   bool\n}\n\nfunc (t *fakeT) Helper() {}\nfunc (t *fakeT) TempDir() string {\n\tif t.dir == \"\" {\n\t\tdir, err := os.MkdirTemp(\"\", \"test\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tt.dir = dir\n\t\tt.Cleanup(func() { os.RemoveAll(dir) })\n\t}\n\treturn t.dir\n}\nfunc (t *fakeT) Cleanup(f func()) { t.cleanups = append(t.cleanups, f) }\nfunc (t *fakeT) Fatalf(format string, args ...any) {\n\tt.failed = true\n\tpanic(fmt.Sprintf(format, args...))\n}\nfunc (t *fakeT) finish() {\n\tfor i := len(t.cleanups) - 1; i >= 0; i-- { // last registered runs first, like testing\n\t\tt.cleanups[i]()\n\t}\n}\n\nfunc run(name string, test func(t TB)) (dir string) {\n\tt := &fakeT{name: name}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Printf(\"--- FAIL: %s: %v\\n\", name, r)\n\t\t} else {\n\t\t\tfmt.Printf(\"--- PASS: %s\\n\", name)\n\t\t}\n\t\tt.finish()\n\t}()\n\ttest(t)\n\treturn t.dir\n}\n\nfunc main() {\n\tctx := context.Background()\n\tcases := []struct {\n\t\tname    string\n\t\tdeposit int\n\t\tamount  int\n\t\twantErr bool\n\t\twant    int\n\t}{\n\t\t{\"withdraw part\", 100, 30, false, 70},\n\t\t{\"withdraw all\", 50, 50, false, 0},\n\t\t{\"overdraw is refused by CHECK\", 20, 25, true, 20},\n\t}\n\tvar dirs []string\n\tfor _, tc := range cases {\n\t\tdirs = append(dirs, run(tc.name, func(t TB) {\n\t\t\tdb := newTestDB(t)\n\t\t\t// Every case starts empty: earlier cases inserted \"ada\" too.\n\t\t\tvar n int\n\t\t\tdb.QueryRow(\"SELECT count(*) FROM accounts\").Scan(&n)\n\t\t\tif n != 0 {\n\t\t\t\tt.Fatalf(\"leaked %d rows from another test\", n)\n\t\t\t}\n\t\t\tif err := open(ctx, db, \"ada\", tc.deposit); err != nil {\n\t\t\t\tt.Fatalf(\"open: %v\", err)\n\t\t\t}\n\t\t\terr := withdraw(ctx, db, \"ada\", tc.amount)\n\t\t\tif (err != nil) != tc.wantErr {\n\t\t\t\tt.Fatalf(\"withdraw error = %v, want error %v\", err, tc.wantErr)\n\t\t\t}\n\t\t\tvar balance int\n\t\t\tdb.QueryRow(\"SELECT balance FROM accounts WHERE owner = 'ada'\").Scan(&balance)\n\t\t\tif balance != tc.want {\n\t\t\t\tt.Fatalf(\"balance = %d, want %d\", balance, tc.want)\n\t\t\t}\n\t\t}))\n\t}\n\trun(\"a deliberately wrong expectation\", func(t TB) {\n\t\tdb := newTestDB(t)\n\t\tif err := withdraw(ctx, db, \"nobody\", 1); err == nil {\n\t\t\tt.Fatalf(\"expected an error\")\n\t\t}\n\t\tt.Fatalf(\"balance = %d, want %d\", 0, 1)\n\t})\n\n\tdistinct := map[string]bool{}\n\tremoved := 0\n\tfor _, d := range dirs {\n\t\tdistinct[d] = true\n\t\tif _, err := os.Stat(d); errors.Is(err, os.ErrNotExist) {\n\t\t\tremoved++\n\t\t}\n\t}\n\tfmt.Printf(\"%d cases used %d separate databases; %d removed after cleanup\\n\", len(dirs), len(distinct), removed)\n}","language":"go","title":"Table-driven cases, one database each","walkthrough":"All three table cases pass, and none sees the account a previous case created, because each starts from an empty, freshly migrated file. The overdraw case passes because CHECK (balance >= 0) rejects the UPDATE and the balance stays 20. The deliberate failure prints its Fatalf message. The summary reports three cases, three distinct databases and three directories removed after cleanup."},{"body":"In a real package the helper lives in a _test.go file or an internal testing package, and tests call it with *testing.T. Because each test owns its file, t.Parallel is safe at both levels: subtests run concurrently against separate databases, so there is no shared lock to wait on and no ordering dependency. t.Context, available since Go 1.24, is cancelled just before cleanup runs, which is a good default context for queries.","code":"package store\n\nimport \"testing\"\n\nfunc TestWithdraw(t *testing.T) {\n\tt.Parallel()\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tdb := newTestDB(t) // its own file in its own t.TempDir()\n\t\t\tif err := open(t.Context(), db, \"ada\", tc.deposit); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\t// ...\n\t\t})\n\t}\n}","language":"go","title":"The same helper in a _test.go file","walkthrough":"The loop variable tc is per iteration since Go 1.22, so parallel subtests read their own case. Each subtest calls newTestDB(t) with its own t, which ties the database lifetime to that subtest rather than to the parent."},{"body":"A plain :memory: database exists per connection, so a pooled *sql.DB can run the migration on one connection and the query on another that sees an empty database. It works only with SetMaxOpenConns(1) and a pool that never closes its last connection, or with a named shared-memory URI that leaks state between tests using the same name. A temporary file avoids those traps, exercises WAL and locking like production, and is still fast because the operating system caches it. One database shared across parallel tests makes results depend on order and timing; give each test its own.","title":"Why not :memory: or one shared database"},{"body":"Most of a fresh database's cost is applying the schema. When the migration list grows, migrate one template file once per package in TestMain and copy it per test with VACUUM INTO or a plain file copy, since nothing else has it open. Test the migration runner itself separately, from an empty file and from saved old versions. Avoid sleeping to provoke SQLITE_BUSY; hold a transaction on one connection explicitly instead, so a concurrency test is deterministic.","title":"Keep tests fast"}],"takeaway":"Give every test its own migrated SQLite file in t.TempDir through a helper that uses Helper, Cleanup and Fatalf. Tests then use the real engine and schema, run in parallel without interference and leave nothing behind.","title":"Test against real SQLite: a fresh migrated database file per test","unitID":"sqlite-project","wrongAnswers":["Parallel tests drop each other's tables","SQLite forgets tables when a transaction ends"]},{"conceptTag":"sqlite.notes-repository","designGuide":{"cautions":["One writer at a time: keep transactions short.","Triggers and FTS add work to every write."],"cost":"About two hundred lines of Go and two migrations; the ongoing cost is keeping tests for every migration and behaviour.","family":"sqlite","flow":["Open: DSN + migrate","Write in IMMEDIATE tx","Version-checked UPDATE","Search quoted FTS5"],"ratings":[],"strengths":["One file holds data, schema version and search index.","Constraints and triggers keep related rows consistent."]},"hint":"Follow the version number: what does the first save change, and which row can the second UPDATE still match?","id":"sqlite.notes-repository","introduction":"This project puts the course together in one package-sized program: a repository type that owns its *sql.DB, configures every connection through the DSN, migrates with PRAGMA user_version, keeps writes in short transactions, detects lost updates with a version column, and offers ranked search that is safe for any input. The same shape fits a command-line tool, a small web service or the coming GopherForge SQLite project template, where a program writes its database under /sandbox in the next app update.","nuance":"The first save sets version to 2, so the second UPDATE ... WHERE version = 1 matches no row. The repository then finds the note still exists and returns ErrConflict instead of overwriting.","objective":"Build a small notes store on SQLite that migrates itself, writes in IMMEDIATE transactions with RETURNING and optimistic versions, cascades tags, and searches with FTS5, with a check for every behaviour.","question":"Two people edit note 1, both having read version 1. The first save succeeds. What happens to the second?","references":["https://go.dev/doc/database/execute-transactions","https://www.sqlite.org/lang_returning.html","https://www.sqlite.org/foreignkeys.html","https://www.sqlite.org/fts5.html","https://pkg.go.dev/modernc.org/sqlite"],"reviewAnswer":"WHERE id = ? AND version = ?, then check zero rows","reviewPrompt":"How does Update detect lost edits?","sections":[{"body":"Two migrations define the schema. The first creates a STRICT notes table with a CHECK on the title and a version column, and a STRICT WITHOUT ROWID note_tags table whose foreign key cascades deletes; the second adds an external-content FTS5 index with triggers and rebuilds it so existing notes become searchable. Open builds one DSN that turns on foreign keys and a busy timeout for every pooled connection, selects WAL with synchronous=NORMAL, and sets _txlock=immediate so every BeginTx issues BEGIN IMMEDIATE and takes the write lock before reading.","title":"Schema and configuration"},{"body":"Create inserts with RETURNING id, version and writes tags in the same transaction. Update changes a row only WHERE id = ? AND version = ?, and tells a conflict from a missing note with a second query inside the same transaction. Delete uses RETURNING to detect a missing note. Search quotes every word before MATCH and can filter by tag. main exercises each behaviour and prints one PASS or FAIL line per check, then closes and reopens the store.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"strings\"\n\n\t_ \"modernc.org/sqlite\"\n)\n\n// ---- schema ---------------------------------------------------------------\n\nvar migrations = []string{\n\t`CREATE TABLE notes (\n\t\tid      INTEGER PRIMARY KEY,\n\t\ttitle   TEXT NOT NULL CHECK (title <> ''),\n\t\tbody    TEXT NOT NULL DEFAULT '',\n\t\tversion INTEGER NOT NULL DEFAULT 1\n\t) STRICT;\n\tCREATE TABLE note_tags (\n\t\tnote_id INTEGER NOT NULL REFERENCES notes (id) ON DELETE CASCADE,\n\t\ttag     TEXT NOT NULL,\n\t\tPRIMARY KEY (note_id, tag)\n\t) STRICT, WITHOUT ROWID;\n\tCREATE INDEX note_tags_tag ON note_tags (tag, note_id);`,\n\n\t`CREATE VIRTUAL TABLE notes_fts USING fts5 (title, body, content='notes', content_rowid='id');\n\tCREATE TRIGGER notes_ai AFTER INSERT ON notes BEGIN\n\t\tINSERT INTO notes_fts (rowid, title, body) VALUES (new.id, new.title, new.body);\n\tEND;\n\tCREATE TRIGGER notes_ad AFTER DELETE ON notes BEGIN\n\t\tINSERT INTO notes_fts (notes_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);\n\tEND;\n\tCREATE TRIGGER notes_au AFTER UPDATE OF title, body ON notes BEGIN\n\t\tINSERT INTO notes_fts (notes_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);\n\t\tINSERT INTO notes_fts (rowid, title, body) VALUES (new.id, new.title, new.body);\n\tEND;\n\tINSERT INTO notes_fts (notes_fts) VALUES ('rebuild');`,\n}\n\n// ---- repository -----------------------------------------------------------\n\nvar (\n\tErrNotFound = errors.New(\"note not found\")\n\tErrConflict = errors.New(\"note was changed by someone else\")\n)\n\ntype Note struct {\n\tID      int64\n\tTitle   string\n\tBody    string\n\tVersion int64\n\tTags    []string\n}\n\ntype Store struct{ db *sql.DB }\n\n// Open configures every pooled connection through the DSN: foreign keys are\n// per connection, writers wait instead of failing, and BeginTx takes the write\n// lock up front with BEGIN IMMEDIATE.\nfunc Open(ctx context.Context, path string) (*Store, error) {\n\tdsn := \"file:\" + path + \"?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)\" +\n\t\t\"&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate\"\n\tdb, err := sql.Open(\"sqlite\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Store{db: db}\n\tif err := s.migrate(ctx); err != nil {\n\t\tdb.Close()\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc (s *Store) Close() error {\n\ts.db.Exec(\"PRAGMA optimize\")\n\treturn s.db.Close()\n}\n\nfunc (s *Store) migrate(ctx context.Context) error {\n\tvar v int\n\tif err := s.db.QueryRowContext(ctx, \"PRAGMA user_version\").Scan(&v); err != nil {\n\t\treturn err\n\t}\n\tif v > len(migrations) {\n\t\treturn fmt.Errorf(\"schema version %d is newer than this program\", v)\n\t}\n\tfor ; v < len(migrations); v++ {\n\t\terr := s.inTx(ctx, func(tx *sql.Tx) error {\n\t\t\tif _, err := tx.ExecContext(ctx, migrations[v]); err != nil {\n\t\t\t\treturn fmt.Errorf(\"migration %d: %w\", v+1, err)\n\t\t\t}\n\t\t\t_, err := tx.ExecContext(ctx, fmt.Sprintf(\"PRAGMA user_version = %d\", v+1))\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// inTx commits when fn succeeds and rolls back otherwise.\nfunc (s *Store) inTx(ctx context.Context, fn func(*sql.Tx) error) error {\n\ttx, err := s.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback() // a no-op after Commit\n\tif err := fn(tx); err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}\n\nfunc setTags(ctx context.Context, tx *sql.Tx, id int64, tags []string) error {\n\tif _, err := tx.ExecContext(ctx, \"DELETE FROM note_tags WHERE note_id = ?\", id); err != nil {\n\t\treturn err\n\t}\n\tfor _, tag := range tags {\n\t\tif _, err := tx.ExecContext(ctx, \"INSERT OR IGNORE INTO note_tags (note_id, tag) VALUES (?, ?)\", id, strings.ToLower(tag)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Store) Create(ctx context.Context, title, body string, tags ...string) (Note, error) {\n\tn := Note{Title: title, Body: body}\n\terr := s.inTx(ctx, func(tx *sql.Tx) error {\n\t\terr := tx.QueryRowContext(ctx, \"INSERT INTO notes (title, body) VALUES (?, ?) RETURNING id, version\", title, body).\n\t\t\tScan(&n.ID, &n.Version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setTags(ctx, tx, n.ID, tags)\n\t})\n\tif err != nil {\n\t\treturn Note{}, err\n\t}\n\treturn s.Get(ctx, n.ID)\n}\n\nfunc (s *Store) Get(ctx context.Context, id int64) (Note, error) {\n\tvar n Note\n\tvar tags sql.NullString\n\terr := s.db.QueryRowContext(ctx, `\n\t\tSELECT n.id, n.title, n.body, n.version,\n\t\t\t   (SELECT group_concat(tag, ',') FROM (SELECT tag FROM note_tags WHERE note_id = n.id ORDER BY tag))\n\t\tFROM notes n WHERE n.id = ?`, id).Scan(&n.ID, &n.Title, &n.Body, &n.Version, &tags)\n\tif errors.Is(err, sql.ErrNoRows) {\n\t\treturn Note{}, ErrNotFound\n\t}\n\tif tags.Valid {\n\t\tn.Tags = strings.Split(tags.String, \",\")\n\t}\n\treturn n, err\n}\n\n// Update succeeds only if the caller saw the current version.\nfunc (s *Store) Update(ctx context.Context, n Note) (Note, error) {\n\terr := s.inTx(ctx, func(tx *sql.Tx) error {\n\t\tvar version int64\n\t\terr := tx.QueryRowContext(ctx, `\n\t\t\tUPDATE notes SET title = ?, body = ?, version = version + 1\n\t\t\tWHERE id = ? AND version = ? RETURNING version`, n.Title, n.Body, n.ID, n.Version).Scan(&version)\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\tvar exists bool\n\t\t\tif err := tx.QueryRowContext(ctx, \"SELECT EXISTS (SELECT 1 FROM notes WHERE id = ?)\", n.ID).Scan(&exists); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\treturn ErrConflict\n\t\t\t}\n\t\t\treturn ErrNotFound\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setTags(ctx, tx, n.ID, n.Tags)\n\t})\n\tif err != nil {\n\t\treturn Note{}, err\n\t}\n\treturn s.Get(ctx, n.ID)\n}\n\nfunc (s *Store) Delete(ctx context.Context, id int64) error {\n\treturn s.inTx(ctx, func(tx *sql.Tx) error {\n\t\tvar gone int64\n\t\terr := tx.QueryRowContext(ctx, \"DELETE FROM notes WHERE id = ? RETURNING id\", id).Scan(&gone)\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn ErrNotFound\n\t\t}\n\t\treturn err\n\t})\n}\n\ntype Hit struct {\n\tID      int64\n\tTitle   string\n\tSnippet string\n}\n\n// Search treats the input as plain words, never as FTS5 syntax.\nfunc (s *Store) Search(ctx context.Context, input string, tag string) ([]Hit, error) {\n\tvar terms []string\n\tfor _, w := range strings.Fields(input) {\n\t\tterms = append(terms, `\"`+strings.ReplaceAll(w, `\"`, `\"\"`)+`\"`)\n\t}\n\tif len(terms) == 0 {\n\t\treturn nil, nil\n\t}\n\trows, err := s.db.QueryContext(ctx, `\n\t\tSELECT n.id, n.title, snippet(notes_fts, 1, '[', ']', '...', 5)\n\t\tFROM notes_fts JOIN notes n ON n.id = notes_fts.rowid\n\t\tWHERE notes_fts MATCH ?\n\t\t  AND (? = '' OR EXISTS (SELECT 1 FROM note_tags t WHERE t.note_id = n.id AND t.tag = ?))\n\t\tORDER BY rank, n.id`, strings.Join(terms, \" \"), tag, tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar hits []Hit\n\tfor rows.Next() {\n\t\tvar h Hit\n\t\tif err := rows.Scan(&h.ID, &h.Title, &h.Snippet); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thits = append(hits, h)\n\t}\n\treturn hits, rows.Err()\n}\n\n// ---- checks ---------------------------------------------------------------\n\nfunc check(name string, ok bool, detail ...any) {\n\tstatus := \"PASS\"\n\tif !ok {\n\t\tstatus = \"FAIL\"\n\t}\n\tfmt.Printf(\"%s %s\", status, name)\n\tif len(detail) > 0 {\n\t\tfmt.Print(\": \", fmt.Sprint(detail...))\n\t}\n\tfmt.Println()\n}\n\nfunc ids(hits []Hit) []int64 {\n\tvar out []int64\n\tfor _, h := range hits {\n\t\tout = append(out, h.ID)\n\t}\n\treturn out\n}\n\nfunc main() {\n\tctx := context.Background()\n\tdir, err := os.MkdirTemp(\"\", \"notes\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"notes.db\")\n\n\ts, err := Open(ctx, path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar version int\n\ts.db.QueryRow(\"PRAGMA user_version\").Scan(&version)\n\tcheck(\"migrations reach the latest version\", version == len(migrations), version)\n\n\ta, _ := s.Create(ctx, \"Pool sizing\", \"SQLite allows one writer at a time; readers continue in WAL mode.\", \"sqlite\", \"Go\")\n\tb, _ := s.Create(ctx, \"Context deadlines\", \"Every query takes a context so a slow writer cannot hang a request.\", \"go\")\n\tc, _ := s.Create(ctx, \"Backups\", \"VACUUM INTO writes a consistent copy while writers continue.\", \"sqlite\", \"ops\")\n\tcheck(\"create returns ids and version 1\", a.ID == 1 && b.ID == 2 && c.ID == 3 && a.Version == 1)\n\tcheck(\"tags are normalised and sorted\", slices.Equal(a.Tags, []string{\"go\", \"sqlite\"}), a.Tags)\n\n\t_, err = s.Create(ctx, \"\", \"empty title\")\n\tcheck(\"CHECK rejects an empty title and rolls back\", err != nil && strings.Contains(err.Error(), \"CHECK constraint failed\"))\n\n\thits, _ := s.Search(ctx, \"writer\", \"\")\n\tcheck(\"search finds both notes about writers\", slices.Equal(ids(hits), []int64{1, 2}) || slices.Equal(ids(hits), []int64{2, 1}), ids(hits))\n\thits, _ = s.Search(ctx, \"writer\", \"go\")\n\tcheck(\"search filters by tag\", len(hits) == 2)\n\thits, _ = s.Search(ctx, \"writers\", \"ops\")\n\tcheck(\"snippet marks the match\", len(hits) == 1 && strings.Contains(hits[0].Snippet, \"[writers]\"), hits[0].Snippet)\n\thits, err = s.Search(ctx, `c++ \"unbalanced OR`, \"\")\n\tcheck(\"user input is never parsed as FTS5 syntax\", err == nil && len(hits) == 0, err)\n\n\tedit := a\n\tedit.Body = \"Use BEGIN IMMEDIATE so a transaction takes the write lock before it reads.\"\n\tedit.Tags = []string{\"sqlite\", \"transactions\"}\n\tupdated, err := s.Update(ctx, edit)\n\tcheck(\"update bumps the version\", err == nil && updated.Version == 2, updated.Version)\n\thits, _ = s.Search(ctx, \"immediate\", \"\")\n\told, _ := s.Search(ctx, \"readers\", \"\")\n\tcheck(\"triggers reindex the updated body\", slices.Equal(ids(hits), []int64{1}) && len(old) == 0)\n\n\t_, err = s.Update(ctx, edit) // edit still carries version 1\n\tcheck(\"a stale version is a conflict\", errors.Is(err, ErrConflict), err)\n\t_, err = s.Update(ctx, Note{ID: 99, Title: \"x\", Version: 1})\n\tcheck(\"updating a missing note is not found\", errors.Is(err, ErrNotFound), err)\n\n\tcheck(\"delete removes the note\", s.Delete(ctx, c.ID) == nil)\n\tvar tagRows int\n\ts.db.QueryRow(\"SELECT count(*) FROM note_tags WHERE note_id = ?\", c.ID).Scan(&tagRows)\n\thits, _ = s.Search(ctx, \"vacuum\", \"\")\n\tcheck(\"ON DELETE CASCADE removed its tags and the index entry\", tagRows == 0 && len(hits) == 0)\n\tcheck(\"deleting twice is not found\", errors.Is(s.Delete(ctx, c.ID), ErrNotFound))\n\n\t_, err = s.db.Exec(\"INSERT INTO note_tags (note_id, tag) VALUES (42, 'orphan')\")\n\tcheck(\"foreign keys are enforced on pooled connections\", err != nil && strings.Contains(err.Error(), \"FOREIGN KEY\"))\n\n\ts.Close()\n\ts, err = Open(ctx, path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer s.Close()\n\tagain, err := s.Get(ctx, a.ID)\n\tcheck(\"reopening keeps data and skips applied migrations\", err == nil && again.Version == 2 && slices.Equal(again.Tags, []string{\"sqlite\", \"transactions\"}), again.Tags)\n}","language":"go","title":"The repository and its checks","walkthrough":"All seventeen checks pass. The migrations reach version 2, the three notes get ids 1 to 3 and Go is stored as go. An empty title fails the CHECK and leaves no row. writer matches notes 1 and 2, the tag filter keeps both, and the snippet brackets writers. Input with c++ and an unbalanced quote returns no rows and no error. Update moves note 1 to version 2 and the triggers reindex it; replaying version 1 is a conflict. Deleting note 3 cascades its tags and index entry, an orphan tag is refused, and the reopened store skips migrations."},{"body":"inTx begins, defers Rollback and commits only when the callback returns nil; Rollback after a successful Commit returns sql.ErrTxDone and changes nothing. Each transaction does a few statements and no network or user interaction, because in SQLite one open write transaction blocks every other writer. BEGIN IMMEDIATE means two concurrent updates queue on the busy timeout instead of both reading and then one failing with SQLITE_BUSY when it tries to write. Keep the *sql.Tx inside the callback; it is bound to one connection and must not be shared between goroutines.","title":"Transactions stay short and owned"},{"body":"A client reads a note, edits it for a minute and saves. Locking the row for that minute is impossible in SQLite and undesirable anywhere. Instead the client sends back the version it read, and the UPDATE matches only if that version is still current, incrementing it with RETURNING version. Zero rows means either someone else saved first or the note is gone; the repository checks which inside the same transaction and returns ErrConflict or ErrNotFound, sentinel errors callers test with errors.Is and map to HTTP 409 or 404.","title":"Optimistic concurrency with a version column"},{"body":"Open the store once at startup, fail fast when migrations fail or the file is newer than the code, and close it at shutdown, which runs PRAGMA optimize. Handlers receive the store, not the *sql.DB, so every query goes through the repository and its tests. In the next GopherForge update, a SQLite project can keep such a file under /sandbox with the project and inspect its tables, schema and rows in the per-project database browser.","code":"func run(ctx context.Context) error {\n\tstore, err := notes.Open(ctx, \"/sandbox/notes.db\")\n\tif err != nil {\n\t\treturn err // includes \"schema version N is newer than this program\"\n\t}\n\tdefer store.Close() // runs PRAGMA optimize, then closes the pool\n\t// hand store to handlers; never share *sql.Tx across goroutines\n\treturn serve(ctx, store)\n}","language":"go","title":"Wiring it into a program","walkthrough":"The path is the only environment-specific value. The error from Open already explains a schema that is too new, so the program can print it and exit instead of guessing. The deferred Close runs after serve returns, when no handler is still using the pool."},{"body":"Turn the checks in main into table-driven tests with the temporary-database helper from the previous lesson, add a test that runs every migration against a saved version-1 file, and add a concurrency test that holds one IMMEDIATE transaction while a second Update waits. Add a nightly VACUUM INTO backup with an integrity check. If reads grow, open a second, read-only pool with query_only for searches, and keep a single-connection pool for writes so writers never contend inside the process.","title":"Where to take it next"}],"takeaway":"A good SQLite repository owns its pool and DSN, migrates with user_version at startup, writes in short IMMEDIATE transactions with RETURNING, guards edits with a version column, lets foreign keys and triggers keep related data consistent, and quotes every search term.","title":"Project: a tested notes repository with migrations, transactions and full-text search","unitID":"sqlite-project","wrongAnswers":["It silently overwrites the first person's change","It waits for the busy timeout and then succeeds"]}],"revision":"2026-11-29.1","schemaVersion":1,"solutions":{},"units":[{"id":"sqlite-foundations","lessons":[{"conceptTags":["sqlite.first-database"],"explanation":"SQLite is a library, not a server: your Go process opens a single file and runs the SQL engine in its own address space. database/sql supplies the pool, statements and transactions; a driver supplies the engine. This course uses the pure-Go modernc.org/sqlite driver for its runnable examples, and every program here works the same in a native Go environment. The next GopherForge update adds a SQLite project template whose Go program uses database/sql through the app's bundled gopherforge.app/sqlite driver (registered as sqlite, backed by the system SQLite on iPhone and iPad); databases a program writes under /sandbox are kept with the project; and a database browser per project shows tables, schema and rows, offers a SQL console, and imports and exports .sqlite and .db files through Files.","id":"sqlite.first-database","objective":"Open a file database through database/sql, see that sql.Open connects lazily, and run Exec, Query and QueryRow with placeholders and complete error handling.","task":{"reading":{}},"title":"Open a SQLite database from Go: database/sql, a driver and a file"},{"conceptTags":["sqlite.drivers-dsn"],"explanation":"Three mature SQLite drivers exist for Go and they differ in how the C library reaches your binary: translated to Go, linked through cgo, or compiled to WebAssembly. Whichever you pick, most SQLite settings belong to a connection rather than to the file, and database/sql opens connections whenever it likes. A setting that is not in the data source name is a setting some of your connections do not have.","id":"sqlite.drivers-dsn","objective":"Compare modernc.org/sqlite, mattn/go-sqlite3 and ncruces/go-sqlite3, and use DSN parameters so that every pooled connection gets the same pragmas and transaction mode.","task":{"reading":{}},"title":"Choose a SQLite driver and configure every connection through the DSN"},{"conceptTags":["sqlite.memory-pool"],"explanation":"The filename :memory: does not name one database; it asks SQLite for a new, private, empty database for this connection. database/sql happily opens a second connection when two queries overlap, and that connection sees nothing the first one created. The usual symptom is a test that passes alone and fails with \"no such table\" as soon as something runs concurrently.","id":"sqlite.memory-pool","objective":"Explain why an in-memory database vanishes between pooled connections and choose between a single connection, the memdb VFS, shared cache and a temporary file.","task":{"reading":{}},"title":":memory: is per connection: the pool, SetMaxOpenConns(1), memdb and shared cache"},{"conceptTags":["sqlite.type-affinity"],"explanation":"In most databases a column has a type and every value in it has that type. In SQLite a value carries its own storage class (NULL, INTEGER, REAL, TEXT or BLOB) and the column only has an affinity, a preference applied when a conversion is lossless. VARCHAR(3) does not limit length and a column named INTEGER can hold the word abc. STRICT tables, available since SQLite 3.37, restore the rules you probably expected.","id":"sqlite.type-affinity","objective":"Predict the storage class SQLite gives each value from a column's declared type, see what Go receives when scanning into any, and use STRICT tables to reject values that do not fit.","task":{"reading":{}},"title":"Type affinity, dynamic typing and STRICT tables"},{"conceptTags":["sqlite.rowid-keys"],"explanation":"Almost every SQLite table is a B-tree keyed by a hidden 64-bit integer, the rowid. Declaring a column exactly INTEGER PRIMARY KEY makes it that key, which is fast and is what LastInsertId returns. A small spelling difference, INT instead of INTEGER, gives you a second, separate key, and AUTOINCREMENT changes how ids are reused at a cost most tables do not need.","id":"sqlite.rowid-keys","objective":"Recognize when a primary key is an alias for the rowid, decide whether AUTOINCREMENT is worth its cost, and know when a WITHOUT ROWID table fits.","task":{"reading":{}},"title":"INTEGER PRIMARY KEY, rowid, AUTOINCREMENT and WITHOUT ROWID"},{"conceptTags":["sqlite.nulls-time"],"explanation":"Two things trip up nearly every Go program that talks to SQLite: a NULL arriving in a plain string, and time values stored in whatever format the driver happened to choose. SQLite has no date type, so the format is your decision. Make both explicit in the schema and in the scan targets and the surprises go away.","id":"sqlite.nulls-time","objective":"Scan nullable columns with sql.NullString, sql.Null[T] and pointers, write NULL-aware SQL, and store times in a format that sorts and that SQLite's date functions understand.","task":{"reading":{}},"title":"NULLs and time values: sql.Null, pointers, COALESCE and a time format you choose"},{"conceptTags":["sqlite.foreign-keys"],"explanation":"SQLite parses and stores every REFERENCES clause, and then, for backward compatibility, ignores it unless the connection has run PRAGMA foreign_keys = ON. The setting is not stored in the file and must be enabled on every connection, so a database written by a tool or a forgotten code path can already contain orphans.","id":"sqlite.foreign-keys","objective":"Show that REFERENCES clauses are not enforced by default, enable enforcement for every connection through the DSN, use ON DELETE CASCADE and find existing violations with foreign_key_check.","task":{"reading":{}},"title":"Foreign keys are off until each connection turns them on"}],"summary":"database/sql and lazy opens, drivers and DSN pragmas, :memory: and the pool, type affinity and STRICT tables, rowid keys, NULLs, time values and foreign keys.","title":"SQLite from Go: connections, drivers and types","translationNote":"Examples run natively against modernc.org/sqlite. The next GopherForge update adds a SQLite project template using the bundled gopherforge.app/sqlite driver, registered as sqlite and backed by the system SQLite."},{"id":"sqlite-data","lessons":[{"conceptTags":["sqlite.transactions-returning"],"explanation":"A transfer that debits one account and fails to credit the other is worse than no transfer at all. A transaction makes the two updates one unit: SQLite commits both or neither, even if the process dies halfway. RETURNING, available since SQLite 3.35, lets an INSERT or UPDATE report the values it produced, so you learn the new id, a default or the updated balance without a second query that could see a different state.","id":"sqlite.transactions-returning","objective":"Group related writes in a database/sql transaction that always rolls back on failure, read generated values with RETURNING, and classify a constraint failure by its extended SQLite result code.","task":{"reading":{}},"title":"Transactions and RETURNING: all-or-nothing changes that hand back what they wrote"},{"conceptTags":["sqlite.upsert"],"explanation":"Insert this row, or update the one that is already there is one of the most common writes in an application. Doing it as SELECT-then-INSERT in Go is a race; SQLite does it atomically with the UPSERT clause, ON CONFLICT, added in 3.24. The older INSERT OR REPLACE looks similar but is a different operation: it deletes the conflicting row and inserts a new one, which quietly changes ids and can cascade into child tables.","id":"sqlite.upsert","objective":"Write ON CONFLICT DO UPDATE and DO NOTHING statements that use excluded values and RETURNING, and explain why INSERT OR REPLACE changes rowids and fires cascading deletes.","task":{"reading":{}},"title":"UPSERT with ON CONFLICT: counters, insert-if-absent and why INSERT OR REPLACE deletes rows"},{"conceptTags":["sqlite.wal-busy"],"explanation":"In SQLite's default rollback-journal mode a writer must wait for readers to finish and readers wait while a writer commits. Write-ahead logging changes that: writers append to a separate -wal file, readers keep reading a consistent snapshot, and the two no longer block each other. There is still exactly one writer at a time, so a second writer either fails at once with SQLITE_BUSY or, with busy_timeout, waits its turn.","id":"sqlite.wal-busy","objective":"Switch a database to write-ahead logging, explain which settings persist in the file and which are per connection, and turn SQLITE_BUSY into a bounded wait with busy_timeout.","task":{"reading":{}},"title":"WAL mode, synchronous and busy_timeout: readers that never wait and writers that queue"},{"conceptTags":["sqlite.begin-immediate"],"explanation":"A plain BEGIN in SQLite is deferred: it takes no lock until the first statement, starts as a read transaction and tries to upgrade to a write transaction at the first write. If another connection committed in between, the reader's snapshot is stale and cannot be upgraded. SQLite reports that immediately as SQLITE_BUSY_SNAPSHOT, extended code 517, without calling the busy handler, so the busy_timeout from the previous lesson does nothing for it. Starting write transactions with BEGIN IMMEDIATE avoids the problem entirely.","id":"sqlite.begin-immediate","objective":"Explain why a deferred transaction that reads and then writes can fail with SQLITE_BUSY_SNAPSHOT regardless of busy_timeout, and prevent it with BEGIN IMMEDIATE through _txlock and a single-writer pool.","task":{"reading":{}},"title":"BEGIN IMMEDIATE and one writer: avoid SQLITE_BUSY_SNAPSHOT that no timeout can fix"},{"conceptTags":["sqlite.json-functions"],"explanation":"SQLite has no separate JSON column type, but its JSON functions, built into the core library since 3.38, read and edit JSON stored as TEXT. That makes it practical to keep a flexible payload next to ordinary columns: validate it on write, query into it with path expressions, and promote the fields you filter on into generated columns that can be indexed like any other.","id":"sqlite.json-functions","objective":"Store JSON documents with a validity check, query paths with json_extract, -> and ->>, expand arrays with json_each and index a field through a generated column.","task":{"reading":{}},"title":"JSON in SQLite: json_extract, -> and ->>, json_each and indexed generated columns"},{"conceptTags":["sqlite.window-ctes"],"explanation":"Reports often need a value that depends on neighbouring rows: a running total, the change since yesterday, the best two days per region. Window functions, in SQLite since 3.25, compute those without collapsing rows the way GROUP BY does. Common table expressions name intermediate results, and WITH RECURSIVE can generate rows, such as every day in a range or every reply in a thread, that are not stored anywhere.","id":"sqlite.window-ctes","objective":"Compute running totals, differences and shares with window functions, select the top rows per group with row_number, and walk series and trees with recursive common table expressions.","task":{"reading":{}},"title":"Window functions and CTEs: running totals, top N per group and recursive queries"},{"conceptTags":["sqlite.query-plans"],"explanation":"An SQLite query that is fast on a hundred rows can scan the whole table on a million. EXPLAIN QUERY PLAN tells you how the planner will run a statement before you discover it in production: whether it scans or searches, which index it uses, whether it can answer from the index alone, and whether it needs a temporary B-tree to sort. Reading it takes a few minutes to learn and pays off on every query you write.","id":"sqlite.query-plans","objective":"Read EXPLAIN QUERY PLAN output from Go, add indexes that turn scans into searches and remove temporary sorts, use expression indexes for computed filters, and keep statistics fresh with ANALYZE and PRAGMA optimize.","task":{"reading":{}},"title":"Read EXPLAIN QUERY PLAN: SCAN, SEARCH, covering indexes, sorts and ANALYZE"}],"summary":"Transactions and RETURNING, UPSERT, WAL and busy_timeout, BEGIN IMMEDIATE, JSON functions, window functions and CTEs, and query plans.","title":"Transactions, concurrency and queries","translationNote":"Each program uses temporary files or in-memory databases. In the next app update, databases a program writes under /sandbox are kept with the project."},{"id":"sqlite-project","lessons":[{"conceptTags":["sqlite.migrations-user-version"],"explanation":"A SQLite file outlives the binary that created it: users keep it, copy it and open it with the next release. A migration runner must know which schema the file has and move it forward exactly once per step. SQLite gives every database a 32-bit integer in its header, PRAGMA user_version, that the library never touches. Store the schema version there and change it in the same transaction as the schema itself, because SQLite DDL is transactional.","id":"sqlite.migrations-user-version","objective":"Apply append-only migrations that record their version in PRAGMA user_version inside the same transaction, skip applied steps, roll back a failing step and refuse a newer schema.","task":{"reading":{}},"title":"Migrate a schema with PRAGMA user_version: ordered steps, one transaction each"},{"conceptTags":["sqlite.fts5-search"],"explanation":"LIKE '%word%' reads every row and knows nothing about words, prefixes or relevance. FTS5 is SQLite's full-text engine: a virtual table that maintains an inverted index of tokens and answers MATCH queries with a bm25 rank. modernc.org/sqlite ships with FTS5 compiled in. The index can store its own copy of the text or point at an ordinary table you already have; the second option, external content, keeps one source of truth but makes keeping the index in sync your job.","id":"sqlite.fts5-search","objective":"Index a table with an external-content FTS5 table kept in sync by triggers, query it with prefixes, phrases, operators and column filters, rank with bm25, and quote user input.","task":{"reading":{}},"title":"Full-text search with FTS5: an external-content index, ranking and safe queries"},{"conceptTags":["sqlite.backups-maintenance"],"explanation":"A SQLite database is a file, which makes it tempting to back it up with cp. In WAL mode the committed state is split between app.db and app.db-wal, and a writer can change either while you copy. SQLite provides safe ways to produce a consistent snapshot while the program keeps running, and a few maintenance commands that keep the file compact and the query planner well informed.","id":"sqlite.backups-maintenance","objective":"Take a consistent backup of a WAL database with VACUUM INTO, verify the copy, reclaim free pages, truncate the WAL with a checkpoint and keep planner statistics current.","task":{"reading":{}},"title":"Back up and maintain a live database: VACUUM INTO, checkpoints, VACUUM and ANALYZE"},{"conceptTags":["sqlite.testing-temp-databases"],"explanation":"Because SQLite is a library, tests can use the real engine with the real schema instead of a mock, and still run in milliseconds. The question is isolation: tests that share one database see each other's rows, and an in-memory database interacts badly with the connection pool. A helper that gives every test its own migrated file in a temporary directory solves both and keeps the tests safe to run in parallel.","id":"sqlite.testing-temp-databases","objective":"Write a test helper that opens a migrated file database in t.TempDir, registers cleanup, and lets table-driven and parallel tests run against isolated databases.","task":{"reading":{}},"title":"Test against real SQLite: a fresh migrated database file per test"},{"conceptTags":["sqlite.notes-repository"],"explanation":"This project puts the course together in one package-sized program: a repository type that owns its *sql.DB, configures every connection through the DSN, migrates with PRAGMA user_version, keeps writes in short transactions, detects lost updates with a version column, and offers ranked search that is safe for any input. The same shape fits a command-line tool, a small web service or the coming GopherForge SQLite project template, where a program writes its database under /sandbox in the next app update.","id":"sqlite.notes-repository","objective":"Build a small notes store on SQLite that migrates itself, writes in IMMEDIATE transactions with RETURNING and optimistic versions, cascades tags, and searches with FTS5, with a check for every behaviour.","task":{"reading":{}},"title":"Project: a tested notes repository with migrations, transactions and full-text search"}],"summary":"Migrations with user_version, FTS5 search, backups and maintenance, tests with temporary databases, and a complete notes repository.","title":"SQLite project: a tested notes repository","translationNote":"The project runs natively with go run. The next app update adds a per-project database browser with tables, schema, rows and a SQL console, plus .sqlite and .db import and export through Files."}]}