peppa/bench/sqlite/schema-port/drizzle-check.ts
Асель eeb326cc4f PEP-36: PM decision — Node 26 + node:sqlite; drizzle shim and check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:28:59 +05:00

97 lines
5.8 KiB
TypeScript

// PEP-36 prototype: Peppa's ported schema through drizzle on node:sqlite (Node 26) or
// bun:sqlite (Bun) — migrations, typed round trips, transactions, and the cost of a
// hook-like write through the ORM.
// node drizzle-check.ts bun drizzle-check.ts
import { eq, sql } from "drizzle-orm";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as schema from "./schema.ts";
const isBun = typeof (globalThis as any).Bun !== "undefined";
const dir = mkdtempSync(join(tmpdir(), "pep36-"));
const file = join(dir, "peppa.db");
const migrationsFolder = new URL("migrations", import.meta.url).pathname;
let db: any;
if (isBun) {
const { Database } = await import("bun:sqlite" as string);
const { drizzle } = await import("drizzle-orm/bun-sqlite");
const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
const d = new Database(file, { create: true });
for (const p of ["PRAGMA busy_timeout = 5000", "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA foreign_keys = ON"]) d.exec(p);
db = drizzle(d, { schema });
migrate(db, { migrationsFolder });
} else {
const { drizzleNodeSqlite } = await import("./node-sqlite-driver.ts");
const { migrate } = await import("drizzle-orm/better-sqlite3/migrator");
db = drizzleNodeSqlite(file, schema);
migrate(db, { migrationsFolder });
}
const ok = (name: string, cond: boolean, extra = "") => console.log(`${cond ? "ok " : "FAIL"} ${name}${extra ? ` — ${extra}` : ""}`);
const [user] = db.insert(schema.users).values({ giteaId: 1, login: "mock-pm", telegramChatId: 9007199254740991 }).returning().all();
const [project] = db.insert(schema.projects).values({ slug: "p", key: "P", name: "P", giteaOwner: "o", giteaRepo: "r", workspacePath: "/tmp", ownerId: user.id }).returning().all();
ok("insert … returning", project.id === 1 && project.createdAt instanceof Date, `createdAt ${project.createdAt.toISOString()}`);
ok("bigint chat id round trip", db.select().from(schema.users).get().telegramChatId === 9007199254740991);
// createTask as it has to look on SQLite: synchronous transaction, BEGIN IMMEDIATE.
const createTask = (title: string) =>
db.transaction(
(tx: any) => {
const [p] = tx.update(schema.projects).set({ nextTaskNumber: sql`${schema.projects.nextTaskNumber} + 1` }).where(eq(schema.projects.id, 1)).returning().all();
return tx.insert(schema.tasks).values({ projectId: 1, number: p.nextTaskNumber - 1, title }).returning().get();
},
{ behavior: "immediate" },
);
const t1 = createTask("Первая");
const t2 = createTask("Вторая");
ok("sync transaction", t1.number === 1 && t2.number === 2 && t2.status === "backlog");
try {
db.transaction((tx: any) => {
tx.update(schema.projects).set({ nextTaskNumber: 100 }).where(eq(schema.projects.id, 1)).run();
throw new Error("boom");
});
} catch {}
ok("rollback on throw", db.select().from(schema.projects).get().nextTaskNumber === 3);
let asyncRefused = false;
try {
await db.transaction(async (tx: any) => {
await tx.update(schema.projects).set({ nextTaskNumber: 200 }).where(eq(schema.projects.id, 1));
});
} catch (e) {
asyncRefused = /synchronous/.test((e as Error).message);
}
ok("async transaction", isBun ? true : asyncRefused, isBun ? "bun-sqlite: commits after the first await (not refused) — see tx-check.ts" : "refused with a clear error");
const [sess] = db.insert(schema.sessions).values({ projectId: 1, taskId: t1.id, tmuxName: "peppa-P-1-s1" }).returning().all();
db.insert(schema.questions).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, kind: "permission", text: "Удалить build?", options: ["Да", "Нет"], awaitingHook: true }).run();
const q = db.query.questions.findFirst({ with: { session: true, task: true } }).sync();
ok("json + boolean + relations", Array.isArray(q.options) && q.options[1] === "Нет" && q.awaitingHook === true && q.session.tmuxName === "peppa-P-1-s1" && q.task.title === "Первая");
db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 1 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 2 } } }).run();
db.insert(schema.settings).values({ key: "heartbeat:bot", value: { at: 3 } }).onConflictDoUpdate({ target: schema.settings.key, set: { value: { at: 3 } } }).run();
ok("upsert json", db.select().from(schema.settings).get().value.at === 3);
db.insert(schema.telegramOutbox).values({ dedupeKey: "q:1", method: "sendMessage", params: { chat_id: 42, text: "?" } }).run();
// core/telegram.ts compares params->>'chat_id' with a string. Postgres ->> returns text;
// SQLite ->> returns the JSON number as a number, so the same SQL finds nothing.
const asText = db.select().from(schema.telegramOutbox).where(sql`${schema.telegramOutbox.params}->>'chat_id' = ${"42"}`).all();
const asCast = db.select().from(schema.telegramOutbox).where(sql`cast(${schema.telegramOutbox.params}->>'chat_id' as text) = ${"42"}`).all();
ok("json ->> as in core/telegram.ts differs from Postgres", asText.length === 0 && asCast.length === 1, "needs cast(… as text) on SQLite");
// Cost of the hook's write through the ORM (update session + insert event), one process.
const n = 20000;
const t0 = performance.now();
for (let i = 0; i < n; i++)
db.transaction(
(tx: any) => {
tx.update(schema.sessions).set({ status: "running", lastActivityAt: new Date() }).where(eq(schema.sessions.id, sess.id)).run();
tx.insert(schema.events).values({ projectId: 1, taskId: t1.id, sessionId: sess.id, type: "turn_end", payload: { i } }).run();
},
{ behavior: "immediate" },
);
const us = ((performance.now() - t0) / n) * 1000;
console.log(`${isBun ? "bun:sqlite" : "node:sqlite"} via drizzle: ${us.toFixed(1)} µs per hook transaction (${n} in one process)`);
rmSync(dir, { recursive: true, force: true });