With expo-sqlite
it's not possible to execute few depending statements inside single transaction - db.transaction
does not work with async/promise and tx.executeSql
just enqueues sql statement but does not execute it.
Database
class has two methods - execute
(to execute single statement without transaction) and transaction(cb)
to execute few statements inside a transaction
execute
method takes an SQL string as first parameter and array of values to replace ?
symbols as second parameter
transaction
method takes an async function as parameter. Callback function receives an instance of Connection
class
which has execute
method with signature as above
Constructor of Database
class takes database name as first parameter and optional object as second. Available options:
-
prepareConnFn
Async function to execute after connecting to database. Function receives aConnection
instance,execute
andtransaction
methods will wait for resolve of returned promise. This can be used to enable foreign keys, for example -
migrateFn
Similar toprepareConnFn
but for migration purposes (to prepare and update tables). It will receive separateConnection
instance
See an example in db.js
for example of migration function and prepare function. You can omit them if not needed.
Usage
import {Database} from "./database";
const db = new Database("main");
...
await db.transaction(async connection => {
const res1 = await connection.execute('some sql query');
await connection.execute('some another query depending on res1');
await connection.execute('and another');
});
...
await db.execute('some sql containing ?', ['values to replace ?']);
I came here because when I set expo sqlite app to production, it does not work as expected. Does this gist solve that issue?