DataAccess class

High-level API for persisting Dart objects into a local SQLite database.

DataAccess is a singleton: always access it through DataAccess.instance. It abstracts the differences between mobile platforms (Android, iOS, macOS), which use the native sqflite plugin, and desktop platforms (Linux, Windows), which use sqflite_common_ffi.

Entities exposed to this API are plain Dart classes that declare:

  • A toMap() method returning a Map<String, dynamic>.
  • A named constructor fromMap(Map<String, Object?>).
  • An instance method fromMap(Map<String, Object?>) used by generic getters.
  • Optional getters: pKeyAuto, notNulls, uniques, checks, defaults, fKeys.

Filters passed as afterWhere text are inserted as is after WHERE: never build them from user input. Put ? placeholders in them and pass the values in whereArgs instead.

See the package README for a complete usage example.

Properties

autoAddColumns ↔ bool
When true, a column added to an entity is added to its table the first time the table is used (ALTER TABLE ... ADD COLUMN: type, DEFAULT, boolean CHECK; NOT NULL only together with a DEFAULT). Columns are never dropped or renamed. Defaults to false.
getter/setter pair
db → Future<Database>
Opens (or returns the already opened) application database.
no setter
debugOpenCount → int
Number of times the application database was opened (for tests).
no setter
encryptionEnabled → bool
Whether the application database is opened with an encryption key.
no setter
enforceForeignKeys ↔ bool
When true, PRAGMA foreign_keys = ON is set when the database opens, so the fKeys of the entities are enforced. Set it before the first access (or call closeDB to apply it). Defaults to false, because enforcing them could break an application that inserts a child before its parent.
getter/setter pair
hashCode → int
The hash code for this object.
no setterinherited
migrations ↔ Map<int, Future<void> Function()>
Versioned migrations, run when the database opens: each step n above the database version (PRAGMA user_version) runs once, in increasing order, in its own transaction, which then sets the version to n. The DataAccess methods called inside a step take part in its transaction. A failing step is rolled back and makes the opening fail. Set them before the first access.
getter/setter pair
onError ↔ B012ErrorHandler?
Receives every error turned into false, null or [] outside strict mode (the error is also printed with debugPrint, as before).
getter/setter pair
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
strict ↔ bool
When true, methods that report a failure as false, null or [] throw the real error instead. "Nothing found" is still null or []. Defaults to false, the 2.0.3 behaviour.
getter/setter pair
webSqliteWasmUri ↔ Uri?
In a browser, the WebAssembly SQLite to load, relative to the page. Defaults to sqlite3mc.wasm (SQLite3MultipleCiphers, which also opens unencrypted databases). dart run b012_data:setup_web puts it in the application's web/ folder.
getter/setter pair

Methods

changeDB(String? newDBName) → Future<void>
Switches the application database to newDBName.
changeEncryptionKey(String newKey) → Future<void>
Changes the key of the encrypted application database. Files keep their own key, stored inside the encrypted database, so they need no rewriting.
checkIfEntityTableExists<T>() → Future<bool>
Returns true if the entity table T exists.
checkIfTableExists(String table) → Future<bool>
Returns true if a table named table exists.
cleanAllTablesData() → Future<void>
Removes every row from every user-defined table of the database. The tables themselves are kept.
closeDB() → Future<void>
Closes the current application database (if any).
countElementsOf<T>({String expression = '*', String? afterWhere, List<Object?>? whereArgs}) → Future<int>
Counts rows of T, optionally filtered by afterWhere and whereArgs.
createTableIfNotExists(Object entity) → Future<void>
Creates the entity table for entity if it does not exist yet, with the indexes and uniqueIndexes it declares (also created on an existing table when missing). With autoAddColumns, adds the columns the table lacks. Concurrent calls are serialized; a table already seen is not looked up again.
debugClearRegistry() → void
Forgets every registration (tests only).
deleteObjet<T>([String? afterWhere, List<Object?>? whereArgs]) → Future<bool>
Deletes rows of T matching afterWhere (? placeholders take their values from whereArgs). When afterWhere is null every row of the table is removed (the table itself is preserved).
delObjet<T>(List<String> whereColumns, List<Object> whereArgs, {String whereMcop = 'AND'}) → Future<bool>
Deletes every row of T matching whereColumns / whereArgs.
dropDB(String dbPath) → Future<void>
Deletes the database file located at dbPath.
dropTable<T>() → Future<void>
Drops the entity table T if it exists.
encryptDatabase(String key, {Iterable<String> alsoFiles = const <String>[]}) → Future<void>
Encrypts in place, with key, the unencrypted application database and the files DiscData saved by name (it keeps their list), then keeps using key. Files saved by name before 2.1 are not in that list: pass their names in alsoFiles. Nothing else in the files folder is touched (on Android it is shared with other plugins). Safe to call again after an interruption: what is already encrypted is kept, the rest is encrypted.
get<T>(Object tableEntityInstance, String afterWhere, [List<Object?>? whereArgs]) → Future<T?>
Returns a single entity of type T matching the afterWhere clause, or null when no row matches. ? placeholders in afterWhere take their values from whereArgs.
getAColumnFrom<C, T>(String columnName, {String? afterWhere, List<Object?>? whereArgs}) → Future<List<C>>
Returns every value of column columnName (typed as C) from the entity table T, optionally filtered by afterWhere and whereArgs.
getAColumnFromWithTableName<T>(String columnName, String table, {String? afterWhere, List<Object?>? whereArgs}) → Future<List<T>>
Like getAColumnFrom but accepts an arbitrary table name (or a join expression). Useful for querying non-entity tables such as sqlite_master or to run joined queries with table aliases.
getAll<T>(Object tableEntityInstance) → Future<List<T>?>
Returns every object of type T currently stored, or null when the table is empty.
getAllSorted<T>(Object tableEntityInstance, String afterWhere, [List<Object?>? whereArgs]) → Future<List<T>?>
Returns every object of type T matching afterWhere, or null when no row matches. Sort by putting ORDER BY at the end of afterWhere; ? placeholders take their values from whereArgs.
getEntityColumnsName<T>() → Future<List<String>>
Returns the list of column names of the entity table T as currently stored in SQLite. Useful to detect schema drift (columns added or removed on the Dart side).
getLogin<T>(Object tableEntityInstance, String identifierColumnName, String identifierValue, String passwordColumnName, String passwordValue) → Future<T?>
Authenticates a user by matching identifierColumnName=identifierValue and passwordColumnName=passwordValue against the entity table T.
getSomeColumnsFrom<T>(String listDesColonne, {String? afterWhere, List<Object?>? whereArgs}) → Future<List<Map<String, Object?>>>
Returns raw rows (as List<Map<String, Object?>>) for the columns listDesColonne of the entity table T.
getSommeColumnsWithTableName(String listDesColonne, String table, {String? afterWhere, List<Object?>? whereArgs}) → Future<List<Map<String, Object?>>>
Like getSomeColumnsFrom but takes an arbitrary table name (or a join expression). Useful for non-entity tables or join queries.
insertObjet(Object? object, {bool orReplace = false}) → Future<bool>
Inserts object into its corresponding table.
insertObjetList(List<Object?>? objectlist, {bool orReplace = false}) → Future<bool>
Inserts a list of entity objects into their corresponding table.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
openDB(String dbPath) → Future<Database>
Opens a database located at dbPath and returns it.
query<T>(Object tableEntityInstance, {String? where, List<Object?>? whereArgs, String? orderBy, int? limit, int? offset}) → Future<List<T>>
Entities of type T matching where (? placeholders take their values from whereArgs), sorted by orderBy (inserted as is: never from user input), limit rows from offset. Returns [] when nothing matches.
rawExecute(String sql, [List<Object?>? args]) → Future<int>
Runs any other statement with ? placeholders bound to args and returns the number of rows it changed.
rawQuery(String sql, [List<Object?>? args]) → Future<List<Map<String, Object?>>>
Runs a SELECT with ? placeholders bound to args and returns the rows. Booleans and dates are bound as b012_data stores them.
rawQueryAs<T>(Object tableEntityInstance, String sql, [List<Object?>? args]) → Future<List<T>>
Like rawQuery, each row read through fromMap of tableEntityInstance.
registerEntity<T>(String tableName) → void
The table of the entity class T is tableName instead of the class name. Every method follows it, whether it receives an instance or only the type T. Register before using the entity; recommended when the application is obfuscated, since class names then change from one build to the next.
showCreateTable(Object entity) → String
Returns the CREATE TABLE statement generated for entity based on the getters (pKeyAuto, notNulls, uniques, checks, defaults, fKeys) and the types declared in toMap().
toString() → String
A string representation of this object.
inherited
transaction<R>(Future<R> action()) → Future<R>
Runs action in a transaction: everything or nothing. The DataAccess methods called inside action take part in it; a transaction started inside a transaction joins it. Inside a transaction a failing method throws instead of returning false (even outside strict mode), so that every change is rolled back; the error is rethrown.
updateSomeColumnsOf<T>(List<String> columnsToUpadate, List<String> whereColumns, List<Object> values, {String whereMcop = 'AND'}) → Future<bool>
Updates one or more columns of the entity T.
updateWholeObject(Object newObject, List<String> whereColumns, List<Object> values, {String whereMcop = 'AND'}) → Future<bool>
Updates every column of an entity instance except the primary key.
useEncryptionKey(String? key) → Future<void>
Opens the application database with key from now on (null: no key). The database currently open is closed; the next access reopens it.

Operators

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

Static Properties

instance → DataAccess
Global singleton instance.
final