Angel3 ORM for SQLite
SQLite support for Angel3 ORM. It needs SQLite 3.35 or later.
Choosing an executor
The package has two executors:
SqliteAsyncExecutor |
SqliteExecutor |
|
|---|---|---|
| Driver | sqlite_async |
sqlite3 |
| Where statements run | In background isolates, so they don't block your isolate | On your isolate, which waits for each one |
| Connections | A pool in WAL mode: one connection writes, several read | One |
| A read outside a transaction, while a transaction runs | Runs at once on a reading connection, and sees the rows as they were before the transaction. With a single connection, it waits for the transaction to end | Waits for the transaction to end |
| In-memory database | Only with a single connection (see below) | Yes |
| Use it for | A server | Tests, command-line programs, scripts |
Both store values the same way, so a database written by one can be read by the other.
Don't open the same database object with both at once. Each executor tracks the transactions of the database object it is given, so transactions of one wouldn't wait for those of the other.
Usage
dependencies:
angel3_orm: ^10.2.0
angel3_orm_sqlite: ^10.0.0
sqlite_async: ^0.14.7 # for SqliteAsyncExecutor
sqlite3: ^3.9.0 # for SqliteExecutor
import 'package:angel3_orm_sqlite/angel3_orm_sqlite.dart';
import 'package:sqlite_async/sqlite_async.dart';
Future<void> main() async {
var executor = SqliteAsyncExecutor(SqliteDatabase(path: 'app.db'));
// The queries generated by `angel3_orm_generator`, e.g.
var todo = await (TodoQuery()..values.title = 'Write docs').insert(executor);
print(todo.value.title);
await executor.close();
}
With sqlite3
import 'package:angel3_orm_sqlite/angel3_orm_sqlite.dart';
import 'package:sqlite3/sqlite3.dart';
var executor = SqliteExecutor(sqlite3.open('app.db'));
sqlite3 opens a database with no busy timeout. If another connection or process holds the write lock, a transaction fails at once with database is locked. To wait instead, set a timeout, for example database.execute('PRAGMA busy_timeout = 5000'). sqlite_async sets its own.
One connection, or in memory
SqliteAsyncExecutor can also run on a single connection of a sqlite3 database, such as one in memory for tests. With a single connection, a read waits for a running transaction, as with SqliteExecutor.
import 'package:angel3_orm_sqlite/angel3_orm_sqlite.dart';
import 'package:sqlite3/sqlite3.dart';
import 'package:sqlite_async/sqlite_async.dart';
var executor = SqliteAsyncExecutor(
SqliteDatabase.singleConnection(
SqliteConnection.synchronousWrapper(sqlite3.openInMemory()),
),
);
Closing
close() closes the database once its transactions, and the queries given before the call, have ended. Calling it again returns the same Future.
After close() is called, a query or transaction given outside a transaction fails at once. It returns a Future that fails with a StateError.
Migrations
Create the tables with your models' migrations and the SqliteMigrationRunner of angel3_migration_runner 10.1.0 or later. The runner takes a sqlite3 database. For SqliteAsyncExecutor, run the migrations on the file before you open it with sqlite_async:
import 'package:angel3_migration_runner/sqlite.dart';
import 'package:angel3_orm_sqlite/angel3_orm_sqlite.dart';
import 'package:sqlite3/sqlite3.dart';
import 'package:sqlite_async/sqlite_async.dart';
Future<SqliteAsyncExecutor> open() async {
var raw = sqlite3.open('app.db');
await SqliteMigrationRunner(raw, migrations: [TodoMigration()]).up();
raw.close();
return SqliteAsyncExecutor(SqliteDatabase(path: 'app.db'));
}
Transactions
executor.transaction starts with BEGIN IMMEDIATE, so it holds the database's write lock for as long as it runs.
- A write given outside the transaction waits for it to end.
- A read (
SELECT) given outside the transaction depends on the executor:- With
SqliteExecutor, it also waits, because the transaction holds the only connection. - With
SqliteAsyncExecutor, it doesn't wait, because it runs on a reading connection of its own. The exception is a single connection, where it waits too.
- With
Which executor to use inside a transaction
Give the transaction's queries to the executor that its callback receives. Those queries run inside the transaction wherever they are given from, even from a stream listener created before the transaction.
A query given to another executor of the same database works differently:
- It runs inside the transaction only when it is given from the callback's own code.
- From anywhere else, it runs outside the transaction. If it is one that waits for the transaction to end (see above), the transaction must not await it, or the two wait for each other.
With SqliteAsyncExecutor, don't give statements to the SqliteDatabase itself during a transaction. sqlite_async throws a LockError for them.
Nested transactions and savepoints
A transaction inside a transaction is a SAVEPOINT. If its callback fails, only the savepoint is rolled back. The ORM's updates and deletes each make one.
Savepoints run one at a time. A statement given to the transaction while a savepoint runs, for example from Future.wait over several updates, waits for the savepoint to end.
So a savepoint's callback must not wait for a statement that was given to the transaction's executor from outside the callback's own code, such as by a stream listener created earlier. That statement waits for the savepoint, and the savepoint would wait for it.
Statements run one at a time
- Within a transaction. With
SqliteAsyncExecutor, a transaction's statements run one at a time. That way, nothing runs after a statement that made SQLite roll the transaction back. - Across requests. Transactions from separate requests run one after another, because SQLite allows only one writer at a time. Reads outside them don't wait.
Ending a transaction
- Before it commits. The transaction waits for the queries given in it that weren't awaited.
- While it commits or rolls back:
- A statement given to the transaction fails with a
StateError, rather than running outside it. - Some code of the callback runs later, such as a timer. If that code gives a statement or a transaction to another executor of the database, or closes it, the call also fails with a
StateError.
- A statement given to the transaction fails with a
- After it has ended. A statement given to its executor fails with a
StateError. Code from the callback that runs later and uses another executor of the database behaves differently by executor:- With
SqliteExecutor, the statement runs outside the transaction, like code afterawait executor.transaction(...). - With
SqliteAsyncExecutor, it fails with aLockErrorfromsqlite_async, which remembers its lock in the callback's zone.
- With
- When SQLite rolls the whole transaction back after an error, as a trigger's
RAISE(ROLLBACK)does, the transaction runs no more statements and throws aStateError, rather than running the rest outside it.
How values are stored
| Dart | SQLite |
|---|---|
DateTime |
UTC text, such as 2024-03-10 12:34:56.000000Z, which sorts in time order. A year before 0 or after 9999 throws an ArgumentError |
bool |
0 or 1 |
Uint8List |
BLOB |
Map, List (including a List<int>) |
JSON text, in which a DateTime is text as above |
A field of a binary, varBinary or varBinaryMax column must be a Uint8List to be stored as a BLOB. The executor doesn't know the column types, so it stores any other List<int> as JSON text.
Placeholders
A query's @name placeholders are bound by position. A query with a placeholder that has no value fails with an ArgumentError, because SQLite would read it as a parameter of its own.
- Comments and bracketed names count. An
@wordin an SQL comment of raw SQL, such as-- @todo, is a placeholder. So is one in a name in square brackets, such as[col@x]. Quote such a name with double quotes instead. - Quoted strings don't count. An
@wordinside a quoted string is not a placeholder.
Known limitations
- Connection state with
SqliteAsyncExecutor. Outside a transaction, aSELECTruns on any reading connection. So a query about the writing connection's state, such asSELECT last_insert_rowid()orchanges(), gives the wrong value. Run it in a transaction, together with the statement it is about. - Backslashes in raw SQL. The placeholders of raw SQL are found by the parser of
angel3_orm. It reads\'in a quoted string as an escaped quote, as MySQL does, though SQLite doesn't. So a string that ends in a backslash, such as'C:\', hides the placeholders after it. Bind the string as a value instead. - Savepoint rollback with
SqliteAsyncExecutor. In rare cases a savepoint fails, and rolling it back fails too.sqlite_asyncthen ignores the rollback error, so the savepoint's writes may be committed with the transaction.SqliteExecutorrolls back the whole transaction instead. - Dates. The date-part queries (
where.createdAt.yearand so on) useEXTRACT, which SQLite doesn't have. A comparison without the time (includeTime: false) compares text, so withequalsit matches no stored time. - JSON. The JSON queries (
where.data.propertyand so on) are written for PostgreSQL. A JSON column is read back as text, not as aMapor aList. skipLocked. It has no effect, because SQLite locks the whole database, not rows.