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

Sqlite.test.ts

98 lines4.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, it } from "@effect/vitest";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as SqlClient from "effect/sql/SqlClient";
12​
13import * as SqlitePersistence from "./Sqlite.ts";
14​
15// Linux names an open, already-deleted file "<path> (deleted)" in /proc/self/fd.
16// SQLite names its temp files "etilqs_*" and, without TMPDIR, puts them in
17// /var/tmp while os.tmpdir() is /tmp, so match the name, not the directory.
18const openDeletedTempFiles = () =>
19 NodeFS.readdirSync("/proc/self/fd").flatMap((fd) => {
20 try {
21 const target = NodeFS.readlinkSync(`/proc/self/fd/${fd}`);
22 return target.includes("/etilqs_") && target.endsWith(" (deleted)") ? [target] : [];
23 } catch {
24 return [];
25 }
26 });
27​
28it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
29 "keeps a write transaction's statement journal off the temp directory",
30 () => {
31 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-temp-"));
32 const persistence = SqlitePersistence.layerFromPath(
33 NodePath.join(tempDir, "state.sqlite"),
34 ).pipe(Layer.provide(NodeServices.layer));
35​
36 return Effect.gen(function* () {
37 const sql = yield* SqlClient.SqlClient;
38 yield* sql`CREATE TABLE journal_probe(id INTEGER PRIMARY KEY, payload TEXT NOT NULL)`;
39 for (let id = 0; id < 64; id++) {
40 yield* sql`INSERT INTO journal_probe VALUES (${id}, ${"x".repeat(4096)})`;
41 }
42 const before = new Set(openDeletedTempFiles());
43 const opened = yield* sql.withTransaction(
44 Effect.gen(function* () {
45 // A multi-row update can fail halfway, so SQLite journals every page
46 // it changes, here well past the 64 KiB it holds in memory by default.
47 yield* sql`UPDATE journal_probe SET payload = payload || 'y'`;
48 return openDeletedTempFiles().filter((target) => !before.has(target));
49 }),
50 );
51 assert.deepEqual(opened, []);
52 }).pipe(
53 Effect.provide(persistence),
54 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
55 );
56 },
57);
58​
59it.effect("drops planner statistics a database already has", () => {
60 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
61 const dbPath = NodePath.join(tempDir, "state.sqlite");
62 const persistence = () =>
63 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer));
64​
65 return Effect.gen(function* () {
66 yield* Effect.gen(function* () {
67 const sql = yield* SqlClient.SqlClient;
68 yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
69 yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
70 yield* sql`ANALYZE walk_probe`;
71 }).pipe(Effect.provide(persistence()));
72​
73 yield* Effect.gen(function* () {
74 const sql = yield* SqlClient.SqlClient;
75 const stats = yield* sql<{ readonly count: number }>`
76 SELECT COUNT(*) AS count FROM sqlite_stat1
77 `;
78 assert.equal(stats[0]?.count, 0);
79 // A connection still using the old stats scans the table at each step.
80 const plan = yield* sql<{ readonly detail: string }>`
81 EXPLAIN QUERY PLAN
82 WITH RECURSIVE retained(node_id) AS (
83 SELECT 'node-2'
84 UNION
85 SELECT parent.parent_node_id FROM walk_probe AS parent
86 INNER JOIN retained ON parent.node_id = retained.node_id
87 )
88 SELECT node_id FROM retained
89 `;
90 assert.include(
91 plan.map((row) => row.detail),
92 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
93 );
94 }).pipe(Effect.provide(persistence()));
95 }).pipe(
96 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
97 );
98});