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