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:
-
prepareConnFnAsync function to execute after connecting to database. Function receives aConnectioninstance,executeandtransactionmethods will wait for resolve of returned promise. This can be used to enable foreign keys, for example -
migrateFnSimilar toprepareConnFnbut for migration purposes (to prepare and update tables). It will receive separateConnectioninstance
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 ?']);
This wrapper is exactly what I needed, I was struggling all day to get the callback based interface of expo-sqlite to work but with your wrapper everything was working in less than 10min. Thanks for sharing, expo-sqlite docs should mention this wrapper or actually just provide it because using the current websql is difficult to use with react. (Not to mention that websql is so poorly designed in the first place, e.g., not keeping the order of success and error callbacks the same between functions :(