import type { Database } from "bun:sqlite"; import type { SeedEntryInput } from "../cli"; import { fallbackSeedDescription } from "../seed_files"; type SeededCommand = { name: string; description: string | null; }; export function importSeedEntries( database: Database, entries: SeedEntryInput[], source: string, ): void { const upsert = database.query( `INSERT INTO seed_metadata (command_name, description, source, updated_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(command_name) DO UPDATE SET description = excluded.description, source = excluded.source, updated_at = excluded.updated_at`, ); database.transaction((items: SeedEntryInput[]) => { for (const entry of items) { upsert.run(entry.name, entry.description ?? null, source, now()); } })(entries); } export function hydrateSeedMetadata(database: Database): string[] { const pending = seedCommandsNeedingHydration(database); if (pending.length === 0) { return []; } const names = pending.map((row) => row.name); const seed = database .query("SELECT description, source FROM seed_metadata WHERE command_name = ?1"); const current = database.query( "SELECT description, source FROM command_metadata WHERE command_name = ?1", ); const insert = database.query( `INSERT INTO command_metadata (command_name, description, source, updated_at) VALUES (?1, ?2, ?3, ?4)`, ); const update = database.query( `UPDATE command_metadata SET description = ?2, source = ?3, updated_at = ?4 WHERE command_name = ?1`, ); database.transaction((names: string[]) => { for (const name of names) { const row = seed.get(name) as { description: string | null; source: string }; const existing = current.get(name) as { source: string } | null; const description = row.description ?? fallbackSeedDescription(); if (!existing) { insert.run(name, description, row.source, now()); continue; } if (existing.source === "seed-import") { update.run(name, description, row.source, now()); } } })(names); return names; } export function seededCommandNames(database: Database): SeededCommand[] { return database .query( `SELECT command_name AS name, description FROM seed_metadata ORDER BY command_name ASC`, ) .all() as SeededCommand[]; } export function seedCommandsNeedingHydration(database: Database): { name: string }[] { return database .query( `SELECT commands.name FROM commands INNER JOIN seed_metadata ON seed_metadata.command_name = commands.name LEFT JOIN command_metadata ON command_metadata.command_name = commands.name WHERE command_metadata.command_name IS NULL OR command_metadata.source = 'seed-import'`, ) .all() as { name: string }[]; } function now(): number { return Math.floor(Date.now() / 1000); }