angel3_orm_sqlite 10.0.0
angel3_orm_sqlite: ^10.0.0 copied to clipboard
SQLite support for Angel3 ORM, on sqlite_async or sqlite3. Includes functionality for querying and transactions.
Angel3 ORM for SQLite #
SQLite support for Angel3 ORM. SQLite 3.35 or later is required. It has two executors:
SqliteAsyncExecutor |
SqliteExecutor |
|
|---|---|---|
| Driver | sqlite_async |
sqlite3 |
| Statements run | in background isolates: they do not block the isolate that gives them | on the isolate that gives them, which waits for each |
| Connections | a pool of one that writes and several that read, in WAL mode | one |
| A query that reads, outside a transaction | runs at once, on a connection that reads, and sees the rows as they were before the transaction; on one connection, waits for the transaction to end | waits for the transaction to end |
| In-memory database | only on one 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. Do not open the same connection with both at once: each executor tracks the transactions of the database object it is given, so transactions of the two would not wait for each 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();
}
Or, 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 its write lock, a transaction fails at once with database is locked. To wait for it instead, set one, e.g. database.execute('PRAGMA busy_timeout = 5000'). sqlite_async sets its own.
SqliteAsyncExecutor also takes one connection of a sqlite3 database, such as one in memory for tests. On one connection, a query that reads waits for a transaction too, 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()),
),
);
close() closes the database once its transactions, and the queries given before it, have ended; calling it again returns the same close. A query or a transaction given outside a transaction after it is called fails at once: it returns a Future that fails with a StateError.
Migrations #
Create the tables with the migrations of the models and SqliteMigrationRunner of angel3_migration_runner 10.1.0 or later, which takes a database of sqlite3. For SqliteAsyncExecutor, run them on the file before opening 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 begins with BEGIN IMMEDIATE, so it holds the write lock of the database for its whole length. A query given outside it that writes waits for it to end. One that only reads, a SELECT, does too with SqliteExecutor, whose one connection the transaction holds, but not with SqliteAsyncExecutor, which reads on a connection of its own, unless it has one connection.
- Give the queries of a transaction to the executor its callback gets. They run in the transaction from anywhere, such as a stream listener made before it. A query given to another executor of the database runs in it only from the code of the callback; from elsewhere it is outside it, and one that waits for it to end, as above, must not be awaited by it. With
SqliteAsyncExecutor, do not give statements to theSqliteDatabaseitself in a transaction:sqlite_asyncthrows aLockErrorfor them. - A transaction in a transaction is a
SAVEPOINT, rolled back alone if its callback fails. An update or a delete of the ORM makes one. Savepoints run one at a time: a statement of the transaction given while one runs, as ofFuture.waitof several updates, waits for it to end. So a savepoint's callback must not wait for a statement given to the transaction's executor from outside its own code, such as by a stream listener made before it: the statement waits for the savepoint, and the savepoint for it. - With
SqliteAsyncExecutor, the statements of a transaction run one at a time, so that none runs after one that SQLite rolled the transaction back for. Transactions of separate requests run one after the other, as SQLite writes one at a time; the reads outside them do not wait. - The transaction waits for the queries given in it that were not awaited before it commits. A statement given to it while it commits or rolls back, or to its executor afterwards, fails with a
StateError, rather than running outside it. Code of its callback that runs later, such as a timer, and gives a statement or a transaction to another executor of the database, or closes it, fails with aStateErrorwhile the transaction commits or rolls back. Once it has ended, withSqliteExecutorthe statement runs outside it, as code afterawait executor.transaction(...)does; withSqliteAsyncExecutorit fails with aLockErrorofsqlite_async, which remembers its lock in the zone of the callback. - If SQLite rolls back the whole transaction after an error, as
RAISE(ROLLBACK)of a trigger 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, 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 (a List<int> too) |
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 does not know the type of a column, so it stores any other List<int> as JSON text.
A query's @name placeholders are bound by position; a query with one that has no value fails with an ArgumentError, as SQLite would read it as a parameter of its own. This includes an @word in an SQL comment of raw SQL, such as -- @todo, or in a name in square brackets, such as [col@x]; quote such a name with double quotes instead. One in a quoted string is not a placeholder.
Known limitations #
- Connection state with
SqliteAsyncExecutor: Outside a transaction, aSELECTruns on any connection that reads, so one of the state of the connection that writes, such asSELECT last_insert_rowid()orchanges(), gives the wrong value. Run it in a transaction, with the statement it is of - Backslashes in raw SQL: The placeholders of raw SQL are found by the parser of
angel3_orm, which reads\'in a quoted string as an escaped quote, as MySQL does, though SQLite does not. 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: If a savepoint fails and rolling it back fails too, which is rare,sqlite_asyncignores the error of the rollback, so the writes of the savepoint may be committed with the transaction.SqliteExecutorrolls back the whole transaction instead - Dates: The parts of a date (
where.createdAt.year, ...) useEXTRACT, which SQLite does not have, and a comparison without the time (includeTime: false) compares text, which matches no stored time withequals - JSON: The JSON queries (
where.data.property, ...) are of PostgreSQL. A JSON column is read back as text, not as aMapor aList skipLocked: It has no effect, as SQLite locks the whole database, not rows