@statewalker/db-sqlite-browser 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,9 +78,15 @@ five databases if their writes do not overlap.
78
78
  second worker (or tab) opening the same `path` fails with an OPFS lock error until the first
79
79
  one is terminated.
80
80
  - **Calls are queued** and transactions open with `BEGIN IMMEDIATE` (see `@statewalker/db-sqlite`).
81
- Rows are plain objects; BLOBs are `Uint8Array`.
82
- - **The engine loads once per `wasmUrl`.** A failed load (for example a wrong `wasmUrl`) is not
83
- retried for that URL.
81
+ Rows are plain objects; BLOBs are `Uint8Array`; an integer above 2^53 is a `bigint`, smaller
82
+ ones are numbers.
83
+ - **`query` runs one statement.** SQL with a second statement, or empty SQL, rejects before the
84
+ engine runs it; `true`/`false`, `undefined` and `Date` parameters bind as `1`/`0`, `NULL` and
85
+ ISO 8601 text. This comes from `@statewalker/db-sqlite`, the same on every SQLite driver. Use
86
+ `exec` for scripts.
87
+ - **The engine loads once per `wasmUrl`.** A failed load (a wrong `wasmUrl`, a network error) is
88
+ not cached: the next call tries again. The same holds for the OPFS pool: after an open failed
89
+ with the OPFS lock error, a later open in the same worker works once the other worker is gone.
84
90
  - **Dependencies:** `@sqlite.org/sqlite-wasm` (the engine), `@statewalker/db-sqlite` (queue and
85
91
  transactions), `@statewalker/db-api` (types).
86
92
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["DbOptions","Db"],"sources":["../src/browser-sqlite-db.ts"],"mappings":";;KASY,mBAAmBA;;EAE7B;;;;;EAKA;;;;;;;;;wBAuDoB,mBAAmB,UAAU,mBAAmB,QAAQC"}
1
+ {"version":3,"file":"index.d.mts","names":["DbOptions","Db"],"sources":["../src/browser-sqlite-db.ts"],"mappings":";;KASY,mBAAmBA;;EAE7B;;;;;EAKA;;;;;;;;;wBA8EoB,mBAAmB,UAAU,mBAAmB,QAAQC"}
package/dist/index.mjs CHANGED
@@ -2,23 +2,36 @@ import sqlite3InitModule from "@sqlite.org/sqlite-wasm";
2
2
  import { newSerialisedSqliteDb } from "@statewalker/db-sqlite";
3
3
  //#region src/browser-sqlite-db.ts
4
4
  const MAIN_THREAD_PATH = "newBrowserSqliteDb: { path } needs a Dedicated Worker (the \"opfs-sahpool\" OPFS VFS runs only there). On the main thread, omit path for an in-memory database.";
5
- /** One engine per wasmUrl, started on first use; one OPFS pool per engine. */
5
+ /**
6
+ * One engine per wasmUrl, started on first use; one OPFS pool per engine. A start that fails is
7
+ * forgotten, so the next call tries again: the pool's install fails while another worker holds the
8
+ * pool, and works once that worker is gone.
9
+ */
6
10
  const engines = /* @__PURE__ */ new Map();
7
11
  const pools = /* @__PURE__ */ new WeakMap();
12
+ /** `promise`, removed from the cache when it rejects (if it is still the cached one). */
13
+ function forgetOnFailure(cache, key, promise) {
14
+ promise.catch(() => {
15
+ if (cache.get(key) === promise) cache.delete(key);
16
+ });
17
+ return promise;
18
+ }
8
19
  function getSqlite3(wasmUrl) {
9
20
  const key = wasmUrl ?? "";
10
21
  let engine = engines.get(key);
11
22
  if (!engine) {
12
23
  engine = sqlite3InitModule(wasmUrl ? { locateFile: (file) => file.endsWith(".wasm") ? wasmUrl : file } : void 0);
13
24
  engines.set(key, engine);
25
+ forgetOnFailure(engines, key, engine);
14
26
  }
15
27
  return engine;
16
28
  }
17
29
  function getPool(sqlite3) {
18
30
  let pool = pools.get(sqlite3);
19
31
  if (!pool) {
20
- pool = sqlite3.installOpfsSAHPoolVfs({});
32
+ pool = sqlite3.installOpfsSAHPoolVfs({ forceReinitIfPreviouslyFailed: true });
21
33
  pools.set(sqlite3, pool);
34
+ forgetOnFailure(pools, sqlite3, pool);
22
35
  }
23
36
  return pool;
24
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/browser-sqlite-db.ts"],"sourcesContent":["import sqlite3InitModule, {\n type BindableValue,\n type Database,\n type SAHPoolUtil,\n type Sqlite3Static,\n} from \"@sqlite.org/sqlite-wasm\";\nimport type { Db, DbOptions } from \"@statewalker/db-api\";\nimport { newSerialisedSqliteDb } from \"@statewalker/db-sqlite\";\n\nexport type BrowserDbOptions = DbOptions & {\n /** URL of `sqlite3.wasm`. Default: the package's own file, located by the bundler. */\n wasmUrl?: string;\n /**\n * Minimum number of files the OPFS pool can hold, when `path` is set. Each open database takes\n * one file and its rollback journal another while it writes. Default: the pool's own (6).\n */\n capacity?: number;\n};\n\nconst MAIN_THREAD_PATH =\n 'newBrowserSqliteDb: { path } needs a Dedicated Worker (the \"opfs-sahpool\" OPFS VFS runs only ' +\n \"there). On the main thread, omit path for an in-memory database.\";\n\ntype InitModule = (module?: { locateFile?: (file: string) => string }) => Promise<Sqlite3Static>;\n\n/** One engine per wasmUrl, started on first use; one OPFS pool per engine. */\nconst engines = new Map<string, Promise<Sqlite3Static>>();\nconst pools = new WeakMap<Sqlite3Static, Promise<SAHPoolUtil>>();\n\nfunction getSqlite3(wasmUrl: string | undefined): Promise<Sqlite3Static> {\n const key = wasmUrl ?? \"\";\n let engine = engines.get(key);\n if (!engine) {\n engine = (sqlite3InitModule as InitModule)(\n wasmUrl ? { locateFile: (file) => (file.endsWith(\".wasm\") ? wasmUrl : file) } : undefined,\n );\n engines.set(key, engine);\n }\n return engine;\n}\n\nfunction getPool(sqlite3: Sqlite3Static): Promise<SAHPoolUtil> {\n let pool = pools.get(sqlite3);\n if (!pool) {\n pool = sqlite3.installOpfsSAHPoolVfs({});\n pools.set(sqlite3, pool);\n }\n return pool;\n}\n\nasync function openPooled(\n sqlite3: Sqlite3Static,\n path: string,\n capacity: number | undefined,\n): Promise<Database> {\n const pool = await getPool(sqlite3);\n if (capacity !== undefined) await pool.reserveMinimumCapacity(capacity);\n return new pool.OpfsSAHPoolDb(path);\n}\n\nconst inDedicatedWorker = () =>\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !==\n \"undefined\";\n\n/**\n * Create a SQLite {@link Db} on `@sqlite.org/sqlite-wasm`.\n *\n * @param options.path OPFS database name; Dedicated Worker only. Omit for in-memory.\n * @param options.wasmUrl URL of `sqlite3.wasm`, when the bundler cannot locate it.\n * @param options.capacity Minimum OPFS pool size in files, with `path`; it only ever grows.\n */\nexport async function newBrowserSqliteDb(options?: BrowserDbOptions): Promise<Db> {\n if (options?.path && !inDedicatedWorker()) throw new Error(MAIN_THREAD_PATH);\n const sqlite3 = await getSqlite3(options?.wasmUrl);\n const db: Database = options?.path\n ? await openPooled(sqlite3, options.path, options.capacity)\n : new sqlite3.oo1.DB(\":memory:\", \"c\");\n return newSerialisedSqliteDb({\n all: (sql, params) =>\n db.exec({\n sql,\n bind: params.length > 0 ? (params as BindableValue[]) : undefined,\n rowMode: \"object\",\n returnValue: \"resultRows\",\n }) as Record<string, unknown>[],\n exec: (sql) => {\n db.exec(sql);\n },\n close: () => db.close(),\n });\n}\n"],"mappings":";;;AAmBA,MAAM,mBACJ;;AAMF,MAAM,0BAAU,IAAI,IAAoC;AACxD,MAAM,wBAAQ,IAAI,QAA6C;AAE/D,SAAS,WAAW,SAAqD;CACvE,MAAM,MAAM,WAAW;CACvB,IAAI,SAAS,QAAQ,IAAI,GAAG;CAC5B,IAAI,CAAC,QAAQ;EACX,SAAU,kBACR,UAAU,EAAE,aAAa,SAAU,KAAK,SAAS,OAAO,IAAI,UAAU,KAAM,IAAI,KAAA,CAClF;EACA,QAAQ,IAAI,KAAK,MAAM;CACzB;CACA,OAAO;AACT;AAEA,SAAS,QAAQ,SAA8C;CAC7D,IAAI,OAAO,MAAM,IAAI,OAAO;CAC5B,IAAI,CAAC,MAAM;EACT,OAAO,QAAQ,sBAAsB,CAAC,CAAC;EACvC,MAAM,IAAI,SAAS,IAAI;CACzB;CACA,OAAO;AACT;AAEA,eAAe,WACb,SACA,MACA,UACmB;CACnB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,IAAI,aAAa,KAAA,GAAW,MAAM,KAAK,uBAAuB,QAAQ;CACtE,OAAO,IAAI,KAAK,cAAc,IAAI;AACpC;AAEA,MAAM,0BACJ,OAAQ,WAAwD,+BAChE;;;;;;;;AASF,eAAsB,mBAAmB,SAAyC;CAChF,IAAI,SAAS,QAAQ,CAAC,kBAAkB,GAAG,MAAM,IAAI,MAAM,gBAAgB;CAC3E,MAAM,UAAU,MAAM,WAAW,SAAS,OAAO;CACjD,MAAM,KAAe,SAAS,OAC1B,MAAM,WAAW,SAAS,QAAQ,MAAM,QAAQ,QAAQ,IACxD,IAAI,QAAQ,IAAI,GAAG,YAAY,GAAG;CACtC,OAAO,sBAAsB;EAC3B,MAAM,KAAK,WACT,GAAG,KAAK;GACN;GACA,MAAM,OAAO,SAAS,IAAK,SAA6B,KAAA;GACxD,SAAS;GACT,aAAa;EACf,CAAC;EACH,OAAO,QAAQ;GACb,GAAG,KAAK,GAAG;EACb;EACA,aAAa,GAAG,MAAM;CACxB,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/browser-sqlite-db.ts"],"sourcesContent":["import sqlite3InitModule, {\n type BindableValue,\n type Database,\n type SAHPoolUtil,\n type Sqlite3Static,\n} from \"@sqlite.org/sqlite-wasm\";\nimport type { Db, DbOptions } from \"@statewalker/db-api\";\nimport { newSerialisedSqliteDb } from \"@statewalker/db-sqlite\";\n\nexport type BrowserDbOptions = DbOptions & {\n /** URL of `sqlite3.wasm`. Default: the package's own file, located by the bundler. */\n wasmUrl?: string;\n /**\n * Minimum number of files the OPFS pool can hold, when `path` is set. Each open database takes\n * one file and its rollback journal another while it writes. Default: the pool's own (6).\n */\n capacity?: number;\n};\n\nconst MAIN_THREAD_PATH =\n 'newBrowserSqliteDb: { path } needs a Dedicated Worker (the \"opfs-sahpool\" OPFS VFS runs only ' +\n \"there). On the main thread, omit path for an in-memory database.\";\n\ntype InitModule = (module?: { locateFile?: (file: string) => string }) => Promise<Sqlite3Static>;\n\n/**\n * One engine per wasmUrl, started on first use; one OPFS pool per engine. A start that fails is\n * forgotten, so the next call tries again: the pool's install fails while another worker holds the\n * pool, and works once that worker is gone.\n */\nconst engines = new Map<string, Promise<Sqlite3Static>>();\nconst pools = new WeakMap<Sqlite3Static, Promise<SAHPoolUtil>>();\n\n/** `promise`, removed from the cache when it rejects (if it is still the cached one). */\nfunction forgetOnFailure<K, V>(\n cache: { get(key: K): Promise<V> | undefined; delete(key: K): unknown },\n key: K,\n promise: Promise<V>,\n): Promise<V> {\n promise.catch(() => {\n if (cache.get(key) === promise) cache.delete(key);\n });\n return promise;\n}\n\nfunction getSqlite3(wasmUrl: string | undefined): Promise<Sqlite3Static> {\n const key = wasmUrl ?? \"\";\n let engine = engines.get(key);\n if (!engine) {\n engine = (sqlite3InitModule as InitModule)(\n wasmUrl ? { locateFile: (file) => (file.endsWith(\".wasm\") ? wasmUrl : file) } : undefined,\n );\n engines.set(key, engine);\n forgetOnFailure(engines, key, engine);\n }\n return engine;\n}\n\nfunction getPool(sqlite3: Sqlite3Static): Promise<SAHPoolUtil> {\n let pool = pools.get(sqlite3);\n if (!pool) {\n // sqlite-wasm caches a failed install too, unless told to try again. The option is\n // documented and implemented by sqlite-wasm but missing from its type declarations.\n const options = { forceReinitIfPreviouslyFailed: true } as Parameters<\n Sqlite3Static[\"installOpfsSAHPoolVfs\"]\n >[0];\n pool = sqlite3.installOpfsSAHPoolVfs(options);\n pools.set(sqlite3, pool);\n forgetOnFailure(pools, sqlite3, pool);\n }\n return pool;\n}\n\nasync function openPooled(\n sqlite3: Sqlite3Static,\n path: string,\n capacity: number | undefined,\n): Promise<Database> {\n const pool = await getPool(sqlite3);\n if (capacity !== undefined) await pool.reserveMinimumCapacity(capacity);\n return new pool.OpfsSAHPoolDb(path);\n}\n\nconst inDedicatedWorker = () =>\n typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !==\n \"undefined\";\n\n/**\n * Create a SQLite {@link Db} on `@sqlite.org/sqlite-wasm`.\n *\n * @param options.path OPFS database name; Dedicated Worker only. Omit for in-memory.\n * @param options.wasmUrl URL of `sqlite3.wasm`, when the bundler cannot locate it.\n * @param options.capacity Minimum OPFS pool size in files, with `path`; it only ever grows.\n */\nexport async function newBrowserSqliteDb(options?: BrowserDbOptions): Promise<Db> {\n if (options?.path && !inDedicatedWorker()) throw new Error(MAIN_THREAD_PATH);\n const sqlite3 = await getSqlite3(options?.wasmUrl);\n const db: Database = options?.path\n ? await openPooled(sqlite3, options.path, options.capacity)\n : new sqlite3.oo1.DB(\":memory:\", \"c\");\n return newSerialisedSqliteDb({\n all: (sql, params) =>\n db.exec({\n sql,\n bind: params.length > 0 ? (params as BindableValue[]) : undefined,\n rowMode: \"object\",\n returnValue: \"resultRows\",\n }) as Record<string, unknown>[],\n exec: (sql) => {\n db.exec(sql);\n },\n close: () => db.close(),\n });\n}\n"],"mappings":";;;AAmBA,MAAM,mBACJ;;;;;;AAUF,MAAM,0BAAU,IAAI,IAAoC;AACxD,MAAM,wBAAQ,IAAI,QAA6C;;AAG/D,SAAS,gBACP,OACA,KACA,SACY;CACZ,QAAQ,YAAY;EAClB,IAAI,MAAM,IAAI,GAAG,MAAM,SAAS,MAAM,OAAO,GAAG;CAClD,CAAC;CACD,OAAO;AACT;AAEA,SAAS,WAAW,SAAqD;CACvE,MAAM,MAAM,WAAW;CACvB,IAAI,SAAS,QAAQ,IAAI,GAAG;CAC5B,IAAI,CAAC,QAAQ;EACX,SAAU,kBACR,UAAU,EAAE,aAAa,SAAU,KAAK,SAAS,OAAO,IAAI,UAAU,KAAM,IAAI,KAAA,CAClF;EACA,QAAQ,IAAI,KAAK,MAAM;EACvB,gBAAgB,SAAS,KAAK,MAAM;CACtC;CACA,OAAO;AACT;AAEA,SAAS,QAAQ,SAA8C;CAC7D,IAAI,OAAO,MAAM,IAAI,OAAO;CAC5B,IAAI,CAAC,MAAM;EAMT,OAAO,QAAQ,sBAAsB,EAHnB,+BAA+B,KAGN,CAAC;EAC5C,MAAM,IAAI,SAAS,IAAI;EACvB,gBAAgB,OAAO,SAAS,IAAI;CACtC;CACA,OAAO;AACT;AAEA,eAAe,WACb,SACA,MACA,UACmB;CACnB,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,IAAI,aAAa,KAAA,GAAW,MAAM,KAAK,uBAAuB,QAAQ;CACtE,OAAO,IAAI,KAAK,cAAc,IAAI;AACpC;AAEA,MAAM,0BACJ,OAAQ,WAAwD,+BAChE;;;;;;;;AASF,eAAsB,mBAAmB,SAAyC;CAChF,IAAI,SAAS,QAAQ,CAAC,kBAAkB,GAAG,MAAM,IAAI,MAAM,gBAAgB;CAC3E,MAAM,UAAU,MAAM,WAAW,SAAS,OAAO;CACjD,MAAM,KAAe,SAAS,OAC1B,MAAM,WAAW,SAAS,QAAQ,MAAM,QAAQ,QAAQ,IACxD,IAAI,QAAQ,IAAI,GAAG,YAAY,GAAG;CACtC,OAAO,sBAAsB;EAC3B,MAAM,KAAK,WACT,GAAG,KAAK;GACN;GACA,MAAM,OAAO,SAAS,IAAK,SAA6B,KAAA;GACxD,SAAS;GACT,aAAa;EACf,CAAC;EACH,OAAO,QAAQ;GACb,GAAG,KAAK,GAAG;EACb;EACA,aAAa,GAAG,MAAM;CACxB,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/db-sqlite-browser",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "SQLite WASM (@sqlite.org/sqlite-wasm) driver for @statewalker/db-api in the browser: in-memory anywhere, OPFS persistence in a Dedicated Worker.",
@@ -22,17 +22,19 @@
22
22
  ".": {
23
23
  "source": "./src/index.ts",
24
24
  "types": "./dist/index.d.mts",
25
- "import": "./dist/index.mjs"
25
+ "import": "./dist/index.mjs",
26
+ "default": "./dist/index.mjs"
26
27
  }
27
28
  },
28
29
  "files": [
29
30
  "dist",
30
- "src"
31
+ "src",
32
+ "!src/**/*.test.ts"
31
33
  ],
32
34
  "dependencies": {
33
35
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
34
- "@statewalker/db-api": "^0.1.5",
35
- "@statewalker/db-sqlite": "^0.1.1"
36
+ "@statewalker/db-sqlite": "^0.1.3",
37
+ "@statewalker/db-api": "^0.1.7"
36
38
  },
37
39
  "devDependencies": {
38
40
  "@playwright/test": "^1.63.0",
@@ -23,10 +23,26 @@ const MAIN_THREAD_PATH =
23
23
 
24
24
  type InitModule = (module?: { locateFile?: (file: string) => string }) => Promise<Sqlite3Static>;
25
25
 
26
- /** One engine per wasmUrl, started on first use; one OPFS pool per engine. */
26
+ /**
27
+ * One engine per wasmUrl, started on first use; one OPFS pool per engine. A start that fails is
28
+ * forgotten, so the next call tries again: the pool's install fails while another worker holds the
29
+ * pool, and works once that worker is gone.
30
+ */
27
31
  const engines = new Map<string, Promise<Sqlite3Static>>();
28
32
  const pools = new WeakMap<Sqlite3Static, Promise<SAHPoolUtil>>();
29
33
 
34
+ /** `promise`, removed from the cache when it rejects (if it is still the cached one). */
35
+ function forgetOnFailure<K, V>(
36
+ cache: { get(key: K): Promise<V> | undefined; delete(key: K): unknown },
37
+ key: K,
38
+ promise: Promise<V>,
39
+ ): Promise<V> {
40
+ promise.catch(() => {
41
+ if (cache.get(key) === promise) cache.delete(key);
42
+ });
43
+ return promise;
44
+ }
45
+
30
46
  function getSqlite3(wasmUrl: string | undefined): Promise<Sqlite3Static> {
31
47
  const key = wasmUrl ?? "";
32
48
  let engine = engines.get(key);
@@ -35,6 +51,7 @@ function getSqlite3(wasmUrl: string | undefined): Promise<Sqlite3Static> {
35
51
  wasmUrl ? { locateFile: (file) => (file.endsWith(".wasm") ? wasmUrl : file) } : undefined,
36
52
  );
37
53
  engines.set(key, engine);
54
+ forgetOnFailure(engines, key, engine);
38
55
  }
39
56
  return engine;
40
57
  }
@@ -42,8 +59,14 @@ function getSqlite3(wasmUrl: string | undefined): Promise<Sqlite3Static> {
42
59
  function getPool(sqlite3: Sqlite3Static): Promise<SAHPoolUtil> {
43
60
  let pool = pools.get(sqlite3);
44
61
  if (!pool) {
45
- pool = sqlite3.installOpfsSAHPoolVfs({});
62
+ // sqlite-wasm caches a failed install too, unless told to try again. The option is
63
+ // documented and implemented by sqlite-wasm but missing from its type declarations.
64
+ const options = { forceReinitIfPreviouslyFailed: true } as Parameters<
65
+ Sqlite3Static["installOpfsSAHPoolVfs"]
66
+ >[0];
67
+ pool = sqlite3.installOpfsSAHPoolVfs(options);
46
68
  pools.set(sqlite3, pool);
69
+ forgetOnFailure(pools, sqlite3, pool);
47
70
  }
48
71
  return pool;
49
72
  }
@@ -1,159 +0,0 @@
1
- import type { Db } from "@statewalker/db-api";
2
- import { runDbConformance, runSqliteTransactionConformance } from "@statewalker/db-tests";
3
- import { afterEach, describe, expect, it } from "vitest";
4
- import { newBrowserSqliteDb } from "./browser-sqlite-db.js";
5
-
6
- /**
7
- * The sqlite-wasm adapter, exercised in a REAL browser (Vitest browser
8
- * mode + Playwright/Chromium). Launched only by `vitest.browser.config.ts` (the
9
- * `test:browser` script) — the Node config excludes `*.browser.test.ts`.
10
- *
11
- * Everything runs in-memory except the OPFS tests, which use Dedicated Workers;
12
- * the node-only file-persistence scenario is skipped via `skipFilePersistence`.
13
- */
14
-
15
- runDbConformance(() => newBrowserSqliteDb(), { placeholder: "?", skipFilePersistence: true });
16
- runSqliteTransactionConformance(() => newBrowserSqliteDb());
17
-
18
- // Dialect-specific browser behavior the shared suite does not cover: FTS5 full-text search.
19
- describe("newBrowserSqliteDb", () => {
20
- let db: Db;
21
-
22
- afterEach(async () => {
23
- if (db) {
24
- await db.close();
25
- }
26
- });
27
-
28
- describe("FTS5", () => {
29
- it("has the trigram tokenizer (substring search)", async () => {
30
- db = await newBrowserSqliteDb();
31
- await db.exec("CREATE VIRTUAL TABLE g USING fts5(c, tokenize='trigram')");
32
- await db.exec("INSERT INTO g VALUES ('idx_lefthand')");
33
- const rows = await db.query<{ c: string }>("SELECT c FROM g WHERE g MATCH 'x_le'");
34
- expect(rows.map((r) => r.c)).toEqual(["idx_lefthand"]);
35
- });
36
-
37
- it("returns empty results for unmatched search terms", async () => {
38
- db = await newBrowserSqliteDb();
39
- await db.exec("CREATE VIRTUAL TABLE docs2_fts USING fts5(content)");
40
- await db.exec(
41
- "INSERT INTO docs2_fts (rowid, content) VALUES (1, 'hello world'), (2, 'goodbye world')",
42
- );
43
-
44
- const rows = await db.query<{ content: string }>(
45
- "SELECT content FROM docs2_fts WHERE docs2_fts MATCH 'nonexistent'",
46
- );
47
- expect(rows).toHaveLength(0);
48
- });
49
-
50
- it("searches across multiple text columns", async () => {
51
- db = await newBrowserSqliteDb();
52
- await db.exec("CREATE VIRTUAL TABLE articles_fts USING fts5(title, body, tokenize='porter')");
53
- await db.exec(`
54
- INSERT INTO articles_fts (rowid, title, body) VALUES
55
- (1, 'Travel Guide', 'Visit the beautiful lakes of Switzerland'),
56
- (2, 'Cooking Tips', 'How to make a perfect lake trout'),
57
- (3, 'Programming', 'Learn about SQL databases')
58
- `);
59
-
60
- const rows = await db.query<{ rowid: number; title: string; score: number }>(`
61
- SELECT rowid, title, bm25(articles_fts) AS score
62
- FROM articles_fts
63
- WHERE articles_fts MATCH 'lake'
64
- ORDER BY score
65
- `);
66
- expect(rows).toHaveLength(2);
67
- const titles = rows.map((r) => r.title);
68
- expect(titles).toContain("Travel Guide");
69
- expect(titles).toContain("Cooking Tips");
70
- });
71
-
72
- it("creates an FTS5 index and performs full-text search", async () => {
73
- db = await newBrowserSqliteDb();
74
- await db.exec("CREATE VIRTUAL TABLE docs_fts USING fts5(content)");
75
- await db.exec(`
76
- INSERT INTO docs_fts (rowid, content) VALUES
77
- (1, 'the quick brown fox jumps over the lazy dog'),
78
- (2, 'a lazy cat sleeps on the mat'),
79
- (3, 'the fox and the hound are friends')
80
- `);
81
-
82
- const rows = await db.query<{ rowid: number; content: string; score: number }>(`
83
- SELECT rowid, content, bm25(docs_fts) AS score
84
- FROM docs_fts
85
- WHERE docs_fts MATCH 'fox'
86
- ORDER BY score
87
- `);
88
-
89
- expect(rows.length).toBeGreaterThanOrEqual(1);
90
- const rowids = rows.map((r) => r.rowid);
91
- expect(rowids).toContain(1);
92
- expect(rowids).toContain(3);
93
- });
94
- });
95
- });
96
-
97
- type TestWorker = {
98
- onmessage: ((event: { data: { count?: number; error?: string } }) => void) | null;
99
- onerror: ((event: { message: string }) => void) | null;
100
- postMessage(message: unknown): void;
101
- terminate(): void;
102
- };
103
- const WorkerClass = (
104
- globalThis as unknown as {
105
- Worker: new (url: URL, options: { type: "module" }) => TestWorker;
106
- }
107
- ).Worker;
108
-
109
- /** Run one action in a fresh Dedicated Worker, then terminate it (as a page reload would). */
110
- function inWorker(
111
- message:
112
- | { path: string; action: "write" | "count" }
113
- | { path: string; action: "open-many"; files: number; capacity?: number },
114
- ): Promise<number> {
115
- return new Promise((resolve, reject) => {
116
- const worker = new WorkerClass(new URL("../test/opfs-test-worker.ts", import.meta.url), {
117
- type: "module",
118
- });
119
- worker.onmessage = ({ data }) => {
120
- worker.terminate();
121
- if (data.error) reject(new Error(data.error));
122
- else resolve(Number(data.count));
123
- };
124
- worker.onerror = (event) => {
125
- worker.terminate();
126
- reject(new Error(event.message));
127
- };
128
- worker.postMessage(message);
129
- });
130
- }
131
-
132
- describe("OPFS persistence (opfs-sahpool)", () => {
133
- it("rejects a persistent path on the main thread", async () => {
134
- await expect(newBrowserSqliteDb({ path: "/main-thread.db" })).rejects.toThrow(
135
- /Dedicated Worker/,
136
- );
137
- });
138
-
139
- it("keeps a path's data from one worker to the next", async () => {
140
- const path = `/persist-${Date.now()}.db`;
141
- expect(await inWorker({ path, action: "write" })).toBe(1);
142
- expect(await inWorker({ path, action: "count" })).toBe(1);
143
- });
144
-
145
- // Order matters: the pool's capacity is stored in OPFS and only grows, so the default-size
146
- // case must run before any test raises it. Files stay in the pool after close, so the
147
- // second case leaves room for the ones the first left behind.
148
- it("runs out of pool files with the default capacity", async () => {
149
- const path = `/full-${Date.now()}`;
150
- await expect(inWorker({ path, action: "open-many", files: 10 })).rejects.toThrow(
151
- /SQLITE_CANTOPEN/,
152
- );
153
- });
154
-
155
- it("opens more databases once capacity is raised", async () => {
156
- const path = `/many-${Date.now()}`;
157
- expect(await inWorker({ path, action: "open-many", files: 10, capacity: 32 })).toBe(10);
158
- });
159
- });
@@ -1,25 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import { runDbConformance, runSqliteTransactionConformance } from "@statewalker/db-tests";
3
- import { describe, expect, it } from "vitest";
4
- import { newBrowserSqliteDb } from "./browser-sqlite-db.js";
5
-
6
- // The same WASM engine as in the browser, in memory: the shared suites run under Node too.
7
- runDbConformance(() => newBrowserSqliteDb(), { placeholder: "?", skipFilePersistence: true });
8
- runSqliteTransactionConformance(() => newBrowserSqliteDb());
9
-
10
- describe("newBrowserSqliteDb under Node", () => {
11
- it("rejects a persistent path outside a Dedicated Worker", async () => {
12
- await expect(newBrowserSqliteDb({ path: "/data.db" })).rejects.toThrow(/Dedicated Worker/);
13
- });
14
-
15
- it("honors a different wasmUrl after an earlier call", async () => {
16
- await expect(newBrowserSqliteDb({ wasmUrl: "/nonexistent/sqlite3.wasm" })).rejects.toThrow();
17
- const wasmPath = createRequire(import.meta.url).resolve("@sqlite.org/sqlite-wasm/sqlite3.wasm");
18
- const db = await newBrowserSqliteDb({ wasmUrl: wasmPath });
19
- try {
20
- expect(await db.query("SELECT 1 AS x")).toEqual([{ x: 1 }]);
21
- } finally {
22
- await db.close();
23
- }
24
- });
25
- });