import * as NodeSqlite from "node:sqlite"; import type * as NodeWorkerThreads from "node:worker_threads"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as Path from "effect/Path"; import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import * as SqliteClient from "./nodeSqliteClient.ts"; const startedWorkers = vi.hoisted((): Array => []); // When on, workers run a script that never announces, like a worker stuck opening the file. const silentWorkers = vi.hoisted(() => ({ on: false, readyOnTerminate: false })); vi.mock("node:worker_threads", async (importOriginal) => { const actual = await importOriginal(); class RecordedWorker extends actual.Worker { constructor(...args: ConstructorParameters) { super( ...((silentWorkers.on ? ["setInterval(() => {}, 1 << 30);", { eval: true }] : args) as ConstructorParameters), ); startedWorkers.push(this); } override terminate() { // A "ready" already queued when termination starts reaches the parent before "exit". if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" }); return super.terminate(); } } return { ...actual, Worker: RecordedWorker }; }); const withReaderClient = ( use: (sql: SqlClient.SqlClient) => Effect.Effect, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-" }); const filename = path.join(directory, "state.sqlite"); return yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* sql`INSERT INTO entries VALUES ('first')`; return yield* use(sql); }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true }))); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); const countEntries = (sql: SqlClient.SqlClient) => Effect.map( sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`, (rows) => rows[0]?.count, ); const layer = it.layer(SqliteClient.layer({ filename: ":memory:" })); layer("NodeSqliteClient", (it) => { it.effect("retries preparing a query after the missing schema becomes available", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`; const error = yield* select.pipe(Effect.flip); assert.equal(error._tag, "SqlError"); assert.equal(error.reason.operation, "prepare"); yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`; yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`; assert.deepEqual(yield* select, [{ name: "recovered" }]); assert.deepEqual(yield* select.values, [["recovered"]]); }), ); it.effect("runs prepared queries and returns positional values", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`; yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`; const rows = yield* sql<{ readonly id: number; readonly name: string }>` SELECT id, name FROM entries ORDER BY id `; assert.equal(rows.length, 2); assert.equal(rows[0]?.name, "alpha"); assert.equal(rows[1]?.name, "beta"); const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values; assert.equal(values.length, 2); assert.equal(values[0]?.[1], "alpha"); assert.equal(values[1]?.[1], "beta"); const unpreparedValues = yield* sql`SELECT id, name FROM entries ORDER BY id` .valuesUnprepared; assert.deepEqual(unpreparedValues, values); }), ); it.effect("returns a typed failure when an unprepared statement cannot be prepared", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const error = yield* Effect.flip(sql.unsafe("SELECT FROM").unprepared); assert.equal(error._tag, "SqlError"); assert.equal(error.reason.operation, "prepare"); }), ); it.effect("classifies constraint failures by their SQLite result code", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`; yield* sql`INSERT INTO constrained VALUES ('taken')`; const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip); assert(duplicate.reason._tag === "UniqueViolation"); assert.equal(duplicate.reason.constraint, "constrained.name"); const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip); assert.equal(missing.reason._tag, "ConstraintError"); }), ); }); const largeText = "x".repeat(64 * 1024 + 1); it.effect("keeps large text and blob parameters off cached statements", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const statements: Array = []; const all = NodeSqlite.StatementSync.prototype.all; yield* Effect.acquireRelease( Effect.sync(() => vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( this: NodeSqlite.StatementSync, ...params ) { statements.push(this); return all.apply(this, params); }), ), (spy) => Effect.sync(() => spy.mockRestore()), ); const small = "small"; const queries = [ (value: string | Uint8Array | ArrayBuffer) => sql`SELECT length(${value}) AS size`, (value: string | Uint8Array | ArrayBuffer) => sql.unsafe("SELECT length($value) AS size", [{ $value: value }]), (value: string | Uint8Array | ArrayBuffer) => sql.unsafe("SELECT length($value) AS callable", [ Object.assign(() => {}, { $value: value }), ]), ]; const cached = new Set(); const large = new Set(); const largeBlobs = [new Uint8Array(64 * 1024 + 1), new ArrayBuffer(64 * 1024 + 1)]; for (const value of [small, largeText, ...largeBlobs, small]) { const expected = typeof value === "string" ? value.length : value.byteLength; for (const query of queries) { assert.deepEqual((yield* query(value)).map(Object.values), [[expected]]); assert.deepEqual(yield* query(value).values, [[expected]]); for (const statement of statements.splice(0)) { (value === small ? cached : large).add(statement); } } } // Small parameters keep reusing the one cached statement for each query. assert.equal(cached.size, queries.length); // Each large execution gets a statement that nothing holds on to afterwards. assert.equal(large.size, queries.length * 6); assert.isTrue(cached.isDisjointFrom(large)); }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), ); it.effect("reads integers on the values path as the caller asked, cached or not", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; for (const value of ["small", largeText]) { const values = sql`SELECT 1 AS id, length(${value}) AS size`.values; assert.deepEqual(yield* values.pipe(Effect.provideService(SqlClient.SafeIntegers, true)), [ [1n, BigInt(value.length)], ]); assert.deepEqual(yield* values, [[1, value.length]]); } }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), ); it.effect("leaves a parameter it cannot measure for the statement to handle", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const detached = new DataView(new ArrayBuffer(8)); structuredClone(detached.buffer, { transfer: [detached.buffer] }); // What a detached view binds as varies by Node version; match the statement itself. const native = new NodeSqlite.DatabaseSync(":memory:"); const expected = native.prepare("SELECT length(?) AS size").all(detached); native.close(); assert.deepEqual(yield* sql`SELECT length(${detached}) AS size`, expected); const throwing = { get $value(): string { throw new Error("unreadable"); }, }; const error = yield* sql.unsafe("SELECT length($value) AS size", [throwing]).pipe(Effect.flip); assert.equal(error.reason.operation, "execute"); // Only the statement reads a getter, so it runs once as it would natively. let reads = 0; const counting = { get $value(): number { return ++reads; }, }; assert.deepEqual(yield* sql.unsafe("SELECT $value AS value", [counting]), [{ value: 1 }]); assert.equal(reads, 1); }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), ); const makeTempDatabase = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" }); const filename = path.join(directory, "state.sqlite"); // node:sqlite connections fail a busy statement at once unless given a timeout. const other = yield* Effect.acquireRelease( Effect.sync(() => new NodeSqlite.DatabaseSync(filename)), (database) => Effect.sync(() => database.close()), ); yield* Effect.sync(() => { other.exec(` PRAGMA journal_mode = WAL; CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL); INSERT INTO counters VALUES (1, 0); `); }); return { filename, other }; }); it.effect("keeps another connection from committing between a transaction's read and write", () => Effect.gen(function* () { const { filename, other } = yield* makeTempDatabase; yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql.withTransaction( Effect.gen(function* () { const [row] = yield* sql<{ readonly value: number }>` SELECT value FROM counters WHERE id = 1 `; // With a deferred BEGIN this commit lands and the write below fails // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out. yield* Effect.sync(() => assert.throws( () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"), /database is locked/, ), ); yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`; }), ); yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1")); assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]); }).pipe(Effect.provide(SqliteClient.layer({ filename }))); }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("reports a transaction blocked by another writer as a lock timeout", () => Effect.gen(function* () { const { filename, other } = yield* makeTempDatabase; yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`PRAGMA busy_timeout = 0`; const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values); yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE")); const error = yield* read.pipe(Effect.flip); assert.equal(error.reason._tag, "LockTimeoutError"); yield* Effect.sync(() => other.exec("COMMIT")); assert.deepEqual(yield* read, [[0]]); }).pipe(Effect.provide(SqliteClient.layer({ filename }))); }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("returns a typed failure when the database cannot be opened", () => Effect.gen(function* () { const error = yield* Effect.flip( Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped), ); assert.equal(error._tag, "SqlError"); assert.equal(error.reason.operation, "open"); }), ); it.effect( "recovers a prepared query immediately after an exclusive database lock is released", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-prepare-" }); const filename = path.join(directory, "state.sqlite"); const blocker = yield* Effect.acquireRelease( Effect.sync(() => new NodeSqlite.DatabaseSync(filename)), (database) => Effect.sync(() => database.close()), ); yield* Effect.sync(() => { blocker.exec("CREATE TABLE entries(value TEXT); INSERT INTO entries VALUES ('retained')"); }); yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* Effect.sync(() => blocker.exec("BEGIN EXCLUSIVE")); const select = sql`SELECT value FROM entries`; const error = yield* select.values.pipe(Effect.flip); assert.equal(error._tag, "SqlError"); assert.equal(error.reason.operation, "prepare"); yield* Effect.sync(() => blocker.exec("ROLLBACK")); assert.deepEqual(yield* select.values, [["retained"]]); assert.deepEqual(yield* select, [{ value: "retained" }]); }).pipe(Effect.provide(SqliteClient.layer({ filename }))); }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("lets the writer commit while a read-only transaction is open", () => withReaderClient((sql) => Effect.gen(function* () { const snapshotTaken = yield* Deferred.make(); const writer = yield* Effect.forkChild( Deferred.await(snapshotTaken).pipe( Effect.andThen(sql`INSERT INTO entries VALUES ('second')`), ), ); const counts = yield* sql .withTransaction( Effect.gen(function* () { const before = yield* countEntries(sql); yield* Deferred.succeed(snapshotTaken, undefined); // Holding the writer lock here would deadlock this join. yield* Fiber.join(writer); const after = yield* countEntries(sql); return { before, after }; }), ) .pipe(SqliteClient.readOnly); // The reader keeps the snapshot it began with, and later reads see the commit. assert.deepEqual(counts, { before: 1, after: 1 }); assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2); }), ), ); it.effect("rejects a write in a read-only transaction", () => withReaderClient((sql) => Effect.gen(function* () { const error = yield* sql .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`) .pipe(SqliteClient.readOnly, Effect.flip); assert.equal(error._tag, "SqlError"); assert.include(String(error.reason.cause), "readonly database"); assert.equal(yield* countEntries(sql), 1); }), ), ); it.effect("keeps the reader read-only even if a statement turns query_only off", () => withReaderClient((sql) => Effect.gen(function* () { const error = yield* sql .withTransaction( Effect.gen(function* () { yield* sql`PRAGMA query_only = OFF`; yield* sql`INSERT INTO entries VALUES ('blocked')`; }), ) .pipe(SqliteClient.readOnly, Effect.flip); assert.equal(error._tag, "SqlError"); assert.include(String(error.reason.cause), "readonly database"); assert.equal(yield* countEntries(sql), 1); }), ), ); it.effect("keeps read-only work inside a write transaction on the writer", () => withReaderClient((sql) => sql.withTransaction( Effect.gen(function* () { yield* sql`INSERT INTO entries VALUES ('uncommitted')`; // Only the writer can see its own uncommitted row. const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly); assert.equal(count, 2); }), ), ), ); it.effect("keeps large parameters off the reader worker's cached statements", () => withReaderClient((sql) => Effect.gen(function* () { const read = (value: string) => sql<{ size: number }>`SELECT length(${value}) AS size`.pipe( Effect.map((rows) => rows[0]?.size), ); // Start the worker so its requests can be recorded. yield* countEntries(sql).pipe(SqliteClient.readOnly); const worker = startedWorkers.at(-1)!; const cached: Array = []; const postMessage = worker.postMessage; yield* Effect.acquireRelease( Effect.sync(() => vi.spyOn(worker, "postMessage").mockImplementation(function ( this: NodeWorkerThreads.Worker, message: { readonly cached: boolean }, ) { cached.push(message.cached); return postMessage.call(this, message); }), ), (spy) => Effect.sync(() => spy.mockRestore()), ); assert.equal(yield* read("small").pipe(SqliteClient.readOnly), 5); assert.equal(yield* read(largeText).pipe(SqliteClient.readOnly), largeText.length); assert.deepEqual(cached, [true, false]); }).pipe(Effect.scoped), ), ); it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () => withReaderClient((sql) => Effect.gen(function* () { const startedBefore = startedWorkers.length; const error = yield* sql .withTransaction( Effect.gen(function* () { yield* countEntries(sql); yield* Effect.promise(() => startedWorkers.at(-1)!.terminate()); return yield* countEntries(sql); }), ) .pipe(SqliteClient.readOnly, Effect.flip); assert.equal(error._tag, "SqlError"); assert.include(String(error.reason.cause), "Database reader exited"); assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); assert.equal(startedWorkers.length, startedBefore + 2); }), ), ); it.effect("uses the writer for read-only work on an in-memory database", () => Effect.gen(function* () { const startedBefore = startedWorkers.length; const sql = yield* SqlClient.SqlClient; yield* sql`CREATE TABLE memory_entries(name TEXT NOT NULL)`; yield* sql`INSERT INTO memory_entries VALUES ('kept')`; const rows = yield* sql .withTransaction(sql<{ name: string }>`SELECT name FROM memory_entries`) .pipe(SqliteClient.readOnly); assert.deepEqual(rows, [{ name: "kept" }]); assert.equal(startedWorkers.length, startedBefore); }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", readerWorker: true }))), ); it.effect("keeps a nested transaction inside a read-only transaction on the reader", () => withReaderClient((sql) => Effect.gen(function* () { const snapshotTaken = yield* Deferred.make(); const writer = yield* Effect.forkChild( Deferred.await(snapshotTaken).pipe( Effect.andThen(sql`INSERT INTO entries VALUES ('second')`), ), ); // Callers wrap a store read that opens its own transaction, as the // shell snapshot routes do around getShellSnapshot. const counts = yield* sql .withTransaction( Effect.gen(function* () { const outer = yield* countEntries(sql); yield* Deferred.succeed(snapshotTaken, undefined); yield* Fiber.join(writer); const nested = yield* sql.withTransaction(countEntries(sql)); return { outer, nested }; }), ) .pipe(SqliteClient.readOnly); assert.deepEqual(counts, { outer: 1, nested: 1 }); }), ), ); const withFileClient = ( setup: ( sql: SqlClient.SqlClient, filename: string, ) => Effect.Effect, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" }); const filename = path.join(directory, "state.sqlite"); return yield* Effect.gen(function* () { return yield* setup(yield* SqlClient.SqlClient, filename); }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true }))); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); it.effect("uses the writer when the reader cannot open the database", () => withFileClient((sql, filename) => Effect.gen(function* () { yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* sql`INSERT INTO entries VALUES ('kept')`; // The writer keeps its open file; a read-only open of the path now fails. yield* (yield* FileSystem.FileSystem).remove(filename); const startedBefore = startedWorkers.length; assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1); assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1); assert.equal(startedWorkers.length, startedBefore + 1); }), ), ); it.effect("uses the writer for a database that is not in WAL mode", () => withFileClient((sql) => Effect.gen(function* () { yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; const startedBefore = startedWorkers.length; // A write inside readOnly only succeeds on the writer: the reader is read-only. yield* sql .withTransaction(sql`INSERT INTO entries VALUES ('on the writer')`) .pipe(SqliteClient.readOnly); assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1); assert.equal(startedWorkers.length, startedBefore + 1); }), ), ); const captureWarnings = () => { const warnings: Array = []; const logger = Logger.make(({ logLevel, message }) => { if (logLevel === "Warn") warnings.push(message); }); return { warnings, layer: Logger.layer([logger], { mergeWithExisting: false }) }; }; const silently = (effect: Effect.Effect) => Effect.acquireUseRelease( Effect.sync(() => { silentWorkers.on = true; }), () => effect, () => Effect.sync(() => { silentWorkers.on = false; silentWorkers.readyOnTerminate = false; }), ); it.effect("turns the reader off when its worker never opens the database", () => { const { warnings, layer: logs } = captureWarnings(); return withFileClient((sql) => Effect.gen(function* () { yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* sql`INSERT INTO entries VALUES ('kept')`; const read = yield* silently( Effect.gen(function* () { const fiber = yield* Effect.forkChild( sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), ); yield* Effect.yieldNow; yield* TestClock.adjust("10 seconds"); return yield* Fiber.join(fiber); }), ); assert.equal(read, 1); assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1); assert.lengthOf(warnings, 1); }), ).pipe(Effect.provide(logs)); }); it.effect("lets a read be cancelled while its worker is still starting", () => withFileClient((sql) => Effect.gen(function* () { yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* silently( Effect.gen(function* () { const fiber = yield* Effect.forkChild( sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), ); yield* Effect.yieldNow; // Never returns if the wait for the worker were uninterruptible: the // test clock has not moved, so the startup deadline cannot fire. yield* Fiber.interrupt(fiber); }), ); // The client stays usable: the next read waits out the deadline, then uses the writer. const next = yield* Effect.forkChild( sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), ); yield* Effect.yieldNow; yield* TestClock.adjust("10 seconds"); assert.equal(yield* Fiber.join(next), 0); }), ), ); it.effect("logs one warning when concurrent first reads find the reader unavailable", () => { const { warnings, layer: logs } = captureWarnings(); return withFileClient((sql, filename) => Effect.gen(function* () { yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* (yield* FileSystem.FileSystem).remove(filename); const startedBefore = startedWorkers.length; const counts = yield* Effect.all( [ sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), ], { concurrency: "unbounded" }, ); assert.deepEqual(counts, [0, 0]); assert.equal(startedWorkers.length, startedBefore + 1); assert.lengthOf(warnings, 1); }), ).pipe(Effect.provide(logs)); }); it.effect("does not hand out a worker that reports ready after another read timed it out", () => withFileClient((sql) => Effect.gen(function* () { yield* sql`PRAGMA journal_mode = WAL`; yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`; yield* sql`INSERT INTO entries VALUES ('kept')`; const read = () => sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly); const counts = yield* silently( Effect.gen(function* () { const first = yield* Effect.forkChild(read()); yield* Effect.yieldNow; yield* TestClock.adjust("5 seconds"); const second = yield* Effect.forkChild(read()); yield* Effect.yieldNow; // The first read reaches its deadline and retires the worker; the second // is still waiting when the worker's "ready" arrives, before it exits. silentWorkers.readyOnTerminate = true; yield* TestClock.adjust("5 seconds"); return [yield* Fiber.join(first), yield* Fiber.join(second)]; }), ); assert.deepEqual(counts, [1, 1]); }), ), );