Database class

Constructors

Database({String? path})

Properties

authorizer AuthorizerCallback?
User-supplied authorizer callback. When non-null, every dispatched statement is run past this callback before executing; the callback can AuthorizerResult.deny (throws) or AuthorizerResult.ignore (statement is skipped and a message is returned).
getter/setter pair
backends Iterable<TableBackend>
Every backend known to this database — both in-memory and paged. Order is unspecified.
no setter
coveringScansUsed int
Cumulative count of index-only (covering) scans the executor has served. Reset by resetCounters. Tests use this to assert that a query took the covering path.
getter/setter pair
hashCode int
The hash code for this object.
no setterinherited
inReadOnlySnapshot bool
no setter
inTransaction bool
no setter
lastCteHints Map<String, bool>
no setter
lastPlanLimitPushed bool
no setter
lastPlanSortSkipped bool
no setter
lastPlanTrace List<String>
no setter
path String?
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
rwLock AsyncRwLock
Test/diagnostics hook: returns the in-process RW lock so callers can assert serialization properties.
no setter
tableNames Iterable<String>
no setter
vectorIndexes List<VectorIndexSpec>
Snapshot of every registered vector index. Mutating the returned list has no effect on the database.
no setter
viewNames Iterable<String>
no setter

Methods

applyChangeset(Uint8List bytes, {ChangesetConflictHandler? onConflict}) Future<int>
Apply a previously-recorded changeset blob to this database. Returns the number of changes applied (skipped/aborted changes are not counted). Pass onConflict to decide what to do when a row is missing for UPDATE/DELETE or already present for INSERT — by default conflicts are silently skipped.
backup(String destPath, {int pageSize = 4096}) Future<void>
Online backup: write a consistent SQLite-format snapshot of the current database to destPath. Acquires the writer arm of the engine's read/write lock briefly to take the snapshot, then writes outside the lock so concurrent readers/writers are not blocked for the duration of the disk I/O.
beginSession() Session
Begin a new mutation-recording session. By default the session records every table; call Session.attach to scope it.
beginSnapshot() Future<QueryResult>
Begin a read-only snapshot transaction. The current state of every table is cloned and used as the live view for the duration of the transaction; concurrent writers in the same process block on the writer arm of rwLock until the snapshot is committed/rolled back. Any mutation inside the snapshot is rejected.
checkpointSqlite() Future<void>
Flush any pending -wal content into the main SQLite file and delete the WAL. After this returns the on-disk main file is the canonical image and the diff baseline is reset.
close() Future<void>
Release the cross-process file lock. Idempotent. Always call this when you're done with a path-backed database — otherwise the <path>.lock sidecar will keep readers/writers blocked until the process exits.
createVectorIndex(VectorIndexSpec spec) → void
Register a vector index on spec.table.spec.column. The index is built the first time a query uses it and automatically rebuilt after any mutation of the target table.
detachSession(Session s) → void
Forget the session. Future mutations will not be recorded into it. The session itself remains valid for inspecting captured changes / producing a changeset.
dropVectorIndex(String table, String column) bool
Remove the vector index on table.column, if any. Returns true when a binding was actually dropped.
execute(String sql) Future<QueryResult>
executeScript(String sql) Future<List<QueryResult>>
executeStmt(Statement stmt) Future<QueryResult>
executeWith(String sql, {List<Object?> positional = const [], Map<String, Object?> named = const {}}) Future<QueryResult>
One-shot convenience: prepare sql, bind positional/named, run once, and return the result. Use prepare directly if you want to reuse the statement.
exportSqlite(String path, {int pageSize = 4096, bool includeIndexes = true}) Future<void>
Write every local table (excluding sqlite_* shadow tables) to a real SQLite-format database file at path. The resulting file is readable by package:sqlite3 and the official sqlite3 CLI, including all rows and any non-expression, non-partial single-column indexes.
flush() Future<void>
fts5IndexFor(String tableName, String columnName) Fts5Index
Return (and lazily build) the corpus-aware FTS5 index for tableName.columnName. The index is rebuilt automatically after any mutation of tableName.
importSqlite(String path) Future<String>
Replace the contents of this database with the tables found in the SQLite file at path. The file's CREATE TABLE statements are re-executed against this engine, then rows are bulk-inserted. Indexes stored in the file are recreated by re-executing their CREATE INDEX statements (any indexes the local parser doesn't accept are skipped with a warning row in the returned message).
lookupBackend(String name) TableBackend?
Phase-0 unification scaffold: look up a table by name across both the in-memory and paged backends and return the shared TableBackend view of it. Returns null when no table by that name exists in either registry. Prefer this over poking at _tables / _pagedTables directly when you only need metadata (existence / column names / which backend it lives on).
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
openBlob({required String table, required String column, required int rowid, bool writable = false}) BlobHandle
Open an incremental BLOB I/O handle on a row's BLOB column, analogous to SQLite's sqlite3_blob_open. rowid resolves the target row by INTEGER PRIMARY KEY value when the table has one, falling back to 1-based row position. The returned handle lets callers stream bytes in/out of the column without copying the entire blob through user code.
plannerEqualityHitsEstimate(String tableName, String column) int?
Test/diagnostics hook: the average rows-per-key the planner would charge an equality probe on tableName.column, mirroring the internal _estimateEqualityHits heuristic. Paged tables aren't supported (their stats path doesn't go through _estimateEqualityHits).
plannerRowCountEstimate(String tableName) int
Test/diagnostics hook: the row count the planner currently sees for tableName. Reflects whichever signal _tableRowCountEstimate picks — ANALYZE stats first, then live row count, then 100.
prepare(String sql) PreparedStatement
Parse sql once and return a reusable PreparedStatement. Bind parameters in the SQL (?, ?N, :name, @name, $name) are substituted at .execute(...) time, so the statement can be run many times with different bindings without re-parsing.
resetCounters() → void
Reset perf counters (currently just coveringScansUsed).
snapshotRead<T>(FutureOr<T> body(Database snap)) Future<T>
Snapshot-read primitive: clones the current table set and runs body against the clone. Multiple snapshotRead calls can progress concurrently, and they don't observe writes that happen after the clone moment. The clone is acquired under the read arm of rwLock (so it is consistent with whatever a parallel writer has just committed) and then released immediately, so the body itself runs with no locks held.
table(String name) Table?
toString() String
A string representation of this object.
inherited
warmFts5(String tableName, String columnName) Future<void>
V44: build (or rebuild) the FTS5 corpus for a paged table so hybrid search TVFs can use it. In-memory tables don't need this — fts5IndexFor lazily builds their corpus on demand. Paged corpuses persist in the _fts5IndexCache until the next mutation of tableName invalidates them.
warmVectorIndex(String tableName, String columnName) Future<void>
V49: targeted async warm for a single binding — same async cost as warmVectorIndexes but confined to one (table, column). Idempotent; a no-op when the binding is already built.
warmVectorIndexes() Future<void>
Build every registered vector index that hasn't been warmed yet and, if a persistence path is configured, flush the built state to disk. Callers typically invoke this after bulk-loading rows so the built graph / centroids survive a subsequent reopen.

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Properties

current Database?
The innermost Database whose executeStmt is currently on the call stack, or null when none is. Used by context-sensitive scalar functions.
no setter

Static Methods

open([String? path]) Future<Database>