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: #24660 one read-only transaction must not hold every other read behind it
242it.effect("runs an unrelated read while a read-only transaction holds a reader", () =>
243 withReaderClient((sql) =>
244 Effect.gen(function* () {
245 const held = yield* Deferred.make<void>();
246 const release = yield* Deferred.make<void>();
247 const holder = yield* sql
248 .withTransaction(
249 countEntries(sql).pipe(
250 Effect.andThen(Deferred.succeed(held, undefined)),
251 Effect.andThen(Deferred.await(release)),
252 ),
253 )
254 .pipe(SqliteClient.readOnly, Effect.forkChild);
255 yield* Deferred.await(held);
256
257 // The holder ends only after this read, so a single reader permit deadlocks here.
258 const count = yield* countEntries(sql).pipe(SqliteClient.readOnly);
259 yield* Deferred.succeed(release, undefined);
260 yield* Fiber.join(holder);
261
262 assert.equal(count, 1);
263 }),
264 ),
265);
266
267// regression: #19226 read-only transactions run on the separate reader connection
268it.effect("rejects a write in a read-only transaction", () =>
269 withReaderClient((sql) =>
270 Effect.gen(function* () {
271 const error = yield* sql
272 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
273 .pipe(SqliteClient.readOnly, Effect.flip);
274
275 assert.equal(error._tag, "SqlError");
276 assert.include(String(error.reason.cause), "readonly database");
277 assert.equal(yield* countEntries(sql), 1);
278 }),
279 ),
280);
281
282it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
283 withReaderClient((sql) =>
284 Effect.gen(function* () {
285 const error = yield* sql
286 .withTransaction(
287 Effect.gen(function* () {
288 yield* sql`PRAGMA query_only = OFF`;
289 yield* sql`INSERT INTO entries VALUES ('blocked')`;
290 }),
291 )
292 .pipe(SqliteClient.readOnly, Effect.flip);
293
294 assert.equal(error._tag, "SqlError");
295 assert.include(String(error.reason.cause), "readonly database");
296 assert.equal(yield* countEntries(sql), 1);
297 }),
298 ),
299);
300
301it.effect("keeps read-only work inside a write transaction on the writer", () =>
302 withReaderClient((sql) =>
303 sql.withTransaction(
304 Effect.gen(function* () {
305 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
306 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
307 assert.equal(count, 2);
308 }),
309 ),
310 ),
311);
312
313it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
314 withReaderClient((sql) =>
315 Effect.gen(function* () {
316 const startedBefore = startedWorkers.length;
317 const error = yield* sql
318 .withTransaction(
319 Effect.gen(function* () {
320 yield* countEntries(sql);
321 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
322 return yield* countEntries(sql);
323 }),
324 )
325 .pipe(SqliteClient.readOnly, Effect.flip);
326
327 assert.equal(error._tag, "SqlError");
328 assert.include(String(error.reason.cause), "Database reader exited");
329 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
330 assert.equal(startedWorkers.length, startedBefore + 2);
331 }),
332 ),
333);
334
335const withFileClient = <A, E>(
336 setup: (
337 sql: SqlClient.SqlClient,
338 filename: string,
339 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
340) =>
341 Effect.gen(function* () {
342 const fs = yield* FileSystem.FileSystem;
343 const path = yield* Path.Path;
344 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
345 const filename = path.join(directory, "state.sqlite");
346 return yield* Effect.gen(function* () {
347 return yield* setup(yield* SqlClient.SqlClient, filename);
348 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
349 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
350
351it.effect("uses the writer when the reader cannot open the database", () =>
352 withFileClient((sql, filename) =>
353 Effect.gen(function* () {
354 yield* sql`PRAGMA journal_mode = WAL`;
355 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
356 yield* sql`INSERT INTO entries VALUES ('kept')`;
357 yield* (yield* FileSystem.FileSystem).remove(filename);
358 const startedBefore = startedWorkers.length;
359
360 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
361 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
362 assert.equal(startedWorkers.length, startedBefore + 1);
363 }),
364 ),
365);
366
367it.effect("finishes masked database cleanup after its caller is interrupted", () =>
368 Effect.gen(function* () {
369 const sql = yield* SqlClient.SqlClient;
370 yield* sql`CREATE TABLE cleanup_writes(value INTEGER PRIMARY KEY)`;
371 const entered = yield* Deferred.make<void>();
372 const work = yield* Effect.forkChild(
373 Deferred.succeed(entered, undefined).pipe(
374 Effect.andThen(Effect.never),
375 Effect.onInterrupt(() =>
376 Effect.gen(function* () {
377 yield* sql`INSERT INTO cleanup_writes VALUES (1)`;
378 yield* sql.withTransaction(sql`INSERT INTO cleanup_writes VALUES (2)`);
379 }),
380 ),
381 ),
382 { startImmediately: true },
383 );
384 yield* Deferred.await(entered);
385 yield* Fiber.interrupt(work);
386 assert.deepEqual(yield* sql`SELECT value FROM cleanup_writes ORDER BY value`.values, [
387 [1],
388 [2],
389 ]);
390 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
391);
392
393// 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
394const eventLoopTurn = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
395
396it.effect.each([
397 { reservation: false, masked: false },
398 { reservation: false, masked: true },
399 { reservation: true, masked: false },
400 { reservation: true, masked: true },
401])(
402 "preserves caller cancellation while waiting (reservation=$reservation, masked=$masked)",
403 ({ reservation, masked }) =>
404 Effect.gen(function* () {
405 const sql = yield* SqlClient.SqlClient;
406 yield* sql`CREATE TABLE entries(value INTEGER)`;
407 const held = yield* Deferred.make<void>();
408 const release = yield* Deferred.make<void>();
409 const holder = yield* Effect.forkChild(
410 sql.withTransaction(
411 Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
412 ),
413 { startImmediately: true },
414 );
415 yield* Deferred.await(held);
416 const entered = yield* Deferred.make<void>();
417 const body = sql`INSERT INTO entries VALUES (1)`.pipe(
418 Effect.andThen(Deferred.succeed(entered, undefined)),
419 );
420 const acquire = reservation
421 ? Effect.scoped(
422 Effect.gen(function* () {
423 const connection = yield* sql.reserve;
424 yield* connection.executeUnprepared("INSERT INTO entries VALUES (1)", [], undefined);
425 yield* Deferred.succeed(entered, undefined);
426 }),
427 )
428 : sql.withTransaction(body);
429 const waiter = yield* Effect.forkChild(masked ? Effect.uninterruptible(acquire) : acquire, {
430 startImmediately: true,
431 });
432 const cancelled = yield* Effect.forkChild(Fiber.interrupt(waiter), {
433 startImmediately: true,
434 });
435 yield* Effect.gen(function* () {
436 yield* eventLoopTurn;
437 assert.equal(cancelled.pollUnsafe() !== undefined, !masked);
438 assert.isFalse(yield* Deferred.isDone(entered));
439 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
440 yield* Fiber.join(holder);
441 yield* Fiber.join(cancelled);
442 assert.equal(yield* Deferred.isDone(entered), masked);
443 yield* sql.withTransaction(sql`INSERT INTO entries VALUES (2)`);
444 assert.deepEqual(
445 yield* sql`SELECT value FROM entries ORDER BY value`.values,
446 masked ? [[1], [2]] : [[2]],
447 );
448 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
449);