sqflite
for Flutter inspired by sqlbrite
pubspec.yaml
dependencies:
...
sqlbrite: <latest_version>
$ flutter packages get
import 'package:sqlbrite/sqlbrite.dart';
BriteDatabase
:final Database db = await openDb();
final briteDb = BriteDatabase(db);
final briteDb = BriteDatabase(db, logger: null); // disable logging.
BriteDatabase.createQuery
method is similar to Database.query
. Listen to the returned Stream<Query>
which will immediately notify with a Query
to run.BriteDatabase
.class Entity {
factory Entity.fromJson(Map<String, dynamic> map) { ... }
factory Entity.empty() { ... }
Map<String, dynamic> toJson() { ... }
}
mapToOne
extension method on Stream<Query>
// Emits a single row, emit error if the row doesn't exist or more than 1 row in result set.
final Stream<Entity> singleQuery$ = briteDb.createQuery(
'table',
where: 'id = ?',
whereArgs: [id],
limit: 1,
).mapToOne((row) => Entity.fromJson(row));
mapToOneOrDefault
extension method on Stream<Query>
// Emits a single row, or the given default value if the row doesn't exist, or emit error if more than 1 row in result set
final Stream<Entity> singleOrDefaultQuery$ = briteDb.createQuery(
'table',
where: 'id = ?',
whereArgs: [id],
limit: 1,
).mapToOneOrDefault(
(row) => Entity.fromJson(row),
defaultValue: Entity.empty()
);
mapToList
extension method on Stream<Query>
// Emits a list of rows.
final Stream<List<Entity>> listQuery$ = briteDb.createQuery(
'table',
where: 'name LIKE ?',
whereArgs: [queryName],
).mapToList((row) => Entity.fromJson(row));
Database
// will trigger query stream again
briteDb.insert(
'table',
Entity(...).toJson()
);
// will trigger query stream again
briteDb.update(
'table',
Entity(...).toJson(),
where: 'id = ?',
whereArgs: [id],
);
// will trigger query stream again
briteDb.update(
'table',
where: 'id = ?',
whereArgs: [id],
);
RxDart
operatorsbriteDb
.createQuery(
'table',
where: 'name LIKE ?',
whereArgs: [queryName],
)
.debounceTime(const Duration(milliseconds: 500))
.where(filterQuery) // query is lazy, this lets you not even execute it if you don't need to
.mapToList((row) => Entity.fromJson(row))
.listen(updateUI);
SQL Brite's only responsibility is to be a mechanism for coordinating and composing the notification of updates to tables such that you can update queries as soon as data changes.
This library is not an ORM. It is not a type-safe query mechanism. It's not going to perform database migrations for you.
MIT License
Copyright (c) 2019 - 2022 Petrus Nguyễn Thái Học