Skip to content

Instantly share code, notes, and snippets.

@kilbot
Last active August 27, 2022 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kilbot/a27038adaf95d87259c154f12971ab6f to your computer and use it in GitHub Desktop.
Save kilbot/a27038adaf95d87259c154f12971ab6f to your computer and use it in GitHub Desktop.
RxStorage adapter for expo-sqlite
import { createRxDatabase } from 'rxdb';
import { getRxStorageSQLite, SQLiteQueryWithParams } from 'rxdb-premium/plugins/sqlite';
import { openDatabase, WebSQLDatabase, ResultSet } from 'expo-sqlite';
/**
* Polyfill for TextEncoder
* fixes: ReferenceError: Can't find variable: TextEncoder
*/
import 'fast-text-encoding';
const getSQLiteBasicsExpoSQLite = (openDB: typeof openDatabase) => {
return {
open: async (name: string) => {
return Promise.resolve(openDB(name));
},
all: async (db: WebSQLDatabase, queryWithParams: SQLiteQueryWithParams) => {
const result = new Promise<ResultSet['rows']>((resolve, reject) => {
console.log(`all sql: ${queryWithParams.query}`, queryWithParams.params);
db.exec(
[{ sql: queryWithParams.query, args: queryWithParams.params }],
false,
(err, res) => {
console.log('sql response: ', res);
if (err) {
return reject(err);
}
if (Array.isArray(res)) {
const queryResult = res[0]; // there is only one query
if (Object.prototype.hasOwnProperty.call(queryResult, 'rows')) {
return resolve(queryResult.rows);
}
return reject(queryResult.error);
}
return reject(new Error(`Unexpected response from SQLite: ${res}`));
}
);
});
return result;
},
run: async (db: WebSQLDatabase, queryWithParams: SQLiteQueryWithParams) => {
console.log(`run sql: ${queryWithParams.query}`, queryWithParams.params);
db.exec([{ sql: queryWithParams.query, args: queryWithParams.params }], false, () => {});
},
close: async (db: WebSQLDatabase) => {
return db.closeAsync();
},
journalMode: '',
};
};
const myRxDatabase = await createRxDatabase({
name: 'exampledb',
storage: getRxStorageSQLite({
sqliteBasics: getSQLiteBasicsExpoSQLite(openDatabase)
}),
multiInstance: false,
ignoreDuplicate: true,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment