Query iteration, bulk loading, backup and integrity
Live engine layout and counters are available through
SHOW LSM STATUS.
Database.Query, Session.Query, Tx.Query and Stmt.Query return *db.Rows.
Each has a QueryContext variant. A database query owns an independent session;
a session or transaction query sees its own private writes and serializes other
calls on that session until the result closes.
rows, err := database.QueryContext(ctx,
"SELECT id, name FROM customers WHERE id BETWEEN 10 AND 20 ORDER BY id")
if err != nil { return err }
defer rows.Close()
for rows.Next() {
var id int64
var name string
if err := rows.Scan(&id, &name); err != nil { return err }
fmt.Println(id, name)
}
return rows.Err()
Simple single-table filtering/projection queries stream from a pinned statement
snapshot. Clustered primary-key order in either direction, LIMIT/OFFSET,
primary-key equality and a single composite key interval are supported without
materializing all matches. Cursor memory does not grow with the result count.
Joins, grouping, arbitrary sorting, DISTINCT, views, subqueries and other blocking
operators use the ordinary executor. Rows.Materialized() makes that fallback
visible to callers. The row order matches the query; SQL without ORDER BY does
not promise a particular order.
Always close results when stopping early. Exhaustion, context cancellation and database/session shutdown automatically release the iterator, snapshot and session gate, including when the consumer never calls Next again. Do not keep an idle result open indefinitely: it pins old MVCC versions. Next/Scan are meant for one consumer; Close may run concurrently. Scan errors leave the current row available for another Scan.
Rows.Columns() returns copied column definitions with constraint SQL text;
internal executable DEFAULT/CHECK ASTs are omitted. Rows.Values() returns
caller-owned SQL values in projection order. Scan accepts *sql.Value, *int64,
*int, *float64, *string, *[]byte, *bool, *any, and database/sql.Scanner
implementations such as database/sql.NullInt64. NULL fails for non-nullable
scalar destinations. Typed scanning rejects incompatible types, overflowing
native integers and integer-to-float conversions outside the exact integer
range of float64. Scanned BLOB buffers remain valid after Next and Close; changing
them cannot mutate the database. Prepared query bindings remain private until
their result closes, so concurrent executions do not reuse a live cursor's AST.
Rows.ValuesInto(dst) provides the same owned values while reusing the slice
and each BLOB buffer's capacity. Pass its returned slice into the next call to
reduce copying allocations. Each call gives up the old contents and all aliases
to those destination buffers; use Values() when retaining independent rows.
NULL clears the destination value, while an empty non-NULL BLOB remains an empty
byte slice. The returned values remain valid after closing the result.
Streaming cursors reuse private decoded row maps and BLOB buffers. Simple
physical projections decode directly into those buffers; expressions keep
source and output buffers separate. This applies to native, prepared,
database/sql, MySQL streaming reads and PostgreSQL COPY. Public Values, Scan
and ordinary execution results remain independently owned. Lower-level SQL
consumers can opt into RowCursor.NextInto(dst) with an exclusively owned
destination; RowCursor.Next() continues to return independent rows.
Atomic bulk insertion
Database.BulkInsert(ctx, table, columns, source) consumes a db.BulkSource
callback returning []any bindings and io.EOF. It prepares INSERT shapes in
batches of 256 rows and commits the entire import in one transaction. Ordinary
SQL affinity, defaults, primary/unique keys, checks, foreign keys, triggers and
index maintenance apply. Source errors, malformed rows, constraint failures and
cancellation roll back all inserted rows and return a count of zero.
next := func(ctx context.Context) ([]any, error) {
record, err := csvReader.Read()
if err != nil { return nil, err }
return []any{record[0], record[1]}, nil
}
count, err := database.BulkInsert(ctx, "customers", []string{"id", "name"}, next)
Sources execute synchronously and should honor the supplied context when their
own I/O may block. Row buffers and BLOB bindings may be reused on the next source
call. The transaction retains pending writes and locks until commit; invoke the
API in separate chunks if bounded transaction memory matters more than all-or-
nothing import semantics. The CLI .import FILE TABLE now uses this API: invalid
CSV or SQL data leaves no partially inserted rows. Automatic table creation for
an absent table still precedes import, so a failed import may leave an empty table.
Consistent online backup
Database.BackupContext(ctx, destination) (or Backup) copies committed raw
key/value state at one pinned MVCC snapshot, including catalog, rows and indexes.
Other sessions continue executing while it copies. Private transaction writes
are excluded. This creates a durable, reopenable database, even when the source
has WAL or WAL fsync disabled. It does not copy changing WAL files or require a
source checkpoint. The copy is written in bounded batches to a temporary sibling
directory, flushed and synced, then published with a directory rename and parent
sync. Close and cancellation clean up incomplete staged copies.
The destination must not exist and must lie outside the source database directory.
Its parent directory must exist. Existing databases are never overwritten. Restore
by calling db.Open(destination, options); no import/replay procedure is required.
The backup preserves logical state, not SSTable layout, historical MVCC versions,
original sequence numbers or WAL history. Long backups retain old versions and
use additional disk space. An error syncing the parent after publication can
leave a complete backup at the destination; inspect that path before retrying.
CLI: .backup DIRECTORY.
Read-only integrity checking
Database.CheckIntegrityContext(ctx) (or CheckIntegrity) reports checked rows,
secondary entries, catalog objects, SSTables and physical entries. It validates
one SQL snapshot for row encoding/types, primary keys, CHECK/NOT NULL/UNIQUE
constraints, foreign-key references, clustered-key agreement and missing, stale
or extra index entries. Persisted catalog objects must agree with the committed
catalog. It also opens current immutable SSTables with the block cache disabled
to verify metadata/index/data checksums, internal key ordering, sizes, manifest
agreement and bloom-filter false negatives, including obsolete row versions.
The checker never repairs or rewrites data. Diagnostics name the table, row, index or SSTable concerned, and cancellation releases all readers. It may use memory proportional to the number of distinct UNIQUE values, and is intended for explicit operational checks. Unflushed data is checked logically; live WAL history is not reread. A nullable column omitted from a legacy row after ALTER ADD COLUMN is interpreted as NULL, matching normal execution.
CLI: .integrity, which prints ok and verification counts or an error.
.bail on exits with a failure status when either backup or integrity fails.
Dot commands are available in interactive terminal sessions. Scripts redirected
into the CLI must opt in with --allow-dot-commands; otherwise encountering a dot
command reports an error and exits with status 1. The setting applies to all dot
commands, including shell execution, file access and exit commands.
Quick storage status
CLI .status prints the current database path, effective WAL and fsync mode,
persisted SSTable page target, default query and lock timeouts, deadlock detection,
compression for future L0 and L1-L6 blocks, active and immutable memtable bytes, and the
number and total size of SSTables at each occupied level. It takes a cheap
snapshot of live counters and file metadata, so it is useful during normal
operation. For example, it distinguishes a database running without WAL from
one writing WAL without fsync; both settings affect crash durability.
.status does not scan data or verify checksums. Use .integrity for that
explicit check. For per-file bounds, cache counters and compaction counters,
use .manifest. A large L0 file count can indicate that flushes are arriving
faster than background compaction; compare several status snapshots before
drawing a conclusion from one moment.
Compression describes future writes; existing SSTables can contain different
codecs. Timeouts and deadlock detection describe this CLI instance. They are
selected at open and are not persistent database settings. Use PRAGMA collation
to read the persisted database-wide text mode.
Explaining a slow query
CLI .explain SELECT ... shows access, filters, join order, sorting and LIMIT,
with short explanations of their effect. It accepts exactly one SELECT-family
statement and produces an estimated plan without evaluating the SELECT.
.explain SELECT id, name FROM customers WHERE id=42
.explain SELECT id, name FROM customers ORDER BY name LIMIT 20
PointLookup means a direct primary-key read. SeekGE / SeekLT seek to a
starting key in forward / reverse order; the plan details describe any bounds.
MultiGet batches point reads. OpenIndex
identifies an index. Rewind indicates scan access, and SorterSort indicates
a separate sort. A scan can be appropriate when most rows are needed. For a
selective predicate, check whether an index starts with the filtering columns;
for sorting, check whether its key order matches ORDER BY. Residual filters
still validate rows obtained through an index.
Run EXPLAIN ANALYZE SELECT ...; explicitly when you need actual row reads,
join/probe counts, execution times, allocation or spill evidence. It executes
the query and a FOR UPDATE / FOR SHARE clause can acquire locks. Compare
actual work with the estimated plan and representative parameter values before
changing an index. A large LIMIT/OFFSET, a broad join or a sort over many rows
can account for work even when an index is present. After substantial data
changes, ANALYZE; refreshes the persisted statistics used for access and join
choices; ordinary writes do not refresh them automatically.
For lock contention, .locks prints waiting sessions and blocking session IDs.
Use independent sessions to investigate active transactions; calls on the same
session serialize. See SQL and lock diagnostics for the Go API
and lock timing, and SQL surprises when the issue is the
answer rather than execution cost.
Backup, restore and upgrades
Create .backup DIRECTORY into a new directory before an upgrade or a schema
change whose recovery cost matters. Reopen that directory and run .integrity
to validate the copy. Restoring means opening the backup directory with the
desired runtime options; it needs no SQL import. Keep the original directory
until the restored data has been checked. WAL settings at runtime are visible
through .status.
Use .plan or SQL EXPLAIN on a supported schema change before executing it
to inspect expected scans, rewrites and locking. See
schema change planning for limitations and online
index operations. These commands report work; they do not validate every
existing row or guarantee that the later operation will succeed.
Execute an already parsed SELECT
Protocol adapters can use Session.QueryParsedContext(ctx, query, statement) to execute an already parsed SELECT. Parse with sql.ParseWithOptions(query, session.ParseOptions()) so the AST uses the session's SQL syntax. The query string supplies activity text only; the parsed statement determines execution. The caller must exclusively own the statement and leave it unchanged until the returned Rows closes. Admission, snapshots, catalog resolution, and cancellation follow QueryContext.
Session.QueryParsedContextInto(ctx, dst, query, statement) accepts a non-nil *db.ExecResult and a non-nil *sql.SelectStmt. It returns (result, rows, err) through one admission, timeout, and snapshot:
- A catalog-proven primary-key point lookup or eligible small IN/range read returns
result == dstandrows == nil, reusing the destination's column, row, and BLOB storage when possible. A missing key produces an empty result. Small IN/range reads follow the limits described below. - Other SELECT shapes return
result == niland non-nilrows, leavingdstunchanged. Consume and close those rows; inspectRows.Materialized()to distinguish streaming from a materialized fallback. - Check
errbefore consuming either result. Destination contents are unspecified on error.
The statement remains exclusively owned until execution completes or the returned rows close. Destination ownership follows prepared result reuse: give up prior contents and all aliases on entry, and use a separate destination per concurrent reader. This API does not cache SQL text or query answers.
Observe session shutdown
Session.ClosingContext() returns a stable context canceled when that session or its owning database starts closing. Normal statement completion, statement cancellation, and Rows.Close() leave it live. Observing the context does not acquire the session execution gate. Protocol adapters can use its Done() channel to interrupt a blocked response write even after query rows are exhausted. The context belongs to the session; callers cannot cancel it.
Bounded primary-key reads
Small literal primary-key IN and range reads can use Session.QueryParsedContextInto to return reusable materialized storage without creating a streaming cursor. This additional path supports a single signed-integer primary key and simple physical-column projections. IN lists have at most 64 entries; bounded ranges require LIMIT at most 64 and OFFSET at most 1,024. Optional ordering must follow that primary key. The bounded path admits at most 64 rows and 64 KiB of encoded row data; these are optimization limits, not limits on SQL query results.
SELECT id, payload FROM events WHERE id IN (9, 2, 5) ORDER BY id;
SELECT id, payload FROM events WHERE id >= 2 ORDER BY id DESC LIMIT 20;
Oversized data and unsupported shapes fall back within the original statement snapshot, leaving the supplied destination unchanged. Missing keys, duplicate IN values, NULLs, reverse order, LIMIT/OFFSET, session dialects, and private transaction writes retain their ordinary SQL behavior. SQL without ORDER BY does not promise row order. Bounds containing arithmetic follow the session's dialect rather than being folded under native integer-division rules. Current execution recipes can be reused; query answers are not cached.
Reusable streaming and storage buffers
For lower-level SQL consumers, RowCursor.NextInto(dst) reuses an exclusively owned row map and each field's independently owned BLOB buffer. Give up every old value and alias before calling; destination fields must not share BLOB buffers. Returned values do not alias storage pages or private cursor rows. Use Next() or pass nil to obtain independent rows that remain valid after cursor movement and Close. Normal application Rows.Values, Rows.Scan, and execution results keep their ownership guarantees; database/sql.RawBytes retains its standard borrowed lifetime.
Storage integrations can opt into LSMTree.NewIteratorAtRangeReusable(snapshot, lower, upper, reverse) or NewIteratorRangeReusable(lower, upper, reverse) for [lower, upper) traversal. Key and Value borrow iterator buffers until the next movement or Close. Keep an explicit snapshot pinned for the iterator's lifetime. storage.IteratorValueInto(iterator, dst) copies the current value into caller-owned capacity; that copy survives movement and Close. Invalid iterators return an empty destination slice. Ordinary range iterators keep their existing ownership contract.
LSMTree.GetMultiAtForReader(keys, snapshot, reader) reads a key batch through a reader-sharded view with a pinned snapshot. Results retain input positions, including missing keys, and duplicate keys receive independent value copies. GetMultiAtForReaderBounded(keys, snapshot, reader, maxBytes) returns (values, fits, err). The byte budget counts every found value, including duplicates; missing and empty values use no bytes. A negative budget fails. Exceeding the budget returns (nil, false, nil) without exposing partial results or borrowed data.