Open History to see the last commit
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 Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as SqlClient from "effect/sql/SqlClient";
11
12import * as SqlitePersistence from "./Sqlite.ts";
13
14it.effect("drops planner statistics a database already has", () => {
15 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
16 const dbPath = NodePath.join(tempDir, "state.sqlite");
17 const persistence = () =>
18 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer));
19
20 return Effect.gen(function* () {
21 yield* Effect.gen(function* () {
22 const sql = yield* SqlClient.SqlClient;
23 yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
24 yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
25 yield* sql`ANALYZE walk_probe`;
26 }).pipe(Effect.provide(persistence()));
27
28 yield* Effect.gen(function* () {
29 const sql = yield* SqlClient.SqlClient;
30 const stats = yield* sql<{ readonly count: number }>`
31 SELECT COUNT(*) AS count FROM sqlite_stat1
32 `;
33 assert.equal(stats[0]?.count, 0);
34 // A connection still using the old stats scans the table at each step.
35 const plan = yield* sql<{ readonly detail: string }>`
36 EXPLAIN QUERY PLAN
37 WITH RECURSIVE retained(node_id) AS (
38 SELECT 'node-2'
39 UNION
40 SELECT parent.parent_node_id FROM walk_probe AS parent
41 INNER JOIN retained ON parent.node_id = retained.node_id
42 )
43 SELECT node_id FROM retained
44 `;
45 assert.include(
46 plan.map((row) => row.detail),
47 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
48 );
49 }).pipe(Effect.provide(persistence()));
50 }).pipe(
51 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
52 );
53});