11import type { BaseOptions , IDBBatchAtomicVFSOptions , Options } from '../types'
22import SQLiteAsyncESMFactory from 'wa-sqlite/dist/wa-sqlite-async.mjs'
33import { IDBBatchAtomicVFS } from 'wa-sqlite/src/examples/IDBBatchAtomicVFS.js'
4+ import { IDBMirrorVFS } from 'wa-sqlite/src/examples/IDBMirrorVFS.js'
45
56export { IDBBatchAtomicVFS } from 'wa-sqlite/src/examples/IDBBatchAtomicVFS.js'
7+ export { IDBMirrorVFS } from 'wa-sqlite/src/examples/IDBMirrorVFS.js'
68
7- export type IDBVFSOptions = IDBBatchAtomicVFSOptions & {
8- /**
9- * @default 'idb-sqlite-vfs'
10- */
11- idbName ?: string
12- }
9+ export type IDBVFSOptions = IDBBatchAtomicVFSOptions
1310
1411/**
15- * storage data in IndexedDB,
16- * use IDBBatchAtomicVFS with `wa-sqlite-async.wasm` (larger than sync version), better compatibility
12+ * Store data in IndexedDB,
13+ * Use ` IDBBatchAtomicVFS` with `wa-sqlite-async.wasm` (larger than sync version), better compatibility
1714 * @param fileName db file name
1815 * @param options options
1916 * @example
@@ -35,21 +32,59 @@ export async function useIdbStorage(
3532) : Promise < Options > {
3633 const {
3734 url,
38- idbName = 'idb-sqlite-vfs' ,
3935 lockPolicy = 'shared+hint' ,
4036 lockTimeout = Infinity ,
4137 readonly,
4238 } = options
4339 const sqliteModule = await SQLiteAsyncESMFactory (
4440 url ? { locateFile : ( ) => url } : undefined ,
4541 )
42+ const idbName = fileName . endsWith ( '.db' ) ? fileName : `${ fileName } .db`
4643 const vfsOptions = { idbName, lockPolicy, lockTimeout }
4744 /// keep-sorted
45+ return {
46+ path : idbName ,
47+ readonly,
48+ sqliteModule,
49+ vfsFn : IDBMirrorVFS . create ,
50+ vfsOptions,
51+ }
52+ }
53+
54+ /**
55+ * Store data in memory and sync to IndexedDB,
56+ * Use `IDBMirrorVFS` with `wa-sqlite-async.wasm` (larger than sync version), better performance compare to `IDBBatchAtomicVFS`
57+ * @param fileName db file name
58+ * @param options options
59+ * @example
60+ * ```ts
61+ * import { useIdbMemoryStorage } from '@subframe7536/sqlite-wasm/idb'
62+ * import { getAsyncWasmURL, initSQLite } from '@subframe7536/sqlite-wasm'
63+ *
64+ * // const url = 'https://cdn.jsdelivr.net/gh/rhashimoto/wa-sqlite@v0.9.9/dist/wa-sqlite-async.wasm'
65+ * const url = getAsyncWasmURL()
66+ *
67+ * const { run, changes, lastInsertRowId, close, sqlite, db } = await initSQLite(
68+ * useIdbMemoryStorage('test', { url })
69+ * )
70+ * ```
71+ */
72+ export async function useIdbMemoryStorage (
73+ fileName : string ,
74+ options : BaseOptions = { } ,
75+ ) : Promise < Options > {
76+ const {
77+ url,
78+ readonly,
79+ } = options
80+ const sqliteModule = await SQLiteAsyncESMFactory (
81+ url ? { locateFile : ( ) => url } : undefined ,
82+ )
83+ /// keep-sorted
4884 return {
4985 path : fileName . endsWith ( '.db' ) ? fileName : `${ fileName } .db` ,
5086 readonly,
5187 sqliteModule,
5288 vfsFn : IDBBatchAtomicVFS . create ,
53- vfsOptions,
5489 }
5590}
0 commit comments