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

Sqlite.ts

53 lines1.6 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 { ServerConfig } from "../../config.ts";
11​
12const setup = Layer.effectDiscard(
13 Effect.gen(function* () {
14 const sql = yield* SqlClient.SqlClient;
15 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
16 yield* sql`PRAGMA busy_timeout = 5000;`;
17 yield* sql`PRAGMA foreign_keys = ON;`;
18 yield* sql`PRAGMA journal_mode = WAL;`;
19 yield* runMigrations();
20 }),
21);
22​
23export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
24 dbPath: string,
25) {
26 const fs = yield* FileSystem.FileSystem;
27 const path = yield* Path.Path;
28 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
29​
30 return Layer.provideMerge(
31 setup,
32 NodeSqliteClient.layer({
33 filename: dbPath,
34 spanAttributes: {
35 "db.name": path.basename(dbPath),
36 "service.name": "t3-server",
37 },
38 }),
39 );
40}, Layer.unwrap);
41​
42export const SqlitePersistenceMemory = Layer.provideMerge(
43 setup,
44 NodeSqliteClient.layer({ filename: ":memory:" }),
45);
46​
47export const layerConfig = Layer.unwrap(
48 Effect.gen(function* () {
49 const { dbPath } = yield* ServerConfig;
50 yield* initializeV2Database(dbPath);
51 return makeSqlitePersistenceLive(dbPath);
52 }),
53);