Open History to see the last commit
1#!/usr/bin/env node
2
3// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
4import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NodeOS from "node:os";
7import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
8import * as Console from "effect/Console";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15import * as SqlClient from "effect/unstable/sql/SqlClient";
16import { Argument, Command, Flag } from "effect/unstable/cli";
17
18import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
19
20export const SqliteStateOperation = Schema.Literals(["query", "exec"]);
21export type SqliteStateOperation = typeof SqliteStateOperation.Type;
22
23export class SqliteStateMultipleSqlSourcesError extends Schema.TaggedErrorClass<SqliteStateMultipleSqlSourcesError>()(
24 "SqliteStateMultipleSqlSourcesError",
25 {},
26) {
27 override get message(): string {
28 return "Provide only one of --sql or --file.";
29 }
30}
31
32export class SqliteStateMissingSqlSourceError extends Schema.TaggedErrorClass<SqliteStateMissingSqlSourceError>()(
33 "SqliteStateMissingSqlSourceError",
34 {},
35) {
36 override get message(): string {
37 return "Provide one of --sql or --file.";
38 }
39}
40
41export class SqliteStateEmptySqlError extends Schema.TaggedErrorClass<SqliteStateEmptySqlError>()(
42 "SqliteStateEmptySqlError",
43 {},
44) {
45 override get message(): string {
46 return "SQL input is empty.";
47 }
48}
49
50export class SqliteStateDatabaseMissingError extends Schema.TaggedErrorClass<SqliteStateDatabaseMissingError>()(
51 "SqliteStateDatabaseMissingError",
52 {
53 databasePath: Schema.String,
54 },
55) {
56 override get message(): string {
57 return `Database does not exist at '${this.databasePath}'. Start T3 once to run migrations.`;
58 }
59}
60
61export class SqliteStateSharedHomeMutationError extends Schema.TaggedErrorClass<SqliteStateSharedHomeMutationError>()(
62 "SqliteStateSharedHomeMutationError",
63 {},
64) {
65 override get message(): string {
66 return "Refusing to mutate the shared ~/.t3 database. Use an isolated --base-dir.";
67 }
68}
69
70export class SqliteStateSqlFileError extends Schema.TaggedErrorClass<SqliteStateSqlFileError>()(
71 "SqliteStateSqlFileError",
72 {
73 filePath: Schema.String,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return `Failed to read SQL from '${this.filePath}'.`;
79 }
80}
81
82export class SqliteStateDatabaseError extends Schema.TaggedErrorClass<SqliteStateDatabaseError>()(
83 "SqliteStateDatabaseError",
84 {
85 operation: SqliteStateOperation,
86 databasePath: Schema.String,
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 return `Failed to ${this.operation} SQLite database at '${this.databasePath}'.`;
92 }
93}
94
95const SqliteStateValue = Schema.Union([
96 Schema.Null,
97 Schema.String,
98 Schema.Number,
99 Schema.Array(Schema.Number),
100]);
101const SqliteStateRow = Schema.Record(Schema.String, SqliteStateValue);
102const SqliteStateQueryResult = Schema.Struct({
103 operation: Schema.Literal("query"),
104 database: Schema.String,
105 rows: Schema.Array(SqliteStateRow),
106});
107const SqliteStateExecResult = Schema.Struct({
108 operation: Schema.Literal("exec"),
109 database: Schema.String,
110 backup: Schema.String,
111});
112const SqliteStateResult = Schema.Union([SqliteStateQueryResult, SqliteStateExecResult]);
113const encodeSqliteStateResult = Schema.encodeEffect(fromJsonStringPretty(SqliteStateResult));
114
115export type SqliteStateResult = typeof SqliteStateResult.Type;
116
117type RawSqliteValue = null | string | number | bigint | Uint8Array;
118type RawSqliteRow = Readonly<Record<string, RawSqliteValue>>;
119
120export interface RunSqliteStateInput {
121 readonly operation: SqliteStateOperation;
122 readonly baseDir: string;
123 readonly sql?: string | undefined;
124 readonly file?: string | undefined;
125}
126
127export interface RunSqliteStateOptions {
128 readonly sharedHome?: string | undefined;
129}
130
131const resolveSqlSource = Effect.fn("resolveSqliteStateSqlSource")(function* (
132 sql: string | undefined,
133 file: string | undefined,
134) {
135 if (sql !== undefined && file !== undefined) {
136 return yield* new SqliteStateMultipleSqlSourcesError();
137 }
138 if (sql === undefined && file === undefined) {
139 return yield* new SqliteStateMissingSqlSourceError();
140 }
141
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 let source: string;
145 if (sql !== undefined) {
146 source = sql;
147 } else {
148 const filePath = path.resolve(file as string);
149 source = yield* fs
150 .readFileString(filePath)
151 .pipe(Effect.mapError((cause) => new SqliteStateSqlFileError({ filePath, cause })));
152 }
153
154 const trimmed = source.trim();
155 if (trimmed.length === 0) {
156 return yield* new SqliteStateEmptySqlError();
157 }
158 return trimmed;
159});
160
161function normalizeSqliteValue(value: RawSqliteValue): typeof SqliteStateValue.Type {
162 if (typeof value === "bigint") {
163 const numericValue = Number(value);
164 return Number.isSafeInteger(numericValue) ? numericValue : value.toString();
165 }
166 if (value instanceof Uint8Array) {
167 return Array.from(value);
168 }
169 return value;
170}
171
172function normalizeSqliteRow(row: RawSqliteRow): typeof SqliteStateRow.Type {
173 return Object.fromEntries(
174 Object.entries(row).map(([key, value]) => [key, normalizeSqliteValue(value)]),
175 );
176}
177
178export const runSqliteState = Effect.fn("runSqliteState")(function* (
179 input: RunSqliteStateInput,
180 options: RunSqliteStateOptions = {},
181) {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const baseDir = path.resolve(input.baseDir);
185 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
186 const databasePath = path.join(baseDir, "userdata", "state.sqlite");
187 const source = yield* resolveSqlSource(input.sql, input.file);
188
189 if (!(yield* fs.exists(databasePath))) {
190 return yield* new SqliteStateDatabaseMissingError({ databasePath });
191 }
192 if (input.operation === "exec") {
193 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
194 fs.realPath(baseDir),
195 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
196 ]);
197 if (canonicalBaseDir === canonicalSharedHome) {
198 return yield* new SqliteStateSharedHomeMutationError();
199 }
200 }
201
202 const program = Effect.gen(function* () {
203 const sql = yield* SqlClient.SqlClient;
204 yield* sql.unsafe("PRAGMA busy_timeout = 5000").unprepared;
205
206 if (input.operation === "query") {
207 const rows = yield* sql.unsafe<RawSqliteRow>(source).unprepared.pipe(
208 Effect.provideService(SqlClient.SafeIntegers, true),
209 Effect.map((rows) => rows.map(normalizeSqliteRow)),
210 );
211 return {
212 operation: "query",
213 database: databasePath,
214 rows,
215 } as const;
216 }
217
218 const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
219 const backupPath = `${databasePath}.backup-${timestamp}`;
220 yield* sql`VACUUM INTO ${backupPath}`;
221 yield* fs.chmod(backupPath, 0o600);
222 yield* sql.withTransaction(sql.unsafe(source).unprepared);
223
224 return {
225 operation: "exec",
226 database: databasePath,
227 backup: backupPath,
228 } as const;
229 });
230
231 return yield* program.pipe(
232 Effect.provide(
233 NodeSqliteClient.layer({
234 filename: databasePath,
235 readonly: input.operation === "query",
236 }),
237 ),
238 Effect.mapError(
239 (cause) =>
240 new SqliteStateDatabaseError({
241 operation: input.operation,
242 databasePath,
243 cause,
244 }),
245 ),
246 );
247});
248
249export const t3SqliteStateCommand = Command.make(
250 "t3-sqlite-state",
251 {
252 operation: Argument.choice("operation", SqliteStateOperation.literals).pipe(
253 Argument.withDescription("Run a read-only query or a backed-up fixture mutation."),
254 ),
255 baseDir: Flag.string("base-dir").pipe(
256 Flag.withDescription("Explicit T3 base directory containing userdata/state.sqlite."),
257 ),
258 sql: Flag.string("sql").pipe(
259 Flag.optional,
260 Flag.withDescription("SQL source supplied directly on the command line."),
261 ),
262 file: Flag.string("file").pipe(
263 Flag.optional,
264 Flag.withDescription("Path to a SQL source file."),
265 ),
266 },
267 ({ operation, baseDir, sql, file }) =>
268 runSqliteState({
269 operation,
270 baseDir,
271 sql: Option.getOrUndefined(sql),
272 file: Option.getOrUndefined(file),
273 }).pipe(Effect.flatMap(encodeSqliteStateResult), Effect.flatMap(Console.log)),
274).pipe(
275 Command.withDescription(
276 "Inspect or seed an isolated T3 SQLite database with automatic backups for writes.",
277 ),
278);
279
280if (import.meta.main) {
281 Command.run(t3SqliteStateCommand, { version: "0.0.0" }).pipe(
282 Effect.provide(NodeServices.layer),
283 NodeRuntime.runMain,
284 );
285}