SQLite
suggest changeSQLite is a full SQL database that runs inside your process. There's no server: a database is a single file (or lives in memory) and queries are function calls into a C library. That makes it a great fit for command-line tools, desktop and Flutter apps, tests, caches, and small to medium web services.
The Relational databases article shows the basics of package:sqlite3 next to PostgreSQL and MySQL: opening a database, execute, select, prepared statements and SqliteException. This article goes further: recommended pragmas, how Dart values map to SQLite types, named parameters, a reusable transaction helper with savepoints, RETURNING and upserts, bulk inserts, streaming large results, custom SQL functions, JSON, full-text search, schema migrations, isolates, change notifications, backups and error codes.
Setup
dependencies:
sqlite3: ^3.7.1
package:sqlite3 binds to the SQLite C library with dart:ffi. Since version 3 the package has a build hook that downloads a pre-compiled SQLite for your platform (Windows, macOS, Linux, Android, iOS) and bundles it with your app, so you don't install anything yourself. Version 3.7.1 ships SQLite 3.54.0 with FTS5, JSON and math functions enabled.
The first dart run prints Running build hooks... while the library is fetched and cached. When you compile your program, use dart build cli rather than dart compile exe so the native library is shipped next to the executable (see Compiling to executables).
The API is synchronous. select returns a ResultSet directly, not a Future. SQLite queries usually take microseconds, so the overhead of an async API would cost more than it saves. For slow queries, use a background isolate, as shown later.
Opening a database and recommended pragmas
sqlite3.open(path) opens (and creates, if needed) a database file. sqlite3.openInMemory() creates a private in-memory database that disappears when it's closed, which is ideal for tests.
SQLite's defaults favour backwards compatibility over speed and safety, so most apps set a few pragmas right after opening a connection:
import 'dart:io';
import 'package:sqlite3/sqlite3.dart';
Database openDatabase(String path) {
final db = sqlite3.open(path);
db.execute('''
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
''');
return db;
}
void main() {
print('SQLite ${sqlite3.version.libVersion}');
final dir = Directory.systemTemp.createTempSync('sqlite_demo');
final path = '${dir.path}/app.db';
final db = openDatabase(path);
db.execute('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)');
db.execute('INSERT INTO notes (body) VALUES (?)', ['first note']);
for (final pragma in ['journal_mode', 'synchronous', 'foreign_keys', 'busy_timeout']) {
final value = db.select('PRAGMA $pragma').first.values.first;
print('$pragma = $value');
}
print(dir.listSync().map((f) => f.uri.pathSegments.last).toList()..sort());
db.close();
// Open the same file read-only.
final ro = sqlite3.open(path, mode: OpenMode.readOnly);
print(ro.select('SELECT body FROM notes').map((r) => r['body']).toList());
try {
ro.execute('DELETE FROM notes');
} on SqliteException catch (e) {
print('read-only: ${e.message}');
}
ro.close();
dir.deleteSync(recursive: true);
}
Output:
SQLite 3.54.0
journal_mode = wal
synchronous = 1
foreign_keys = 1
busy_timeout = 5000
[app.db, app.db-shm, app.db-wal]
[first note]
read-only: attempt to write a readonly database
What the pragmas do:
journal_mode = WAL(write-ahead log) lets readers keep reading while a writer writes, and makes writes faster. It's stored in the database file, so it stays on. WAL mode creates the-waland-shmfiles next to the database; copy all three if you copy a database while it's open (or better, use a backup, see below).synchronous = NORMALis safe in WAL mode (a power loss can lose the last transactions but won't corrupt the database) and much faster than the defaultFULL.foreign_keys = ON: for historical reasons SQLite ignoresREFERENCESconstraints unless you turn this on, for every connection.busy_timeout = 5000: when another connection holds the write lock, wait up to 5 seconds instead of failing immediately with "database is locked".
execute runs every statement in the string, which is why the four pragmas can be set in one call. Use OpenMode.readOnly for connections that must never write, and OpenMode.readWrite to fail instead of creating a missing file.
Types and parameters
SQLite has five storage classes. package:sqlite3 converts them to and from Dart types:
| SQLite | Dart (read) | Dart values you can bind |
|---|---|---|
NULL |
null |
null |
INTEGER |
int |
int, bool (as 0/1), BigInt within 64 bits |
REAL |
double |
double |
TEXT |
String |
String |
BLOB |
Uint8List |
List<int> / Uint8List |
There are no date or boolean column types. Store booleans as 0/1 and dates either as Unix time (an integer, easy to compare and index) or as ISO-8601 text (readable, and what SQLite's date functions expect). Binding a DateTime directly throws an ArgumentError.
By default SQLite lets you store any value in any column. Add STRICT to a table definition and it enforces the declared types instead:
import 'dart:typed_data';
import 'package:sqlite3/sqlite3.dart';
void main() {
final db = sqlite3.openInMemory();
db.execute('''
CREATE TABLE events (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER NOT NULL, -- bool stored as 0/1
created_at INTEGER NOT NULL, -- Unix time in milliseconds
due TEXT, -- ISO-8601 text
score REAL,
thumb BLOB
) STRICT
''');
final created = DateTime.utc(2026, 10, 17, 9, 30);
db.execute(
'INSERT INTO events (title, done, created_at, due, score, thumb) VALUES (?, ?, ?, ?, ?, ?)',
[
'Ship release',
true, // bool is bound as 1
created.millisecondsSinceEpoch,
DateTime.utc(2026, 11, 1).toIso8601String(),
4.5,
Uint8List.fromList([0x89, 0x50, 0x4e, 0x47]),
],
);
// Numbered parameters can be reused.
db.execute('INSERT INTO events (title, done, created_at) VALUES (?1, 0, ?2)', [
'Write docs',
created.millisecondsSinceEpoch,
]);
// Named parameters (:name, @name or $name) need a prepared statement.
final stmt = db.prepare('SELECT * FROM events WHERE done = :done OR title = :title');
final rows = stmt.selectWith(StatementParameters.named({':done': 1, ':title': 'Write docs'}));
stmt.close();
for (final row in rows) {
final done = row['done'] == 1;
final createdAt = DateTime.fromMillisecondsSinceEpoch(row['created_at'] as int, isUtc: true);
final due = switch (row['due']) { String s => DateTime.parse(s), _ => null };
print('${row['title']}: done=$done created=$createdAt due=$due');
print(' score=${row['score']} (${row['score'].runtimeType}) '
'thumb=${row['thumb']} (${row['thumb'].runtimeType})');
}
try {
db.execute('INSERT INTO events (title, done, created_at) VALUES (?, ?, ?)',
['Bad', false, DateTime.now()]);
} on ArgumentError catch (e) {
print('ArgumentError: ${e.message}');
}
try {
db.execute("INSERT INTO events (title, done, created_at) VALUES ('Bad', 0, 'yesterday')");
} on SqliteException catch (e) {
print('SqliteException: ${e.message}');
}
final big = db.select('SELECT 9223372036854775807 AS max, typeof(1.0) AS t').first;
print('max=${big['max']} t=${big['t']}');
db.close();
}
Output:
Ship release: done=true created=2026-10-17 09:30:00.000Z due=2026-11-01 00:00:00.000Z
score=4.5 (double) thumb=[137, 80, 78, 71] (Uint8List)
Write docs: done=false created=2026-10-17 09:30:00.000Z due=null
score=null (Null) thumb=null (Null)
ArgumentError: Allowed parameters must either be null or bool, int, num, String or List<int>.
SqliteException: cannot store TEXT value in INTEGER column events.created_at
max=9223372036854775807 t=real
Parameter styles:
?placeholders are bound in order from the list.?1,?2refer to list positions, so one value can be used several times.:name,@nameand$nameare named parameters.Database.selectonly takes a list, so for named parameters prepare a statement and callselectWith/executeWithwithStatementParameters.named. The map keys include the prefix character.
Never build SQL with string interpolation ('... WHERE title = $title'). Besides the SQL injection risk, a parameter is parsed once and can be reused through a prepared statement.
Transactions, RETURNING and upserts
Every statement outside an explicit transaction runs in its own transaction. To group statements, run BEGIN / COMMIT / ROLLBACK yourself. A small helper that also supports nesting with savepoints makes that hard to get wrong:
import 'package:sqlite3/sqlite3.dart';
/// Runs [action] in a transaction. Nested calls use savepoints.
T transaction<T>(Database db, T Function() action) {
final outermost = db.autocommit;
db.execute(outermost ? 'BEGIN IMMEDIATE' : 'SAVEPOINT nested');
try {
final result = action();
db.execute(outermost ? 'COMMIT' : 'RELEASE nested');
return result;
} catch (_) {
db.execute(outermost ? 'ROLLBACK' : 'ROLLBACK TO nested; RELEASE nested');
rethrow;
}
}
void main() {
final db = sqlite3.openInMemory();
db.execute('''
PRAGMA foreign_keys = ON;
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
owner TEXT NOT NULL UNIQUE,
balance INTEGER NOT NULL CHECK (balance >= 0)
);
CREATE TABLE transfers (
id INTEGER PRIMARY KEY,
from_id INTEGER NOT NULL REFERENCES accounts(id),
to_id INTEGER NOT NULL REFERENCES accounts(id),
amount INTEGER NOT NULL
);
''');
// RETURNING gives back generated values without a second query.
final ids = db
.select('INSERT INTO accounts (owner, balance) VALUES (?, ?), (?, ?) RETURNING id, owner',
['alice', 100, 'bob', 20])
.map((r) => '${r['owner']}=${r['id']}')
.toList();
print('created $ids');
// Upsert: insert or update when the unique key already exists.
db.execute('''
INSERT INTO accounts (owner, balance) VALUES (?, ?)
ON CONFLICT (owner) DO UPDATE SET balance = balance + excluded.balance
''', ['bob', 30]);
void transfer(int from, int to, int amount) => transaction(db, () {
db.execute('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, from]);
db.execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, to]);
db.execute('INSERT INTO transfers (from_id, to_id, amount) VALUES (?, ?, ?)',
[from, to, amount]);
});
void printBalances() => print(db
.select('SELECT owner, balance FROM accounts ORDER BY id')
.map((r) => '${r['owner']}: ${r['balance']}')
.join(', '));
printBalances();
transfer(1, 2, 70);
printBalances();
for (final (from, to, amount) in [(1, 2, 500), (1, 99, 10)]) {
try {
transfer(from, to, amount);
} on SqliteException catch (e) {
print('transfer $from->$to failed: ${e.message}');
}
}
printBalances();
// Nested transaction: the inner failure is rolled back, the outer work is kept.
transaction(db, () {
db.execute("INSERT INTO accounts (owner, balance) VALUES ('carol', 5)");
try {
transaction(db, () {
db.execute("INSERT INTO accounts (owner, balance) VALUES ('dave', 5)");
throw StateError('changed my mind');
});
} on StateError catch (e) {
print('inner: ${e.message}');
}
});
printBalances();
print('transfers: ${db.select('SELECT count(*) AS n FROM transfers').first['n']}');
db.close();
}
Output:
created [alice=1, bob=2]
alice: 100, bob: 50
alice: 30, bob: 120
transfer 1->2 failed: CHECK constraint failed: balance >= 0
transfer 1->99 failed: FOREIGN KEY constraint failed
alice: 30, bob: 120
inner: changed my mind
alice: 30, bob: 120, carol: 5
transfers: 1
Notes:
db.autocommitistruewhen no transaction is active, which is how the helper knows whether it's the outermost call.BEGIN IMMEDIATEtakes the write lock right away. With plainBEGIN(deferred), a transaction that starts by reading and later writes can fail withSQLITE_BUSYif another connection wrote in between, andbusy_timeoutcan't help in that case. UseIMMEDIATEfor transactions that write.SAVEPOINT/ROLLBACK TO/RELEASEundo only the inner part. Savepoints with the same name nest;ROLLBACK TO nestedrefers to the most recent one.RETURNING(onINSERT,UPDATEandDELETE) returns rows, so useselectrather thanexecuteto read them. For a single insert,db.lastInsertRowIdworks too.- In an upsert,
excluded.balanceis the value that theINSERTtried to write.
Bulk inserts and large results
In autocommit mode, SQLite syncs every single INSERT to disk. Inside one transaction it syncs once at COMMIT. The difference is huge:
import 'dart:io';
import 'package:sqlite3/sqlite3.dart';
void main() {
final dir = Directory.systemTemp.createTempSync('sqlite_bulk');
final db = sqlite3.open('${dir.path}/bulk.db');
db.execute('CREATE TABLE readings (id INTEGER PRIMARY KEY, sensor TEXT, value REAL)');
final insert = db.prepare('INSERT INTO readings (sensor, value) VALUES (?, ?)', persistent: true);
// 1,000 inserts, each in its own implicit transaction.
var sw = Stopwatch()..start();
for (var i = 0; i < 1000; i++) {
insert.execute(['s${i % 10}', i * 0.5]);
}
print('1000 rows, autocommit: ${sw.elapsedMilliseconds} ms');
// 100,000 inserts in one transaction.
sw = Stopwatch()..start();
db.execute('BEGIN');
for (var i = 0; i < 100000; i++) {
insert.execute(['s${i % 10}', i * 0.5]);
}
db.execute('COMMIT');
print('100000 rows, one tx: ${sw.elapsedMilliseconds} ms');
insert.close();
// select() loads every row into memory; selectCursor() steps through them.
final query = db.prepare('SELECT sensor, value FROM readings WHERE value > ?');
final cursor = query.selectCursor([1000.0]);
var count = 0;
var sum = 0.0;
while (cursor.moveNext()) {
final row = cursor.current;
count++;
sum += row['value'] as double;
}
query.close();
print('rows=$count avg=${(sum / count).toStringAsFixed(2)}');
db.close();
dir.deleteSync(recursive: true);
}
Output (on a Windows desktop with an SSD):
1000 rows, autocommit: 5691 ms
100000 rows, one tx: 203 ms
rows=97999 avg=25500.00
That's more than 5 ms per row in autocommit mode versus about 2 microseconds per row inside a transaction.
persistent: true tells SQLite that the statement will be kept around and reused many times. Prepared statements hold native resources: call close() on them when you're done (closing the database also closes them).
select reads all rows into a ResultSet in memory. selectCursor returns an IteratingCursor that steps through the rows one at a time, which keeps memory flat when you process millions of rows. Don't run other statements on the same prepared statement until the cursor is exhausted.
Custom SQL functions, aggregates and collations
Because SQLite runs in your process, it can call back into Dart. You can register scalar functions, aggregate functions and collations (sort orders) written in Dart and use them in SQL:
import 'package:sqlite3/sqlite3.dart';
/// Median of all non-null numeric values in a group.
class Median implements AggregateFunction<List<num>> {
@override
AggregateContext<List<num>> createContext() => AggregateContext(<num>[]);
@override
void step(SqliteArguments arguments, AggregateContext<List<num>> context) {
if (arguments[0] case num n) context.value.add(n);
}
@override
Object? finalize(AggregateContext<List<num>> context) {
final values = context.value..sort();
if (values.isEmpty) return null;
final mid = values.length ~/ 2;
return values.length.isOdd ? values[mid] : (values[mid - 1] + values[mid]) / 2;
}
}
void main() {
final db = sqlite3.openInMemory();
// Scalar function: slugify('Hello, World!') -> 'hello-world'
db.createFunction(
functionName: 'slugify',
argumentCount: const AllowedArgumentCount(1),
deterministic: true,
function: (args) {
final text = args[0];
if (text is! String) return null;
return text.toLowerCase().replaceAll(RegExp(r'[^a-z0-9]+'), '-').replaceAll(RegExp(r'^-|-$'), '');
},
);
db.createAggregateFunction(
functionName: 'median',
argumentCount: const AllowedArgumentCount(1),
deterministic: true,
function: Median(),
);
// Collation: compare strings by length, then alphabetically.
db.createCollation(
name: 'by_length',
function: (a, b) {
final c = (a?.length ?? 0).compareTo(b?.length ?? 0);
return c != 0 ? c : (a ?? '').compareTo(b ?? '');
},
);
db.execute('''
CREATE TABLE posts (title TEXT, author TEXT, words INTEGER);
INSERT INTO posts VALUES
('Hello, World!', 'ann', 120),
('Dart 3: Records & Patterns', 'ann', 1800),
('SQLite in 5 minutes', 'ben', 640),
('Why FFI?', 'ben', 300),
('Isolates', 'ben', 950);
''');
for (final row in db.select('SELECT slugify(title) AS slug FROM posts')) {
print(row['slug']);
}
print(db.select('SELECT author, median(words) AS m FROM posts GROUP BY author'));
print(db
.select('SELECT title FROM posts ORDER BY title COLLATE by_length')
.map((r) => r['title'])
.toList());
db.close();
}
Output:
hello-world
dart-3-records-patterns
sqlite-in-5-minutes
why-ffi
isolates
[{author: ann, m: 960.0}, {author: ben, m: 640}]
[Isolates, Why FFI?, Hello, World!, SQLite in 5 minutes, Dart 3: Records & Patterns]
args is a List<Object?> with the SQL arguments already converted to Dart values. Mark a function deterministic when the same input always gives the same output; SQLite then can use it in indexes and generated columns and evaluate it fewer times. Functions are registered per connection, so register them in your openDatabase helper.
Note that median returned 960.0 for ann (the average of 120 and 1800, a double) and 640 for ben (the middle element, an int): whatever Dart value you return is converted back to the matching SQLite type.
JSON
SQLite has built-in JSON functions that work on JSON stored as text. -> extracts a JSON fragment, ->> extracts an SQL value, json_each turns an array into rows, and json_object / json_group_array build JSON. Combined with jsonEncode / jsonDecode from dart:convert (see JSON), that gives you a flexible document store:
import 'dart:convert';
import 'package:sqlite3/sqlite3.dart';
void main() {
final db = sqlite3.openInMemory();
db.execute(r'''
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL CHECK (json_valid(data)),
customer TEXT GENERATED ALWAYS AS (data ->> '$.customer') VIRTUAL
);
CREATE INDEX orders_customer ON orders (customer);
''');
final orders = [
{'customer': 'ann', 'items': [{'sku': 'KB-01', 'qty': 1, 'price': 49.9}], 'gift': false},
{'customer': 'ben', 'items': [{'sku': 'MS-01', 'qty': 2, 'price': 19.99}, {'sku': 'KB-01', 'qty': 1, 'price': 49.9}]},
{'customer': 'ann', 'items': [{'sku': 'MN-27', 'qty': 1, 'price': 279.0}], 'gift': true},
];
final insert = db.prepare('INSERT INTO orders (data) VALUES (?)');
for (final o in orders) {
insert.execute([jsonEncode(o)]);
}
insert.close();
// ->> extracts an SQL value, -> extracts JSON text.
final rows = db.select(r'''
SELECT id, customer, data -> '$.items[0]' AS first_item, data ->> '$.gift' AS gift
FROM orders WHERE customer = ?
''', ['ann']);
for (final r in rows) {
final item = jsonDecode(r['first_item'] as String) as Map<String, dynamic>;
print('order ${r['id']} ${r['customer']}: first sku ${item['sku']}, gift=${r['gift']}');
}
// json_each turns an array into rows, so normal SQL aggregation works on it.
final totals = db.select(r'''
SELECT o.customer,
sum(i.value ->> '$.qty' * (i.value ->> '$.price')) AS total
FROM orders o, json_each(o.data, '$.items') i
GROUP BY o.customer ORDER BY o.customer
''');
print(totals);
// Build JSON in SQL and decode it in Dart.
final summary = db.select(r'''
SELECT json_group_array(json_object('id', id, 'n', json_array_length(data, '$.items'))) AS j
FROM orders
''').first['j'] as String;
print(jsonDecode(summary));
db.close();
}
Output:
order 1 ann: first sku KB-01, gift=0
order 3 ann: first sku MN-27, gift=1
[{customer: ann, total: 328.9}, {customer: ben, total: 89.88}]
[{id: 1, n: 1}, {id: 2, n: 2}, {id: 3, n: 1}]
The generated column customer is computed from the JSON on read (VIRTUAL) and can be indexed, so WHERE customer = ? uses the index instead of parsing every document. Use raw strings (r'''...''') for SQL with JSON paths, otherwise Dart treats $.items as string interpolation.
JSON true / false come back from ->> as 1 / 0. For speed, SQLite also has a binary JSON format, JSONB; the package exports a jsonb codec that encodes Dart objects to JSONB blobs directly.
Full-text search with FTS5
The FTS5 extension builds an inverted index for fast word search with ranking and highlighting. An "external content" FTS table indexes columns of a normal table, and triggers keep it in sync:
import 'package:sqlite3/sqlite3.dart';
void main() {
final db = sqlite3.openInMemory();
db.execute('''
CREATE TABLE articles (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL);
-- External-content FTS5 index over articles(title, body).
CREATE VIRTUAL TABLE articles_fts USING fts5(
title, body, content='articles', content_rowid='id', tokenize='porter unicode61'
);
-- Keep the index in sync with the table.
CREATE TRIGGER articles_ai AFTER INSERT ON articles BEGIN
INSERT INTO articles_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER articles_ad AFTER DELETE ON articles BEGIN
INSERT INTO articles_fts(articles_fts, rowid, title, body)
VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER articles_au AFTER UPDATE ON articles BEGIN
INSERT INTO articles_fts(articles_fts, rowid, title, body)
VALUES ('delete', old.id, old.title, old.body);
INSERT INTO articles_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
''');
final insert = db.prepare('INSERT INTO articles (title, body) VALUES (?, ?)');
for (final (title, body) in [
('Async and await', 'Futures complete later; await suspends the function until the future completes.'),
('Isolates', 'Isolates run Dart code in parallel. Each isolate has its own memory and event loop.'),
('Streams', 'A stream delivers a sequence of asynchronous events. Use await for to consume it.'),
('SQLite', 'SQLite is an embedded database. Queries run synchronously in the calling isolate.'),
]) {
insert.execute([title, body]);
}
insert.close();
final search = db.prepare('''
SELECT a.id, a.title,
snippet(articles_fts, 1, '[', ']', '...', 10) AS snip
FROM articles_fts
JOIN articles a ON a.id = articles_fts.rowid
WHERE articles_fts MATCH ?
ORDER BY bm25(articles_fts, 10.0, 1.0)
''');
for (final q in ['isolate', 'await AND future', 'title:streams OR sqlite', '"event loop"', 'async*']) {
final hits = search.select([q]);
print('$q -> ${hits.length} hit(s)');
for (final h in hits) {
print(' ${h['id']} ${h['title']}: ${h['snip']}');
}
}
search.close();
try {
db.select('SELECT rowid FROM articles_fts WHERE articles_fts MATCH ?', ['C++ (']);
} on SqliteException catch (e) {
print('bad query: ${e.message}');
}
db.close();
}
Output:
isolate -> 2 hit(s)
2 Isolates: ...Each [isolate] has its own memory and event loop.
4 SQLite: ...Queries run synchronously in the calling [isolate].
await AND future -> 1 hit(s)
1 Async and await: [Futures] complete later; [await] suspends the function until the [future]...
title:streams OR sqlite -> 2 hit(s)
4 SQLite: [SQLite] is an embedded database. Queries run synchronously in the...
3 Streams: A stream delivers a sequence of asynchronous events. Use await...
"event loop" -> 1 hit(s)
2 Isolates: ...Each isolate has its own memory and [event loop].
async* -> 2 hit(s)
1 Async and await: Futures complete later; await suspends the function until the future...
3 Streams: A stream delivers a sequence of [asynchronous] events. Use await...
bad query: fts5: syntax error near "+"
How it works:
tokenize='porter unicode61'splits text into words in a Unicode-aware way and applies Porter stemming, soisolatealso matchesisolatesandasync*(a prefix query) matchesasynchronous.- The
MATCHquery language supportsAND,OR,NOT,"phrases",prefix*andcolumn:term. bm25()returns a relevance score where lower is better; the arguments weight the columns (a match intitlecounts 10 times as much as inbody).snippet()returns a fragment of a column with the matches marked.- User input that isn't valid query syntax throws
SqliteException. To search for the literal text the user typed, quote it as a phrase:'"${input.replaceAll('"', '""')}"'.
Schema migrations with user_version
Each SQLite database has a free integer in its header, PRAGMA user_version, which the package exposes as db.userVersion. It's the natural place to record which schema version a database file has. Store migrations as an ordered list and apply the missing ones at startup, each in its own transaction:
import 'dart:io';
import 'package:sqlite3/sqlite3.dart';
/// Each entry upgrades the schema by one version. Never edit or reorder
/// entries that have shipped; only append new ones.
const migrations = <String>[
// 1
'''
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
''',
// 2
'''
ALTER TABLE users ADD COLUMN email TEXT;
CREATE UNIQUE INDEX users_email ON users (email);
''',
// 3
'''
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title TEXT NOT NULL
);
''',
];
void migrate(Database db) {
final current = db.userVersion;
if (current > migrations.length) {
throw StateError('database version $current is newer than this app (${migrations.length})');
}
for (var v = current; v < migrations.length; v++) {
db.execute('BEGIN IMMEDIATE');
try {
db.execute(migrations[v]);
db.userVersion = v + 1;
db.execute('COMMIT');
print(' migrated to version ${v + 1}');
} catch (_) {
db.execute('ROLLBACK');
rethrow;
}
}
}
void main() {
final dir = Directory.systemTemp.createTempSync('sqlite_migrate');
final path = '${dir.path}/app.db';
for (var run = 1; run <= 2; run++) {
print('run $run');
final db = sqlite3.open(path);
migrate(db);
print(' version ${db.userVersion}, tables: '
'${db.select("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name").map((r) => r['name']).toList()}');
db.close();
}
dir.deleteSync(recursive: true);
}
Output:
run 1
migrated to version 1
migrated to version 2
migrated to version 3
version 3, tables: [posts, users]
run 2
version 3, tables: [posts, users]
Schema changes (CREATE, ALTER) are transactional in SQLite, so a failed migration leaves the database at the previous version. ALTER TABLE is limited (you can add, rename and drop columns, but not change a column's type or constraints). For bigger changes, create a new table, copy the data with INSERT INTO new SELECT ... FROM old, drop the old table and rename the new one, all in one migration.
Isolates, change notifications and backups
A Database object wraps a native pointer and can't be sent to another isolate. To run a slow query without blocking the main isolate (in Flutter: without dropping frames), open a second connection in the worker isolate. With WAL mode, it can read while the main connection writes:
import 'dart:io';
import 'dart:isolate';
import 'package:sqlite3/sqlite3.dart';
/// Runs a slow report in a background isolate. A Database can't be sent
/// between isolates, so the worker opens its own connection to the same file.
Future<List<(String, int)>> topSensors(String path) => Isolate.run(() {
final db = sqlite3.open(path, mode: OpenMode.readOnly);
try {
return db
.select('''
SELECT sensor, count(*) AS n FROM readings
GROUP BY sensor ORDER BY n DESC, sensor LIMIT 3
''')
.map((r) => (r['sensor'] as String, r['n'] as int))
.toList();
} finally {
db.close();
}
});
Future<void> main() async {
final dir = Directory.systemTemp.createTempSync('sqlite_iso');
final path = '${dir.path}/data.db';
final db = sqlite3.open(path)..execute('PRAGMA journal_mode = WAL');
db.execute('CREATE TABLE readings (id INTEGER PRIMARY KEY, sensor TEXT, value REAL)');
// Change notifications for this connection.
final sub = db.updates.listen((u) => print('update: ${u.kind.name} ${u.tableName} rowid=${u.rowId}'));
db.execute("INSERT INTO readings (sensor, value) VALUES ('a', 1.5)");
db.execute("UPDATE readings SET value = 2.0 WHERE sensor = 'a'");
db.execute("DELETE FROM readings WHERE sensor = 'a'");
await Future<void>.delayed(Duration.zero); // let the stream deliver events
await sub.cancel();
final insert = db.prepare('INSERT INTO readings (sensor, value) VALUES (?, ?)');
db.execute('BEGIN');
for (var i = 0; i < 50000; i++) {
insert.execute([i % 10 < 5 ? 'boiler' : (i % 10 < 8 ? 'attic' : 'garage'), i.toDouble()]);
}
db.execute('COMMIT');
insert.close();
final top = await topSensors(path);
print('top sensors: $top');
// Online backup into a new file, with progress.
final backupPath = '${dir.path}/backup.db';
final target = sqlite3.open(backupPath);
await for (final progress in db.backup(target, nPage: 100)) {
if (progress == 1) print('backup done');
}
print('backup rows: ${target.select('SELECT count(*) AS n FROM readings').first['n']}');
target.close();
// Or write a compacted copy with plain SQL.
db.execute('VACUUM INTO ?', ['${dir.path}/compact.db']);
print('compact.db exists: ${File('${dir.path}/compact.db').existsSync()}');
db.close();
dir.deleteSync(recursive: true);
}
Output:
update: insert readings rowid=1
update: update readings rowid=1
update: delete readings rowid=1
top sensors: [(boiler, 25000), (attic, 15000), (garage, 10000)]
backup done
backup rows: 50000
compact.db exists: true
Isolate.runstarts an isolate, runs the closure and returns its result. Records, lists and strings are copied back to the caller. See Isolates for more.db.updatesis aStream<SqliteUpdate>reporting every row that this connection inserts, updates or deletes. It's handy for refreshing a UI or invalidating a cache (see Caching). Changes made by other connections are not reported. The events are delivered asynchronously, which is why the example yields to the event loop before cancelling the subscription.db.commitsanddb.rollbacksare similar streams for transactions.db.backup(target)copies a live database page by page using SQLite's online backup API and reports progress from 0 to 1. Other connections can keep using the source database while it runs.VACUUM INTO 'file'writes a compacted, defragmented copy of the database in one statement.
If you want this all done for you, package:drift (introduced in Relational databases) runs SQLite in a background isolate with NativeDatabase.createInBackground and turns queries into auto-updating Streams.
Locking and error codes
SQLite allows many readers but only one writer at a time per database file. When a connection can't get the write lock within busy_timeout, the statement fails with SQLITE_BUSY ("database is locked"). Other errors carry their own result codes:
import 'dart:io';
import 'package:sqlite3/sqlite3.dart';
void main() {
final dir = Directory.systemTemp.createTempSync('sqlite_err');
final path = '${dir.path}/app.db';
final writer = sqlite3.open(path)..execute('PRAGMA journal_mode = WAL');
writer.execute('CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL)');
final other = sqlite3.open(path)..execute('PRAGMA busy_timeout = 200');
writer.execute('BEGIN IMMEDIATE'); // takes the write lock
writer.execute("INSERT INTO kv VALUES ('a', '1')");
// Readers are not blocked in WAL mode; they see the last committed state.
print('reader sees ${other.select('SELECT count(*) AS n FROM kv').first['n']} rows');
final sw = Stopwatch()..start();
try {
other.execute("INSERT INTO kv VALUES ('b', '2')");
} on SqliteException catch (e) {
print('waited ${sw.elapsedMilliseconds >= 200 ? '>= 200 ms' : '?'}, '
'code ${e.resultCode}: ${e.message}');
}
writer.execute('COMMIT');
final cases = {
'unique': "INSERT INTO kv VALUES ('a', 'dup')",
'not null': "INSERT INTO kv VALUES ('c', NULL)",
'syntax': 'SELEC * FROM kv',
'no table': 'SELECT * FROM missing',
};
for (final MapEntry(:key, :value) in cases.entries) {
try {
other.execute(value);
} on SqliteException catch (e) {
print('$key: ${e.resultCode}/${e.extendedResultCode} ${e.message}');
}
}
other.close();
writer.close();
dir.deleteSync(recursive: true);
}
Output:
reader sees 0 rows
waited >= 200 ms, code 5: database is locked
unique: 19/1555 UNIQUE constraint failed: kv.k
not null: 19/1299 NOT NULL constraint failed: kv.v
syntax: 1/1 near "SELEC": syntax error
no table: 1/1 no such table: missing
resultCode is the primary code (5 = SQLITE_BUSY, 19 = SQLITE_CONSTRAINT, 1 = SQLITE_ERROR) and extendedResultCode narrows it down (1555 = SQLITE_CONSTRAINT_PRIMARYKEY, 1299 = SQLITE_CONSTRAINT_NOTNULL, 2067 = SQLITE_CONSTRAINT_UNIQUE, 787 = SQLITE_CONSTRAINT_FOREIGNKEY). Check codes rather than parsing messages. The package also exports the constants in SqlError and SqlExtendedError, for example SqlExtendedError.SQLITE_CONSTRAINT_UNIQUE.
If you see "database is locked" even with a timeout, look for a transaction that stays open too long (a BEGIN without COMMIT, or slow work between them) or for a deferred transaction upgrading from read to write.
Best practices
- Open one connection per isolate and keep it for the lifetime of the app. Opening is cheap, but pragmas, custom functions and prepared statements are per connection. Put all setup in one
openDatabasefunction. - Turn on WAL mode,
foreign_keysand abusy_timeouton every connection. - Wrap related writes and all bulk inserts in a transaction, and use
BEGIN IMMEDIATEfor transactions that write. - Use
STRICTtables to catch type mix-ups early, and store dates consistently (Unix milliseconds or ISO-8601 UTC). - Always bind values with parameters, never interpolate them into SQL.
- Close prepared statements and databases in
finallyblocks. - Move slow queries off the main isolate, especially in Flutter.
- Version your schema with
user_versionand append-only migrations. - Back up with
db.backuporVACUUM INTO, not by copying the file while it's open. - Use in-memory databases in tests:
sqlite3.openInMemory()is fast and gives every test a clean database (see Parameterized tests).