@powersync/adapter-sql-js
v0.0.17
Published
A development db adapter based on SQL.js for JourneyApps PowerSync
Downloads
6,792
Keywords
Readme
PowerSync SQL-JS Adapter
A development package for PowerSync which uses SQL.js to provide a pure JavaScript SQLite implementation. This eliminates the need for native dependencies and enables seamless development with Expo Go and other JavaScript-only environments.
This adapter is specifically intended to streamline the development workflow and will be much slower than DB adapters that use native dependencies. Every write operation triggers a complete rewrite of the entire database file to persistent storage, not just the changed data. In addition to the performance overheads, this adapter doesn't provide any of the SQLite consistency guarantees - you may end up with missing data or a corrupted database file if the app is killed while writing to the database file.
For production use, when building React Native apps we recommend switching to our react-native-quick-sqlite or OP-SQLite adapters when making production builds as they give substantially better performance.
Note: Alpha Release
This package is currently in an alpha release.
Usage
By default the SQLJS adapter will be in-memory. Read further for persister examples.
import { SQLJSOpenFactory } from '@powersync/adapter-sql-js';
const powersync = new PowerSyncDatabase({
schema: AppSchema,
database: new SQLJSOpenFactory({
dbFilename: 'powersync.db'
})
});Persister examples
Expo
We can use the Expo File System to persist the database in an Expo app.
import { PowerSyncDatabase, SQLJSOpenFactory, SQLJSPersister } from '@powersync/react-native';
import * as FileSystem from 'expo-file-system';
const powersync = new PowerSyncDatabase({
schema: AppSchema,
database: new SQLJSOpenFactory({
dbFilename: 'powersync.db',
persister: createSQLJSPersister('powersync.db')
})
});
const createSQLJSPersister = (dbFilename: string): SQLJSPersister => {
const dbPath = `${FileSystem.documentDirectory}${dbFilename}`;
return {
readFile: async (): Promise<ArrayLike<number> | Buffer | null> => {
try {
const fileInfo = await FileSystem.getInfoAsync(dbPath);
if (!fileInfo.exists) {
return null;
}
const result = await FileSystem.readAsStringAsync(dbPath, {
encoding: FileSystem.EncodingType.Base64
});
const binary = atob(result);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
} catch (error) {
console.error('Error reading database file:', error);
return null;
}
},
writeFile: async (data: ArrayLike<number> | Buffer): Promise<void> => {
try {
const uint8Array = new Uint8Array(data);
const binary = Array.from(uint8Array, (byte) => String.fromCharCode(byte)).join('');
const base64 = btoa(binary);
await FileSystem.writeAsStringAsync(dbPath, base64, {
encoding: FileSystem.EncodingType.Base64
});
} catch (error) {
console.error('Error writing database file:', error);
throw error;
}
}
};
};