|
| 1 | +import SQLiteESMFactory from 'wa-sqlite-fts5/wa-sqlite.mjs' |
| 2 | +import { OPFSWriteAheadVFS } from 'wa-sqlite/src/examples/OPFSWriteAheadVFS.js' |
| 3 | + |
| 4 | +import type { BaseStorageOptions, InitSQLiteOptions, OPFSWriteAheadVFSOptions } from '../types' |
| 5 | + |
| 6 | +export { OPFSWriteAheadVFS } from 'wa-sqlite/src/examples/OPFSWriteAheadVFS.js' |
| 7 | + |
| 8 | +export type OPFSWriteAheadStorageOptions = OPFSWriteAheadVFSOptions |
| 9 | + |
| 10 | +/** |
| 11 | + * Store data in [OPFS](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system) |
| 12 | + * using write-ahead logging for improved performance and concurrency, |
| 13 | + * use `OPFSWriteAheadVFS` with `wa-sqlite.wasm`, smaller and faster sync build |
| 14 | + * |
| 15 | + * **MUST RUN IN WEB WORKER** |
| 16 | + * |
| 17 | + * Requires OPFS `readwrite-unsafe` locking mode — **Chromium browsers only** |
| 18 | + * |
| 19 | + * Only journal mode `DELETE` (default) or `OFF` should be used. |
| 20 | + * For multiple-statement write transactions, `BEGIN IMMEDIATE` or `BEGIN EXCLUSIVE` must be used. |
| 21 | + * @param path db file directory path |
| 22 | + * @param options options |
| 23 | + * @example |
| 24 | + * ```ts |
| 25 | + * import { initSQLite, isOpfsReadWriteUnsafeSupported } from '@subframe7536/sqlite-wasm' |
| 26 | + * import { useOpfsWriteAheadStorage } from '@subframe7536/sqlite-wasm/opfs-wa' |
| 27 | + * |
| 28 | + * // optional url |
| 29 | + * const url = 'https://cdn.jsdelivr.net/npm/@subframe7536/sqlite-wasm/dist/wa-sqlite.wasm' |
| 30 | + * |
| 31 | + * // must run in web worker |
| 32 | + * if (await isOpfsReadWriteUnsafeSupported()) { |
| 33 | + * const { run, changes, lastInsertRowId, close } = await initSQLite( |
| 34 | + * useOpfsWriteAheadStorage('test.db', { url }) |
| 35 | + * ) |
| 36 | + * } |
| 37 | + * ``` |
| 38 | + */ |
| 39 | +export async function useOpfsWriteAheadStorage( |
| 40 | + path: string, |
| 41 | + options: OPFSWriteAheadStorageOptions & BaseStorageOptions = {}, |
| 42 | +): Promise<InitSQLiteOptions> { |
| 43 | + const { url, nTmpFiles, autoCheckpoint, backstopInterval, ...rest } = options |
| 44 | + const sqliteModule = await SQLiteESMFactory(url ? { locateFile: () => url } : undefined) |
| 45 | + const vfsOptions: OPFSWriteAheadVFSOptions = {} |
| 46 | + if (nTmpFiles !== undefined) {vfsOptions.nTmpFiles = nTmpFiles} |
| 47 | + if (autoCheckpoint !== undefined) {vfsOptions.autoCheckpoint = autoCheckpoint} |
| 48 | + if (backstopInterval !== undefined) {vfsOptions.backstopInterval = backstopInterval} |
| 49 | + |
| 50 | + return { |
| 51 | + path, |
| 52 | + sqliteModule, |
| 53 | + vfsFn: OPFSWriteAheadVFS.create, |
| 54 | + vfsOptions, |
| 55 | + ...rest, |
| 56 | + } |
| 57 | +} |
0 commit comments