# sqflite 2.4.5

Flutter plugin for SQLite, a self-contained, high-reliability, embedded, SQL database engine.




## Installing
```
export PUB_HOSTED_URL=https://pub.mirror.p-hatan.ir
flutter pub add sqflite
```
Published: 2026-10-21T14:07:10.037023Z
Expected archive SHA-256: 21a9750de2deb464946e9f41c7ddf176e25553618afdfc774868cd454990c06a

Available in cache; verification: upstream_checksum
## Direct dependencies
- flutter: map[sdk:flutter]
- path: >=1.8.0 <3.0.0
- sqflite_android: >=2.4.5 <4.0.0
- sqflite_common: >=2.5.9 <4.0.0
- sqflite_darwin: >=2.4.3 <4.0.0
- sqflite_platform_interface: >=2.4.1 <4.0.0

## Package README (untrusted upstream documentation)
# sqflite

[![pub package](https://img.shields.io/pub/v/sqflite.svg)](https://pub.dev/packages/sqflite)

SQLite plugin for [Flutter](https://flutter.io).
Supports iOS, Android and MacOS.

* Support transactions and batches
* Automatic version managment during open
* Helpers for insert/query/update/delete queries
* DB operation executed in a background thread on iOS and Android

Other platforms support:
* Linux/Windows/DartVM support using [sqflite_common_ffi](https://pub.dev/packages/sqflite_common_ffi)
* Experimental Web support using [sqflite_common_ffi_web](https://pub.dev/packages/sqflite_common_ffi_web).

Usage example: 
* [notepad_sqflite](https://github.com/alextekartik/flutter_app_example/tree/master/notepad_sqflite): Simple flutter notepad working on iOS/Android/Windows/linux/Mac

## Getting Started

To get started, you need to add `sqflite` to your project. Follow the steps below:

1. Open the terminal in your project root. You can do this by pressing `Alt+F12` in Android Studio or `` Ctrl+` `` in VS Code.

2. Run the following command:

```bash
flutter pub add sqflite
```

This command will add a line to your package's `pubspec.yaml` file and run an implicit `flutter pub get`. The added line will look like this:

```yaml
dependencies:
  sqflite: 
```

## Usage example

Import `sqflite.dart`

```dart
import 'package:sqflite/sqflite.dart';
```

### Opening a database

A SQLite database is a file in the file system identified by a path. If relative, this path is relative to the path
obtained by `getDatabasesPath()`, which is the default database directory on Android and the documents directory on iOS/MacOS.

```dart
var db = await openDatabase('my_db.db');
```

There is a basic migration mechanism to handle schema changes during opening.

Many applications use one database and would never need to close it (it will be closed when the application is
terminated). If you want to release resources, you can close the database.

```dart
await db.close();
```

* See [more information on opening a database](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/opening_db.md).
* Full [migration example](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md)

### Raw SQL queries
    
Demo code to perform Raw SQL queries

```dart
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// Delete the database
await deleteDatabase(path);

// open the database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

// Update some record
int count = await database.rawUpdate(
    'UPDATE Test SET name = ?, value = ? WHERE name = ?',
    ['updated name', '9876', 'some name']);
print('updated: $count');

// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
List<Map> expectedList = [
  {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
  {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
];
print(list);
print(expectedList);
assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
count = Sqflite
    .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);

// Delete a record
count = await database
    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);

// Close the database
await database.close();
```

Basic information on SQL [here](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/sql.md).

### SQL helpers

Example using the helpers

```dart
final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';

class Todo {
  int id;
  String title;
  bool done;

  Map<String, Object?> toMap() {
    var map = <String, Object?>{
      columnTitle: title,
      columnDone: done == true ? 1 : 0
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  Todo();

  Todo.fromMap(Map<String, Object?> map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

class TodoProvider {
  Database db;

  Future open(String path) async {
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('''
create table $tableTodo ( 
  $columnId integer primary key autoincrement, 
  $columnTitle text not null,
  $columnDone integer not null)
''');
    });
  }

  Future<Todo> insert(Todo todo) async {
    todo.id = await db.insert(tableTodo, todo.toMap());
    return todo;
  }

  Future<Todo> getTodo(int id) async {
    List<Map> maps = await db.query(tableTodo,
        columns: [columnId, columnDone, columnTitle],
        where: '$columnId = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      return Todo.fromMap(maps.first);
    }
    return null;
  }

  Future<int> delete(int id) async {
    return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> update(Todo todo) async {
    return await db.update(tableTodo, todo.toMap(),
        where: '$columnId = ?', whereArgs: [todo.id]);
  }

  Future close() async => db.close();
}
```

### Read results

Assuming the following read results:

```dart
List<Map<String, Object?>> records = await db.query('my_table');
```

Resulting map items are read-only

```dart
// get the first record
Map<String, Object?> mapRead = records.first;
// Update it in memory...this will throw an exception
mapRead['my_column'] = 1;
// Crash... `mapRead` is read-only
```

You need to create a new map if you want to modify it in memory:

```dart
// get the first record
Map<String, Object?> map = Map<String, Object?>.from(mapRead);
// Update it in memory now
map['my_column'] = 1;
```

### Transaction

Don't use the database but only use the Transaction object in a transaction
to access the database. Keep in mind that the callbacks ```onCreate``` ```onUpgrade``` ```onDowngrade``` are already internally wrapped in a transaction, so there is no need to wrap your statements in a transaction within those callbacks.

```dart
await database.transaction((txn) async {
  // Ok
  await txn.execute('CREATE TABLE Test1 (id INTEGER PRIMARY KEY)');
  
  // DON'T  use the database object in a transaction
  // this will deadlock!
  await database.execute('CREATE TABLE Test2 (id INTEGER PRIMARY KEY)');
});
```

A transaction is committed if the callback does not throw an error. If an error is thrown,
the transaction is cancelled and the same error is re-thrown. So to rollback a transaction one way is to throw an exception.

```dart
try {
   await database.transaction((txn) async {
      await txn.update('TABLE', {'foo': 'bar'});
   });
   // No error, the transaction is committed
} catch (e, st) {
   // this reliably catch if there is a key conflict
   // We know that the transaction is rolled back.
}

try {
  await database.transaction((txn) async {
    // ...
    // cancel the transaction (any error will do)
    throw StateError('cancel transaction');
  });
} catch (e, st) {
  // We know that the transaction is rolled back.
}
```
You can however catch the exception inside the transaction and not rethrow it to commit the transaction. Only the failed statement will not be executed.

```dart
await database.transaction((txn) async {
  // ...
  try {
    await txn.update('TABLE', {'foo': 'bar'});
  } catch (e, st) {
   // this reliably catch if there is a key conflict
   // We know that the transaction is rolled back.
  }
  // ...
  // The transaction will be committed
});
```
### Batch support

To avoid ping-pong between dart and native code, you can use `Batch`:

```dart
batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();
```

Getting the result for each operation has a cost (id for insertion and number of changes for
update and delete), especially on Android where an extra SQL request is executed.
If you don't care about the result and worry about performance in big batches, you can use

```dart
await batch.commit(noResult: true);
```

Warning, during a transaction, the batch won't be committed until the transaction is committed

```dart
await database.transaction((txn) async {
  var batch = txn.batch();
  
  // ...
  
  // commit but the actual commit will happen when the transaction is committed
  // however the data is available in this transaction
  await batch.commit();
  
  //  ...
});
```

By default a batch stops as soon as it encounters an error (which typically reverts the uncommitted changes). You 
can ignore errors so that every successfull operation is ran and committed even if one operation fails:

```dart
await batch.commit(continueOnError: true);
```

## Table and column names

In general it is better to avoid using SQLite keywords for entity names. If any of the following
name is used:

    "add","all","alter","and","as","autoincrement","between","case","check","collate","commit","constraint","create","default","deferrable","delete","distinct","drop","else","escape","except","exists","foreign","from","group","having","if","in","index","insert","intersect","into","is","isnull","join","limit","not","notnull","null","on","or","order","primary","references","select","set","table","then","to","transaction","union","unique","update","using","values","when","where"
    
the helper will *escape* the name i.e.

```dart
db.query('table')
```
will be equivalent to manually adding double-quote around the table name (confusingly here named `table`)

```dart
db.rawQuery('SELECT * FROM "table"');
```

However in any other raw statement (including `orderBy`, `where`, `groupBy`), make sure to escape the name
properly using double quote. For example see below where the column name `group` is not escaped in the columns
argument, but is escaped in the `where` argument.

```dart
db.query('table', columns: ['group'], where: '"group" = ?', whereArgs: ['my_group']);
```

## Supported SQLite types

No validity check is done on values yet so please avoid non supported types [https://www.sqlite.org/datatype3.html](https://www.sqlite.org/datatype3.html)

`DateTime` is not a supported SQLite type. Personally I store them as 
int (millisSinceEpoch) or string (iso8601)

`bool` is not a supported SQLite type. Use `INTEGER` and 0 and 1 values.

More information on supported types [here](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/supported_types.md).

### INTEGER

* Dart type: `int`
* Supported values: from -2^63 to 2^63 - 1

### REAL

* Dart type: `num`

### TEXT

* Dart type: `String`

### BLOB

* Dart type: `Uint8List`

## Current issues

* Due to the way transaction works in SQLite (threads), concurrent read and write transaction are not supported. 
All calls are currently synchronized and transactions block are exclusive. I thought that a basic way to support 
concurrent access is to open a database multiple times but it only works on iOS as Android reuses the same database object.
I also thought a native thread could be a potential future solution however on android accessing the database in another
thread is blocked while in a transaction...

## More

* [How to](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/how_to.md) guide
* [Notes about Desktop support](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/desktop_support.md)
* [Notes about Encryption support](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/encryption_support.md)
* [Notes about Web support](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/web_support.md)
* [Notes about SQLite versions](https://github.com/tekartik/sqflite/blob/master/sqflite/doc/version.md) as some features may not be available depending on the SQLite version.

## Changelog
## 2.4.5

* Mark the transaction closed when SQLite rolled it back by itself on Android
  (`ConflictAlgorithm.rollback`, `RAISE(ROLLBACK)`...), requires sqflite_android 2.4.5 for the fix

## 2.4.4+2

* Remove `flutter/material` import, adapt example to `material_ui`

## 2.4.4

* Add `sqflite-crud-and-transactions`, `sqflite-open-database` and `sqflite-testing-and-platforms` agent skills in `skills/`, installable with `dart run skills@ get`

## 2.4.3

* Requires dart 3.12

## 2.4.2+1

* Requires dart 3.10

## 2.4.2

* Requires dart 3.7

## 2.4.1

* Add darwin extension to allow creating unprotected folder in iOS (issue #924)

## 2.4.0

* Make `sqflite` a federated plugin including `sqflite_android` and `sqflite_darwin` (iOS/macOS) plugins

## 2.3.3+2

* Remove android v1 embedding support
* Use `compileSdk 34` on Android
* `sdk: >= 3.3.0`

## 2.3.2

* Shared iOS/MacOS darwin implementation
* Remove FMDB podspec dependency

## 2.3.1

* Add iOS/MacOS privacy manifest

## 2.3.0

* Dart 3 only

## 2.2.8+4

* Android: Adds a namespace for compatibility with AGP 8.0.
* Android: Use compile SDK 33
* Export global sqflite API
* iOS set minimum deployment target to 11.0

## 2.2.7

* Dart 3 support

## 2.2.6

* uri support for supported implementations.

## 2.2.5

* Fix concurrency issue in database worker pool (chriscui@google.com)
* add android `setLocale` API call support.

## 2.2.4+1

* Experimental logger support.

## 2.2.3-1

* strict-casts and sdk 2.18 support
 
## 2.2.2

* Fix iOS/MacOS FMDB include for non-swift project

## 2.2.1

* Allow multiple threads on Android, thanks to zhenpingcui

## 2.2.1-1

* Fix iOS/MacOS FMDB include

## 2.2.0+3

* Implements `Database.queryCursor()` and `Database.rawQueryCursor()`
* Dependency update
* Initial support of cross isolate safe
* Transaction v2 update

## 2.1.0+1

* Android: fix parameter binding for non string parameters
* Android: fix unit test

## 2.0.4-dev.1

* Android: Allow turning on WAL in the manifest.

## 2.0.3+1

* MacOS: Fix crash when an invalid number of parameters is specified in the query

## 2.0.3

* iOS/Android: Flutter 3.0 support, makes all the channel calls happen on thread pool instead of the UI thread
* iOS/MacOS: make close happen in a background thread

## 2.0.2+1

* Android build: remove jcenter, compile sdk set to 31

## 2.0.1

* Bump default android thread priority to `THREAD_PRIORITY_DEFAULT`

## 2.0.0+4

* `nnbd` support

## 1.3.2+3

* iOS/macOS: Update FMDB to 2.7.5+
* android: Update gradle to 6.5
* fix logs on iOS

## 1.3.1+2

* add `databaseFactory` setter to change the default sqflite factory.
* Fix empty Blob returned as null on MacOS/iOS
* Test using `integration_test`

## 1.3.0+2

* Add sqflite_common dependency

## 1.2.2+1

* Fix iOS warning on FMDB import
* Support pedantic 1.9
* Check arguments in debug mode (print errors only)

## 1.2.1

* Support Android embedding v2
* Add private mixin
* Support iOS/MacOS incremental build

## 1.2.0

* Add MacOS support

## 1.1.8

* support `deleteDatabase` after hot-restart. Existing, if any, single instance database ìs closed
before deletion

## 1.1.7+3

* Bump flutter/dart dependency version (1.9.1/2.5.0)
* Fix hot and warm restart for opened databases on Android
* Add code documentation, code coverage and build badges
* Fix ios example build

## 1.1.6+5

* Open database in a background thread on Android.
* Prevent database deletion on Android when opening a corrupted database in read-only.
* Fix hot restart ROLLBACK warning
* Fix indexed parameter binding on iOS

## 1.1.5

* Add `databaseExists` as a top level function
* handle relative path in `databaseExists` and `deleteDatabase`
* Supports hot-restart while in a transaction on iOS and Android by recovering the database from the
native world and executing `ROLLBACK` to prevent `SQLITE_BUSY` error
* If in a transaction, execute `ROLLBACK` before closing to prevent `SQLITE_BUSY` error

## 1.1.4

* Make all db operation happen in a separate thread on iOS

## 1.1.3

* Fix deadlock issue on iOS when using isolates

## 1.1.2

* Sqflite now uses a thread handler with a background thread priority by default on Android

## 1.1.1

* Use mixin and extract non flutter code into `sqlite_api.dart`
* Deprecate `SqfliteOptions` which is only used internally

## 1.1.0

* **Breaking change**. Migrate from the deprecated original Android Support
    Library to AndroidX. This shouldn't result in any functional changes, but it
    requires any Android apps using this plugin to [also
    migrate](https://developer.android.com/jetpack/androidx/migrate) if they're
    using the original support library.
    
    You might say thay version should be bumped to 2.0.0, however it is just a tooling issue, code is not changed.
    This is a copy of the changes made in the flutter plugins

## 1.0.0

* Upgrade 0.13.0 version as 1.0.0
* Remove deprecated API (applyBatch, apply)

## 0.13.0

* Add support for `continueOrError` for batches

## 0.12.0

* iOS objective C prefix added to prevent conflict
* on iOS create the directory of the database if it does not exist

## 0.11.2

* add `Database.isOpen` which becomes false once the database is closed

## 0.11.1

* add `Sqflite.hex` to allow querying on blob fields

## 0.11.0

* add `getDatabasesPath` to use as the base location to create a database
* Warning: database are now single instance by default (based on `path`), to use the
  old behavior use `singleInstance = false` when opening a database
* dart2 stable support

## 0.10.0

* Preparing for 1.0
* Remove deprecated methods (re-entrant transactions)
* Add `Transaction.batch`
* Show developer warning to prevent deadlock

## 0.9.0

* Support for in-memory database (`:memory:` path)
* Support for single instance
* new database factory for handling the new options

## 0.8.9

* Upgrade to sdk 27

## 0.8.8

* Allow testing for constraint exception

## 0.8.6

* better sql error report
* catch android native errors
* no longer print an error when deleting a database fails

## 0.8.4

* Add read-only support using `openReadOnlyDatabase`

## 0.8.3

* Allow running a batch during a transaction using `Transaction.applyBatch`
* Restore `Batch.commit` to use outside a transaction

## 0.8.2

* Although already in a transaction, allow creating nested transactions during open

## 0.8.1

* New `Transaction` mechanism not using Zone (old one still supported for now)
* Start using `Batch.apply` instead of `Batch.commit`
* Deprecate `Database.inTransaction` and `Database.synchronized` so that Zones are not used anymore

## 0.7.1

* add `Batch.query`, `Batch.rawQuery` and `Batch.execute`
* pack query result as colums/rows instead of List<Map>

## 0.7.0

* Add support for `--preview-dart-2`

## 0.6.2+1

* Add longer description to pubspec.yaml

## 0.6.2

* Fix travis warning

## 0.6.1

* Add Flutter SDK constraint to pubspec.yaml

## 0.6.0

* add support for `onConfigure` to allow for database configuration

## 0.5.0

* Escape table and column name when needed in insert/update/query/delete
* Export ConflictAlgorithm, escapeName, unescapeName in new sql.dart

## 0.4.0

* Add support for Batch (insert/update/delete)

## 0.3.1

* Remove temp concurrency experiment

## 0.3.0

2018/01/04

* **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin
  3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in
  order to use this version of the plugin. Instructions can be found
  [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1).

## 0.2.4

* Dependency on synchronized updated to >=1.1.0

## 0.2.3

* Make Android sends the reponse in the same thread then the caller to prevent unexpected behavior when an error occured

## 0.2.2

* Fix unchecked warning on Android

## 0.2.0

* Use NSOperationQueue for all db operation on iOS
* Use ThreadHandler for all db operation on Android

## 0.0.3

* Add exception handling

## 0.0.2

* Add sqlite helpers based on Razvan Lung suggestions

## 0.0.1

* Initial experimentation







 
