@nativescript-community/sqlite
v4.1.2
Published
SQLite for NativeScript, everything included: native threads, Node-API and JNI / Objective-C bindings, a default SQLite on each platform. Pick the smaller packages (sqlite-core, sqlite-napi...) to bring your own.
Readme
Table of Contents
Installation
Run the following command from the root of your project:
ns plugin add @nativescript-community/sqlite
This brings everything and needs no setup: sqlite-core (the API and the native core), sqlite-napi (Node-API binding, NativeScript 9.1+), sqlite-bridge (JNI / Objective-C, any NativeScript version) and sqlite-default-engine (the default SQLite):
- Android: androidx
sqlite-bundled(a recent SQLite with FTS5, JSON, RTREE, math functions, ~0.65 MB per ABI), added to your app by this package'sinclude.gradle. EnginelibsqliteJni.so. - iOS: the SQLite of the process: the system SQLite, or the one your app links (e.g. a CocoaPods
SQLCipher).
Everything of sqlite-core is re-exported, and so are its /typeorm and /nanosql entries. The full reference (options, bindings, raw Node-API / bridge use) is in the sqlite-core documentation.
Migrating from 3.x
4.0 keeps the API names and shapes, but a few things changed on purpose (close() and getVersion() return promises, parameters are bound with their real types, WAL is opt-in (wal: true), the native database objects are gone). See the migration guide.
Usage
Every call runs on a native thread and returns a promise: the JS thread is never blocked.
import { openOrCreate } from '@nativescript-community/sqlite';
const db = openOrCreate('my.db'); // a bare name goes to the databases folder (Android) / documents folder (iOS)
await db.execute('CREATE TABLE names (id INTEGER PRIMARY KEY, name TEXT)');
// many statements in one native call, all or nothing
await db.batch(names.map((name, id) => ['INSERT INTO names (id, name) VALUES (?, ?)', [id, name]]));
const rows = await db.select('SELECT * FROM names WHERE id > ?', [10]); // [{ id: 11, name: '...' }, ...]
const first = await db.get('SELECT * FROM names');
await db.each('SELECT * FROM names', [], (err, row) => {}); // streams big results
await db.transaction(async (cancel, tx) => {
// throwing or cancel() rolls back
await tx.execute('INSERT INTO names (id, name) VALUES (?, ?)', [1, 'a']);
});
await db.close();Async and sync
// asynchronous: start many at once, nothing blocks
const [a, b] = await Promise.all([db.get('SELECT * FROM names WHERE id = ?', [1]), db.get('SELECT * FROM names WHERE id = ?', [2])]);
// synchronous (NativeScript 9.1+): block the calling thread, no event loop round trip. Tiny statements in a loop only.
await db.transaction(async () => {
for (let i = 0; i < 5000; i++) db.executeSync('INSERT INTO names (id, name) VALUES (?, ?)', [i, 'n' + i]);
});
const row = db.getSync('SELECT * FROM names WHERE id = ?', [5]);executeSync, selectSync, selectArraySync, getSync and getArraySync throw on NativeScript 8, which uses the bridge. See Async and sync in the core documentation for when each pays off.
WAL (write-ahead logging)
WAL is off by default: databases keep SQLite's default journal, so databases created before the wal option existed open exactly as they did. Opt in with { wal: true } per database, or for all with configure({ defaultOptions: { wal: true } }). With SQLite's default journal every commit creates, syncs and deletes a journal file, which made 500 awaited one-statement writes take 2.6 s on a phone (38 ms in WAL), so it is worth enabling for new databases. WAL adds -wal / -shm files next to the database (deleteDatabase removes them), and switching an existing database to WAL persists in the file. In-memory and read-only databases ignore the option.
Extensions
The default Android engine (androidx sqlite-bundled) can load SQLite extensions; the system SQLite of iOS cannot (see the core documentation for iOS and for compiled-in extensions).
const db = openOrCreate('my.db');
if (db.canLoadExtensions()) {
await db.loadExtension('libmyext.so'); // entry point guessed from the name: sqlite3_myext_init, or pass it as 2nd argument
}
await db.select("SELECT my_function('x')");Ship libmyext.so for each ABI in a folder of your app and declare it in App_Resources/Android/app.gradle (the NativeScript template replaces the default jniLibs folders):
android {
sourceSets { main { jniLibs.srcDir "${rootProject.projectDir}/../../App_Resources/Android/native-libs" } } // native-libs/<abi>/libmyext.so
}Another SQLite for some or all databases
engine is per database and configure sets the default; use them to put SQLCipher or your own build next to the default one:
import { configure, openOrCreate } from '@nativescript-community/sqlite';
const plain = openOrCreate('cache.db'); // default engine
const secure = openOrCreate('secure.db', { engine: 'libsqlcipher.so', initSql: "PRAGMA key = 'secret'" }); // Android: add net.zetetic:sqlcipher-android
configure({ engine: 'libmysqlite.so' }); // or change it for every database opened afterwardsTypeORM
import 'reflect-metadata';
import { DataSource } from 'typeorm/browser';
import { installMixins } from '@nativescript-community/sqlite/typeorm';
installMixins();
const dataSource = new DataSource({ type: 'nativescript', database: 'app.db', entities: [/* ... */], synchronize: true });
await dataSource.initialize();The webpack changes TypeORM's browser build needs are listed in the core documentation.
Node-API on Android, NativeScript 8 on iOS (or the reverse)
You get both bindings on both platforms. Leave the one you do not need out of that platform's build, for example the JNI library on Android: see One platform with Node-API, the other with the bridge in the sqlite-bridge documentation.
Do not want the default SQLite?
Depend on @nativescript-community/sqlite-core and the binding you need instead of this package: no SQLite and no gradle dependency come with them, so there is nothing to override or patch out when you use SQLCipher or your own build. Only need NativeScript 9.1+ with the default SQLite? sqlite-core + sqlite-napi + sqlite-default-engine is the same without the JNI / Objective-C bridges. See Which packages in the core documentation.
