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

nodeSqliteClient.test.ts

184 lines7.6 KB

1import * as NodeSqlite from "node:sqlite";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as SqlClient from "effect/sql/SqlClient";
9​
10import * as SqliteClient from "./nodeSqliteClient.ts";
11​
12const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
13​
14layer("NodeSqliteClient", (it) => {
15 it.effect("retries preparing a query after the missing schema becomes available", () =>
16 Effect.gen(function* () {
17 const sql = yield* SqlClient.SqlClient;
18 const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`;
19 const error = yield* select.pipe(Effect.flip);
20 assert.equal(error._tag, "SqlError");
21 assert.equal(error.reason.operation, "prepare");
22​
23 yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`;
24 yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`;
25 assert.deepEqual(yield* select, [{ name: "recovered" }]);
26 assert.deepEqual(yield* select.values, [["recovered"]]);
27 }),
28 );
29​
30 it.effect("runs prepared queries and returns positional values", () =>
31 Effect.gen(function* () {
32 const sql = yield* SqlClient.SqlClient;
33​
34 yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
35 yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
36​
37 const rows = yield* sql<{ readonly id: number; readonly name: string }>`
38 SELECT id, name FROM entries ORDER BY id
39 `;
40 assert.equal(rows.length, 2);
41 assert.equal(rows[0]?.name, "alpha");
42 assert.equal(rows[1]?.name, "beta");
43​
44 const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
45 assert.equal(values.length, 2);
46 assert.equal(values[0]?.[1], "alpha");
47 assert.equal(values[1]?.[1], "beta");
48​
49 const unpreparedValues = yield* sql`SELECT id, name FROM entries ORDER BY id`
50 .valuesUnprepared;
51 assert.deepEqual(unpreparedValues, values);
52 }),
53 );
54​
55 it.effect("returns a typed failure when an unprepared statement cannot be prepared", () =>
56 Effect.gen(function* () {
57 const sql = yield* SqlClient.SqlClient;
58 const error = yield* Effect.flip(sql.unsafe("SELECT FROM").unprepared);
59​
60 assert.equal(error._tag, "SqlError");
61 assert.equal(error.reason.operation, "prepare");
62 }),
63 );
64​
65 it.effect("classifies constraint failures by their SQLite result code", () =>
66 Effect.gen(function* () {
67 const sql = yield* SqlClient.SqlClient;
68 yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`;
69 yield* sql`INSERT INTO constrained VALUES ('taken')`;
70​
71 const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip);
72 assert(duplicate.reason._tag === "UniqueViolation");
73 assert.equal(duplicate.reason.constraint, "constrained.name");
74​
75 const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip);
76 assert.equal(missing.reason._tag, "ConstraintError");
77 }),
78 );
79});
80​
81const makeTempDatabase = Effect.gen(function* () {
82 const fs = yield* FileSystem.FileSystem;
83 const path = yield* Path.Path;
84 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
85 const filename = path.join(directory, "state.sqlite");
86 // node:sqlite connections fail a busy statement at once unless given a timeout.
87 const other = yield* Effect.acquireRelease(
88 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
89 (database) => Effect.sync(() => database.close()),
90 );
91 yield* Effect.sync(() => {
92 other.exec(`
93 PRAGMA journal_mode = WAL;
94 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
95 INSERT INTO counters VALUES (1, 0);
96 `);
97 });
98 return { filename, other };
99});
100​
101it.effect("keeps another connection from committing between a transaction's read and write", () =>
102 Effect.gen(function* () {
103 const { filename, other } = yield* makeTempDatabase;
104 yield* Effect.gen(function* () {
105 const sql = yield* SqlClient.SqlClient;
106 yield* sql.withTransaction(
107 Effect.gen(function* () {
108 const [row] = yield* sql<{ readonly value: number }>`
109 SELECT value FROM counters WHERE id = 1
110 `;
111 // With a deferred BEGIN this commit lands and the write below fails
112 // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out.
113 yield* Effect.sync(() =>
114 assert.throws(
115 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
116 /database is locked/,
117 ),
118 );
119 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
120 }),
121 );
122 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
123 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
124 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
125 }).pipe(Effect.provide(NodeServices.layer)),
126);
127​
128it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
129 Effect.gen(function* () {
130 const { filename, other } = yield* makeTempDatabase;
131 yield* Effect.gen(function* () {
132 const sql = yield* SqlClient.SqlClient;
133 yield* sql`PRAGMA busy_timeout = 0`;
134 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
135​
136 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
137 const error = yield* read.pipe(Effect.flip);
138 assert.equal(error.reason._tag, "LockTimeoutError");
139​
140 yield* Effect.sync(() => other.exec("COMMIT"));
141 assert.deepEqual(yield* read, [[0]]);
142 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
143 }).pipe(Effect.provide(NodeServices.layer)),
144);
145​
146it.effect("returns a typed failure when the database cannot be opened", () =>
147 Effect.gen(function* () {
148 const error = yield* Effect.flip(
149 Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped),
150 );
151​
152 assert.equal(error._tag, "SqlError");
153 assert.equal(error.reason.operation, "open");
154 }),
155);
156​
157it.effect(
158 "recovers a prepared query immediately after an exclusive database lock is released",
159 () =>
160 Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-prepare-" });
164 const filename = path.join(directory, "state.sqlite");
165 const blocker = yield* Effect.acquireRelease(
166 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
167 (database) => Effect.sync(() => database.close()),
168 );
169 yield* Effect.sync(() => {
170 blocker.exec("CREATE TABLE entries(value TEXT); INSERT INTO entries VALUES ('retained')");
171 });
172 yield* Effect.gen(function* () {
173 const sql = yield* SqlClient.SqlClient;
174 yield* Effect.sync(() => blocker.exec("BEGIN EXCLUSIVE"));
175 const select = sql`SELECT value FROM entries`;
176 const error = yield* select.values.pipe(Effect.flip);
177 assert.equal(error._tag, "SqlError");
178 assert.equal(error.reason.operation, "prepare");
179 yield* Effect.sync(() => blocker.exec("ROLLBACK"));
180 assert.deepEqual(yield* select.values, [["retained"]]);
181 assert.deepEqual(yield* select, [{ value: "retained" }]);
182 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
183 }).pipe(Effect.provide(NodeServices.layer)),
184);