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

Sqlite.ts

59 lines2.0 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/unstable/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 setup = 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 makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
30 dbPath: string,
31) {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
35​
36 return Layer.provideMerge(
37 setup,
38 NodeSqliteClient.layer({
39 filename: dbPath,
40 spanAttributes: {
41 "db.name": path.basename(dbPath),
42 "service.name": "t3code-server",
43 },
44 }),
45 );
46}, Layer.unwrap);
47​
48export const SqlitePersistenceMemory = Layer.provideMerge(
49 setup,
50 NodeSqliteClient.layer({ filename: ":memory:" }),
51);
52​
53export const layerConfig = Layer.unwrap(
54 Effect.gen(function* () {
55 const { dbPath } = yield* ServerConfig.ServerConfig;
56 yield* initializeV2Database(dbPath);
57 return makeSqlitePersistenceLive(dbPath);
58 }),
59);