Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sqlite.test.ts

141 lines5.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as SqlClient from "effect/sql/SqlClient";
12​
13import { WAL_SIZE_LIMIT_BYTES } from "./Sqlite.ts";
14import * as SqlitePersistence from "./Sqlite.ts";
15​
16const lockHolderSource = `
17const { DatabaseSync } = require("node:sqlite");
18const db = new DatabaseSync(process.argv[1]);
19db.exec("BEGIN IMMEDIATE");
20process.stdout.write("locked\\n");
21setTimeout(() => {
22 db.exec("COMMIT");
23 db.close();
24}, Number(process.argv[2]));
25`;
26​
27const spawnWriteLockHolder = (dbPath: string, holdMs: number) =>
28 Effect.promise(
29 () =>
30 new Promise<void>((resolve, reject) => {
31 const holder = NodeChildProcess.spawn(
32 process.execPath,
33 ["-e", lockHolderSource, dbPath, String(holdMs)],
34 { stdio: ["ignore", "pipe", "ignore"] },
35 );
36 holder.stdout.once("data", () => resolve());
37 holder.on("error", reject);
38 holder.on("exit", () =>
39 reject(new Error("lock holder exited before acquiring the write lock")),
40 );
41 }),
42 );
43​
44it.effect("waits out a concurrent writer instead of failing with SQLITE_BUSY", () => {
45 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-busy-"));
46 const dbPath = NodePath.join(tempDir, "state.sqlite");
47​
48 return Effect.gen(function* () {
49 const sql = yield* SqlClient.SqlClient;
50 yield* sql`CREATE TABLE busy_probe(id INTEGER PRIMARY KEY)`;
51 yield* spawnWriteLockHolder(dbPath, 300);
52 yield* sql`INSERT INTO busy_probe(id) VALUES (${1})`;
53 const rows = yield* sql<{ readonly id: number }>`SELECT id FROM busy_probe`;
54 assert.deepEqual([...rows], [{ id: 1 }]);
55 }).pipe(
56 Effect.provide(SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer))),
57 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
58 );
59});
60​
61it.effect("limits the WAL file size in the shared persistence setup", () =>
62 Effect.gen(function* () {
63 const sql = yield* SqlClient.SqlClient;
64 const rows = yield* sql<{ readonly journal_size_limit: number }>`PRAGMA journal_size_limit`;
65 assert.equal(rows[0]?.journal_size_limit, WAL_SIZE_LIMIT_BYTES);
66 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
67);
68​
69it.effect("drops planner statistics a database already has", () => {
70 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
71 const dbPath = NodePath.join(tempDir, "state.sqlite");
72 const persistence = () =>
73 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer));
74​
75 return Effect.gen(function* () {
76 yield* Effect.gen(function* () {
77 const sql = yield* SqlClient.SqlClient;
78 yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
79 yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
80 // Stats from a nearly empty table, as an older build collected on a new install.
81 yield* sql`ANALYZE walk_probe`;
82 }).pipe(Effect.provide(persistence()));
83​
84 yield* Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
86 const stats = yield* sql<{ readonly count: number }>`
87 SELECT COUNT(*) AS count FROM sqlite_stat1
88 `;
89 assert.equal(stats[0]?.count, 0);
90 // A connection still using the old stats scans the table at each step.
91 const plan = yield* sql<{ readonly detail: string }>`
92 EXPLAIN QUERY PLAN
93 WITH RECURSIVE retained(node_id) AS (
94 SELECT 'node-2'
95 UNION
96 SELECT parent.parent_node_id FROM walk_probe AS parent
97 INNER JOIN retained ON parent.node_id = retained.node_id
98 )
99 SELECT node_id FROM retained
100 `;
101 assert.include(
102 plan.map((row) => row.detail),
103 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
104 );
105 }).pipe(Effect.provide(persistence()));
106 }).pipe(
107 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
108 );
109});
110​
111it.effect("only fsyncs the database file at WAL checkpoints", () => {
112 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-sync-"));
113 const dbPath = NodePath.join(tempDir, "state.sqlite");
114​
115 return Effect.gen(function* () {
116 const sql = yield* SqlClient.SqlClient;
117 const rows = yield* sql<{ readonly synchronous: number }>`PRAGMA synchronous`;
118 assert.equal(rows[0]?.synchronous, 1);
119 }).pipe(
120 Effect.provide(SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer))),
121 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
122 );
123});
124​
125it.effect("applies busy_timeout in the shared persistence setup", () =>
126 Effect.gen(function* () {
127 const sql = yield* SqlClient.SqlClient;
128 const rows = yield* sql<{ readonly timeout: number }>`PRAGMA busy_timeout`;
129 assert.equal(rows[0]?.timeout, 5000);
130 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
131);
132​
133it.effect("enables checkpoint_fullfsync in the shared persistence setup", () =>
134 Effect.gen(function* () {
135 const sql = yield* SqlClient.SqlClient;
136 const rows = yield* sql<{
137 readonly checkpoint_fullfsync: number;
138 }>`PRAGMA checkpoint_fullfsync`;
139 assert.equal(rows[0]?.checkpoint_fullfsync, 1);
140 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
141);