Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6import type * as NodeWorkerThreads from "node:worker_threads";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as SqlClient from "effect/sql/SqlClient";
14import { vi } from "vite-plus/test";
15
16import * as SqlitePersistence from "./Sqlite.ts";
17
18const workers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
19
20vi.mock("node:worker_threads", async (importOriginal) => {
21 const actual = await importOriginal<typeof NodeWorkerThreads>();
22 class RecordedWorker extends actual.Worker {
23 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
24 super(...args);
25 workers.push(this);
26 }
27 }
28 return { ...actual, Worker: RecordedWorker };
29});
30
31it.effect("keeps writes moving past a 48 MiB WAL while a reader retains its snapshot", () => {
32 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-burst-"));
33 const dbPath = NodePath.join(tempDir, "state.sqlite");
34 const persistence = SqlitePersistence.layerFromPath(dbPath).pipe(
35 Layer.provide(NodeServices.layer),
36 );
37
38 return Effect.gen(function* () {
39 const sql = yield* SqlClient.SqlClient;
40 const checkpointWorker = workers.at(-1)!;
41 yield* sql`CREATE TABLE burst_probe(id INTEGER PRIMARY KEY, payload BLOB)`;
42 yield* sql`INSERT INTO burst_probe VALUES (1, NULL)`;
43 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
44 const reader = yield* Effect.acquireRelease(
45 Effect.sync(() => new NodeSqlite.DatabaseSync(dbPath, { readOnly: true })),
46 (database) => Effect.sync(() => database.close()),
47 );
48 reader.exec("BEGIN");
49 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 1);
50
51 yield* sql.withTransaction(
52 sql`INSERT INTO burst_probe VALUES (2, zeroblob(${48 * 1024 * 1024}))`,
53 );
54 const state = yield* Effect.callback<{
55 readonly log: number;
56 readonly checkpointed: number;
57 readonly blocked: boolean;
58 }>((resume) => {
59 const onMessage = (message: {
60 readonly type?: string;
61 readonly log?: number;
62 readonly checkpointed?: number;
63 readonly blocked?: boolean;
64 }) => {
65 if (
66 message.type === "checkpoint" &&
67 typeof message.log === "number" &&
68 message.log > 10_000 &&
69 typeof message.checkpointed === "number" &&
70 typeof message.blocked === "boolean"
71 ) {
72 checkpointWorker.off("message", onMessage);
73 resume(
74 Effect.succeed({
75 log: message.log,
76 checkpointed: message.checkpointed,
77 blocked: message.blocked,
78 }),
79 );
80 }
81 };
82 checkpointWorker.on("message", onMessage);
83 checkpointWorker.ref();
84 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
85 checkpointWorker.postMessage("barrier");
86 return Effect.sync(() => checkpointWorker.off("message", onMessage));
87 });
88 assert.isBelow(state.checkpointed, state.log);
89 assert.isFalse(state.blocked);
90
91 yield* sql.withTransaction(sql`INSERT INTO burst_probe VALUES (3, NULL)`);
92 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 1);
93 reader.exec("COMMIT");
94 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 3);
95 }).pipe(
96 Effect.scoped,
97 Effect.provide(persistence),
98 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
99 );
100});
101
102// Linux names an open, already-deleted file "<path> (deleted)" in /proc/self/fd.
103// SQLite names its temp files "etilqs_*" and, without TMPDIR, puts them in
104// /var/tmp while os.tmpdir() is /tmp, so match the name, not the directory.
105const openDeletedTempFiles = () =>
106 NodeFS.readdirSync("/proc/self/fd").flatMap((fd) => {
107 try {
108 const target = NodeFS.readlinkSync(`/proc/self/fd/${fd}`);
109 return target.includes("/etilqs_") && target.endsWith(" (deleted)") ? [target] : [];
110 } catch {
111 return [];
112 }
113 });
114
115it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
116 "keeps a write transaction's statement journal off the temp directory",
117 () => {
118 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-temp-"));
119 const persistence = SqlitePersistence.layerFromPath(
120 NodePath.join(tempDir, "state.sqlite"),
121 ).pipe(Layer.provide(NodeServices.layer));
122
123 return Effect.gen(function* () {
124 const sql = yield* SqlClient.SqlClient;
125 yield* sql`CREATE TABLE journal_probe(id INTEGER PRIMARY KEY, payload TEXT NOT NULL)`;
126 for (let id = 0; id < 64; id++) {
127 yield* sql`INSERT INTO journal_probe VALUES (${id}, ${"x".repeat(4096)})`;
128 }
129 const before = new Set(openDeletedTempFiles());
130 const opened = yield* sql.withTransaction(
131 Effect.gen(function* () {
132 // A multi-row update can fail halfway, so SQLite journals every page
133 // it changes, here well past the 64 KiB it holds in memory by default.
134 yield* sql`UPDATE journal_probe SET payload = payload || 'y'`;
135 return openDeletedTempFiles().filter((target) => !before.has(target));
136 }),
137 );
138 assert.deepEqual(opened, []);
139 }).pipe(
140 Effect.provide(persistence),
141 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
142 );
143 },
144);
145
146it.effect("drops planner statistics a database already has", () => {
147 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
148 const dbPath = NodePath.join(tempDir, "state.sqlite");
149 const persistence = () =>
150 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer));
151
152 return Effect.gen(function* () {
153 yield* Effect.gen(function* () {
154 const sql = yield* SqlClient.SqlClient;
155 yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
156 yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
157 yield* sql`ANALYZE walk_probe`;
158 }).pipe(Effect.provide(persistence()));
159
160 yield* Effect.gen(function* () {
161 const sql = yield* SqlClient.SqlClient;
162 const stats = yield* sql<{ readonly count: number }>`
163 SELECT COUNT(*) AS count FROM sqlite_stat1
164 `;
165 assert.equal(stats[0]?.count, 0);
166 // A connection still using the old stats scans the table at each step.
167 const plan = yield* sql<{ readonly detail: string }>`
168 EXPLAIN QUERY PLAN
169 WITH RECURSIVE retained(node_id) AS (
170 SELECT 'node-2'
171 UNION
172 SELECT parent.parent_node_id FROM walk_probe AS parent
173 INNER JOIN retained ON parent.node_id = retained.node_id
174 )
175 SELECT node_id FROM retained
176 `;
177 assert.include(
178 plan.map((row) => row.detail),
179 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
180 );
181 }).pipe(Effect.provide(persistence()));
182 }).pipe(
183 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
184 );
185});