peppa/packages/db/src/index.ts
2026-11-20 18:56:42 +05:00

82 lines
3.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { and, gte, is, lt, type SQL, type SQLWrapper } 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 };
/**
* PEP-214: «ключ начинается с префикса» диапазоном по первичному ключу. `LIKE 'x:%'` в SQLite
* не берёт индекс (нечувствителен к регистру, `_` и `%` — маски) и просматривает всю таблицу.
*/
export function keyPrefix(column: SQLWrapper, prefix: string): SQL {
const end = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
return and(gte(column as never, prefix), lt(column as never, end)) as SQL;
}
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",
})),
}));
}