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

Sqlite.test.ts

96 lines3.8 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as SqlClient from "effect/unstable/sql/SqlClient";
12​
13import {
14 SqlitePersistenceMemory,
15 WAL_SIZE_LIMIT_BYTES,
16 makeSqlitePersistenceLive,
17} from "./Sqlite.ts";
18​
19const lockHolderSource = `
20const { DatabaseSync } = require("node:sqlite");
21const db = new DatabaseSync(process.argv[1]);
22db.exec("BEGIN IMMEDIATE");
23process.stdout.write("locked\\n");
24setTimeout(() => {
25 db.exec("COMMIT");
26 db.close();
27}, Number(process.argv[2]));
28`;
29​
30const spawnWriteLockHolder = (dbPath: string, holdMs: number) =>
31 Effect.promise(
32 () =>
33 new Promise<void>((resolve, reject) => {
34 const holder = NodeChildProcess.spawn(
35 process.execPath,
36 ["-e", lockHolderSource, dbPath, String(holdMs)],
37 { stdio: ["ignore", "pipe", "ignore"] },
38 );
39 holder.stdout.once("data", () => resolve());
40 holder.on("error", reject);
41 holder.on("exit", () =>
42 reject(new Error("lock holder exited before acquiring the write lock")),
43 );
44 }),
45 );
46​
47it.effect("waits out a concurrent writer instead of failing with SQLITE_BUSY", () => {
48 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-busy-"));
49 const dbPath = NodePath.join(tempDir, "state.sqlite");
50​
51 return Effect.gen(function* () {
52 const sql = yield* SqlClient.SqlClient;
53 yield* sql`CREATE TABLE busy_probe(id INTEGER PRIMARY KEY)`;
54 yield* spawnWriteLockHolder(dbPath, 300);
55 yield* sql`INSERT INTO busy_probe(id) VALUES (${1})`;
56 const rows = yield* sql<{ readonly id: number }>`SELECT id FROM busy_probe`;
57 assert.deepEqual([...rows], [{ id: 1 }]);
58 }).pipe(
59 Effect.provide(makeSqlitePersistenceLive(dbPath).pipe(Layer.provide(NodeServices.layer))),
60 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
61 );
62});
63​
64it.effect("shrinks the WAL file back to the size limit after a large write", () => {
65 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-wal-"));
66 const dbPath = NodePath.join(tempDir, "state.sqlite");
67 const walFileSize = () => NodeFS.statSync(`${dbPath}-wal`).size;
68 // About 25% more 4 KB rows than the limit holds, in one transaction.
69 const rowCount = Math.ceil((WAL_SIZE_LIMIT_BYTES * 1.25) / 4000);
70​
71 return Effect.gen(function* () {
72 const sql = yield* SqlClient.SqlClient;
73 yield* sql`CREATE TABLE wal_probe(payload BLOB)`;
74 yield* sql`
75 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${rowCount})
76 INSERT INTO wal_probe(payload) SELECT randomblob(4000) FROM n
77 `;
78 assert.isAbove(walFileSize(), WAL_SIZE_LIMIT_BYTES);
79​
80 // The auto-checkpoint after the large commit copied every frame into the
81 // database, so the next commit restarts the WAL and cuts the file back.
82 yield* sql`INSERT INTO wal_probe(payload) VALUES (x'00')`;
83 assert.isAtMost(walFileSize(), WAL_SIZE_LIMIT_BYTES);
84 }).pipe(
85 Effect.provide(makeSqlitePersistenceLive(dbPath).pipe(Layer.provide(NodeServices.layer))),
86 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
87 );
88});
89​
90it.effect("applies busy_timeout in the shared persistence setup", () =>
91 Effect.gen(function* () {
92 const sql = yield* SqlClient.SqlClient;
93 const rows = yield* sql<{ readonly timeout: number }>`PRAGMA busy_timeout`;
94 assert.equal(rows[0]?.timeout, 5000);
95 }).pipe(Effect.provide(SqlitePersistenceMemory)),
96);