![screenshot](https://raw.githubusercontent.com/ospfranco/react-native-quick-sqlite/main/header.png)
yarn add react-native-quick-sqlite
npx pod-install
Quick SQLite embeds the latest version of SQLite and provides a low-level API to execute SQL queries, uses fast bindings via JSI. By using an embedded SQLite you get access the latest security patches and latest features.
Inspired/compatible with react-native-sqlite-storage and react-native-sqlite2. Performance metrics are intentionally not posted, annecdotical testimonies suggest anywhere between 2x and 5x speed improvement.
Gotchas
- Javascript cannot represent integers larger than 53 bits, be careful when loading data if it came from other systems. Read more.
- It's not possible to use a browser to debug a JSI app, use Flipper (for android Flipper also has SQLite Database explorer).
- Install the NDK on your machine for android.
API
interface QueryResult {
status?: 0 | 1;
insertId?: number;
rowsAffected: number;
message?: string;
rows?: {
_array: any[];
length: number;
};
metadata?: ColumnMetadata[];
}
interface ColumnMetadata = {
columnName: string;
columnDeclaredType: string;
columnIndex: number;
};
interface BatchQueryResult {
status?: 0 | 1;
rowsAffected?: number;
message?: string;
}
interface ISQLite {
open: (dbName: string, location?: string) => { status: 0 | 1 };
close: (dbName: string) => { status: 0 | 1 };
delete: (dbName: string, location?: string) => { status: 0 | 1 };
executeSql: (
dbName: string,
query: string,
params: any[] | undefined
) => QueryResult;
asyncExecuteSql: (
dbName: string,
query: string,
params: any[] | undefined,
cb: (res: QueryResult) => void
) => void;
executeSqlBatch: (
dbName: string,
commands: SQLBatchParams[]
) => BatchQueryResult;
asyncExecuteSqlBatch: (
dbName: string,
commands: SQLBatchParams[],
cb: (res: BatchQueryResult) => void
) => void;
loadSqlFile: (dbName: string, location: string) => FileLoadResult;
asyncLoadSqlFile: (
dbName: string,
location: string,
cb: (res: FileLoadResult) => void
) => void;
}
WebSQL wrapper
You can get a WebSQL wrapper (meant to be used with TypeORM or other drivers) with a different global call. It's a simple wrapper around the low level API.
openDatabase(
options: IConnectionOptions,
ok: (db: IDBConnection) => void,
fail: (msg: string) => void
): IDBConnection
Usage
Import as early as possible, auto-installs bindings in a thread-safe manner.
import 'react-native-quick-sqlite';
const dbOpenResult = sqlite.open('myDatabase', 'databases');
if (dbOpenResult.status) {
console.error('Database could not be opened');
}
Simple queries
The basic query is synchronous, it will block rendering on large operations, below there are async versions.
let { status, rows } = sqlite.executeSql(
'myDatabase',
'SELECT somevalue FROM sometable'
);
if (!status) {
rows.forEach((row) => {
console.log(row);
});
}
let { status, rowsAffected } = sqlite.executeSql(
'myDatabase',
'UPDATE sometable SET somecolumn = ? where somekey = ?',
[0, 1]
);
if (!status) {
console.log(`Update affected ${rowsAffected} rows`);
}
Transactions
Transactions are supported. However, due to the library being opinionated and mostly not throwing errors you need to return a boolean (true for correct execution, false for incorrect execution) to either commit or rollback the transaction.
JSI bindings are fast but there is still some overhead calling executeSql
for single queries, if you want to execute a large set of commands as fast as possible you should use the executeSqlBatch
method below, it still uses transactions, but only transmits data between JS and native once.
sqlite.transaction('myDatabase', (tx) => {
const {
status,
} = tx.executeSql('UPDATE sometable SET somecolumn = ? where somekey = ?', [
0,
1,
]);
if (status) {
return false;
}
return true;
});
Batch operation
Batch execution allows transactional execution of a set of commands
const commands = [
['CREATE TABLE TEST (id integer)'],
['INSERT INTO TABLE TEST (id) VALUES (?)', [1]][
('INSERT INTO TABLE TEST (id) VALUES (?)', [2])
][('INSERT INTO TABLE TEST (id) VALUES (?)', [[3], [4], [5], [6]])],
];
const result = sqlite.executeSqlBatch('myDatabase', commands);
if (!result.status) {
console.log(`Batch affected ${result.rowsAffected} rows`);
}
Dynamic Column Metadata
In some scenarios, dynamic applications may need to get some metadata information about the returned result set.
This can be done testing the returned data directly, but in some cases may not be enough, for example when data is stored outside
sqlite datatypes. When fetching data directly from tables or views linked to table columns, SQLite is able
to identify the table declared types:
let { status, metadata } = sqlite.executeSql(
'myDatabase',
'SELECT int_column_1, bol_column_2 FROM sometable'
);
if (!status) {
metadata.forEach((column) => {
console.log(`${column.columnName} - ${column.columnDeclaredType}`);
});
}
Async operations
You might have too much SQL to process and it will cause your application to freeze. There are async versions for some of the operations. This will offload the SQLite processing to a different thread.
sqlite.asyncExecuteSql(
'myDatabase',
'SELECT * FROM "User";',
[],
({ status, rows }) => {
if (status === 0) {
console.log('users', rows);
}
}
);
Use built-in SQLite
App size is a real concern for some teams.
On iOS you can use the OS embedded SQLite instance, when running pod-install
add an environment flag:
QUICK_SQLITE_USE_PHONE_VERSION=1 npx pod-install
On Android unfortunately it is not possible to link from C++ to the phone's embedded SQLite. It is also very buggy (vendor changes, old android bugs, etc). The recommended way is to embed your own version of SQLite anyways. Unfortunately this means we are stuck and this library will add some mbs to your app size.
Use TypeORM
You can use this driver with TypeORM and patch-package by the default react-native-sqlite-storage driver. Go inside your node_modules/typeorm
and do a global replace of react-native-sqlite-storage
for react-native-quick-sqlite
and then patch package it. The patch on the example folder you will see an example of what it should look like
More
If you want to learn how to make your own JSI module buy my JSI/C++ Cheatsheet, I'm also available for freelance work.
License
react-native-quick-sqlite is licensed under MIT.