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 // Stats from a nearly empty table, as an older build collected on a new install.
26 yield* sql`ANALYZE walk_probe`;
27 }).pipe(Effect.provide(persistence()));
28
29 yield* Effect.gen(function* () {
30 const sql = yield* SqlClient.SqlClient;
31 const stats = yield* sql<{ readonly count: number }>`
32 SELECT COUNT(*) AS count FROM sqlite_stat1
33 `;
34 assert.equal(stats[0]?.count, 0);
35 // A connection still using the old stats scans the table at each step.
36 const plan = yield* sql<{ readonly detail: string }>`
37 EXPLAIN QUERY PLAN
38 WITH RECURSIVE retained(node_id) AS (
39 SELECT 'node-2'
40 UNION
41 SELECT parent.parent_node_id FROM walk_probe AS parent
42 INNER JOIN retained ON parent.node_id = retained.node_id
43 )
44 SELECT node_id FROM retained
45 `;
46 assert.include(
47 plan.map((row) => row.detail),
48 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
49 );
50 }).pipe(Effect.provide(persistence()));
51 }).pipe(
52 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
53 );
54});