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

Sqlite.ts

57 lines1.9 KB

1import * as Effect from "effect/Effect";
2import * as Layer from "effect/Layer";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as SqlClient from "effect/sql/SqlClient";
6import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7​
8import { runMigrations } from "./Migrations.ts";
9import { initializeV2Database } from "./initializeV2Database.ts";
10import * as ServerConfig from "../config.ts";
11​
12// Size the -wal file is cut back to on the first commit after a WAL reset.
13export const WAL_SIZE_LIMIT_BYTES = 32 * 1024 * 1024;
14​
15const layerSetup = Layer.effectDiscard(
16 Effect.gen(function* () {
17 const sql = yield* SqlClient.SqlClient;
18 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
19 yield* sql`PRAGMA busy_timeout = 5000;`;
20 yield* sql`PRAGMA foreign_keys = ON;`;
21 yield* sql`PRAGMA journal_mode = WAL;`;
22 // PASSIVE checkpoints never shrink the -wal file, so it otherwise keeps its
23 // largest size until the last connection closes.
24 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
25 yield* runMigrations();
26 }),
27);
28​
29export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
30 const fs = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
33​
34 return Layer.provideMerge(
35 layerSetup,
36 NodeSqliteClient.layer({
37 filename: dbPath,
38 spanAttributes: {
39 "db.name": path.basename(dbPath),
40 "service.name": "t3code-server",
41 },
42 }),
43 );
44}, Layer.unwrap);
45​
46export const layerMemory = Layer.provideMerge(
47 layerSetup,
48 NodeSqliteClient.layer({ filename: ":memory:" }),
49);
50​
51export const layerConfig = Layer.unwrap(
52 Effect.gen(function* () {
53 const { dbPath } = yield* ServerConfig.ServerConfig;
54 yield* initializeV2Database(dbPath);
55 return layerFromPath(dbPath);
56 }),
57);