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

nodeSqliteClient.test.ts

387 lines15.4 KB

1import * as NodeSqlite from "node:sqlite";
2import type * as NodeWorkerThreads from "node:worker_threads";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as SqlClient from "effect/sql/SqlClient";
11import { vi } from "vite-plus/test";
12​
13import * as SqliteClient from "./nodeSqliteClient.ts";
14​
15const startedWorkers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
16const silentWorkers = vi.hoisted(() => ({ on: false, readyOnTerminate: false }));
17const failingWorkers = vi.hoisted(() => ({ message: undefined as string | undefined }));
18​
19vi.mock("node:worker_threads", async (importOriginal) => {
20 const actual = await importOriginal<typeof NodeWorkerThreads>();
21 class RecordedWorker extends actual.Worker {
22 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
23 super(
24 ...((silentWorkers.on
25 ? ["setInterval(() => {}, 1 << 30);", { eval: true }]
26 : failingWorkers.message !== undefined
27 ? [`throw new Error(${JSON.stringify(failingWorkers.message)});`, { eval: true }]
28 : args) as ConstructorParameters<typeof actual.Worker>),
29 );
30 startedWorkers.push(this);
31 }
32 override terminate() {
33 // A "ready" already queued when termination starts reaches the parent before "exit".
34 if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" });
35 return super.terminate();
36 }
37 }
38 return { ...actual, Worker: RecordedWorker };
39});
40​
41const withReaderClient = <A, E>(
42 use: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, SqlClient.SqlClient>,
43) =>
44 Effect.gen(function* () {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-" });
48 const filename = path.join(directory, "state.sqlite");
49 return yield* Effect.gen(function* () {
50 const sql = yield* SqlClient.SqlClient;
51 yield* sql`PRAGMA journal_mode = WAL`;
52 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
53 yield* sql`INSERT INTO entries VALUES ('first')`;
54 return yield* use(sql);
55 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
56 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
57​
58const countEntries = (sql: SqlClient.SqlClient) =>
59 Effect.map(
60 sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`,
61 (rows) => rows[0]?.count,
62 );
63​
64const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
65​
66layer("NodeSqliteClient", (it) => {
67 it.effect("retries preparing a query after the missing schema becomes available", () =>
68 Effect.gen(function* () {
69 const sql = yield* SqlClient.SqlClient;
70 const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`;
71 const error = yield* select.pipe(Effect.flip);
72 assert.equal(error._tag, "SqlError");
73 assert.equal(error.reason.operation, "prepare");
74​
75 yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`;
76 yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`;
77 assert.deepEqual(yield* select, [{ name: "recovered" }]);
78 assert.deepEqual(yield* select.values, [["recovered"]]);
79 }),
80 );
81​
82 it.effect("classifies constraint failures by their SQLite result code", () =>
83 Effect.gen(function* () {
84 const sql = yield* SqlClient.SqlClient;
85 yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`;
86 yield* sql`INSERT INTO constrained VALUES ('taken')`;
87​
88 const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip);
89 assert(duplicate.reason._tag === "UniqueViolation");
90 assert.equal(duplicate.reason.constraint, "constrained.name");
91​
92 const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip);
93 assert.equal(missing.reason._tag, "ConstraintError");
94 }),
95 );
96});
97​
98const largeText = "x".repeat(64 * 1024 + 1);
99​
100it.effect("reads integers on the values path as the caller asked, cached or not", () =>
101 Effect.gen(function* () {
102 const sql = yield* SqlClient.SqlClient;
103 for (const value of ["small", largeText]) {
104 const values = sql`SELECT 1 AS id, length(${value}) AS size`.values;
105 assert.deepEqual(yield* values.pipe(Effect.provideService(SqlClient.SafeIntegers, true)), [
106 [1n, BigInt(value.length)],
107 ]);
108 assert.deepEqual(yield* values, [[1, value.length]]);
109 }
110 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
111);
112​
113const makeTempDatabase = Effect.gen(function* () {
114 const fs = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
117 const filename = path.join(directory, "state.sqlite");
118 const other = yield* Effect.acquireRelease(
119 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
120 (database) => Effect.sync(() => database.close()),
121 );
122 yield* Effect.sync(() => {
123 other.exec(`
124 PRAGMA journal_mode = WAL;
125 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
126 INSERT INTO counters VALUES (1, 0);
127 `);
128 });
129 return { filename, other };
130});
131​
132it.effect("keeps another connection from committing between a transaction's read and write", () =>
133 Effect.gen(function* () {
134 const { filename, other } = yield* makeTempDatabase;
135 yield* Effect.gen(function* () {
136 const sql = yield* SqlClient.SqlClient;
137 yield* sql.withTransaction(
138 Effect.gen(function* () {
139 const [row] = yield* sql<{ readonly value: number }>`
140 SELECT value FROM counters WHERE id = 1
141 `;
142 // With a deferred BEGIN this commit lands and the write below fails
143 // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out.
144 yield* Effect.sync(() =>
145 assert.throws(
146 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
147 /database is locked/,
148 ),
149 );
150 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
151 }),
152 );
153 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
154 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
155 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
156 }).pipe(Effect.provide(NodeServices.layer)),
157);
158​
159it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
160 Effect.gen(function* () {
161 const { filename, other } = yield* makeTempDatabase;
162 yield* Effect.gen(function* () {
163 const sql = yield* SqlClient.SqlClient;
164 yield* sql`PRAGMA busy_timeout = 0`;
165 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
166​
167 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
168 const error = yield* read.pipe(Effect.flip);
169 assert.equal(error.reason._tag, "LockTimeoutError");
170​
171 yield* Effect.sync(() => other.exec("COMMIT"));
172 assert.deepEqual(yield* read, [[0]]);
173 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
174 }).pipe(Effect.provide(NodeServices.layer)),
175);
176​
177it.effect("lets the writer commit while a read-only transaction is open", () =>
178 withReaderClient((sql) =>
179 Effect.gen(function* () {
180 const snapshotTaken = yield* Deferred.make<void>();
181 const writer = yield* Effect.forkChild(
182 Deferred.await(snapshotTaken).pipe(
183 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
184 ),
185 );
186 const counts = yield* sql
187 .withTransaction(
188 Effect.gen(function* () {
189 const before = yield* countEntries(sql);
190 yield* Deferred.succeed(snapshotTaken, undefined);
191 // Holding the writer lock here would deadlock this join.
192 yield* Fiber.join(writer);
193 const after = yield* countEntries(sql);
194 return { before, after };
195 }),
196 )
197 .pipe(SqliteClient.readOnly);
198​
199 assert.deepEqual(counts, { before: 1, after: 1 });
200 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2);
201 }),
202 ),
203);
204​
205// regression: #19226 read-only transactions run on the separate reader connection
206it.effect("rejects a write in a read-only transaction", () =>
207 withReaderClient((sql) =>
208 Effect.gen(function* () {
209 const error = yield* sql
210 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
211 .pipe(SqliteClient.readOnly, Effect.flip);
212​
213 assert.equal(error._tag, "SqlError");
214 assert.include(String(error.reason.cause), "readonly database");
215 assert.equal(yield* countEntries(sql), 1);
216 }),
217 ),
218);
219​
220it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
221 withReaderClient((sql) =>
222 Effect.gen(function* () {
223 const error = yield* sql
224 .withTransaction(
225 Effect.gen(function* () {
226 yield* sql`PRAGMA query_only = OFF`;
227 yield* sql`INSERT INTO entries VALUES ('blocked')`;
228 }),
229 )
230 .pipe(SqliteClient.readOnly, Effect.flip);
231​
232 assert.equal(error._tag, "SqlError");
233 assert.include(String(error.reason.cause), "readonly database");
234 assert.equal(yield* countEntries(sql), 1);
235 }),
236 ),
237);
238​
239it.effect("keeps read-only work inside a write transaction on the writer", () =>
240 withReaderClient((sql) =>
241 sql.withTransaction(
242 Effect.gen(function* () {
243 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
244 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
245 assert.equal(count, 2);
246 }),
247 ),
248 ),
249);
250​
251it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
252 withReaderClient((sql) =>
253 Effect.gen(function* () {
254 const startedBefore = startedWorkers.length;
255 const error = yield* sql
256 .withTransaction(
257 Effect.gen(function* () {
258 yield* countEntries(sql);
259 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
260 return yield* countEntries(sql);
261 }),
262 )
263 .pipe(SqliteClient.readOnly, Effect.flip);
264​
265 assert.equal(error._tag, "SqlError");
266 assert.include(String(error.reason.cause), "Database reader exited");
267 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
268 assert.equal(startedWorkers.length, startedBefore + 2);
269 }),
270 ),
271);
272​
273const withFileClient = <A, E>(
274 setup: (
275 sql: SqlClient.SqlClient,
276 filename: string,
277 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
278) =>
279 Effect.gen(function* () {
280 const fs = yield* FileSystem.FileSystem;
281 const path = yield* Path.Path;
282 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
283 const filename = path.join(directory, "state.sqlite");
284 return yield* Effect.gen(function* () {
285 return yield* setup(yield* SqlClient.SqlClient, filename);
286 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
287 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
288​
289it.effect("uses the writer when the reader cannot open the database", () =>
290 withFileClient((sql, filename) =>
291 Effect.gen(function* () {
292 yield* sql`PRAGMA journal_mode = WAL`;
293 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
294 yield* sql`INSERT INTO entries VALUES ('kept')`;
295 yield* (yield* FileSystem.FileSystem).remove(filename);
296 const startedBefore = startedWorkers.length;
297​
298 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
299 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
300 assert.equal(startedWorkers.length, startedBefore + 1);
301 }),
302 ),
303);
304​
305it.effect("finishes masked database cleanup after its caller is interrupted", () =>
306 Effect.gen(function* () {
307 const sql = yield* SqlClient.SqlClient;
308 yield* sql`CREATE TABLE cleanup_writes(value INTEGER PRIMARY KEY)`;
309 const entered = yield* Deferred.make<void>();
310 const work = yield* Effect.forkChild(
311 Deferred.succeed(entered, undefined).pipe(
312 Effect.andThen(Effect.never),
313 Effect.onInterrupt(() =>
314 Effect.gen(function* () {
315 yield* sql`INSERT INTO cleanup_writes VALUES (1)`;
316 yield* sql.withTransaction(sql`INSERT INTO cleanup_writes VALUES (2)`);
317 }),
318 ),
319 ),
320 { startImmediately: true },
321 );
322 yield* Deferred.await(entered);
323 yield* Fiber.interrupt(work);
324 assert.deepEqual(yield* sql`SELECT value FROM cleanup_writes ORDER BY value`.values, [
325 [1],
326 [2],
327 ]);
328 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
329);
330​
331// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary that lets the worker's queued messages land, not a wait for time
332const eventLoopTurn = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
333​
334it.effect.each([
335 { reservation: false, masked: false },
336 { reservation: false, masked: true },
337 { reservation: true, masked: false },
338 { reservation: true, masked: true },
339])(
340 "preserves caller cancellation while waiting (reservation=$reservation, masked=$masked)",
341 ({ reservation, masked }) =>
342 Effect.gen(function* () {
343 const sql = yield* SqlClient.SqlClient;
344 yield* sql`CREATE TABLE entries(value INTEGER)`;
345 const held = yield* Deferred.make<void>();
346 const release = yield* Deferred.make<void>();
347 const holder = yield* Effect.forkChild(
348 sql.withTransaction(
349 Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
350 ),
351 { startImmediately: true },
352 );
353 yield* Deferred.await(held);
354 const entered = yield* Deferred.make<void>();
355 const body = sql`INSERT INTO entries VALUES (1)`.pipe(
356 Effect.andThen(Deferred.succeed(entered, undefined)),
357 );
358 const acquire = reservation
359 ? Effect.scoped(
360 Effect.gen(function* () {
361 const connection = yield* sql.reserve;
362 yield* connection.executeUnprepared("INSERT INTO entries VALUES (1)", [], undefined);
363 yield* Deferred.succeed(entered, undefined);
364 }),
365 )
366 : sql.withTransaction(body);
367 const waiter = yield* Effect.forkChild(masked ? Effect.uninterruptible(acquire) : acquire, {
368 startImmediately: true,
369 });
370 const cancelled = yield* Effect.forkChild(Fiber.interrupt(waiter), {
371 startImmediately: true,
372 });
373 yield* Effect.gen(function* () {
374 yield* eventLoopTurn;
375 assert.equal(cancelled.pollUnsafe() !== undefined, !masked);
376 assert.isFalse(yield* Deferred.isDone(entered));
377 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
378 yield* Fiber.join(holder);
379 yield* Fiber.join(cancelled);
380 assert.equal(yield* Deferred.isDone(entered), masked);
381 yield* sql.withTransaction(sql`INSERT INTO entries VALUES (2)`);
382 assert.deepEqual(
383 yield* sql`SELECT value FROM entries ORDER BY value`.values,
384 masked ? [[1], [2]] : [[2]],
385 );
386 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
387);