SQLite from Go: connections, drivers and types · 3 MIN READ
:memory: is per connection: the pool, SetMaxOpenConns(1), memdb and shared cache
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.
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.
sqlite · A MAP OF THE IDEA
- Need concurrency?
- Yes: temporary file
- No: :memory: + 1 conn
- Shared RAM: vfs=memdb
Useful when
- In-memory databases are fast and leave nothing behind.
- A temporary file gives tests production behaviour.
Watch out
- A pool silently opens new, empty :memory: databases.
- Shared cache brings table locks and SQLITE_LOCKED.
Implementation & operation cost: A conscious choice per use: one pinned connection, a memdb name, or a temporary directory cleaned up after the run.
Why the table disappears
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.
Five ways to open an in-memory or test database
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.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
// twoConnections creates a table on one pooled connection and reads it from another.
func twoConnections(ctx context.Context, label string, db *sql.DB) {
a, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer a.Close()
b, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer b.Close()
if _, err := a.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS t (v INTEGER); INSERT INTO t VALUES (1)"); err != nil {
log.Fatal(err)
}
var n int
if err := b.QueryRowContext(ctx, "SELECT count(*) FROM t").Scan(&n); err != nil {
fmt.Printf("%-22s second connection: %v\n", label, err)
return
}
fmt.Printf("%-22s second connection sees %d row(s)\n", label, n)
}
func open(dsn string) *sql.DB {
db, err := sql.Open("sqlite", dsn)
if err != nil {
log.Fatal(err)
}
return db
}
func main() {
ctx := context.Background()
// Every connection to ":memory:" is a brand-new, empty database.
mem := open(":memory:")
twoConnections(ctx, ":memory:", mem)
mem.Close()
// One connection: the pool can never hand out a second, empty database.
single := open(":memory:")
single.SetMaxOpenConns(1)
for i := 0; i < 2; i++ {
if _, err := single.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS t (v INTEGER); INSERT INTO t VALUES (1)"); err != nil {
log.Fatal(err)
}
}
var n int
if err := single.QueryRowContext(ctx, "SELECT count(*) FROM t").Scan(&n); err != nil {
log.Fatal(err)
}
fmt.Printf("%-22s every statement sees %d row(s), open=%d\n", "MaxOpenConns(1)", n, single.Stats().OpenConnections)
single.Close()
// Named in-memory database in the memdb VFS: shared by connections of this process.
memdb := open("file:/lesson?vfs=memdb")
twoConnections(ctx, "vfs=memdb", memdb)
memdb.Close()
// Shared cache also works, with table-level locks you rarely want.
shared := open("file:lesson?mode=memory&cache=shared")
twoConnections(ctx, "cache=shared", shared)
shared.Close()
// A temporary file behaves exactly like production.
dir, err := os.MkdirTemp("", "pool")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
file := open(filepath.Join(dir, "test.db"))
twoConnections(ctx, "temporary file", file)
file.Close()
}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.
SetMaxOpenConns(1) and its cost
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.
Shared cache is a legacy mode
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.
What to use where
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.
TAKE THIS WITH YOU
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.
Check your understanding
A test opens sql.Open("sqlite", ":memory:"), creates a table, then runs two queries in parallel goroutines. One fails with "no such table". Why?
Go to the source
Progress stays in this browser. No account needed.