peppa/packages/db/src/index.ts
Асель 3a282b8054 PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
  booleans 0/1), one baseline migration; node:sqlite client under drizzle's
  better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
  SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
  (default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
  PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
  `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
  instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only
  snapshot of Postgres, FK order from the schema, row count + foreign key
  checks, file appears only when they pass); old Postgres schema kept in
  packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
  per-project numbering across processes, socket/data_version, migration from
  Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:23:24 +05:00

73 lines
3.1 KiB
TypeScript

import { loadEnv } from "@peppa/shared";
import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session";
import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator";
import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm/relations";
import { is } from "drizzle-orm";
import { getTableConfig, SQLiteTable } from "drizzle-orm/sqlite-core";
import { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core/db";
import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
import type { StatementResultingChanges } from "node:sqlite";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { SqliteClient } from "./client.ts";
import * as schema from "./schema.ts";
export * from "./schema.ts";
export { schema, SqliteClient };
export type Db = BaseSQLiteDatabase<"sync", StatementResultingChanges, typeof schema> & { $client: SqliteClient };
/** Opens Peppa's SQLite database (PEPPA_DB, default ~/.peppa/peppa.db). */
export function createDb(path = loadEnv().PEPPA_DB, opts: { readOnly?: boolean } = {}): Db {
const client = new SqliteClient(path, opts);
const dialect = new SQLiteSyncDialect();
const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
const relational = { fullSchema: schema, schema: tables.tables, tableNamesMap: tables.tableNamesMap };
const session = new BetterSQLiteSession(client as never, dialect, relational as never);
const db = new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Db;
db.$client = client;
return db;
}
// Not `new URL(…, import.meta.url)`: Next's bundler would try to resolve it as an asset.
export const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations");
/** Applies pending migrations (idempotent; safe to run from several processes). */
export function migrateDb(db: Db) {
drizzleMigrate(db as never, { migrationsFolder });
}
export interface TableInfo {
name: string;
columns: { name: string; json: boolean; ms: boolean; bool: boolean }[];
}
/** Peppa's tables, parents before children by foreign keys (for copying data in). */
export function tablesInFkOrder(): TableInfo[] {
const configs = new Map(
Object.values(schema)
.filter((t) => is(t, SQLiteTable))
.map((t) => getTableConfig(t as SQLiteTable))
.map((c) => [c.name, c]),
);
const ordered: string[] = [];
const visit = (name: string, path: string[]) => {
if (ordered.includes(name) || path.includes(name)) return;
for (const fk of configs.get(name)!.foreignKeys) {
const parent = getTableConfig(fk.reference().foreignTable).name;
if (parent !== name) visit(parent, [...path, name]);
}
ordered.push(name);
};
for (const name of [...configs.keys()].sort()) visit(name, []);
return ordered.map((name) => ({
name,
columns: configs.get(name)!.columns.map((c) => ({
name: c.name,
json: c.columnType === "SQLiteTextJson",
ms: c.columnType === "SQLiteTimestamp",
bool: c.columnType === "SQLiteBoolean",
})),
}));
}