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 aMap<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, booleanCHECK;NOT NULLonly together with aDEFAULT). Columns are never dropped or renamed. Defaults tofalse.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 = ONis set when the database opens, so thefKeysof the entities are enforced. Set it before the first access (or call closeDB to apply it). Defaults tofalse, 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
nabove the database version (PRAGMA user_version) runs once, in increasing order, in its own transaction, which then sets the version ton. 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,nullor[]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 asfalse,nullor[]throw the real error instead. "Nothing found" is stillnullor[]. Defaults tofalse, 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_webputs it in the application'sweb/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
trueif the entity tableTexists. -
checkIfTableExists(
String table) → Future< bool> -
Returns
trueif a table namedtableexists. -
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 byafterWhereandwhereArgs. -
createTableIfNotExists(
Object entity) → Future< void> -
Creates the entity table for
entityif it does not exist yet, with theindexesanduniqueIndexesit 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
TmatchingafterWhere(?placeholders take their values fromwhereArgs). WhenafterWhereis 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
TmatchingwhereColumns/whereArgs. -
dropDB(
String dbPath) → Future< void> -
Deletes the database file located at
dbPath. -
dropTable<
T> () → Future< void> -
Drops the entity table
Tif 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 usingkey. Files saved by name before 2.1 are not in that list: pass their names inalsoFiles. 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
Tmatching theafterWhereclause, ornullwhen no row matches.?placeholders inafterWheretake their values fromwhereArgs. -
getAColumnFrom<
C, T> (String columnName, {String? afterWhere, List< Object?> ? whereArgs}) → Future<List< C> > -
Returns every value of column
columnName(typed asC) from the entity tableT, optionally filtered byafterWhereandwhereArgs. -
getAColumnFromWithTableName<
T> (String columnName, String table, {String? afterWhere, List< Object?> ? whereArgs}) → Future<List< T> > -
Like getAColumnFrom but accepts an arbitrary
tablename (or a join expression). Useful for querying non-entity tables such assqlite_masteror to run joined queries with table aliases. -
getAll<
T> (Object tableEntityInstance) → Future< List< T> ?> -
Returns every object of type
Tcurrently stored, ornullwhen the table is empty. -
getAllSorted<
T> (Object tableEntityInstance, String afterWhere, [List< Object?> ? whereArgs]) → Future<List< T> ?> -
Returns every object of type
TmatchingafterWhere, ornullwhen no row matches. Sort by puttingORDER BYat the end ofafterWhere;?placeholders take their values fromwhereArgs. -
getEntityColumnsName<
T> () → Future< List< String> > -
Returns the list of column names of the entity table
Tas 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=identifierValueandpasswordColumnName=passwordValueagainst the entity tableT. -
getSomeColumnsFrom<
T> (String listDesColonne, {String? afterWhere, List< Object?> ? whereArgs}) → Future<List< Map< >String, Object?> > -
Returns raw rows (as
List<Map<String, Object?>>) for the columnslistDesColonneof the entity tableT. -
getSommeColumnsWithTableName(
String listDesColonne, String table, {String? afterWhere, List< Object?> ? whereArgs}) → Future<List< Map< >String, Object?> > -
Like getSomeColumnsFrom but takes an arbitrary
tablename (or a join expression). Useful for non-entity tables or join queries. -
insertObjet(
Object? object, {bool orReplace = false}) → Future< bool> -
Inserts
objectinto 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
dbPathand returns it. -
query<
T> (Object tableEntityInstance, {String? where, List< Object?> ? whereArgs, String? orderBy, int? limit, int? offset}) → Future<List< T> > -
Entities of type
Tmatchingwhere(?placeholders take their values fromwhereArgs), sorted byorderBy(inserted as is: never from user input),limitrows fromoffset. Returns[]when nothing matches. -
rawExecute(
String sql, [List< Object?> ? args]) → Future<int> -
Runs any other statement with
?placeholders bound toargsand returns the number of rows it changed. -
rawQuery(
String sql, [List< Object?> ? args]) → Future<List< Map< >String, Object?> > -
Runs a SELECT with
?placeholders bound toargsand 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
fromMapoftableEntityInstance. -
registerEntity<
T> (String tableName) → void -
The table of the entity class
TistableNameinstead of the class name. Every method follows it, whether it receives an instance or only the typeT. 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 TABLEstatement generated forentitybased on the getters (pKeyAuto,notNulls,uniques,checks,defaults,fKeys) and the types declared intoMap(). -
toString(
) → String -
A string representation of this object.
inherited
-
transaction<
R> (Future< R> action()) → Future<R> -
Runs
actionin a transaction: everything or nothing. The DataAccess methods called insideactiontake part in it; a transaction started inside a transaction joins it. Inside a transaction a failing method throws instead of returningfalse(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
keyfrom 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