tempest-db-js 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/migrations/operations.ts","../src/migrations/codegen.ts","../src/migrations/ddl.ts","../src/migrations/diff.ts","../src/migrations/graph.ts","../src/index.ts","../src/migrations/ir.ts","../src/migrations/introspect.ts","../src/migrations/renames.ts","../src/migrations/runner.ts","../src/migrations/replay.ts","../src/migrations/cli.ts","../src/bin.ts"],"names":["resolve","existsSync","pathToFileURL","createInterface"],"mappings":";;;;;;;;;;AAyCO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF,CAAA;AASO,SAAS,OAAO,EAAA,EAA0B;AAC/C,EAAA,QAAQ,GAAG,IAAA;AAAM,IACf,KAAK,cAAA;AACH,MAAA,OAAO,EAAE,IAAA,EAAM,YAAA,EAAc,KAAA,EAAO,GAAG,KAAA,EAAM;AAAA,IAC/C,KAAK,YAAA;AACH,MAAA,OAAO,EAAE,IAAA,EAAM,cAAA,EAAgB,KAAA,EAAO,GAAG,KAAA,EAAM;AAAA,IACjD,KAAK,cAAA;AACH,MAAA,OAAO,EAAE,MAAM,cAAA,EAAgB,IAAA,EAAM,GAAG,EAAA,EAAI,EAAA,EAAI,GAAG,IAAA,EAAK;AAAA,IAC1D,KAAK,YAAA;AACH,MAAA,OAAO,EAAE,MAAM,aAAA,EAAe,KAAA,EAAO,GAAG,KAAA,EAAO,MAAA,EAAQ,GAAG,MAAA,EAAO;AAAA,IACnE,KAAK,aAAA;AACH,MAAA,OAAO,EAAE,MAAM,YAAA,EAAc,KAAA,EAAO,GAAG,KAAA,EAAO,MAAA,EAAQ,GAAG,MAAA,E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cesContent":["/**\n * tempest-db-js — Phase 6: typed migration operations.\n *\n * Every schema change is a typed `Operation` with a known inverse. This is what\n * gives autogenerated, reversible `down()` and dialect-rendered DDL — never a\n * hand-written `.sql` blob (the anti-Drizzle core).\n */\n\nimport type { ColumnIR, TableIR } from \"./ir.js\";\n\n/** A single, reversible schema operation. */\nexport type Operation =\n | { readonly kind: \"create_table\"; readonly table: TableIR }\n | { readonly kind: \"drop_table\"; readonly table: TableIR }\n | { readonly kind: \"rename_table\"; readonly from: string; readonly to: string }\n | { readonly kind: \"add_column\"; readonly table: string; readonly column: ColumnIR }\n | { readonly kind: \"drop_column\"; readonly table: string; readonly column: ColumnIR }\n | {\n readonly kind: \"alter_column\";\n readonly table: string;\n readonly name: string;\n readonly from: ColumnIR;\n readonly to: ColumnIR;\n }\n | {\n readonly kind: \"rename_column\";\n readonly table: string;\n readonly from: string;\n readonly to: string;\n }\n | {\n // Rebuild a table from `from` to `to`. On SQLite this is the batch /\n // table-rebuild path (SQLite cannot ALTER COLUMN); on PostgreSQL it is\n // realized as per-column ALTER/ADD/DROP.\n readonly kind: \"recreate_table\";\n readonly from: TableIR;\n readonly to: TableIR;\n }\n | { readonly kind: \"execute\"; readonly up: string; readonly down: string | null };\n\n/** Raised when an operation has no safe inverse (e.g. a one-way `execute`). */\nexport class IrreversibleMigration extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IrreversibleMigration\";\n }\n}\n\n/**\n * Compute the inverse of an operation, for autogenerated `down()`.\n *\n * @param op The forward operation.\n * @returns The operation that undoes it.\n * @throws IrreversibleMigration When `op` cannot be safely reversed.\n */\nexport function invert(op: Operation): Operation {\n switch (op.kind) {\n case \"create_table\":\n return { kind: \"drop_table\", table: op.table };\n case \"drop_table\":\n return { kind: \"create_table\", table: op.table };\n case \"rename_table\":\n return { kind: \"rename_table\", from: op.to, to: op.from };\n case \"add_column\":\n return { kind: \"drop_column\", table: op.table, column: op.column };\n case \"drop_column\":\n return { kind: \"add_column\", table: op.table, column: op.column };\n case \"alter_column\":\n return {\n kind: \"alter_column\",\n table: op.table,\n name: op.name,\n from: op.to,\n to: op.from,\n };\n case \"rename_column\":\n return { kind: \"rename_column\", table: op.table, from: op.to, to: op.from };\n case \"recreate_table\":\n return { kind: \"recreate_table\", from: op.to, to: op.from };\n case \"execute\":\n if (op.down === null) {\n throw new IrreversibleMigration(\"execute() operation has no down SQL\");\n }\n return { kind: \"execute\", up: op.down, down: op.up };\n }\n}\n\n/** Invert a list of operations: reverse order, each inverted. */\nexport function invertAll(ops: readonly Operation[]): Operation[] {\n return [...ops].reverse().map(invert);\n}\n","/**\n * tempest-db-js — Phase 6: migration autogeneration.\n *\n * Turns a diff's `Operation[]` into an editable TypeScript migration file with\n * `up()` and an autogenerated, inverted `down()`. Operations are embedded as\n * plain-data literals (they are JSON-serializable), so the file stays readable\n * and hand-editable — never an opaque `.sql` blob.\n */\n\nimport { type Operation, invertAll } from \"./operations.js\";\n\n/** Inputs for one generated migration file. */\nexport interface MigrationDraft {\n readonly revision: string;\n readonly downRevision: readonly string[];\n readonly label: string;\n readonly operations: readonly Operation[];\n}\n\n/** Serialize operations as an indented array literal for the generated file. */\nfunction renderOps(ops: readonly Operation[]): string {\n if (ops.length === 0) return \"[]\";\n const body = ops.map((op) => ` ${JSON.stringify(op)},`).join(\"\\n\");\n return `[\\n${body}\\n ]`;\n}\n\n/**\n * Render a migration file body as TypeScript source.\n *\n * The generated `down()` inverts `up()`; if any operation is irreversible, the\n * generation still succeeds but `down()` throws at run time with a clear message\n * (so reversibility is never silently broken).\n *\n * @param draft The revision id, parents, label, and forward operations.\n * @returns The migration file source.\n */\nexport function generateMigration(draft: MigrationDraft): string {\n let down: string;\n try {\n down = renderOps(invertAll(draft.operations));\n } catch (error) {\n down = `(() => { throw new Error(${JSON.stringify(\n `irreversible migration: ${(error as Error).message}`,\n )}); })()`;\n }\n\n return `import type { Migration, Op } from \"tempest-db-js/migrations\";\n\nexport const revision = ${JSON.stringify(draft.revision)};\nexport const downRevision: string[] = ${JSON.stringify(draft.downRevision)};\nexport const label = ${JSON.stringify(draft.label)};\n\nconst upOps = ${renderOps(draft.operations)};\n\nconst downOps = ${down};\n\nexport const up = (op: Op): void => {\n for (const operation of upOps) op.run(operation);\n};\n\nexport const down = (op: Op): void => {\n for (const operation of downOps) op.run(operation);\n};\n\nexport default { revision, downRevision, label, up, down } satisfies Migration;\n`;\n}\n\n/** Build a short, stable revision id from a label + parent set. */\nexport function makeRevisionId(label: string, parents: readonly string[]): string {\n // Deterministic non-crypto hash (FNV-1a) — no Date/Math.random (build-stable).\n let hash = 0x811c9dc5;\n for (const ch of `${label}|${[...parents].sort().join(\",\")}`) {\n hash ^= ch.charCodeAt(0);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n","/**\n * tempest-db-js — Phase 6: DDL rendering.\n *\n * Renders the dialect-neutral IR + operations to concrete SQL per dialect. This\n * is the ONLY place migration SQL is produced — the same operation yields the\n * right DDL for SQLite or PostgreSQL.\n */\n\nimport type { ColumnType, DefaultValue } from \"../index.js\";\nimport type { Dialect } from \"../url.js\";\nimport type { ColumnIR, TableIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\nfunction quoteId(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/** Map a column type to its SQL type string for the dialect. */\nexport function renderColumnType(type: ColumnType, dialect: Dialect): string {\n const { kind, meta } = type;\n if (dialect === \"sqlite\") {\n switch (kind) {\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"boolean\":\n return \"INTEGER\";\n case \"real\":\n case \"double\":\n return \"REAL\";\n case \"numeric\":\n return \"NUMERIC\";\n case \"blob\":\n return \"BLOB\";\n default:\n return \"TEXT\"; // varchar/char/text/uuid/enum/json/date/time/datetime/timestamp\n }\n }\n // PostgreSQL\n switch (kind) {\n case \"smallint\":\n return \"SMALLINT\";\n case \"integer\":\n return \"INTEGER\";\n case \"bigint\":\n return \"BIGINT\";\n case \"numeric\":\n return meta.precision !== undefined\n ? `NUMERIC(${meta.precision}${meta.scale !== undefined ? `, ${meta.scale}` : \"\"})`\n : \"NUMERIC\";\n case \"real\":\n return \"REAL\";\n case \"double\":\n return \"DOUBLE PRECISION\";\n case \"varchar\":\n return meta.length !== undefined ? `VARCHAR(${meta.length})` : \"VARCHAR\";\n case \"char\":\n return meta.length !== undefined ? `CHAR(${meta.length})` : \"CHAR\";\n case \"text\":\n return \"TEXT\";\n case \"boolean\":\n return \"BOOLEAN\";\n case \"date\":\n return \"DATE\";\n case \"time\":\n return meta.withTimezone ? \"TIME WITH TIME ZONE\" : \"TIME\";\n case \"datetime\":\n case \"timestamp\":\n return meta.withTimezone ? \"TIMESTAMP WITH TIME ZONE\" : \"TIMESTAMP\";\n case \"blob\":\n return \"BYTEA\";\n case \"json\":\n return meta.jsonb ? \"JSONB\" : \"JSON\";\n case \"uuid\":\n return \"UUID\";\n case \"enum\":\n // Named PG enum types are a Phase 6e refinement; fall back to TEXT for now.\n return \"TEXT\";\n }\n}\n\n/** Render a default value into a SQL `DEFAULT` expression for the dialect. */\nexport function renderDefault(def: DefaultValue, dialect: Dialect): string {\n if (def.kind === \"expression\") {\n const expr = def.expression;\n if (typeof expr === \"object\") return expr.raw;\n switch (expr) {\n case \"now\":\n return dialect === \"sqlite\" ? \"CURRENT_TIMESTAMP\" : \"now()\";\n case \"current_date\":\n return \"CURRENT_DATE\";\n case \"current_time\":\n return \"CURRENT_TIME\";\n case \"uuidv4\":\n return dialect === \"sqlite\"\n ? \"(lower(hex(randomblob(16))))\"\n : \"gen_random_uuid()\";\n }\n }\n const value = def.value;\n if (value === null) return \"NULL\";\n if (typeof value === \"boolean\") {\n return dialect === \"sqlite\" ? (value ? \"1\" : \"0\") : value ? \"TRUE\" : \"FALSE\";\n }\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (value instanceof Date) return quoteLiteral(value.toISOString());\n if (typeof value === \"object\") return quoteLiteral(JSON.stringify(value));\n return quoteLiteral(String(value));\n}\n\n/** Render one column definition: `\"name\" TYPE [NOT NULL] [DEFAULT x]`. */\nexport function renderColumnDef(col: ColumnIR, dialect: Dialect): string {\n let sql = `${quoteId(col.name)} ${renderColumnType(col.type, dialect)}`;\n if (col.notNull) sql += \" NOT NULL\";\n if (col.default !== null) sql += ` DEFAULT ${renderDefault(col.default, dialect)}`;\n return sql;\n}\n\n/** The PostgreSQL named-enum type for a column (`<table>_<column>`). */\nfunction enumTypeName(table: string, column: string): string {\n return `${table}_${column}`;\n}\n\n/** True when a column is the sole integer-family PK with no explicit default. */\nfunction isAutoIncrementPk(table: TableIR, col: ColumnIR): boolean {\n return (\n table.primaryKey.length === 1 &&\n table.primaryKey[0] === col.name &&\n col.default === null &&\n (col.type.kind === \"smallint\" ||\n col.type.kind === \"integer\" ||\n col.type.kind === \"bigint\")\n );\n}\n\n/** The PostgreSQL auto-incrementing serial type for an integer-family kind. */\nfunction postgresSerialType(kind: ColumnType[\"kind\"]): string {\n if (kind === \"bigint\") return \"BIGSERIAL\";\n if (kind === \"smallint\") return \"SMALLSERIAL\";\n return \"SERIAL\";\n}\n\n/**\n * Render a CREATE TABLE (plus, on PostgreSQL, any `CREATE TYPE ... AS ENUM` for\n * enum columns, which must precede the table). Returns the statement list.\n */\nfunction renderCreateTable(table: TableIR, dialect: Dialect): string[] {\n const typeStmts: string[] = [];\n const cols = Object.values(table.columns).map((c) => {\n if (dialect === \"postgresql\" && c.type.kind === \"enum\") {\n const typeName = enumTypeName(table.name, c.name);\n const values = (c.type.meta.values ?? []).map(quoteLiteral).join(\", \");\n typeStmts.push(`CREATE TYPE ${quoteId(typeName)} AS ENUM (${values})`);\n let def = `${quoteId(c.name)} ${quoteId(typeName)}`;\n if (c.notNull) def += \" NOT NULL\";\n if (c.default !== null) def += ` DEFAULT ${renderDefault(c.default, dialect)}`;\n return def;\n }\n // A lone integer-family primary key auto-increments (SQLAlchemy semantics).\n // SQLite gets that for free from `INTEGER PRIMARY KEY` (rowid alias); on\n // PostgreSQL it must be SERIAL/BIGSERIAL, or inserts without an explicit id\n // fail the NOT NULL constraint.\n if (dialect === \"postgresql\" && isAutoIncrementPk(table, c)) {\n return `${quoteId(c.name)} ${postgresSerialType(c.type.kind)}`;\n }\n return renderColumnDef(c, dialect);\n });\n if (table.primaryKey.length > 0) {\n cols.push(`PRIMARY KEY (${table.primaryKey.map(quoteId).join(\", \")})`);\n }\n return [\n ...typeStmts,\n `CREATE TABLE ${quoteId(table.name)} (\\n ${cols.join(\",\\n \")}\\n)`,\n ];\n}\n\n/**\n * Render an operation to one or more SQL statements for the dialect.\n *\n * @param op The operation.\n * @param dialect The target dialect.\n * @returns The SQL statements (usually one).\n * @throws Error When the operation is unsupported on the dialect (e.g. SQLite\n * `alter_column`, which needs the Phase 6e batch/table-rebuild path).\n */\nexport function renderOperation(op: Operation, dialect: Dialect): string[] {\n switch (op.kind) {\n case \"create_table\":\n return renderCreateTable(op.table, dialect);\n case \"drop_table\":\n return [`DROP TABLE ${quoteId(op.table.name)}`];\n case \"rename_table\":\n return [`ALTER TABLE ${quoteId(op.from)} RENAME TO ${quoteId(op.to)}`];\n case \"add_column\":\n return [\n `ALTER TABLE ${quoteId(op.table)} ADD COLUMN ${renderColumnDef(op.column, dialect)}`,\n ];\n case \"drop_column\":\n return [`ALTER TABLE ${quoteId(op.table)} DROP COLUMN ${quoteId(op.column.name)}`];\n case \"rename_column\":\n return [\n `ALTER TABLE ${quoteId(op.table)} RENAME COLUMN ${quoteId(op.from)} TO ${quoteId(op.to)}`,\n ];\n case \"alter_column\":\n return renderAlterColumn(op.table, op.to, dialect);\n case \"recreate_table\":\n return dialect === \"sqlite\"\n ? renderSqliteRebuild(op.from, op.to)\n : renderPostgresTableDiff(op.from, op.to);\n case \"execute\":\n return [op.up];\n }\n}\n\n/**\n * SQLite batch / table-rebuild: create a new table with the target schema, copy\n * the columns common to both, swap names. This is how SQLite realizes column\n * changes it cannot `ALTER` (drop/alter type/constraint changes).\n */\nfunction renderSqliteRebuild(from: TableIR, to: TableIR): string[] {\n const tmp = `__new_${to.name}`;\n const common = Object.keys(to.columns).filter((c) => c in from.columns);\n const cols = Object.values(to.columns).map((c) => renderColumnDef(c, \"sqlite\"));\n if (to.primaryKey.length > 0) {\n cols.push(`PRIMARY KEY (${to.primaryKey.map(quoteId).join(\", \")})`);\n }\n const commonSql = common.map(quoteId).join(\", \");\n return [\n \"PRAGMA foreign_keys=off\",\n `CREATE TABLE ${quoteId(tmp)} (\\n ${cols.join(\",\\n \")}\\n)`,\n common.length > 0\n ? `INSERT INTO ${quoteId(tmp)} (${commonSql}) SELECT ${commonSql} FROM ${quoteId(from.name)}`\n : `-- no common columns to copy from ${from.name}`,\n `DROP TABLE ${quoteId(from.name)}`,\n `ALTER TABLE ${quoteId(tmp)} RENAME TO ${quoteId(to.name)}`,\n \"PRAGMA foreign_keys=on\",\n ];\n}\n\n/** PostgreSQL realizes a table recreate as per-column ADD/DROP/ALTER. */\nfunction renderPostgresTableDiff(from: TableIR, to: TableIR): string[] {\n const stmts: string[] = [];\n for (const [name, col] of Object.entries(to.columns)) {\n if (!(name in from.columns)) {\n stmts.push(\n `ALTER TABLE ${quoteId(to.name)} ADD COLUMN ${renderColumnDef(col, \"postgresql\")}`,\n );\n } else {\n stmts.push(...renderAlterColumn(to.name, col, \"postgresql\"));\n }\n }\n for (const name of Object.keys(from.columns)) {\n if (!(name in to.columns)) {\n stmts.push(`ALTER TABLE ${quoteId(to.name)} DROP COLUMN ${quoteId(name)}`);\n }\n }\n return stmts;\n}\n\n/** Render an ALTER COLUMN (PostgreSQL); SQLite needs batch mode (Phase 6e). */\nfunction renderAlterColumn(table: string, to: ColumnIR, dialect: Dialect): string[] {\n if (dialect === \"sqlite\") {\n throw new Error(\n `alter_column on SQLite needs batch/table-rebuild (Phase 6e); column ${table}.${to.name}`,\n );\n }\n const t = quoteId(table);\n const c = quoteId(to.name);\n const stmts = [\n `ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${renderColumnType(to.type, dialect)}`,\n ];\n stmts.push(\n to.notNull\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} SET NOT NULL`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} DROP NOT NULL`,\n );\n stmts.push(\n to.default !== null\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${renderDefault(to.default, dialect)}`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT`,\n );\n return stmts;\n}\n","/**\n * tempest-db-js — Phase 6: the schema differ.\n *\n * Compares two `SchemaIR`s (current vs target) and emits the typed `Operation[]`\n * that turns one into the other. Purely structural — no SQL, no DB.\n */\n\nimport type { ColumnIR, SchemaIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\n/** Stable structural identity of a column, for change detection. */\nfunction columnSignature(col: ColumnIR): string {\n return JSON.stringify({\n type: col.type,\n notNull: col.notNull,\n primaryKey: col.primaryKey,\n default: col.default,\n });\n}\n\n/**\n * Diff `current` → `target`, returning the operations to migrate forward.\n *\n * Order: create new tables, then per-table column adds/alters/drops, then drop\n * removed tables last (so nothing depends on a table being dropped first).\n *\n * @param current The current schema (e.g. from migration replay).\n * @param target The desired schema (e.g. from model reflection).\n * @returns The forward operations.\n */\nexport function diffSchema(current: SchemaIR, target: SchemaIR): Operation[] {\n const ops: Operation[] = [];\n const drops: Operation[] = [];\n\n for (const [name, targetTable] of Object.entries(target.tables)) {\n const currentTable = current.tables[name];\n if (!currentTable) {\n ops.push({ kind: \"create_table\", table: targetTable });\n continue;\n }\n // existing table → diff columns\n for (const [colName, targetCol] of Object.entries(targetTable.columns)) {\n const currentCol = currentTable.columns[colName];\n if (!currentCol) {\n ops.push({ kind: \"add_column\", table: name, column: targetCol });\n } else if (columnSignature(currentCol) !== columnSignature(targetCol)) {\n ops.push({\n kind: \"alter_column\",\n table: name,\n name: colName,\n from: currentCol,\n to: targetCol,\n });\n }\n }\n for (const [colName, currentCol] of Object.entries(currentTable.columns)) {\n if (!targetTable.columns[colName]) {\n ops.push({ kind: \"drop_column\", table: name, column: currentCol });\n }\n }\n }\n\n for (const [name, currentTable] of Object.entries(current.tables)) {\n if (!target.tables[name]) {\n drops.push({ kind: \"drop_table\", table: currentTable });\n }\n }\n\n return [...ops, ...drops];\n}\n","/**\n * tempest-db-js — Phase 6: the revision DAG.\n *\n * Migrations form a directed acyclic graph via `downRevision` (a list of parents,\n * so branches and merges are first-class). This module orders them for applying\n * (topological, deterministic) and finds heads.\n */\n\n/** The minimal graph shape a migration must expose. */\nexport interface RevisionNode {\n readonly revision: string;\n readonly downRevision: readonly string[];\n}\n\n/** Raised when the revision graph contains a cycle. */\nexport class CyclicMigrationGraph extends Error {\n constructor(remaining: readonly string[]) {\n super(`migration graph has a cycle among: ${remaining.join(\", \")}`);\n this.name = \"CyclicMigrationGraph\";\n }\n}\n\n/** Raised when a `downRevision` points at a revision that does not exist. */\nexport class UnknownRevision extends Error {\n constructor(revision: string, parent: string) {\n super(`revision ${revision} references unknown parent ${parent}`);\n this.name = \"UnknownRevision\";\n }\n}\n\n/**\n * Topologically order migrations so every parent precedes its children. Ties are\n * broken by revision id for reproducible builds. Throws on cycles or dangling\n * parents.\n *\n * @param migrations The migrations to order.\n * @returns The migrations in apply order.\n */\nexport function topoOrder<T extends RevisionNode>(migrations: readonly T[]): T[] {\n const byId = new Map<string, T>();\n for (const m of migrations) byId.set(m.revision, m);\n\n const indegree = new Map<string, number>();\n const children = new Map<string, string[]>();\n for (const m of migrations) {\n indegree.set(m.revision, m.downRevision.length);\n for (const parent of m.downRevision) {\n if (!byId.has(parent)) throw new UnknownRevision(m.revision, parent);\n const list = children.get(parent) ?? [];\n list.push(m.revision);\n children.set(parent, list);\n }\n }\n\n // roots: indegree 0, sorted for determinism\n const ready = migrations\n .filter((m) => (indegree.get(m.revision) ?? 0) === 0)\n .map((m) => m.revision)\n .sort();\n\n const ordered: T[] = [];\n while (ready.length > 0) {\n const id = ready.shift() as string;\n ordered.push(byId.get(id) as T);\n const next = (children.get(id) ?? []).sort();\n for (const child of next) {\n const deg = (indegree.get(child) ?? 0) - 1;\n indegree.set(child, deg);\n if (deg === 0) {\n ready.push(child);\n ready.sort();\n }\n }\n }\n\n if (ordered.length !== migrations.length) {\n const remaining = migrations\n .map((m) => m.revision)\n .filter((r) => !ordered.some((o) => o.revision === r));\n throw new CyclicMigrationGraph(remaining);\n }\n return ordered;\n}\n\n/** Revisions that are nobody's parent — the current head(s) of the graph. */\nexport function heads<T extends RevisionNode>(migrations: readonly T[]): string[] {\n const parents = new Set<string>();\n for (const m of migrations) for (const p of m.downRevision) parents.add(p);\n return migrations\n .map((m) => m.revision)\n .filter((r) => !parents.has(r))\n .sort();\n}\n","/**\n * tempest-db-js — feasibility spike for Phase 1.\n *\n * Proves the central design claim: a class-based, SQLAlchemy-style model whose\n * fields are runtime column-builders can drive full static row-type inference in\n * TypeScript, despite TS erasing types at runtime.\n *\n * This is a SPIKE, not the final API. It validates the type machinery only.\n */\n\n/** Phantom marker carrying the static TS type a column maps to. */\ndeclare const TYPE: unique symbol;\n\n/** Column flags that influence the inferred row/insert shape. */\ninterface ColumnFlags {\n readonly primaryKey: boolean;\n readonly notNull: boolean;\n readonly hasDefault: boolean;\n}\n\nconst DEFAULT_FLAGS: ColumnFlags = {\n primaryKey: false,\n notNull: false,\n hasDefault: false,\n};\n\n/**\n * The canonical, dialect-neutral kind of a column type. Mirrors SQLAlchemy's\n * generic types (e.g. `String` → varchar, `Text` → text). Dialect renderers\n * (Phase 4/6) map each kind + meta to concrete SQL per database.\n */\nexport type ColumnTypeKind =\n | \"smallint\"\n | \"integer\"\n | \"bigint\"\n | \"numeric\"\n | \"real\"\n | \"double\"\n | \"varchar\"\n | \"text\"\n | \"char\"\n | \"boolean\"\n | \"date\"\n | \"time\"\n | \"datetime\"\n | \"timestamp\"\n | \"blob\"\n | \"json\"\n | \"uuid\"\n | \"enum\";\n\n/** Parameters that refine a column type and feed the migration IR / DDL. */\nexport interface ColumnTypeMeta {\n /** Max length for `varchar`/`char`. */\n readonly length?: number | undefined;\n /** Total digits for `numeric`. */\n readonly precision?: number | undefined;\n /** Digits after the decimal point for `numeric`. */\n readonly scale?: number | undefined;\n /** `WITH TIME ZONE` for `timestamp`/`time`. */\n readonly withTimezone?: boolean | undefined;\n /** Allowed values for `enum`. */\n readonly values?: readonly string[] | undefined;\n /** Render as `JSONB` (PostgreSQL) instead of `JSON`. */\n readonly jsonb?: boolean | undefined;\n}\n\n/** A structured, dialect-neutral column type descriptor. */\nexport interface ColumnType {\n readonly kind: ColumnTypeKind;\n readonly meta: ColumnTypeMeta;\n}\n\n/**\n * A portable default expression. The token is dialect-neutral; the renderer\n * (Phase 4/6) maps it to the right SQL per database — e.g. `\"now\"` becomes\n * `CURRENT_TIMESTAMP` on SQLite and `now()` on PostgreSQL. Use `{ raw }` as an\n * escape hatch for a verbatim SQL fragment.\n */\nexport type PortableExpression =\n | \"now\"\n | \"current_date\"\n | \"current_time\"\n | \"uuidv4\"\n | { readonly raw: string };\n\n/**\n * A column default. Either a constant literal value or a server-side expression\n * evaluated by the database (mirrors SQLAlchemy's `default` vs `server_default`).\n * Feeds the migration IR (`DefaultIR`).\n */\nexport type DefaultValue =\n | { readonly kind: \"literal\"; readonly value: unknown }\n | { readonly kind: \"expression\"; readonly expression: PortableExpression };\n\n/** Portable server-side default expressions, à la SQLAlchemy's `func`. */\nexport const sql = {\n /** Current timestamp at insert (`CURRENT_TIMESTAMP` / `now()`). */\n now: (): DefaultValue => ({ kind: \"expression\", expression: \"now\" }),\n /** Current date. */\n currentDate: (): DefaultValue => ({ kind: \"expression\", expression: \"current_date\" }),\n /** Current time. */\n currentTime: (): DefaultValue => ({ kind: \"expression\", expression: \"current_time\" }),\n /** A freshly generated UUID v4 (`gen_random_uuid()` / portable fallback). */\n uuidv4: (): DefaultValue => ({ kind: \"expression\", expression: \"uuidv4\" }),\n /** Escape hatch: a verbatim SQL expression rendered as-is. */\n raw: (expression: string): DefaultValue => ({\n kind: \"expression\",\n expression: { raw: expression },\n }),\n} as const;\n\n/** Narrow a `.default()` argument to a `DefaultValue` expression/literal marker. */\nfunction isDefaultValue(value: unknown): value is DefaultValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n ((value as { kind: unknown }).kind === \"literal\" ||\n (value as { kind: unknown }).kind === \"expression\")\n );\n}\n\n/**\n * A typed column builder. Holds runtime metadata (structured `type`, `flags`,\n * `default`, `onUpdate`) and a phantom static type `T` used purely for inference.\n */\nclass Column<T, F extends ColumnFlags = ColumnFlags> {\n /** Phantom: never read at runtime, only inspected by the type system. */\n declare readonly [TYPE]: T;\n\n constructor(\n readonly type: ColumnType,\n readonly flags: F,\n /** The default applied on insert, or `null` for none. */\n readonly defaultValue: DefaultValue | null = null,\n /** The value re-applied on update (e.g. `updated_at`), or `null`. */\n readonly onUpdateValue: DefaultValue | null = null,\n ) {}\n\n primaryKey(): Column<T, F & { primaryKey: true; hasDefault: true }> {\n return new Column(\n this.type,\n { ...this.flags, primaryKey: true, hasDefault: true },\n this.defaultValue,\n this.onUpdateValue,\n );\n }\n\n notNull(): Column<T, F & { notNull: true }> {\n return new Column(\n this.type,\n { ...this.flags, notNull: true },\n this.defaultValue,\n this.onUpdateValue,\n );\n }\n\n /**\n * Set the insert-time default: a constant value of type `T`, or a portable\n * server-side expression from {@link sql} (e.g. `sql.now()`, `sql.uuidv4()`).\n */\n default(value: T | DefaultValue): Column<T, F & { hasDefault: true }> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n return new Column(\n this.type,\n { ...this.flags, hasDefault: true },\n resolved,\n this.onUpdateValue,\n );\n }\n\n /**\n * Re-apply a value whenever the row is updated (e.g. an `updated_at` column\n * with `sql.now()`). Mirrors SQLAlchemy's `onupdate`.\n */\n onUpdate(value: T | DefaultValue): Column<T, F> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n return new Column(this.type, this.flags, this.defaultValue, resolved);\n }\n}\n\n/** Build a `Column` of static type `T` from a kind + optional meta. */\nfunction makeColumn<T>(\n kind: ColumnTypeKind,\n meta: ColumnTypeMeta = {},\n): Column<T, ColumnFlags> {\n return new Column<T, ColumnFlags>({ kind, meta }, DEFAULT_FLAGS);\n}\n\n/**\n * Column factory mirroring SQLAlchemy's typed column constructors. Each entry\n * pairs a distinct SQL type with the TypeScript type it maps to.\n *\n * Notable mappings:\n * - `varchar(n)` (`VARCHAR(n)`) is distinct from `text` (`TEXT`).\n * - `bigInteger` maps to `bigint` (not `number`) to keep 64-bit precision.\n * - `numeric`/`decimal` map to `string` — JavaScript has no exact decimal, and\n * stringifying preserves precision instead of losing it to a float.\n * - `json<T>()` carries the parsed value type; `jsonb` is the PostgreSQL variant.\n * - `enum(...)` infers a string-literal union from its values.\n */\nexport const column = {\n /** `SMALLINT` → `number`. */\n smallInteger: (): Column<number, ColumnFlags> => makeColumn<number>(\"smallint\"),\n /** `INTEGER` → `number`. */\n integer: (): Column<number, ColumnFlags> => makeColumn<number>(\"integer\"),\n /** `BIGINT` → `bigint` (64-bit precision preserved). */\n bigInteger: (): Column<bigint, ColumnFlags> => makeColumn<bigint>(\"bigint\"),\n /** `NUMERIC(precision, scale)` → `string` (exact decimal, no float loss). */\n numeric: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** Alias of {@link column.numeric}. */\n decimal: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** `REAL` → `number`. */\n real: (): Column<number, ColumnFlags> => makeColumn<number>(\"real\"),\n /** `DOUBLE PRECISION` → `number`. */\n double: (): Column<number, ColumnFlags> => makeColumn<number>(\"double\"),\n /** `VARCHAR(length)` → `string`. Distinct from {@link column.text}. */\n varchar: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** Alias of {@link column.varchar} (SQLAlchemy's `String`). */\n string: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** `CHAR(length)` → `string` (fixed-width). */\n char: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"char\", { length }),\n /** `TEXT` → `string` (unbounded). Distinct from {@link column.varchar}. */\n text: (): Column<string, ColumnFlags> => makeColumn<string>(\"text\"),\n /** `BOOLEAN` → `boolean`. */\n boolean: (): Column<boolean, ColumnFlags> => makeColumn<boolean>(\"boolean\"),\n /** `DATE` → `Date`. */\n date: (): Column<Date, ColumnFlags> => makeColumn<Date>(\"date\"),\n /** `TIME` → `string`. Pass `{ timezone: true }` for `WITH TIME ZONE`. */\n time: (options?: { timezone?: boolean }): Column<string, ColumnFlags> =>\n makeColumn<string>(\"time\", { withTimezone: options?.timezone }),\n /**\n * `DATETIME`/`TIMESTAMP` → `Date` (SQLAlchemy's generic `DateTime`). Pass\n * `{ timezone: true }` for `WITH TIME ZONE`. Pair with `.default(sql.now())`\n * and `.onUpdate(sql.now())` for managed `created_at`/`updated_at` columns.\n */\n datetime: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"datetime\", { withTimezone: options?.timezone }),\n /** `TIMESTAMP` → `Date` (SQL-specific). Pass `{ timezone: true }`. */\n timestamp: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"timestamp\", { withTimezone: options?.timezone }),\n /** `BLOB`/`BYTEA` → `Uint8Array`. */\n blob: (): Column<Uint8Array, ColumnFlags> => makeColumn<Uint8Array>(\"blob\"),\n /** `JSON` → the given parsed value type `T` (defaults to `unknown`). */\n json: <T = unknown>(): Column<T, ColumnFlags> => makeColumn<T>(\"json\"),\n /** `JSONB` (PostgreSQL) → the given parsed value type `T`. */\n jsonb: <T = unknown>(): Column<T, ColumnFlags> =>\n makeColumn<T>(\"json\", { jsonb: true }),\n /** `UUID` → `string`. */\n uuid: (): Column<string, ColumnFlags> => makeColumn<string>(\"uuid\"),\n /** `ENUM(...values)` → a string-literal union of the given values. */\n enum: <const E extends string>(...values: E[]): Column<E, ColumnFlags> =>\n makeColumn<E>(\"enum\", { values }),\n} as const;\n\n/** Base class every model extends, SQLAlchemy-declarative style. */\n// biome-ignore lint/complexity/noStaticOnlyClass: declarative base users subclass; column fields live on instances.\nexport abstract class Model {\n static tablename: string;\n}\n\n/** Memoized column maps, keyed by model class (identity is stable per class). */\nconst columnsCache = new WeakMap<ModelClass, Record<string, Column<unknown>>>();\n\n/**\n * Reflect a model class into its column map at runtime, keyed by column name.\n *\n * Instantiates the class once and collects every field that is a `Column`. Used\n * by the serialization layer and (Phase 6) the migration schema reflector.\n *\n * The result is **memoized per class** — a model's columns never change at\n * runtime, and this is called once per row on hot read paths (coercion, joins),\n * so re-instantiating the class every time would dominate large result sets.\n *\n * @param model The model class (subclass of `Model`).\n * @returns A record of column name → `Column` instance (do not mutate).\n */\nexport function columnsOf(model: ModelClass): Record<string, Column<unknown>> {\n const cached = columnsCache.get(model);\n if (cached) return cached;\n const instance = new (model as new () => Model)();\n const out: Record<string, Column<unknown>> = {};\n for (const [key, value] of Object.entries(instance)) {\n if (value instanceof Column) {\n out[key] = value as Column<unknown>;\n }\n }\n columnsCache.set(model, out);\n return out;\n}\n\n/** Pull the static type out of a Column. */\ntype ColType<C> = C extends Column<infer T, infer _F> ? T : never;\n\n/** Keys of the model instance whose values are Columns. */\ntype ColumnKeys<M> = {\n [K in keyof M]: M[K] extends Column<unknown, ColumnFlags> ? K : never;\n}[keyof M];\n\n/** Constructor type for a Model subclass. */\ntype ModelClass = (new () => Model) & { tablename: string };\n\n/** Flatten an intersection into a single object literal for clean inference. */\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The nullability-aware value a column contributes to a row. */\ntype ColValue<Col> = Col extends Column<infer T, infer F>\n ? F extends { notNull: true } | { primaryKey: true }\n ? T\n : T | null\n : never;\n\n/** True when a column has a default (or is a PK) — i.e. optional on insert. */\ntype HasDefault<Col> = Col extends Column<unknown, infer F>\n ? F extends { hasDefault: true }\n ? true\n : false\n : false;\n\n/** Keys of the model whose columns are optional on insert. */\ntype OptionalInsertKeys<I> = {\n [K in ColumnKeys<I>]: HasDefault<I[K]> extends true ? K : never;\n}[ColumnKeys<I>];\n\n/**\n * Infer the SELECT row shape from a model class: every column field becomes its\n * mapped static type. Columns marked notNull/primaryKey are non-nullable; others\n * are `T | null` (SQL semantics — an unconstrained column can be NULL).\n */\nexport type InferModel<C extends ModelClass> = {\n [K in ColumnKeys<InstanceType<C>>]: ColValue<InstanceType<C>[K]>;\n};\n\n/**\n * Infer the INSERT shape: columns with a default (or PK) are optional; the rest\n * are required. Nullability is preserved on both sides.\n */\nexport type InferInsert<C extends ModelClass> = Simplify<\n {\n [K in OptionalInsertKeys<InstanceType<C>>]?: ColValue<InstanceType<C>[K]>;\n } & {\n [K in Exclude<\n ColumnKeys<InstanceType<C>>,\n OptionalInsertKeys<InstanceType<C>>\n >]: ColValue<InstanceType<C>[K]>;\n }\n>;\n\nexport { Column, type ColType, type ColumnFlags, type ModelClass };\n\nexport {\n and,\n type CondNode,\n type Condition,\n isCondition,\n not,\n or,\n toCondNode,\n type WhereArg,\n} from \"./conditions.js\";\n\nexport {\n Agg,\n type AggregateTerm,\n avg,\n count,\n max,\n min,\n type Operator,\n type OperatorsFor,\n OPERATORS,\n type OrderTerm,\n type SelectNode,\n SelectBuilder,\n select,\n type SortDirection,\n sum,\n type WhereInput,\n} from \"./query.js\";\n\nexport {\n DeleteBuilder,\n type DeleteNode,\n del,\n InsertBuilder,\n type InsertNode,\n insert,\n type OnConflict,\n type Returning,\n UpdateBuilder,\n type UpdateNode,\n update,\n} from \"./mutations.js\";\n\nexport {\n type Dialect,\n detectDialect,\n InvalidDatabaseUrl,\n type ParsedDatabaseUrl,\n parseDatabaseUrl,\n} from \"./url.js\";\n\nexport {\n fromDict,\n parse,\n stringify,\n toDict,\n toJSON,\n ValidationError,\n} from \"./serialize.js\";\n\nexport {\n BaseDialect,\n type CompiledQuery,\n getDialect,\n PostgresDialect,\n type QueryNode,\n SqliteDialect,\n} from \"./dialect.js\";\n\nexport {\n type ColRef,\n join,\n JoinBuilder,\n type JoinClause,\n type JoinNode,\n type JoinOn,\n type JoinSelection,\n type JoinWhereInput,\n type Sources,\n} from \"./join.js\";\n\nexport {\n BaseRepository,\n type PaginationFilter,\n type PaginationResult,\n RecordNotFound,\n} from \"./repository.js\";\n\nexport {\n ActiveRecord,\n type ActiveRecordManager,\n activeRecord,\n} from \"./active-record.js\";\n\nexport {\n type BelongsTo,\n belongsTo,\n type HasMany,\n hasMany,\n loadRelations,\n type Relation,\n type RelationValue,\n type WithRelations,\n} from \"./relations.js\";\n\nexport {\n AsyncEngine,\n AsyncResult,\n AsyncSession,\n type AsyncDriver,\n createEngine,\n createSyncEngine,\n type DriverResult,\n type EngineOptions,\n type Executable,\n NoResultError,\n NodeSqliteDriver,\n type PoolOptions,\n QueryExecutionError,\n type QueryLogger,\n type ReservedAsyncDriver,\n type RowOf,\n type SyncDriver,\n SyncEngine,\n SyncResult,\n SyncSession,\n} from \"./engine.js\";\n","/**\n * tempest-db-js — Phase 6: the Schema IR (intermediate representation).\n *\n * A canonical, dialect-neutral description of a database schema. Every source of\n * truth — model reflection (here), migration replay, or DB introspection —\n * produces the SAME `SchemaIR`, so the differ compares like with like and SQL is\n * only ever emitted at the dialect edge (the anti-\"SQL-stitching\" core).\n */\n\nimport {\n type ColumnType,\n type DefaultValue,\n type ModelClass,\n columnsOf,\n} from \"../index.js\";\n\n/** A column's default in the IR. */\nexport type DefaultIR = DefaultValue | null;\n\n/** One column. */\nexport interface ColumnIR {\n readonly name: string;\n readonly type: ColumnType;\n readonly notNull: boolean;\n readonly primaryKey: boolean;\n readonly default: DefaultIR;\n}\n\n/** One table. */\nexport interface TableIR {\n readonly name: string;\n readonly columns: Record<string, ColumnIR>;\n /** Primary-key column names (composite = more than one). */\n readonly primaryKey: readonly string[];\n}\n\n/** A whole schema, keyed by table name. */\nexport interface SchemaIR {\n readonly tables: Record<string, TableIR>;\n}\n\n/** Reflect one model class into a `TableIR`. */\nexport function reflectTable(model: ModelClass): TableIR {\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const [name, col] of Object.entries(columnsOf(model))) {\n const isPk = col.flags.primaryKey;\n columns[name] = {\n name,\n type: col.type,\n notNull: col.flags.notNull || isPk,\n primaryKey: isPk,\n default: col.defaultValue,\n };\n if (isPk) primaryKey.push(name);\n }\n return { name: model.tablename, columns, primaryKey };\n}\n\n/**\n * Reflect a set of model classes into a `SchemaIR`. This is the **target** state\n * the differ compares the current (replayed) schema against.\n *\n * @param models The model classes that make up the schema.\n * @returns The reflected schema IR.\n */\nexport function reflectSchema(models: readonly ModelClass[]): SchemaIR {\n const tables: Record<string, TableIR> = {};\n for (const model of models) {\n const table = reflectTable(model);\n tables[table.name] = table;\n }\n return { tables };\n}\n\n/** An empty schema (the baseline before any migration). */\nexport function emptySchema(): SchemaIR {\n return { tables: {} };\n}\n","/**\n * tempest-db-js — Phase 6d: SQLite introspection + drift detection.\n *\n * Reads the live schema from a SQLite database (via `PRAGMA table_info`) into a\n * `SchemaIR`, and compares it against the models to detect **drift** — the DB\n * diverging from what the migrations/models say it should be. Comparison is done\n * at SQLite's storage-affinity level, so coarse SQLite typing (every string is\n * `TEXT`) does not produce false positives.\n */\n\nimport type { AsyncDriver, SyncDriver } from \"../engine.js\";\nimport type { ColumnType } from \"../index.js\";\nimport type { ModelClass } from \"../index.js\";\nimport { renderColumnType } from \"./ddl.js\";\nimport { type ColumnIR, type SchemaIR, type TableIR, reflectSchema } from \"./ir.js\";\n\n/** SQLite's five storage classes / affinities. */\nexport type SqliteAffinity = \"INTEGER\" | \"TEXT\" | \"REAL\" | \"BLOB\" | \"NUMERIC\";\n\n/** Apply SQLite's affinity rules to a declared type string. */\nexport function sqliteAffinity(declared: string): SqliteAffinity {\n const t = declared.toUpperCase();\n if (t.includes(\"INT\")) return \"INTEGER\";\n if (t.includes(\"CHAR\") || t.includes(\"CLOB\") || t.includes(\"TEXT\")) return \"TEXT\";\n if (t.includes(\"BLOB\") || t === \"\") return \"BLOB\";\n if (t.includes(\"REAL\") || t.includes(\"FLOA\") || t.includes(\"DOUB\")) return \"REAL\";\n return \"NUMERIC\";\n}\n\n/** Map a SQLite affinity back to the closest IR column kind. */\nfunction affinityToKind(affinity: SqliteAffinity): ColumnType[\"kind\"] {\n switch (affinity) {\n case \"INTEGER\":\n return \"integer\";\n case \"REAL\":\n return \"real\";\n case \"BLOB\":\n return \"blob\";\n case \"NUMERIC\":\n return \"numeric\";\n default:\n return \"text\";\n }\n}\n\ninterface PragmaColumn {\n name: string;\n type: string;\n notnull: number;\n pk: number;\n}\n\n/**\n * Read the current SQLite schema into a `SchemaIR`. Lossy by nature (SQLite\n * collapses types into affinities), so types come back as the affinity's kind.\n *\n * @param driver A sync SQLite driver.\n * @returns The introspected schema.\n */\nexport function introspectSqlite(driver: SyncDriver): SchemaIR {\n const tablesRows = driver.execute(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'\",\n [],\n ).rows;\n\n const tables: Record<string, TableIR> = {};\n for (const row of tablesRows) {\n const tableName = String(row.name);\n const info = driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, [])\n .rows as unknown as PragmaColumn[];\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const col of info) {\n const isPk = Number(col.pk) > 0;\n const affinity = sqliteAffinity(col.type);\n columns[col.name] = {\n name: col.name,\n type: { kind: affinityToKind(affinity), meta: {} },\n notNull: Number(col.notnull) === 1 || isPk,\n primaryKey: isPk,\n default: null,\n };\n if (isPk) primaryKey.push(col.name);\n }\n tables[tableName] = { name: tableName, columns, primaryKey };\n }\n return { tables };\n}\n\n/**\n * Compare the live SQLite schema against the models and report drift. Comparison\n * is at the affinity level (so `varchar` vs `TEXT` is not flagged), plus\n * nullability, primary-key, and presence of tables/columns.\n *\n * @param driver A sync SQLite driver.\n * @param models The model classes that define the intended schema.\n * @returns A list of human-readable drift messages — empty means no drift.\n */\nexport function checkDrift(driver: SyncDriver, models: readonly ModelClass[]): string[] {\n const actual = introspectSqlite(driver);\n const expected = reflectSchema(models);\n const issues: string[] = [];\n\n for (const [tableName, expectedTable] of Object.entries(expected.tables)) {\n const actualTable = actual.tables[tableName];\n if (!actualTable) {\n issues.push(`table \"${tableName}\" is missing from the database`);\n continue;\n }\n for (const [colName, expectedCol] of Object.entries(expectedTable.columns)) {\n const actualCol = actualTable.columns[colName];\n if (!actualCol) {\n issues.push(`column \"${tableName}.${colName}\" is missing from the database`);\n continue;\n }\n const expAff = sqliteAffinity(renderColumnType(expectedCol.type, \"sqlite\"));\n const actAff = sqliteAffinity(renderColumnType(actualCol.type, \"sqlite\"));\n if (expAff !== actAff) {\n issues.push(\n `column \"${tableName}.${colName}\" affinity differs: model ${expAff}, db ${actAff}`,\n );\n }\n if (expectedCol.notNull !== actualCol.notNull) {\n issues.push(`column \"${tableName}.${colName}\" nullability differs`);\n }\n if (expectedCol.primaryKey !== actualCol.primaryKey) {\n issues.push(`column \"${tableName}.${colName}\" primary-key flag differs`);\n }\n }\n for (const colName of Object.keys(actualTable.columns)) {\n if (!expectedTable.columns[colName]) {\n issues.push(\n `column \"${tableName}.${colName}\" exists in the database but not in the model`,\n );\n }\n }\n }\n\n for (const tableName of Object.keys(actual.tables)) {\n if (!expected.tables[tableName]) {\n issues.push(`table \"${tableName}\" exists in the database but not in the models`);\n }\n }\n\n return issues;\n}\n\n/** Map a PostgreSQL `information_schema` type name to the closest IR kind. */\nfunction pgTypeToKind(dataType: string, udtName: string): ColumnType[\"kind\"] {\n const t = dataType.toLowerCase();\n if (t === \"user-defined\") return \"enum\"; // a named enum type\n if (t === \"smallint\") return \"smallint\";\n if (t === \"integer\") return \"integer\";\n if (t === \"bigint\") return \"bigint\";\n if (t === \"numeric\") return \"numeric\";\n if (t === \"real\") return \"real\";\n if (t === \"double precision\") return \"double\";\n if (t === \"character varying\") return \"varchar\";\n if (t === \"character\") return \"char\";\n if (t === \"text\") return \"text\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"date\") return \"date\";\n if (t.startsWith(\"time\")) return t.startsWith(\"timestamp\") ? \"timestamp\" : \"time\";\n if (t === \"bytea\") return \"blob\";\n if (t === \"json\") return \"json\";\n if (t === \"jsonb\") return \"json\";\n if (t === \"uuid\") return \"uuid\";\n return udtName === \"jsonb\" ? \"json\" : \"text\";\n}\n\n/**\n * Read the current PostgreSQL schema into a `SchemaIR` from `information_schema`.\n *\n * Not exercised by the in-repo test suite (no PostgreSQL in CI); mirrors\n * {@link introspectSqlite} for the async driver.\n *\n * @param driver An async PostgreSQL driver.\n * @returns The introspected schema.\n */\nexport async function introspectPostgres(driver: AsyncDriver): Promise<SchemaIR> {\n const tablesResult = await driver.execute(\n \"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name != 'tempest_db_js_migrations'\",\n [],\n );\n const tables: Record<string, TableIR> = {};\n for (const row of tablesResult.rows) {\n const tableName = String(row.table_name);\n const colsResult = await driver.execute(\n \"SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_name = $1\",\n [tableName],\n );\n const pkResult = await driver.execute(\n `SELECT a.attname AS name FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)\n WHERE i.indrelid = $1::regclass AND i.indisprimary`,\n [tableName],\n );\n const pkSet = new Set(pkResult.rows.map((r) => String(r.name)));\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const col of colsResult.rows) {\n const name = String(col.column_name);\n const isPk = pkSet.has(name);\n columns[name] = {\n name,\n type: {\n kind: pgTypeToKind(String(col.data_type), String(col.udt_name)),\n meta: {},\n },\n notNull: col.is_nullable === \"NO\" || isPk,\n primaryKey: isPk,\n default: null,\n };\n if (isPk) primaryKey.push(name);\n }\n tables[tableName] = { name: tableName, columns, primaryKey };\n }\n return { tables };\n}\n\n/**\n * Drift check for PostgreSQL: compares the live schema (introspected) against the\n * models by column kind, nullability, primary-key, and presence. Structural —\n * not exercised in CI (no PostgreSQL).\n *\n * @param driver An async PostgreSQL driver.\n * @param models The model classes that define the intended schema.\n * @returns A list of drift messages — empty means no drift.\n */\nexport async function checkDriftPostgres(\n driver: AsyncDriver,\n models: readonly ModelClass[],\n): Promise<string[]> {\n const actual = await introspectPostgres(driver);\n const expected = reflectSchema(models);\n const issues: string[] = [];\n for (const [tableName, expectedTable] of Object.entries(expected.tables)) {\n const actualTable = actual.tables[tableName];\n if (!actualTable) {\n issues.push(`table \"${tableName}\" is missing from the database`);\n continue;\n }\n for (const [colName, expectedCol] of Object.entries(expectedTable.columns)) {\n const actualCol = actualTable.columns[colName];\n if (!actualCol) {\n issues.push(`column \"${tableName}.${colName}\" is missing from the database`);\n continue;\n }\n if (expectedCol.type.kind !== actualCol.type.kind) {\n issues.push(\n `column \"${tableName}.${colName}\" type differs: model ${expectedCol.type.kind}, db ${actualCol.type.kind}`,\n );\n }\n if (expectedCol.notNull !== actualCol.notNull) {\n issues.push(`column \"${tableName}.${colName}\" nullability differs`);\n }\n }\n for (const colName of Object.keys(actualTable.columns)) {\n if (!expectedTable.columns[colName]) {\n issues.push(\n `column \"${tableName}.${colName}\" exists in the database but not in the model`,\n );\n }\n }\n }\n for (const tableName of Object.keys(actual.tables)) {\n if (!expected.tables[tableName]) {\n issues.push(`table \"${tableName}\" exists in the database but not in the models`);\n }\n }\n return issues;\n}\n","/**\n * tempest-db-js — Phase 6: rename detection.\n *\n * The differ ({@link diffSchema}) is deliberately conservative: a renamed column\n * looks like a drop + add, and a renamed table like a drop + create. That is the\n * *safe* default (never guesses), but it loses data. This module turns those\n * add/drop pairs into rename *candidates* the CLI can confirm — interactively at\n * a TTY, or explicitly via flags — and folds confirmed ones back into a single\n * `rename_table` / `rename_column` operation.\n *\n * Everything here is pure and structural (no SQL, no DB, no I/O), so the\n * detection and folding are fully testable; the actual prompting lives in the\n * `tempest-db` bin.\n */\n\nimport type { ColumnIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\n/** A possible rename the differ emitted as a drop + add/create pair. */\nexport type RenameCandidate =\n | { readonly kind: \"table\"; readonly from: string; readonly to: string }\n | {\n readonly kind: \"column\";\n readonly table: string;\n readonly from: string;\n readonly to: string;\n };\n\n/** Structural identity of a column, ignoring its name. */\nfunction columnShape(col: ColumnIR): string {\n return JSON.stringify({\n type: col.type,\n notNull: col.notNull,\n primaryKey: col.primaryKey,\n default: col.default,\n });\n}\n\n/** Structural identity of a table's columns, ignoring the table name. */\nfunction tableShape(columns: Readonly<Record<string, ColumnIR>>): string {\n return Object.entries(columns)\n .map(([name, col]) => `${name}:${columnShape(col)}`)\n .sort()\n .join(\"|\");\n}\n\n/**\n * Detect rename candidates in a forward operation list.\n *\n * A table rename is a `create_table` + `drop_table` whose column shapes match\n * exactly. A column rename is an `add_column` + `drop_column` on the same table\n * whose column shapes match exactly. Only unambiguous 1:1 shape matches are\n * reported — if two dropped columns share a shape, neither is offered (the\n * mapping would be a guess).\n *\n * @param ops The forward operations from {@link diffSchema}.\n * @returns The rename candidates found (never mutates `ops`).\n */\nexport function detectRenames(ops: readonly Operation[]): RenameCandidate[] {\n const candidates: RenameCandidate[] = [];\n\n // --- table renames ---\n const creates = ops.filter((o) => o.kind === \"create_table\");\n const tableDrops = ops.filter((o) => o.kind === \"drop_table\");\n const takenCreate = new Set<string>();\n const takenDrop = new Set<string>();\n for (const create of creates) {\n const createShape = tableShape(create.table.columns);\n const matches = tableDrops.filter(\n (d) => !takenDrop.has(d.table.name) && tableShape(d.table.columns) === createShape,\n );\n // Only a unique match is a safe rename; ambiguity → leave as drop + create.\n const uniqueCreate =\n creates.filter(\n (c) =>\n !takenCreate.has(c.table.name) && tableShape(c.table.columns) === createShape,\n ).length === 1;\n if (matches.length === 1 && uniqueCreate) {\n const drop = matches[0] as Extract<Operation, { kind: \"drop_table\" }>;\n if (drop.table.name !== create.table.name) {\n candidates.push({ kind: \"table\", from: drop.table.name, to: create.table.name });\n takenCreate.add(create.table.name);\n takenDrop.add(drop.table.name);\n }\n }\n }\n\n // --- column renames (per table) ---\n const adds = ops.filter((o) => o.kind === \"add_column\");\n const colDrops = ops.filter((o) => o.kind === \"drop_column\");\n const tables = new Set([...adds.map((o) => o.table), ...colDrops.map((o) => o.table)]);\n for (const table of tables) {\n const tableAdds = adds.filter((o) => o.table === table);\n const tableColDrops = colDrops.filter((o) => o.table === table);\n const takenAdd = new Set<string>();\n const takenColDrop = new Set<string>();\n for (const add of tableAdds) {\n const shape = columnShape(add.column);\n const dropMatches = tableColDrops.filter(\n (d) => !takenColDrop.has(d.column.name) && columnShape(d.column) === shape,\n );\n const addMatches = tableAdds.filter(\n (a) => !takenAdd.has(a.column.name) && columnShape(a.column) === shape,\n );\n if (dropMatches.length === 1 && addMatches.length === 1) {\n const drop = dropMatches[0] as Extract<Operation, { kind: \"drop_column\" }>;\n candidates.push({\n kind: \"column\",\n table,\n from: drop.column.name,\n to: add.column.name,\n });\n takenAdd.add(add.column.name);\n takenColDrop.add(drop.column.name);\n }\n }\n }\n\n return candidates;\n}\n\n/** Match a table-rename candidate against an op pair. */\nfunction isTableRename(\n op: Operation,\n r: Extract<RenameCandidate, { kind: \"table\" }>,\n): boolean {\n return (\n (op.kind === \"create_table\" && op.table.name === r.to) ||\n (op.kind === \"drop_table\" && op.table.name === r.from)\n );\n}\n\n/** Match a column-rename candidate against an op pair. */\nfunction isColumnRename(\n op: Operation,\n r: Extract<RenameCandidate, { kind: \"column\" }>,\n): boolean {\n return (\n (op.kind === \"add_column\" && op.table === r.table && op.column.name === r.to) ||\n (op.kind === \"drop_column\" && op.table === r.table && op.column.name === r.from)\n );\n}\n\n/**\n * Fold confirmed renames into an operation list: each confirmed candidate's\n * drop + add/create pair is removed and replaced by a single rename operation,\n * inserted at the position of the first op it replaces (preserving order).\n *\n * @param ops The forward operations from {@link diffSchema}.\n * @param confirmed The rename candidates the user accepted.\n * @returns A new operation list with renames applied.\n */\nexport function applyRenames(\n ops: readonly Operation[],\n confirmed: readonly RenameCandidate[],\n): Operation[] {\n const out: Operation[] = [];\n const emitted = new Set<RenameCandidate>();\n\n for (const op of ops) {\n const match = confirmed.find((r) =>\n r.kind === \"table\" ? isTableRename(op, r) : isColumnRename(op, r),\n );\n if (!match) {\n out.push(op);\n continue;\n }\n // Emit the rename once (at the first op of the pair); skip both members.\n if (!emitted.has(match)) {\n emitted.add(match);\n out.push(\n match.kind === \"table\"\n ? { kind: \"rename_table\", from: match.from, to: match.to }\n : { kind: \"rename_column\", table: match.table, from: match.from, to: match.to },\n );\n }\n }\n return out;\n}\n","/**\n * tempest-db-js — Phase 6: the migration runner.\n *\n * The `Op` facade records operations; the `MigrationRunner` renders them to SQL\n * (per dialect) and runs them through a sync driver, tracking applied revisions\n * in a `tempest_db_js_migrations` table. Upgrades/downgrades respect the revision DAG.\n *\n * SQLite execution is real (via `node:sqlite`); the same code path serves any\n * sync driver.\n */\n\nimport type { SyncDriver } from \"../engine.js\";\nimport type { Dialect } from \"../url.js\";\nimport { renderOperation } from \"./ddl.js\";\nimport { topoOrder } from \"./graph.js\";\nimport type { ColumnIR, TableIR } from \"./ir.js\";\nimport { type Operation, invertAll } from \"./operations.js\";\n\n/**\n * The facade injected into `up()`/`down()`. Each method records an operation;\n * the runner renders and executes them after the function returns.\n */\nexport class Op {\n readonly operations: Operation[] = [];\n\n /** Record a raw operation (used by autogenerated migrations). */\n run(operation: Operation): void {\n this.operations.push(operation);\n }\n\n createTable(table: TableIR): void {\n this.run({ kind: \"create_table\", table });\n }\n dropTable(table: TableIR): void {\n this.run({ kind: \"drop_table\", table });\n }\n renameTable(from: string, to: string): void {\n this.run({ kind: \"rename_table\", from, to });\n }\n addColumn(table: string, column: ColumnIR): void {\n this.run({ kind: \"add_column\", table, column });\n }\n dropColumn(table: string, column: ColumnIR): void {\n this.run({ kind: \"drop_column\", table, column });\n }\n alterColumn(table: string, name: string, from: ColumnIR, to: ColumnIR): void {\n this.run({ kind: \"alter_column\", table, name, from, to });\n }\n renameColumn(table: string, from: string, to: string): void {\n this.run({ kind: \"rename_column\", table, from, to });\n }\n /** Rebuild a table (SQLite batch-mode / PostgreSQL per-column alters). */\n recreateTable(from: TableIR, to: TableIR): void {\n this.run({ kind: \"recreate_table\", from, to });\n }\n /** Raw SQL escape hatch (e.g. a data migration). `down` may be `null`. */\n execute(up: string, down: string | null = null): void {\n this.run({ kind: \"execute\", up, down });\n }\n}\n\n/** A migration file's shape. */\nexport interface Migration {\n readonly revision: string;\n readonly downRevision: readonly string[];\n readonly label?: string;\n up(op: Op): void;\n down(op: Op): void;\n}\n\nconst VERSION_TABLE = \"tempest_db_js_migrations\";\n\n/** Runs migrations against a sync driver, tracking applied revisions. */\nexport class MigrationRunner {\n constructor(\n private readonly driver: SyncDriver,\n private readonly dialect: Dialect,\n ) {}\n\n /** Create the version-tracking table if it does not exist. */\n ensureVersionTable(): void {\n this.driver.execute(\n `CREATE TABLE IF NOT EXISTS \"${VERSION_TABLE}\" (revision TEXT PRIMARY KEY, applied_at TEXT NOT NULL, down_revision TEXT NOT NULL)`,\n [],\n );\n }\n\n /** The set of applied revision ids. */\n applied(): Set<string> {\n this.ensureVersionTable();\n const { rows } = this.driver.execute(`SELECT revision FROM \"${VERSION_TABLE}\"`, []);\n return new Set(rows.map((r) => String(r.revision)));\n }\n\n private runOps(ops: readonly Operation[]): void {\n for (const op of ops) {\n for (const stmt of renderOperation(op, this.dialect)) {\n const trimmed = stmt.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"--\")) continue;\n this.driver.execute(stmt, []);\n }\n }\n }\n\n private record(migration: Migration, appliedAt: string): void {\n this.driver.execute(\n `INSERT INTO \"${VERSION_TABLE}\" (revision, applied_at, down_revision) VALUES (?, ?, ?)`,\n [migration.revision, appliedAt, migration.downRevision.join(\",\")],\n );\n }\n\n private forget(revision: string): void {\n this.driver.execute(`DELETE FROM \"${VERSION_TABLE}\" WHERE revision = ?`, [revision]);\n }\n\n /**\n * Apply all pending migrations up to the head(s), in DAG order.\n *\n * @param migrations All known migrations.\n * @param appliedAt Timestamp string to stamp (pass one in — the runtime has no\n * wall clock of its own here).\n * @returns The revision ids that were applied this run.\n */\n upgrade(migrations: readonly Migration[], appliedAt: string): string[] {\n const done = this.applied();\n const ordered = topoOrder(migrations);\n const ran: string[] = [];\n for (const migration of ordered) {\n if (done.has(migration.revision)) continue;\n const op = new Op();\n migration.up(op);\n this.runOps(op.operations);\n this.record(migration, appliedAt);\n ran.push(migration.revision);\n }\n return ran;\n }\n\n /**\n * Revert the last `steps` applied migrations (default 1), newest first.\n *\n * @param migrations All known migrations.\n * @param steps How many applied revisions to roll back.\n * @returns The revision ids that were reverted.\n */\n downgrade(migrations: readonly Migration[], steps = 1): string[] {\n const done = this.applied();\n const ordered = topoOrder(migrations).filter((m) => done.has(m.revision));\n const toRevert = ordered.slice(-steps).reverse();\n const reverted: string[] = [];\n for (const migration of toRevert) {\n const op = new Op();\n // Prefer the migration's own down(); fall back to inverting up().\n if (migration.down.length >= 0) {\n try {\n migration.down(op);\n } catch {\n op.operations.length = 0;\n }\n }\n if (op.operations.length === 0) {\n const upOp = new Op();\n migration.up(upOp);\n op.operations.push(...invertAll(upOp.operations));\n }\n this.runOps(op.operations);\n this.forget(migration.revision);\n reverted.push(migration.revision);\n }\n return reverted;\n }\n}\n","/**\n * tempest-db-js — Phase 6: migration replay → virtual schema IR.\n *\n * Applies a migration's operations to an in-memory `SchemaIR`, building the\n * \"current\" schema without touching a database. This is the hybrid source of\n * truth for autogenerate: diff the replayed schema against the reflected models.\n */\n\nimport { topoOrder } from \"./graph.js\";\nimport { type SchemaIR, type TableIR, emptySchema } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\nimport { type Migration, Op } from \"./runner.js\";\n\n/** Apply one operation to a schema, returning the updated schema. */\nexport function applyOperation(schema: SchemaIR, op: Operation): SchemaIR {\n const tables: Record<string, TableIR> = { ...schema.tables };\n switch (op.kind) {\n case \"create_table\":\n tables[op.table.name] = op.table;\n break;\n case \"drop_table\":\n delete tables[op.table.name];\n break;\n case \"rename_table\": {\n const t = tables[op.from];\n if (t) {\n delete tables[op.from];\n tables[op.to] = { ...t, name: op.to };\n }\n break;\n }\n case \"recreate_table\":\n delete tables[op.from.name];\n tables[op.to.name] = op.to;\n break;\n case \"add_column\": {\n const t = tables[op.table];\n if (t) {\n tables[op.table] = {\n ...t,\n columns: { ...t.columns, [op.column.name]: op.column },\n };\n }\n break;\n }\n case \"drop_column\": {\n const t = tables[op.table];\n if (t) {\n const columns = { ...t.columns };\n delete columns[op.column.name];\n tables[op.table] = { ...t, columns };\n }\n break;\n }\n case \"alter_column\": {\n const t = tables[op.table];\n if (t) {\n tables[op.table] = {\n ...t,\n columns: { ...t.columns, [op.name]: op.to },\n };\n }\n break;\n }\n case \"rename_column\": {\n const t = tables[op.table];\n const col = t?.columns[op.from];\n if (t && col) {\n const columns = { ...t.columns };\n delete columns[op.from];\n columns[op.to] = { ...col, name: op.to };\n tables[op.table] = { ...t, columns };\n }\n break;\n }\n case \"execute\":\n // raw SQL is opaque to the IR\n break;\n }\n return { tables };\n}\n\n/**\n * Replay migrations (in DAG order) into a virtual `SchemaIR` — the \"current\"\n * schema, computed without a database.\n *\n * @param migrations All known migrations.\n * @returns The schema after applying every migration's `up()`.\n */\nexport function replaySchema(migrations: readonly Migration[]): SchemaIR {\n let schema = emptySchema();\n for (const migration of topoOrder(migrations)) {\n const op = new Op();\n migration.up(op);\n for (const operation of op.operations) {\n schema = applyOperation(schema, operation);\n }\n }\n return schema;\n}\n","/**\n * tempest-db-js — migration CLI (programmatic core).\n *\n * `runMigrationCli(argv, config)` dispatches Alembic-style commands against a\n * driver + a set of migrations + (optionally) the models. It returns lines and\n * an exit code rather than touching `process`, so it is fully testable; a thin\n * `bin` wrapper just maps `process.argv`/`process.exit` onto it.\n */\n\nimport type { SyncDriver } from \"../engine.js\";\nimport type { ModelClass } from \"../index.js\";\nimport type { Dialect } from \"../url.js\";\nimport { generateMigration, makeRevisionId } from \"./codegen.js\";\nimport { renderOperation } from \"./ddl.js\";\nimport { diffSchema } from \"./diff.js\";\nimport { heads as graphHeads, topoOrder } from \"./graph.js\";\nimport { checkDrift } from \"./introspect.js\";\nimport { reflectSchema } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\nimport { type RenameCandidate, applyRenames, detectRenames } from \"./renames.js\";\nimport { replaySchema } from \"./replay.js\";\nimport { type Migration, MigrationRunner, Op } from \"./runner.js\";\n\n/** Configuration the CLI operates against. */\nexport interface CliConfig {\n readonly driver: SyncDriver;\n readonly dialect: Dialect;\n readonly migrations: readonly Migration[];\n readonly models?: readonly ModelClass[];\n /** Timestamp string stamped on applied revisions (no wall clock here). */\n readonly appliedAt?: string;\n}\n\n/** The result of a CLI run. */\nexport interface CliResult {\n readonly code: number;\n readonly lines: string[];\n}\n\n/**\n * Identity helper for authoring a typed migration config file. Gives editor\n * autocompletion and type-checking on the object the `tempest-db` bin loads.\n *\n * @example\n * ```ts\n * // tempest-db.config.mjs\n * import { defineMigrationConfig } from \"tempest-db-js/migrations\";\n * import { NodeSqliteDriver } from \"tempest-db-js\";\n * import { migrations } from \"./migrations/index.js\";\n * import { User } from \"./models.js\";\n *\n * export default defineMigrationConfig({\n * driver: NodeSqliteDriver.open(\"app.db\"),\n * dialect: \"sqlite\",\n * migrations,\n * models: [User],\n * });\n * ```\n *\n * @param config The migration config to pass through unchanged.\n * @returns The same config, typed as `CliConfig`.\n */\nexport function defineMigrationConfig(config: CliConfig): CliConfig {\n return config;\n}\n\nfunction ok(lines: string[]): CliResult {\n return { code: 0, lines };\n}\nfunction fail(lines: string[]): CliResult {\n return { code: 1, lines };\n}\n\n/**\n * Parse rename flags into explicit rename candidates.\n *\n * `--rename-table <from>:<to>` and `--rename-column <table>.<from>:<to>` may each\n * be repeated. Malformed specs are ignored (the safe drop + add stays).\n *\n * @param rest The command arguments.\n * @returns The explicitly requested renames.\n */\nfunction parseRenameFlags(rest: readonly string[]): RenameCandidate[] {\n const out: RenameCandidate[] = [];\n for (let i = 0; i < rest.length; i += 1) {\n const arg = rest[i];\n if (arg === \"--rename-table\") {\n const [from, to] = (rest[i + 1] ?? \"\").split(\":\");\n i += 1;\n if (from && to) out.push({ kind: \"table\", from, to });\n } else if (arg === \"--rename-column\") {\n const [left, to] = (rest[i + 1] ?? \"\").split(\":\");\n i += 1;\n const dot = left?.lastIndexOf(\".\") ?? -1;\n if (left && to && dot > 0) {\n out.push({\n kind: \"column\",\n table: left.slice(0, dot),\n from: left.slice(dot + 1),\n to,\n });\n }\n }\n }\n return out;\n}\n\n/** Pending migrations (DAG order) not yet applied. */\nfunction pending(config: CliConfig, runner: MigrationRunner): Migration[] {\n const done = runner.applied();\n return topoOrder(config.migrations).filter((m) => !done.has(m.revision));\n}\n\n/**\n * Run one CLI command.\n *\n * Commands: `current`, `history`, `heads`, `upgrade [--sql]`, `downgrade [N]`,\n * `check`, `revision -m <msg> [--autogenerate]`.\n *\n * @param argv The command and its arguments (without the program name).\n * @param config The driver, migrations, and models to operate on.\n * @returns Output lines and an exit code.\n */\nexport function runMigrationCli(argv: readonly string[], config: CliConfig): CliResult {\n const [command, ...rest] = argv;\n const runner = new MigrationRunner(config.driver, config.dialect);\n const appliedAt = config.appliedAt ?? \"1970-01-01T00:00:00.000Z\";\n\n switch (command) {\n case \"current\": {\n const applied = [...runner.applied()].sort();\n return ok(applied.length > 0 ? applied : [\"(no migrations applied)\"]);\n }\n\n case \"heads\":\n return ok(graphHeads(config.migrations));\n\n case \"history\": {\n const done = runner.applied();\n return ok(\n topoOrder(config.migrations).map(\n (m) =>\n `${done.has(m.revision) ? \"✓\" : \"·\"} ${m.revision}${m.label ? ` — ${m.label}` : \"\"}`,\n ),\n );\n }\n\n case \"upgrade\": {\n if (rest.includes(\"--sql\")) {\n const lines: string[] = [];\n for (const migration of pending(config, runner)) {\n const op = new Op();\n migration.up(op);\n lines.push(`-- ${migration.revision}`);\n for (const operation of op.operations) {\n for (const stmt of renderOperation(operation, config.dialect))\n lines.push(`${stmt};`);\n }\n }\n return ok(lines.length > 0 ? lines : [\"-- nothing to upgrade\"]);\n }\n const ran = runner.upgrade(config.migrations, appliedAt);\n return ok(ran.length > 0 ? ran.map((r) => `applied ${r}`) : [\"nothing to upgrade\"]);\n }\n\n case \"downgrade\": {\n const steps = rest[0] ? Number(rest[0]) : 1;\n const reverted = runner.downgrade(config.migrations, steps);\n return ok(\n reverted.length > 0\n ? reverted.map((r) => `reverted ${r}`)\n : [\"nothing to downgrade\"],\n );\n }\n\n case \"check\": {\n if (!config.models) return fail([\"check requires models in the config\"]);\n // Drift: live DB vs models (SQLite introspection).\n const drift =\n config.dialect === \"sqlite\" ? checkDrift(config.driver, config.models) : [];\n // Pending model changes not yet captured by a migration.\n const undiffed = diffSchema(\n replaySchema(config.migrations),\n reflectSchema(config.models),\n );\n const issues = [\n ...drift.map((d) => `drift: ${d}`),\n ...undiffed.map((o) => `uncaptured: ${o.kind}`),\n ];\n return issues.length > 0 ? fail(issues) : ok([\"no drift; models match migrations\"]);\n }\n\n case \"revision\": {\n if (!config.models)\n return fail([\"revision --autogenerate requires models in the config\"]);\n const msgIndex = rest.indexOf(\"-m\");\n const label = msgIndex >= 0 ? (rest[msgIndex + 1] ?? \"revision\") : \"revision\";\n const parents = graphHeads(config.migrations);\n let ops: Operation[] = rest.includes(\"--autogenerate\")\n ? diffSchema(replaySchema(config.migrations), reflectSchema(config.models))\n : [];\n if (rest.includes(\"--autogenerate\")) {\n // Fold add/drop pairs into renames: `--autorename` accepts every\n // detected candidate; otherwise only the explicit `--rename-*` flags.\n const confirmed = rest.includes(\"--autorename\")\n ? detectRenames(ops)\n : parseRenameFlags(rest);\n if (confirmed.length > 0) ops = applyRenames(ops, confirmed);\n }\n const source = generateMigration({\n revision: makeRevisionId(label, parents),\n downRevision: parents,\n label,\n operations: ops,\n });\n return ok(source.split(\"\\n\"));\n }\n\n default:\n return fail([\n `unknown command ${JSON.stringify(command)}`,\n \"commands: current | history | heads | upgrade [--sql] | downgrade [N] | check | revision -m <msg> [--autogenerate]\",\n ]);\n }\n}\n","#!/usr/bin/env node\n/**\n * tempest-db-js — `tempest-db` executable.\n *\n * A thin wrapper around {@link runMigrationCli}: it discovers a config module,\n * loads it, injects a real timestamp, dispatches the command, prints the output\n * lines, and maps the result code onto `process.exit`. All the migration logic\n * lives in the (fully testable) programmatic core — this file only touches\n * `process`, the filesystem, and the wall clock.\n *\n * @example\n * ```bash\n * tempest-db upgrade\n * tempest-db revision -m \"add users\" --autogenerate\n * tempest-db --config db/tempest.config.mjs current\n * ```\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport type { CliConfig } from \"./migrations/cli.js\";\nimport { runMigrationCli } from \"./migrations/cli.js\";\nimport { diffSchema } from \"./migrations/diff.js\";\nimport { reflectSchema } from \"./migrations/ir.js\";\nimport { type RenameCandidate, detectRenames } from \"./migrations/renames.js\";\nimport { replaySchema } from \"./migrations/replay.js\";\n\n/** Config file names looked up in the current directory, in order. */\nconst DEFAULT_CONFIG_NAMES: readonly string[] = [\n \"tempest-db.config.mjs\",\n \"tempest-db.config.js\",\n \"tempest-db.config.cjs\",\n];\n\n/**\n * Pull the `--config <path>` flag out of the argv, returning the path (if any)\n * and the remaining arguments for the CLI command itself.\n *\n * @param argv The process arguments (without node + script).\n * @returns The explicit config path (or `null`) and the leftover argv.\n */\nfunction extractConfigFlag(argv: readonly string[]): {\n configPath: string | null;\n rest: string[];\n} {\n const rest: string[] = [];\n let configPath: string | null = null;\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === \"--config\" || arg === \"-c\") {\n configPath = argv[i + 1] ?? null;\n i += 1;\n } else if (arg?.startsWith(\"--config=\")) {\n configPath = arg.slice(\"--config=\".length);\n } else if (arg !== undefined) {\n rest.push(arg);\n }\n }\n return { configPath, rest };\n}\n\n/**\n * Resolve the config file path: the explicit `--config` value, or the first of\n * the default names that exists in the current directory.\n *\n * @param explicit The `--config` value, or `null` to search defaults.\n * @returns The absolute config path, or `null` if none was found.\n */\nfunction resolveConfigPath(explicit: string | null): string | null {\n if (explicit) return resolve(process.cwd(), explicit);\n for (const name of DEFAULT_CONFIG_NAMES) {\n const candidate = resolve(process.cwd(), name);\n if (existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Dynamically import a config module and extract the `CliConfig` from its\n * `default` export (or a named `config` export as a fallback).\n *\n * @param path The absolute path to the config module.\n * @returns The loaded migration config.\n * @throws If the module has neither a default nor a `config` export.\n */\nasync function loadConfig(path: string): Promise<CliConfig> {\n const mod = (await import(pathToFileURL(path).href)) as {\n default?: CliConfig;\n config?: CliConfig;\n };\n const config = mod.default ?? mod.config;\n if (!config) {\n throw new Error(\n `config at ${path} must default-export (or export \\`config\\`) a CliConfig`,\n );\n }\n return config;\n}\n\n/** Turn a confirmed candidate into the `--rename-*` flag args the CLI parses. */\nfunction renameToFlags(r: RenameCandidate): string[] {\n return r.kind === \"table\"\n ? [\"--rename-table\", `${r.from}:${r.to}`]\n : [\"--rename-column\", `${r.table}.${r.from}:${r.to}`];\n}\n\n/**\n * When running `revision --autogenerate` at an interactive TTY, detect rename\n * candidates and ask the user to confirm each; return the `--rename-*` flags for\n * the accepted ones. No-op when not autogenerating, when `--autorename` or\n * explicit `--rename-*` flags are already present, when there are no models, or\n * when stdin is not a TTY (CI, pipes).\n *\n * @param config The loaded migration config.\n * @param rest The CLI command arguments.\n * @returns Extra `--rename-*` args to append before dispatching.\n */\nasync function promptRenames(\n config: CliConfig,\n rest: readonly string[],\n): Promise<string[]> {\n const decided =\n rest.includes(\"--autorename\") ||\n rest.includes(\"--rename-table\") ||\n rest.includes(\"--rename-column\");\n if (\n rest[0] !== \"revision\" ||\n !rest.includes(\"--autogenerate\") ||\n decided ||\n !config.models ||\n !process.stdin.isTTY\n ) {\n return [];\n }\n\n const ops = diffSchema(replaySchema(config.migrations), reflectSchema(config.models));\n const candidates = detectRenames(ops);\n if (candidates.length === 0) return [];\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const flags: string[] = [];\n try {\n for (const c of candidates) {\n const what =\n c.kind === \"table\"\n ? `table \"${c.from}\" → \"${c.to}\"`\n : `column \"${c.table}.${c.from}\" → \"${c.table}.${c.to}\"`;\n const answer = (await rl.question(`Rename ${what}? [y/N] `)).trim().toLowerCase();\n if (answer === \"y\" || answer === \"yes\") flags.push(...renameToFlags(c));\n }\n } finally {\n rl.close();\n }\n return flags;\n}\n\n/**\n * Run the `tempest-db` CLI end to end: discover + load the config, dispatch the\n * command, print output, and exit with the CLI's status code.\n *\n * @param argv The process arguments (without node + script).\n * @returns A promise resolving once the command has printed and exit is set.\n */\nexport async function main(argv: readonly string[]): Promise<void> {\n const { configPath, rest } = extractConfigFlag(argv);\n const resolved = resolveConfigPath(configPath);\n if (!resolved) {\n process.stderr.write(\n `tempest-db: no config found. Create one of ${DEFAULT_CONFIG_NAMES.join(\n \", \",\n )} or pass --config <path>.\\n`,\n );\n process.exitCode = 1;\n return;\n }\n\n let config: CliConfig;\n try {\n config = await loadConfig(resolved);\n } catch (error) {\n process.stderr.write(`tempest-db: ${(error as Error).message}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const withClock: CliConfig = {\n ...config,\n appliedAt: config.appliedAt ?? new Date().toISOString(),\n };\n const renameFlags = await promptRenames(withClock, rest);\n const result = runMigrationCli([...rest, ...renameFlags], withClock);\n const sink = result.code === 0 ? process.stdout : process.stderr;\n for (const line of result.lines) sink.write(`${line}\\n`);\n process.exitCode = result.code;\n}\n\n// Only auto-run when invoked as a program (not when imported by a test).\nif (import.meta.url === pathToFileURL(process.argv[1] ?? \"\").href) {\n void main(process.argv.slice(2));\n}\n"]}
1
+ {"version":3,"sources":["../src/migrations/operations.ts","../src/migrations/codegen.ts","../src/migrations/ddl.ts","../src/migrations/diff.ts","../src/migrations/graph.ts","../src/index.ts","../src/migrations/ir.ts","../src/migrations/introspect.ts","../src/migrations/renames.ts","../src/migrations/runner.ts","../src/migrations/replay.ts","../src/migrations/cli.ts","../src/bin.ts"],"names":["resolve","existsSync","pathToFileURL","createInterface"],"mappings":";;;;;;;;;;AAyCO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF,CAAA;AASO,SAAS,OAAO,EAAA,EAA0B;AAC/C,EAAA,QAAQ,GAAG,IAAA;AAAM,IACf,KAAK,cAAA;AACH,MAAA,OAAO,EAAE,IAAA,EAAM,YAAA,EAAc,KAAA,EAAO,GAAG,KAAA,EAAM;AAAA,IAC/C,KAAK,YAAA;AACH,MAAA,OAAO,EAAE,IAAA,EAAM,cAAA,EAAgB,KAAA,EAAO,GAAG,KAAA,EAAM;AAAA,IACjD,KAAK,cAAA;AACH,MAAA,OAAO,EAAE,MAAM,cAAA,EAAgB,IAAA,EAAM,GAAG,EAAA,EAAI,EAAA,EAAI,GAAG,IAAA,EAAK;AAAA,IAC1D,KAAK,YAAA;AACH,MAAA,OAAO,EAAE,MAAM,aAAA,EAAe,KAAA,EAAO,GAAG,KAAA,EAAO,MAAA,EAAQ,GAAG,MAAA,EAAO;AAAA,IACnE,KAAK,aAAA;AACH,MAAA,OAAO,EAAE,MAAM,YAAA,EAAc,KAAA,EAAO,GAAG,KAAA,EAAO,MAAA,EAAQ,GAAG,MAAA,EAAO;AAAA,IAClE,KAAK,cAAA;AACH,MAAA,OAAO;AAAA,QACL,IAAA,EAAM,cAAA;AAAA,QACN,OAAO,EAAA,CAAG,KAAA;AAAA,QACV,MAAM,EAAA,CAAG,IAAA;A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,CAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AACjC","file":"bin.cjs","sourcesContent":["/**\n * tempest-db-js — Phase 6: typed migration operations.\n *\n * Every schema change is a typed `Operation` with a known inverse. This is what\n * gives autogenerated, reversible `down()` and dialect-rendered DDL — never a\n * hand-written `.sql` blob (the anti-Drizzle core).\n */\n\nimport type { ColumnIR, TableIR } from \"./ir.js\";\n\n/** A single, reversible schema operation. */\nexport type Operation =\n | { readonly kind: \"create_table\"; readonly table: TableIR }\n | { readonly kind: \"drop_table\"; readonly table: TableIR }\n | { readonly kind: \"rename_table\"; readonly from: string; readonly to: string }\n | { readonly kind: \"add_column\"; readonly table: string; readonly column: ColumnIR }\n | { readonly kind: \"drop_column\"; readonly table: string; readonly column: ColumnIR }\n | {\n readonly kind: \"alter_column\";\n readonly table: string;\n readonly name: string;\n readonly from: ColumnIR;\n readonly to: ColumnIR;\n }\n | {\n readonly kind: \"rename_column\";\n readonly table: string;\n readonly from: string;\n readonly to: string;\n }\n | {\n // Rebuild a table from `from` to `to`. On SQLite this is the batch /\n // table-rebuild path (SQLite cannot ALTER COLUMN); on PostgreSQL it is\n // realized as per-column ALTER/ADD/DROP.\n readonly kind: \"recreate_table\";\n readonly from: TableIR;\n readonly to: TableIR;\n }\n | { readonly kind: \"execute\"; readonly up: string; readonly down: string | null };\n\n/** Raised when an operation has no safe inverse (e.g. a one-way `execute`). */\nexport class IrreversibleMigration extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IrreversibleMigration\";\n }\n}\n\n/**\n * Compute the inverse of an operation, for autogenerated `down()`.\n *\n * @param op The forward operation.\n * @returns The operation that undoes it.\n * @throws IrreversibleMigration When `op` cannot be safely reversed.\n */\nexport function invert(op: Operation): Operation {\n switch (op.kind) {\n case \"create_table\":\n return { kind: \"drop_table\", table: op.table };\n case \"drop_table\":\n return { kind: \"create_table\", table: op.table };\n case \"rename_table\":\n return { kind: \"rename_table\", from: op.to, to: op.from };\n case \"add_column\":\n return { kind: \"drop_column\", table: op.table, column: op.column };\n case \"drop_column\":\n return { kind: \"add_column\", table: op.table, column: op.column };\n case \"alter_column\":\n return {\n kind: \"alter_column\",\n table: op.table,\n name: op.name,\n from: op.to,\n to: op.from,\n };\n case \"rename_column\":\n return { kind: \"rename_column\", table: op.table, from: op.to, to: op.from };\n case \"recreate_table\":\n return { kind: \"recreate_table\", from: op.to, to: op.from };\n case \"execute\":\n if (op.down === null) {\n throw new IrreversibleMigration(\"execute() operation has no down SQL\");\n }\n return { kind: \"execute\", up: op.down, down: op.up };\n }\n}\n\n/** Invert a list of operations: reverse order, each inverted. */\nexport function invertAll(ops: readonly Operation[]): Operation[] {\n return [...ops].reverse().map(invert);\n}\n","/**\n * tempest-db-js — Phase 6: migration autogeneration.\n *\n * Turns a diff's `Operation[]` into an editable TypeScript migration file with\n * `up()` and an autogenerated, inverted `down()`. Operations are embedded as\n * plain-data literals (they are JSON-serializable), so the file stays readable\n * and hand-editable — never an opaque `.sql` blob.\n */\n\nimport { type Operation, invertAll } from \"./operations.js\";\n\n/** Inputs for one generated migration file. */\nexport interface MigrationDraft {\n readonly revision: string;\n readonly downRevision: readonly string[];\n readonly label: string;\n readonly operations: readonly Operation[];\n}\n\n/** Serialize operations as an indented array literal for the generated file. */\nfunction renderOps(ops: readonly Operation[]): string {\n if (ops.length === 0) return \"[]\";\n const body = ops.map((op) => ` ${JSON.stringify(op)},`).join(\"\\n\");\n return `[\\n${body}\\n ]`;\n}\n\n/**\n * Render a migration file body as TypeScript source.\n *\n * The generated `down()` inverts `up()`; if any operation is irreversible, the\n * generation still succeeds but `down()` throws at run time with a clear message\n * (so reversibility is never silently broken).\n *\n * @param draft The revision id, parents, label, and forward operations.\n * @returns The migration file source.\n */\nexport function generateMigration(draft: MigrationDraft): string {\n let down: string;\n try {\n down = renderOps(invertAll(draft.operations));\n } catch (error) {\n down = `(() => { throw new Error(${JSON.stringify(\n `irreversible migration: ${(error as Error).message}`,\n )}); })()`;\n }\n\n return `import type { Migration, Op } from \"tempest-db-js/migrations\";\n\nexport const revision = ${JSON.stringify(draft.revision)};\nexport const downRevision: string[] = ${JSON.stringify(draft.downRevision)};\nexport const label = ${JSON.stringify(draft.label)};\n\nconst upOps = ${renderOps(draft.operations)};\n\nconst downOps = ${down};\n\nexport const up = (op: Op): void => {\n for (const operation of upOps) op.run(operation);\n};\n\nexport const down = (op: Op): void => {\n for (const operation of downOps) op.run(operation);\n};\n\nexport default { revision, downRevision, label, up, down } satisfies Migration;\n`;\n}\n\n/** Build a short, stable revision id from a label + parent set. */\nexport function makeRevisionId(label: string, parents: readonly string[]): string {\n // Deterministic non-crypto hash (FNV-1a) — no Date/Math.random (build-stable).\n let hash = 0x811c9dc5;\n for (const ch of `${label}|${[...parents].sort().join(\",\")}`) {\n hash ^= ch.charCodeAt(0);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n","/**\n * tempest-db-js — Phase 6/9: DDL rendering.\n *\n * Renders the dialect-neutral IR + operations to concrete SQL per dialect. This\n * is the ONLY place migration SQL is produced — the same operation yields the\n * right DDL for SQLite, PostgreSQL or MySQL.\n */\n\nimport type { ColumnType, DefaultValue } from \"../index.js\";\nimport type { Dialect } from \"../url.js\";\nimport type { ColumnIR, TableIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\n/** Quote an identifier for the dialect (backticks on MySQL, double-quotes else). */\nfunction quoteId(name: string, dialect: Dialect): string {\n return dialect === \"mysql\"\n ? `\\`${name.replace(/`/g, \"``\")}\\``\n : `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/** Map a column type to its SQL type string for the dialect. */\nexport function renderColumnType(type: ColumnType, dialect: Dialect): string {\n const { kind, meta } = type;\n if (dialect === \"sqlite\") {\n switch (kind) {\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"boolean\":\n return \"INTEGER\";\n case \"real\":\n case \"double\":\n return \"REAL\";\n case \"numeric\":\n return \"NUMERIC\";\n case \"blob\":\n return \"BLOB\";\n default:\n return \"TEXT\"; // varchar/char/text/uuid/enum/json/date/time/datetime/timestamp\n }\n }\n if (dialect === \"mysql\") {\n switch (kind) {\n case \"smallint\":\n return \"SMALLINT\";\n case \"integer\":\n return \"INT\";\n case \"bigint\":\n return \"BIGINT\";\n case \"numeric\":\n return meta.precision !== undefined\n ? `DECIMAL(${meta.precision}${meta.scale !== undefined ? `, ${meta.scale}` : \"\"})`\n : \"DECIMAL\";\n case \"real\":\n return \"FLOAT\";\n case \"double\":\n return \"DOUBLE\";\n case \"varchar\":\n return `VARCHAR(${meta.length ?? 255})`;\n case \"char\":\n return `CHAR(${meta.length ?? 255})`;\n case \"text\":\n return \"TEXT\";\n case \"boolean\":\n return \"TINYINT(1)\";\n case \"date\":\n return \"DATE\";\n case \"time\":\n return \"TIME\";\n case \"datetime\":\n case \"timestamp\":\n return \"DATETIME\";\n case \"blob\":\n return \"BLOB\";\n case \"json\":\n return \"JSON\";\n case \"uuid\":\n return \"CHAR(36)\";\n case \"enum\":\n return `ENUM(${(meta.values ?? []).map(quoteLiteral).join(\", \")})`;\n }\n }\n // PostgreSQL\n switch (kind) {\n case \"smallint\":\n return \"SMALLINT\";\n case \"integer\":\n return \"INTEGER\";\n case \"bigint\":\n return \"BIGINT\";\n case \"numeric\":\n return meta.precision !== undefined\n ? `NUMERIC(${meta.precision}${meta.scale !== undefined ? `, ${meta.scale}` : \"\"})`\n : \"NUMERIC\";\n case \"real\":\n return \"REAL\";\n case \"double\":\n return \"DOUBLE PRECISION\";\n case \"varchar\":\n return meta.length !== undefined ? `VARCHAR(${meta.length})` : \"VARCHAR\";\n case \"char\":\n return meta.length !== undefined ? `CHAR(${meta.length})` : \"CHAR\";\n case \"text\":\n return \"TEXT\";\n case \"boolean\":\n return \"BOOLEAN\";\n case \"date\":\n return \"DATE\";\n case \"time\":\n return meta.withTimezone ? \"TIME WITH TIME ZONE\" : \"TIME\";\n case \"datetime\":\n case \"timestamp\":\n return meta.withTimezone ? \"TIMESTAMP WITH TIME ZONE\" : \"TIMESTAMP\";\n case \"blob\":\n return \"BYTEA\";\n case \"json\":\n return meta.jsonb ? \"JSONB\" : \"JSON\";\n case \"uuid\":\n return \"UUID\";\n case \"enum\":\n // Named PG enum types are handled in renderCreateTable; fall back to TEXT.\n return \"TEXT\";\n }\n}\n\n/** Render a default value into a SQL `DEFAULT` expression for the dialect. */\nexport function renderDefault(def: DefaultValue, dialect: Dialect): string {\n if (def.kind === \"expression\") {\n const expr = def.expression;\n if (typeof expr === \"object\") return expr.raw;\n switch (expr) {\n case \"now\":\n return dialect === \"postgresql\" ? \"now()\" : \"CURRENT_TIMESTAMP\";\n case \"current_date\":\n return \"CURRENT_DATE\";\n case \"current_time\":\n return \"CURRENT_TIME\";\n case \"uuidv4\":\n if (dialect === \"postgresql\") return \"gen_random_uuid()\";\n if (dialect === \"mysql\") return \"(UUID())\";\n return \"(lower(hex(randomblob(16))))\";\n }\n }\n const value = def.value;\n if (value === null) return \"NULL\";\n if (typeof value === \"boolean\") {\n return dialect === \"postgresql\" ? (value ? \"TRUE\" : \"FALSE\") : value ? \"1\" : \"0\";\n }\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (value instanceof Date) return quoteLiteral(value.toISOString());\n if (typeof value === \"object\") return quoteLiteral(JSON.stringify(value));\n return quoteLiteral(String(value));\n}\n\n/** Render one column definition: `\"name\" TYPE [NOT NULL] [DEFAULT x]`. */\nexport function renderColumnDef(col: ColumnIR, dialect: Dialect): string {\n let sql = `${quoteId(col.name, dialect)} ${renderColumnType(col.type, dialect)}`;\n if (col.notNull) sql += \" NOT NULL\";\n if (col.default !== null) sql += ` DEFAULT ${renderDefault(col.default, dialect)}`;\n return sql;\n}\n\n/** The PostgreSQL named-enum type for a column (`<table>_<column>`). */\nfunction enumTypeName(table: string, column: string): string {\n return `${table}_${column}`;\n}\n\n/** True when a column is the sole integer-family PK with no explicit default. */\nfunction isAutoIncrementPk(table: TableIR, col: ColumnIR): boolean {\n return (\n table.primaryKey.length === 1 &&\n table.primaryKey[0] === col.name &&\n col.default === null &&\n (col.type.kind === \"smallint\" ||\n col.type.kind === \"integer\" ||\n col.type.kind === \"bigint\")\n );\n}\n\n/** The PostgreSQL auto-incrementing serial type for an integer-family kind. */\nfunction postgresSerialType(kind: ColumnType[\"kind\"]): string {\n if (kind === \"bigint\") return \"BIGSERIAL\";\n if (kind === \"smallint\") return \"SMALLSERIAL\";\n return \"SERIAL\";\n}\n\n/**\n * Render a CREATE TABLE (plus, on PostgreSQL, any `CREATE TYPE ... AS ENUM` for\n * enum columns, which must precede the table). Returns the statement list.\n *\n * Auto-increment for a lone integer-family primary key (SQLAlchemy semantics):\n * - SQLite: free via `INTEGER PRIMARY KEY` (rowid alias).\n * - PostgreSQL: `SERIAL`/`BIGSERIAL`.\n * - MySQL: `AUTO_INCREMENT` on the column (which must also be a key).\n */\nfunction renderCreateTable(table: TableIR, dialect: Dialect): string[] {\n const typeStmts: string[] = [];\n const cols = Object.values(table.columns).map((c) => {\n if (dialect === \"postgresql\" && c.type.kind === \"enum\") {\n const typeName = enumTypeName(table.name, c.name);\n const values = (c.type.meta.values ?? []).map(quoteLiteral).join(\", \");\n typeStmts.push(`CREATE TYPE ${quoteId(typeName, dialect)} AS ENUM (${values})`);\n let def = `${quoteId(c.name, dialect)} ${quoteId(typeName, dialect)}`;\n if (c.notNull) def += \" NOT NULL\";\n if (c.default !== null) def += ` DEFAULT ${renderDefault(c.default, dialect)}`;\n return def;\n }\n if (dialect === \"postgresql\" && isAutoIncrementPk(table, c)) {\n return `${quoteId(c.name, dialect)} ${postgresSerialType(c.type.kind)}`;\n }\n if (dialect === \"mysql\" && isAutoIncrementPk(table, c)) {\n return `${quoteId(c.name, dialect)} ${renderColumnType(c.type, dialect)} NOT NULL AUTO_INCREMENT`;\n }\n return renderColumnDef(c, dialect);\n });\n if (table.primaryKey.length > 0) {\n cols.push(\n `PRIMARY KEY (${table.primaryKey.map((c) => quoteId(c, dialect)).join(\", \")})`,\n );\n }\n return [\n ...typeStmts,\n `CREATE TABLE ${quoteId(table.name, dialect)} (\\n ${cols.join(\",\\n \")}\\n)`,\n ];\n}\n\n/**\n * Render an operation to one or more SQL statements for the dialect.\n *\n * @param op The operation.\n * @param dialect The target dialect.\n * @returns The SQL statements (usually one).\n * @throws Error When the operation is unsupported on the dialect (e.g. SQLite\n * `alter_column`, which needs the table-rebuild path).\n */\nexport function renderOperation(op: Operation, dialect: Dialect): string[] {\n switch (op.kind) {\n case \"create_table\":\n return renderCreateTable(op.table, dialect);\n case \"drop_table\":\n return [`DROP TABLE ${quoteId(op.table.name, dialect)}`];\n case \"rename_table\":\n return dialect === \"mysql\"\n ? [`RENAME TABLE ${quoteId(op.from, dialect)} TO ${quoteId(op.to, dialect)}`]\n : [\n `ALTER TABLE ${quoteId(op.from, dialect)} RENAME TO ${quoteId(op.to, dialect)}`,\n ];\n case \"add_column\":\n return [\n `ALTER TABLE ${quoteId(op.table, dialect)} ADD COLUMN ${renderColumnDef(op.column, dialect)}`,\n ];\n case \"drop_column\":\n return [\n `ALTER TABLE ${quoteId(op.table, dialect)} DROP COLUMN ${quoteId(op.column.name, dialect)}`,\n ];\n case \"rename_column\":\n return [\n `ALTER TABLE ${quoteId(op.table, dialect)} RENAME COLUMN ${quoteId(op.from, dialect)} TO ${quoteId(op.to, dialect)}`,\n ];\n case \"alter_column\":\n return renderAlterColumn(op.table, op.to, dialect);\n case \"recreate_table\":\n return dialect === \"sqlite\"\n ? renderSqliteRebuild(op.from, op.to)\n : renderTableDiff(op.from, op.to, dialect);\n case \"execute\":\n return [op.up];\n }\n}\n\n/**\n * SQLite batch / table-rebuild: create a new table with the target schema, copy\n * the columns common to both, swap names. This is how SQLite realizes column\n * changes it cannot `ALTER` (drop/alter type/constraint changes).\n */\nfunction renderSqliteRebuild(from: TableIR, to: TableIR): string[] {\n const tmp = `__new_${to.name}`;\n const common = Object.keys(to.columns).filter((c) => c in from.columns);\n const cols = Object.values(to.columns).map((c) => renderColumnDef(c, \"sqlite\"));\n if (to.primaryKey.length > 0) {\n cols.push(\n `PRIMARY KEY (${to.primaryKey.map((c) => quoteId(c, \"sqlite\")).join(\", \")})`,\n );\n }\n const commonSql = common.map((c) => quoteId(c, \"sqlite\")).join(\", \");\n return [\n \"PRAGMA foreign_keys=off\",\n `CREATE TABLE ${quoteId(tmp, \"sqlite\")} (\\n ${cols.join(\",\\n \")}\\n)`,\n common.length > 0\n ? `INSERT INTO ${quoteId(tmp, \"sqlite\")} (${commonSql}) SELECT ${commonSql} FROM ${quoteId(from.name, \"sqlite\")}`\n : `-- no common columns to copy from ${from.name}`,\n `DROP TABLE ${quoteId(from.name, \"sqlite\")}`,\n `ALTER TABLE ${quoteId(tmp, \"sqlite\")} RENAME TO ${quoteId(to.name, \"sqlite\")}`,\n \"PRAGMA foreign_keys=on\",\n ];\n}\n\n/** PostgreSQL/MySQL realize a table recreate as per-column ADD/DROP/ALTER. */\nfunction renderTableDiff(from: TableIR, to: TableIR, dialect: Dialect): string[] {\n const stmts: string[] = [];\n for (const [name, col] of Object.entries(to.columns)) {\n if (!(name in from.columns)) {\n stmts.push(\n `ALTER TABLE ${quoteId(to.name, dialect)} ADD COLUMN ${renderColumnDef(col, dialect)}`,\n );\n } else {\n stmts.push(...renderAlterColumn(to.name, col, dialect));\n }\n }\n for (const name of Object.keys(from.columns)) {\n if (!(name in to.columns)) {\n stmts.push(\n `ALTER TABLE ${quoteId(to.name, dialect)} DROP COLUMN ${quoteId(name, dialect)}`,\n );\n }\n }\n return stmts;\n}\n\n/**\n * Render an ALTER COLUMN. SQLite needs table-rebuild (unsupported here); MySQL\n * uses a single `MODIFY COLUMN` (type + NOT NULL + DEFAULT together); PostgreSQL\n * uses separate `ALTER COLUMN ... TYPE / SET|DROP NOT NULL / SET|DROP DEFAULT`.\n */\nfunction renderAlterColumn(table: string, to: ColumnIR, dialect: Dialect): string[] {\n if (dialect === \"sqlite\") {\n throw new Error(\n `alter_column on SQLite needs a table-rebuild (recreate_table); column ${table}.${to.name}`,\n );\n }\n if (dialect === \"mysql\") {\n return [\n `ALTER TABLE ${quoteId(table, dialect)} MODIFY COLUMN ${renderColumnDef(to, dialect)}`,\n ];\n }\n const t = quoteId(table, dialect);\n const c = quoteId(to.name, dialect);\n const stmts = [\n `ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${renderColumnType(to.type, dialect)}`,\n ];\n stmts.push(\n to.notNull\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} SET NOT NULL`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} DROP NOT NULL`,\n );\n stmts.push(\n to.default !== null\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${renderDefault(to.default, dialect)}`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT`,\n );\n return stmts;\n}\n","/**\n * tempest-db-js — Phase 6: the schema differ.\n *\n * Compares two `SchemaIR`s (current vs target) and emits the typed `Operation[]`\n * that turns one into the other. Purely structural — no SQL, no DB.\n */\n\nimport type { ColumnIR, SchemaIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\n/** Stable structural identity of a column, for change detection. */\nfunction columnSignature(col: ColumnIR): string {\n return JSON.stringify({\n type: col.type,\n notNull: col.notNull,\n primaryKey: col.primaryKey,\n default: col.default,\n });\n}\n\n/**\n * Diff `current` → `target`, returning the operations to migrate forward.\n *\n * Order: create new tables, then per-table column adds/alters/drops, then drop\n * removed tables last (so nothing depends on a table being dropped first).\n *\n * @param current The current schema (e.g. from migration replay).\n * @param target The desired schema (e.g. from model reflection).\n * @returns The forward operations.\n */\nexport function diffSchema(current: SchemaIR, target: SchemaIR): Operation[] {\n const ops: Operation[] = [];\n const drops: Operation[] = [];\n\n for (const [name, targetTable] of Object.entries(target.tables)) {\n const currentTable = current.tables[name];\n if (!currentTable) {\n ops.push({ kind: \"create_table\", table: targetTable });\n continue;\n }\n // existing table → diff columns\n for (const [colName, targetCol] of Object.entries(targetTable.columns)) {\n const currentCol = currentTable.columns[colName];\n if (!currentCol) {\n ops.push({ kind: \"add_column\", table: name, column: targetCol });\n } else if (columnSignature(currentCol) !== columnSignature(targetCol)) {\n ops.push({\n kind: \"alter_column\",\n table: name,\n name: colName,\n from: currentCol,\n to: targetCol,\n });\n }\n }\n for (const [colName, currentCol] of Object.entries(currentTable.columns)) {\n if (!targetTable.columns[colName]) {\n ops.push({ kind: \"drop_column\", table: name, column: currentCol });\n }\n }\n }\n\n for (const [name, currentTable] of Object.entries(current.tables)) {\n if (!target.tables[name]) {\n drops.push({ kind: \"drop_table\", table: currentTable });\n }\n }\n\n return [...ops, ...drops];\n}\n","/**\n * tempest-db-js — Phase 6: the revision DAG.\n *\n * Migrations form a directed acyclic graph via `downRevision` (a list of parents,\n * so branches and merges are first-class). This module orders them for applying\n * (topological, deterministic) and finds heads.\n */\n\n/** The minimal graph shape a migration must expose. */\nexport interface RevisionNode {\n readonly revision: string;\n readonly downRevision: readonly string[];\n}\n\n/** Raised when the revision graph contains a cycle. */\nexport class CyclicMigrationGraph extends Error {\n constructor(remaining: readonly string[]) {\n super(`migration graph has a cycle among: ${remaining.join(\", \")}`);\n this.name = \"CyclicMigrationGraph\";\n }\n}\n\n/** Raised when a `downRevision` points at a revision that does not exist. */\nexport class UnknownRevision extends Error {\n constructor(revision: string, parent: string) {\n super(`revision ${revision} references unknown parent ${parent}`);\n this.name = \"UnknownRevision\";\n }\n}\n\n/**\n * Topologically order migrations so every parent precedes its children. Ties are\n * broken by revision id for reproducible builds. Throws on cycles or dangling\n * parents.\n *\n * @param migrations The migrations to order.\n * @returns The migrations in apply order.\n */\nexport function topoOrder<T extends RevisionNode>(migrations: readonly T[]): T[] {\n const byId = new Map<string, T>();\n for (const m of migrations) byId.set(m.revision, m);\n\n const indegree = new Map<string, number>();\n const children = new Map<string, string[]>();\n for (const m of migrations) {\n indegree.set(m.revision, m.downRevision.length);\n for (const parent of m.downRevision) {\n if (!byId.has(parent)) throw new UnknownRevision(m.revision, parent);\n const list = children.get(parent) ?? [];\n list.push(m.revision);\n children.set(parent, list);\n }\n }\n\n // roots: indegree 0, sorted for determinism\n const ready = migrations\n .filter((m) => (indegree.get(m.revision) ?? 0) === 0)\n .map((m) => m.revision)\n .sort();\n\n const ordered: T[] = [];\n while (ready.length > 0) {\n const id = ready.shift() as string;\n ordered.push(byId.get(id) as T);\n const next = (children.get(id) ?? []).sort();\n for (const child of next) {\n const deg = (indegree.get(child) ?? 0) - 1;\n indegree.set(child, deg);\n if (deg === 0) {\n ready.push(child);\n ready.sort();\n }\n }\n }\n\n if (ordered.length !== migrations.length) {\n const remaining = migrations\n .map((m) => m.revision)\n .filter((r) => !ordered.some((o) => o.revision === r));\n throw new CyclicMigrationGraph(remaining);\n }\n return ordered;\n}\n\n/** Revisions that are nobody's parent — the current head(s) of the graph. */\nexport function heads<T extends RevisionNode>(migrations: readonly T[]): string[] {\n const parents = new Set<string>();\n for (const m of migrations) for (const p of m.downRevision) parents.add(p);\n return migrations\n .map((m) => m.revision)\n .filter((r) => !parents.has(r))\n .sort();\n}\n","/**\n * tempest-db-js — feasibility spike for Phase 1.\n *\n * Proves the central design claim: a class-based, SQLAlchemy-style model whose\n * fields are runtime column-builders can drive full static row-type inference in\n * TypeScript, despite TS erasing types at runtime.\n *\n * This is a SPIKE, not the final API. It validates the type machinery only.\n */\n\n/** Phantom marker carrying the static TS type a column maps to. */\ndeclare const TYPE: unique symbol;\n\n/** Column flags that influence the inferred row/insert shape. */\ninterface ColumnFlags {\n readonly primaryKey: boolean;\n readonly notNull: boolean;\n readonly hasDefault: boolean;\n}\n\nconst DEFAULT_FLAGS: ColumnFlags = {\n primaryKey: false,\n notNull: false,\n hasDefault: false,\n};\n\n/**\n * The canonical, dialect-neutral kind of a column type. Mirrors SQLAlchemy's\n * generic types (e.g. `String` → varchar, `Text` → text). Dialect renderers\n * (Phase 4/6) map each kind + meta to concrete SQL per database.\n */\nexport type ColumnTypeKind =\n | \"smallint\"\n | \"integer\"\n | \"bigint\"\n | \"numeric\"\n | \"real\"\n | \"double\"\n | \"varchar\"\n | \"text\"\n | \"char\"\n | \"boolean\"\n | \"date\"\n | \"time\"\n | \"datetime\"\n | \"timestamp\"\n | \"blob\"\n | \"json\"\n | \"uuid\"\n | \"enum\";\n\n/** Parameters that refine a column type and feed the migration IR / DDL. */\nexport interface ColumnTypeMeta {\n /** Max length for `varchar`/`char`. */\n readonly length?: number | undefined;\n /** Total digits for `numeric`. */\n readonly precision?: number | undefined;\n /** Digits after the decimal point for `numeric`. */\n readonly scale?: number | undefined;\n /** `WITH TIME ZONE` for `timestamp`/`time`. */\n readonly withTimezone?: boolean | undefined;\n /** Allowed values for `enum`. */\n readonly values?: readonly string[] | undefined;\n /** Render as `JSONB` (PostgreSQL) instead of `JSON`. */\n readonly jsonb?: boolean | undefined;\n}\n\n/** A structured, dialect-neutral column type descriptor. */\nexport interface ColumnType {\n readonly kind: ColumnTypeKind;\n readonly meta: ColumnTypeMeta;\n}\n\n/**\n * A portable default expression. The token is dialect-neutral; the renderer\n * (Phase 4/6) maps it to the right SQL per database — e.g. `\"now\"` becomes\n * `CURRENT_TIMESTAMP` on SQLite and `now()` on PostgreSQL. Use `{ raw }` as an\n * escape hatch for a verbatim SQL fragment.\n */\nexport type PortableExpression =\n | \"now\"\n | \"current_date\"\n | \"current_time\"\n | \"uuidv4\"\n | { readonly raw: string };\n\n/**\n * A column default. Either a constant literal value or a server-side expression\n * evaluated by the database (mirrors SQLAlchemy's `default` vs `server_default`).\n * Feeds the migration IR (`DefaultIR`).\n */\nexport type DefaultValue =\n | { readonly kind: \"literal\"; readonly value: unknown }\n | { readonly kind: \"expression\"; readonly expression: PortableExpression };\n\n/** Portable server-side default expressions, à la SQLAlchemy's `func`. */\nexport const sql = {\n /** Current timestamp at insert (`CURRENT_TIMESTAMP` / `now()`). */\n now: (): DefaultValue => ({ kind: \"expression\", expression: \"now\" }),\n /** Current date. */\n currentDate: (): DefaultValue => ({ kind: \"expression\", expression: \"current_date\" }),\n /** Current time. */\n currentTime: (): DefaultValue => ({ kind: \"expression\", expression: \"current_time\" }),\n /** A freshly generated UUID v4 (`gen_random_uuid()` / portable fallback). */\n uuidv4: (): DefaultValue => ({ kind: \"expression\", expression: \"uuidv4\" }),\n /** Escape hatch: a verbatim SQL expression rendered as-is. */\n raw: (expression: string): DefaultValue => ({\n kind: \"expression\",\n expression: { raw: expression },\n }),\n} as const;\n\n/** Narrow a `.default()` argument to a `DefaultValue` expression/literal marker. */\nfunction isDefaultValue(value: unknown): value is DefaultValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n ((value as { kind: unknown }).kind === \"literal\" ||\n (value as { kind: unknown }).kind === \"expression\")\n );\n}\n\n/**\n * A typed column builder. Holds runtime metadata (structured `type`, `flags`,\n * `default`, `onUpdate`) and a phantom static type `T` used purely for inference.\n */\nclass Column<T, F extends ColumnFlags = ColumnFlags> {\n /** Phantom: never read at runtime, only inspected by the type system. */\n declare readonly [TYPE]: T;\n\n constructor(\n readonly type: ColumnType,\n readonly flags: F,\n /** The default applied on insert, or `null` for none. */\n readonly defaultValue: DefaultValue | null = null,\n /** The value re-applied on update (e.g. `updated_at`), or `null`. */\n readonly onUpdateValue: DefaultValue | null = null,\n ) {}\n\n primaryKey(): Column<T, F & { primaryKey: true; hasDefault: true }> {\n return new Column(\n this.type,\n { ...this.flags, primaryKey: true, hasDefault: true },\n this.defaultValue,\n this.onUpdateValue,\n );\n }\n\n notNull(): Column<T, F & { notNull: true }> {\n return new Column(\n this.type,\n { ...this.flags, notNull: true },\n this.defaultValue,\n this.onUpdateValue,\n );\n }\n\n /**\n * Set the insert-time default: a constant value of type `T`, or a portable\n * server-side expression from {@link sql} (e.g. `sql.now()`, `sql.uuidv4()`).\n */\n default(value: T | DefaultValue): Column<T, F & { hasDefault: true }> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n return new Column(\n this.type,\n { ...this.flags, hasDefault: true },\n resolved,\n this.onUpdateValue,\n );\n }\n\n /**\n * Re-apply a value whenever the row is updated (e.g. an `updated_at` column\n * with `sql.now()`). Mirrors SQLAlchemy's `onupdate`.\n */\n onUpdate(value: T | DefaultValue): Column<T, F> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n return new Column(this.type, this.flags, this.defaultValue, resolved);\n }\n}\n\n/** Build a `Column` of static type `T` from a kind + optional meta. */\nfunction makeColumn<T>(\n kind: ColumnTypeKind,\n meta: ColumnTypeMeta = {},\n): Column<T, ColumnFlags> {\n return new Column<T, ColumnFlags>({ kind, meta }, DEFAULT_FLAGS);\n}\n\n/**\n * Column factory mirroring SQLAlchemy's typed column constructors. Each entry\n * pairs a distinct SQL type with the TypeScript type it maps to.\n *\n * Notable mappings:\n * - `varchar(n)` (`VARCHAR(n)`) is distinct from `text` (`TEXT`).\n * - `bigInteger` maps to `bigint` (not `number`) to keep 64-bit precision.\n * - `numeric`/`decimal` map to `string` — JavaScript has no exact decimal, and\n * stringifying preserves precision instead of losing it to a float.\n * - `json<T>()` carries the parsed value type; `jsonb` is the PostgreSQL variant.\n * - `enum(...)` infers a string-literal union from its values.\n */\nexport const column = {\n /** `SMALLINT` → `number`. */\n smallInteger: (): Column<number, ColumnFlags> => makeColumn<number>(\"smallint\"),\n /** `INTEGER` → `number`. */\n integer: (): Column<number, ColumnFlags> => makeColumn<number>(\"integer\"),\n /** `BIGINT` → `bigint` (64-bit precision preserved). */\n bigInteger: (): Column<bigint, ColumnFlags> => makeColumn<bigint>(\"bigint\"),\n /** `NUMERIC(precision, scale)` → `string` (exact decimal, no float loss). */\n numeric: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** Alias of {@link column.numeric}. */\n decimal: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** `REAL` → `number`. */\n real: (): Column<number, ColumnFlags> => makeColumn<number>(\"real\"),\n /** `DOUBLE PRECISION` → `number`. */\n double: (): Column<number, ColumnFlags> => makeColumn<number>(\"double\"),\n /** `VARCHAR(length)` → `string`. Distinct from {@link column.text}. */\n varchar: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** Alias of {@link column.varchar} (SQLAlchemy's `String`). */\n string: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** `CHAR(length)` → `string` (fixed-width). */\n char: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"char\", { length }),\n /** `TEXT` → `string` (unbounded). Distinct from {@link column.varchar}. */\n text: (): Column<string, ColumnFlags> => makeColumn<string>(\"text\"),\n /** `BOOLEAN` → `boolean`. */\n boolean: (): Column<boolean, ColumnFlags> => makeColumn<boolean>(\"boolean\"),\n /** `DATE` → `Date`. */\n date: (): Column<Date, ColumnFlags> => makeColumn<Date>(\"date\"),\n /** `TIME` → `string`. Pass `{ timezone: true }` for `WITH TIME ZONE`. */\n time: (options?: { timezone?: boolean }): Column<string, ColumnFlags> =>\n makeColumn<string>(\"time\", { withTimezone: options?.timezone }),\n /**\n * `DATETIME`/`TIMESTAMP` → `Date` (SQLAlchemy's generic `DateTime`). Pass\n * `{ timezone: true }` for `WITH TIME ZONE`. Pair with `.default(sql.now())`\n * and `.onUpdate(sql.now())` for managed `created_at`/`updated_at` columns.\n */\n datetime: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"datetime\", { withTimezone: options?.timezone }),\n /** `TIMESTAMP` → `Date` (SQL-specific). Pass `{ timezone: true }`. */\n timestamp: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"timestamp\", { withTimezone: options?.timezone }),\n /** `BLOB`/`BYTEA` → `Uint8Array`. */\n blob: (): Column<Uint8Array, ColumnFlags> => makeColumn<Uint8Array>(\"blob\"),\n /** `JSON` → the given parsed value type `T` (defaults to `unknown`). */\n json: <T = unknown>(): Column<T, ColumnFlags> => makeColumn<T>(\"json\"),\n /** `JSONB` (PostgreSQL) → the given parsed value type `T`. */\n jsonb: <T = unknown>(): Column<T, ColumnFlags> =>\n makeColumn<T>(\"json\", { jsonb: true }),\n /** `UUID` → `string`. */\n uuid: (): Column<string, ColumnFlags> => makeColumn<string>(\"uuid\"),\n /** `ENUM(...values)` → a string-literal union of the given values. */\n enum: <const E extends string>(...values: E[]): Column<E, ColumnFlags> =>\n makeColumn<E>(\"enum\", { values }),\n} as const;\n\n/** Base class every model extends, SQLAlchemy-declarative style. */\n// biome-ignore lint/complexity/noStaticOnlyClass: declarative base users subclass; column fields live on instances.\nexport abstract class Model {\n static tablename: string;\n}\n\n/** Memoized column maps, keyed by model class (identity is stable per class). */\nconst columnsCache = new WeakMap<ModelClass, Record<string, Column<unknown>>>();\n\n/**\n * Reflect a model class into its column map at runtime, keyed by column name.\n *\n * Instantiates the class once and collects every field that is a `Column`. Used\n * by the serialization layer and (Phase 6) the migration schema reflector.\n *\n * The result is **memoized per class** — a model's columns never change at\n * runtime, and this is called once per row on hot read paths (coercion, joins),\n * so re-instantiating the class every time would dominate large result sets.\n *\n * @param model The model class (subclass of `Model`).\n * @returns A record of column name → `Column` instance (do not mutate).\n */\nexport function columnsOf(model: ModelClass): Record<string, Column<unknown>> {\n const cached = columnsCache.get(model);\n if (cached) return cached;\n const instance = new (model as new () => Model)();\n const out: Record<string, Column<unknown>> = {};\n for (const [key, value] of Object.entries(instance)) {\n if (value instanceof Column) {\n out[key] = value as Column<unknown>;\n }\n }\n columnsCache.set(model, out);\n return out;\n}\n\n/** Pull the static type out of a Column. */\ntype ColType<C> = C extends Column<infer T, infer _F> ? T : never;\n\n/** Keys of the model instance whose values are Columns. */\ntype ColumnKeys<M> = {\n [K in keyof M]: M[K] extends Column<unknown, ColumnFlags> ? K : never;\n}[keyof M];\n\n/** Constructor type for a Model subclass. */\ntype ModelClass = (new () => Model) & { tablename: string };\n\n/** Flatten an intersection into a single object literal for clean inference. */\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The nullability-aware value a column contributes to a row. */\ntype ColValue<Col> = Col extends Column<infer T, infer F>\n ? F extends { notNull: true } | { primaryKey: true }\n ? T\n : T | null\n : never;\n\n/** True when a column has a default (or is a PK) — i.e. optional on insert. */\ntype HasDefault<Col> = Col extends Column<unknown, infer F>\n ? F extends { hasDefault: true }\n ? true\n : false\n : false;\n\n/** Keys of the model whose columns are optional on insert. */\ntype OptionalInsertKeys<I> = {\n [K in ColumnKeys<I>]: HasDefault<I[K]> extends true ? K : never;\n}[ColumnKeys<I>];\n\n/**\n * Infer the SELECT row shape from a model class: every column field becomes its\n * mapped static type. Columns marked notNull/primaryKey are non-nullable; others\n * are `T | null` (SQL semantics — an unconstrained column can be NULL).\n */\nexport type InferModel<C extends ModelClass> = {\n [K in ColumnKeys<InstanceType<C>>]: ColValue<InstanceType<C>[K]>;\n};\n\n/**\n * Infer the INSERT shape: columns with a default (or PK) are optional; the rest\n * are required. Nullability is preserved on both sides.\n */\nexport type InferInsert<C extends ModelClass> = Simplify<\n {\n [K in OptionalInsertKeys<InstanceType<C>>]?: ColValue<InstanceType<C>[K]>;\n } & {\n [K in Exclude<\n ColumnKeys<InstanceType<C>>,\n OptionalInsertKeys<InstanceType<C>>\n >]: ColValue<InstanceType<C>[K]>;\n }\n>;\n\nexport { Column, type ColType, type ColumnFlags, type ModelClass };\n\nexport {\n and,\n type CondNode,\n type Condition,\n isCondition,\n not,\n or,\n toCondNode,\n type WhereArg,\n} from \"./conditions.js\";\n\nexport {\n Agg,\n type AggregateTerm,\n avg,\n count,\n max,\n min,\n type Operator,\n type OperatorsFor,\n OPERATORS,\n type OrderTerm,\n type SelectNode,\n SelectBuilder,\n select,\n type SortDirection,\n sum,\n type WhereInput,\n} from \"./query.js\";\n\nexport {\n DeleteBuilder,\n type DeleteNode,\n del,\n InsertBuilder,\n type InsertNode,\n insert,\n type OnConflict,\n type Returning,\n UpdateBuilder,\n type UpdateNode,\n update,\n} from \"./mutations.js\";\n\nexport {\n type Dialect,\n detectDialect,\n InvalidDatabaseUrl,\n type ParsedDatabaseUrl,\n parseDatabaseUrl,\n} from \"./url.js\";\n\nexport {\n fromDict,\n parse,\n stringify,\n toDict,\n toJSON,\n ValidationError,\n} from \"./serialize.js\";\n\nexport {\n BaseDialect,\n type CompiledQuery,\n getDialect,\n MysqlDialect,\n PostgresDialect,\n type QueryNode,\n SqliteDialect,\n} from \"./dialect.js\";\n\nexport {\n type ColRef,\n join,\n JoinBuilder,\n type JoinClause,\n type JoinNode,\n type JoinOn,\n type JoinSelection,\n type JoinWhereInput,\n type Sources,\n} from \"./join.js\";\n\nexport {\n BaseRepository,\n type PaginationFilter,\n type PaginationResult,\n RecordNotFound,\n} from \"./repository.js\";\n\nexport {\n ActiveRecord,\n type ActiveRecordManager,\n activeRecord,\n} from \"./active-record.js\";\n\nexport {\n type BelongsTo,\n belongsTo,\n type HasMany,\n hasMany,\n loadRelations,\n type Relation,\n type RelationValue,\n type WithRelations,\n} from \"./relations.js\";\n\nexport {\n AsyncEngine,\n AsyncResult,\n AsyncSession,\n type AsyncDriver,\n createEngine,\n createSyncEngine,\n type DriverResult,\n type EngineOptions,\n type Executable,\n NoResultError,\n NodeSqliteDriver,\n type PoolOptions,\n QueryExecutionError,\n type QueryLogger,\n type ReservedAsyncDriver,\n type RowOf,\n type SyncDriver,\n SyncEngine,\n SyncResult,\n SyncSession,\n} from \"./engine.js\";\n","/**\n * tempest-db-js — Phase 6: the Schema IR (intermediate representation).\n *\n * A canonical, dialect-neutral description of a database schema. Every source of\n * truth — model reflection (here), migration replay, or DB introspection —\n * produces the SAME `SchemaIR`, so the differ compares like with like and SQL is\n * only ever emitted at the dialect edge (the anti-\"SQL-stitching\" core).\n */\n\nimport {\n type ColumnType,\n type DefaultValue,\n type ModelClass,\n columnsOf,\n} from \"../index.js\";\n\n/** A column's default in the IR. */\nexport type DefaultIR = DefaultValue | null;\n\n/** One column. */\nexport interface ColumnIR {\n readonly name: string;\n readonly type: ColumnType;\n readonly notNull: boolean;\n readonly primaryKey: boolean;\n readonly default: DefaultIR;\n}\n\n/** One table. */\nexport interface TableIR {\n readonly name: string;\n readonly columns: Record<string, ColumnIR>;\n /** Primary-key column names (composite = more than one). */\n readonly primaryKey: readonly string[];\n}\n\n/** A whole schema, keyed by table name. */\nexport interface SchemaIR {\n readonly tables: Record<string, TableIR>;\n}\n\n/** Reflect one model class into a `TableIR`. */\nexport function reflectTable(model: ModelClass): TableIR {\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const [name, col] of Object.entries(columnsOf(model))) {\n const isPk = col.flags.primaryKey;\n columns[name] = {\n name,\n type: col.type,\n notNull: col.flags.notNull || isPk,\n primaryKey: isPk,\n default: col.defaultValue,\n };\n if (isPk) primaryKey.push(name);\n }\n return { name: model.tablename, columns, primaryKey };\n}\n\n/**\n * Reflect a set of model classes into a `SchemaIR`. This is the **target** state\n * the differ compares the current (replayed) schema against.\n *\n * @param models The model classes that make up the schema.\n * @returns The reflected schema IR.\n */\nexport function reflectSchema(models: readonly ModelClass[]): SchemaIR {\n const tables: Record<string, TableIR> = {};\n for (const model of models) {\n const table = reflectTable(model);\n tables[table.name] = table;\n }\n return { tables };\n}\n\n/** An empty schema (the baseline before any migration). */\nexport function emptySchema(): SchemaIR {\n return { tables: {} };\n}\n","/**\n * tempest-db-js — Phase 6d: SQLite introspection + drift detection.\n *\n * Reads the live schema from a SQLite database (via `PRAGMA table_info`) into a\n * `SchemaIR`, and compares it against the models to detect **drift** — the DB\n * diverging from what the migrations/models say it should be. Comparison is done\n * at SQLite's storage-affinity level, so coarse SQLite typing (every string is\n * `TEXT`) does not produce false positives.\n */\n\nimport type { AsyncDriver, SyncDriver } from \"../engine.js\";\nimport type { ColumnType } from \"../index.js\";\nimport type { ModelClass } from \"../index.js\";\nimport { renderColumnType } from \"./ddl.js\";\nimport { type ColumnIR, type SchemaIR, type TableIR, reflectSchema } from \"./ir.js\";\n\n/** SQLite's five storage classes / affinities. */\nexport type SqliteAffinity = \"INTEGER\" | \"TEXT\" | \"REAL\" | \"BLOB\" | \"NUMERIC\";\n\n/** Apply SQLite's affinity rules to a declared type string. */\nexport function sqliteAffinity(declared: string): SqliteAffinity {\n const t = declared.toUpperCase();\n if (t.includes(\"INT\")) return \"INTEGER\";\n if (t.includes(\"CHAR\") || t.includes(\"CLOB\") || t.includes(\"TEXT\")) return \"TEXT\";\n if (t.includes(\"BLOB\") || t === \"\") return \"BLOB\";\n if (t.includes(\"REAL\") || t.includes(\"FLOA\") || t.includes(\"DOUB\")) return \"REAL\";\n return \"NUMERIC\";\n}\n\n/** Map a SQLite affinity back to the closest IR column kind. */\nfunction affinityToKind(affinity: SqliteAffinity): ColumnType[\"kind\"] {\n switch (affinity) {\n case \"INTEGER\":\n return \"integer\";\n case \"REAL\":\n return \"real\";\n case \"BLOB\":\n return \"blob\";\n case \"NUMERIC\":\n return \"numeric\";\n default:\n return \"text\";\n }\n}\n\ninterface PragmaColumn {\n name: string;\n type: string;\n notnull: number;\n pk: number;\n}\n\n/**\n * Read the current SQLite schema into a `SchemaIR`. Lossy by nature (SQLite\n * collapses types into affinities), so types come back as the affinity's kind.\n *\n * @param driver A sync SQLite driver.\n * @returns The introspected schema.\n */\nexport function introspectSqlite(driver: SyncDriver): SchemaIR {\n const tablesRows = driver.execute(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'tempest_db_js_migrations'\",\n [],\n ).rows;\n\n const tables: Record<string, TableIR> = {};\n for (const row of tablesRows) {\n const tableName = String(row.name);\n const info = driver.execute(`PRAGMA table_info(${JSON.stringify(tableName)})`, [])\n .rows as unknown as PragmaColumn[];\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const col of info) {\n const isPk = Number(col.pk) > 0;\n const affinity = sqliteAffinity(col.type);\n columns[col.name] = {\n name: col.name,\n type: { kind: affinityToKind(affinity), meta: {} },\n notNull: Number(col.notnull) === 1 || isPk,\n primaryKey: isPk,\n default: null,\n };\n if (isPk) primaryKey.push(col.name);\n }\n tables[tableName] = { name: tableName, columns, primaryKey };\n }\n return { tables };\n}\n\n/**\n * Compare the live SQLite schema against the models and report drift. Comparison\n * is at the affinity level (so `varchar` vs `TEXT` is not flagged), plus\n * nullability, primary-key, and presence of tables/columns.\n *\n * @param driver A sync SQLite driver.\n * @param models The model classes that define the intended schema.\n * @returns A list of human-readable drift messages — empty means no drift.\n */\nexport function checkDrift(driver: SyncDriver, models: readonly ModelClass[]): string[] {\n const actual = introspectSqlite(driver);\n const expected = reflectSchema(models);\n const issues: string[] = [];\n\n for (const [tableName, expectedTable] of Object.entries(expected.tables)) {\n const actualTable = actual.tables[tableName];\n if (!actualTable) {\n issues.push(`table \"${tableName}\" is missing from the database`);\n continue;\n }\n for (const [colName, expectedCol] of Object.entries(expectedTable.columns)) {\n const actualCol = actualTable.columns[colName];\n if (!actualCol) {\n issues.push(`column \"${tableName}.${colName}\" is missing from the database`);\n continue;\n }\n const expAff = sqliteAffinity(renderColumnType(expectedCol.type, \"sqlite\"));\n const actAff = sqliteAffinity(renderColumnType(actualCol.type, \"sqlite\"));\n if (expAff !== actAff) {\n issues.push(\n `column \"${tableName}.${colName}\" affinity differs: model ${expAff}, db ${actAff}`,\n );\n }\n if (expectedCol.notNull !== actualCol.notNull) {\n issues.push(`column \"${tableName}.${colName}\" nullability differs`);\n }\n if (expectedCol.primaryKey !== actualCol.primaryKey) {\n issues.push(`column \"${tableName}.${colName}\" primary-key flag differs`);\n }\n }\n for (const colName of Object.keys(actualTable.columns)) {\n if (!expectedTable.columns[colName]) {\n issues.push(\n `column \"${tableName}.${colName}\" exists in the database but not in the model`,\n );\n }\n }\n }\n\n for (const tableName of Object.keys(actual.tables)) {\n if (!expected.tables[tableName]) {\n issues.push(`table \"${tableName}\" exists in the database but not in the models`);\n }\n }\n\n return issues;\n}\n\n/** Map a PostgreSQL `information_schema` type name to the closest IR kind. */\nfunction pgTypeToKind(dataType: string, udtName: string): ColumnType[\"kind\"] {\n const t = dataType.toLowerCase();\n if (t === \"user-defined\") return \"enum\"; // a named enum type\n if (t === \"smallint\") return \"smallint\";\n if (t === \"integer\") return \"integer\";\n if (t === \"bigint\") return \"bigint\";\n if (t === \"numeric\") return \"numeric\";\n if (t === \"real\") return \"real\";\n if (t === \"double precision\") return \"double\";\n if (t === \"character varying\") return \"varchar\";\n if (t === \"character\") return \"char\";\n if (t === \"text\") return \"text\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"date\") return \"date\";\n if (t.startsWith(\"time\")) return t.startsWith(\"timestamp\") ? \"timestamp\" : \"time\";\n if (t === \"bytea\") return \"blob\";\n if (t === \"json\") return \"json\";\n if (t === \"jsonb\") return \"json\";\n if (t === \"uuid\") return \"uuid\";\n return udtName === \"jsonb\" ? \"json\" : \"text\";\n}\n\n/**\n * Read the current PostgreSQL schema into a `SchemaIR` from `information_schema`.\n *\n * Not exercised by the in-repo test suite (no PostgreSQL in CI); mirrors\n * {@link introspectSqlite} for the async driver.\n *\n * @param driver An async PostgreSQL driver.\n * @returns The introspected schema.\n */\nexport async function introspectPostgres(driver: AsyncDriver): Promise<SchemaIR> {\n const tablesResult = await driver.execute(\n \"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name != 'tempest_db_js_migrations'\",\n [],\n );\n const tables: Record<string, TableIR> = {};\n for (const row of tablesResult.rows) {\n const tableName = String(row.table_name);\n const colsResult = await driver.execute(\n \"SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_name = $1\",\n [tableName],\n );\n const pkResult = await driver.execute(\n `SELECT a.attname AS name FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)\n WHERE i.indrelid = $1::regclass AND i.indisprimary`,\n [tableName],\n );\n const pkSet = new Set(pkResult.rows.map((r) => String(r.name)));\n const columns: Record<string, ColumnIR> = {};\n const primaryKey: string[] = [];\n for (const col of colsResult.rows) {\n const name = String(col.column_name);\n const isPk = pkSet.has(name);\n columns[name] = {\n name,\n type: {\n kind: pgTypeToKind(String(col.data_type), String(col.udt_name)),\n meta: {},\n },\n notNull: col.is_nullable === \"NO\" || isPk,\n primaryKey: isPk,\n default: null,\n };\n if (isPk) primaryKey.push(name);\n }\n tables[tableName] = { name: tableName, columns, primaryKey };\n }\n return { tables };\n}\n\n/**\n * Drift check for PostgreSQL: compares the live schema (introspected) against the\n * models by column kind, nullability, primary-key, and presence. Structural —\n * not exercised in CI (no PostgreSQL).\n *\n * @param driver An async PostgreSQL driver.\n * @param models The model classes that define the intended schema.\n * @returns A list of drift messages — empty means no drift.\n */\nexport async function checkDriftPostgres(\n driver: AsyncDriver,\n models: readonly ModelClass[],\n): Promise<string[]> {\n const actual = await introspectPostgres(driver);\n const expected = reflectSchema(models);\n const issues: string[] = [];\n for (const [tableName, expectedTable] of Object.entries(expected.tables)) {\n const actualTable = actual.tables[tableName];\n if (!actualTable) {\n issues.push(`table \"${tableName}\" is missing from the database`);\n continue;\n }\n for (const [colName, expectedCol] of Object.entries(expectedTable.columns)) {\n const actualCol = actualTable.columns[colName];\n if (!actualCol) {\n issues.push(`column \"${tableName}.${colName}\" is missing from the database`);\n continue;\n }\n if (expectedCol.type.kind !== actualCol.type.kind) {\n issues.push(\n `column \"${tableName}.${colName}\" type differs: model ${expectedCol.type.kind}, db ${actualCol.type.kind}`,\n );\n }\n if (expectedCol.notNull !== actualCol.notNull) {\n issues.push(`column \"${tableName}.${colName}\" nullability differs`);\n }\n }\n for (const colName of Object.keys(actualTable.columns)) {\n if (!expectedTable.columns[colName]) {\n issues.push(\n `column \"${tableName}.${colName}\" exists in the database but not in the model`,\n );\n }\n }\n }\n for (const tableName of Object.keys(actual.tables)) {\n if (!expected.tables[tableName]) {\n issues.push(`table \"${tableName}\" exists in the database but not in the models`);\n }\n }\n return issues;\n}\n","/**\n * tempest-db-js — Phase 6: rename detection.\n *\n * The differ ({@link diffSchema}) is deliberately conservative: a renamed column\n * looks like a drop + add, and a renamed table like a drop + create. That is the\n * *safe* default (never guesses), but it loses data. This module turns those\n * add/drop pairs into rename *candidates* the CLI can confirm — interactively at\n * a TTY, or explicitly via flags — and folds confirmed ones back into a single\n * `rename_table` / `rename_column` operation.\n *\n * Everything here is pure and structural (no SQL, no DB, no I/O), so the\n * detection and folding are fully testable; the actual prompting lives in the\n * `tempest-db` bin.\n */\n\nimport type { ColumnIR } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\n\n/** A possible rename the differ emitted as a drop + add/create pair. */\nexport type RenameCandidate =\n | { readonly kind: \"table\"; readonly from: string; readonly to: string }\n | {\n readonly kind: \"column\";\n readonly table: string;\n readonly from: string;\n readonly to: string;\n };\n\n/** Structural identity of a column, ignoring its name. */\nfunction columnShape(col: ColumnIR): string {\n return JSON.stringify({\n type: col.type,\n notNull: col.notNull,\n primaryKey: col.primaryKey,\n default: col.default,\n });\n}\n\n/** Structural identity of a table's columns, ignoring the table name. */\nfunction tableShape(columns: Readonly<Record<string, ColumnIR>>): string {\n return Object.entries(columns)\n .map(([name, col]) => `${name}:${columnShape(col)}`)\n .sort()\n .join(\"|\");\n}\n\n/**\n * Detect rename candidates in a forward operation list.\n *\n * A table rename is a `create_table` + `drop_table` whose column shapes match\n * exactly. A column rename is an `add_column` + `drop_column` on the same table\n * whose column shapes match exactly. Only unambiguous 1:1 shape matches are\n * reported — if two dropped columns share a shape, neither is offered (the\n * mapping would be a guess).\n *\n * @param ops The forward operations from {@link diffSchema}.\n * @returns The rename candidates found (never mutates `ops`).\n */\nexport function detectRenames(ops: readonly Operation[]): RenameCandidate[] {\n const candidates: RenameCandidate[] = [];\n\n // --- table renames ---\n const creates = ops.filter((o) => o.kind === \"create_table\");\n const tableDrops = ops.filter((o) => o.kind === \"drop_table\");\n const takenCreate = new Set<string>();\n const takenDrop = new Set<string>();\n for (const create of creates) {\n const createShape = tableShape(create.table.columns);\n const matches = tableDrops.filter(\n (d) => !takenDrop.has(d.table.name) && tableShape(d.table.columns) === createShape,\n );\n // Only a unique match is a safe rename; ambiguity → leave as drop + create.\n const uniqueCreate =\n creates.filter(\n (c) =>\n !takenCreate.has(c.table.name) && tableShape(c.table.columns) === createShape,\n ).length === 1;\n if (matches.length === 1 && uniqueCreate) {\n const drop = matches[0] as Extract<Operation, { kind: \"drop_table\" }>;\n if (drop.table.name !== create.table.name) {\n candidates.push({ kind: \"table\", from: drop.table.name, to: create.table.name });\n takenCreate.add(create.table.name);\n takenDrop.add(drop.table.name);\n }\n }\n }\n\n // --- column renames (per table) ---\n const adds = ops.filter((o) => o.kind === \"add_column\");\n const colDrops = ops.filter((o) => o.kind === \"drop_column\");\n const tables = new Set([...adds.map((o) => o.table), ...colDrops.map((o) => o.table)]);\n for (const table of tables) {\n const tableAdds = adds.filter((o) => o.table === table);\n const tableColDrops = colDrops.filter((o) => o.table === table);\n const takenAdd = new Set<string>();\n const takenColDrop = new Set<string>();\n for (const add of tableAdds) {\n const shape = columnShape(add.column);\n const dropMatches = tableColDrops.filter(\n (d) => !takenColDrop.has(d.column.name) && columnShape(d.column) === shape,\n );\n const addMatches = tableAdds.filter(\n (a) => !takenAdd.has(a.column.name) && columnShape(a.column) === shape,\n );\n if (dropMatches.length === 1 && addMatches.length === 1) {\n const drop = dropMatches[0] as Extract<Operation, { kind: \"drop_column\" }>;\n candidates.push({\n kind: \"column\",\n table,\n from: drop.column.name,\n to: add.column.name,\n });\n takenAdd.add(add.column.name);\n takenColDrop.add(drop.column.name);\n }\n }\n }\n\n return candidates;\n}\n\n/** Match a table-rename candidate against an op pair. */\nfunction isTableRename(\n op: Operation,\n r: Extract<RenameCandidate, { kind: \"table\" }>,\n): boolean {\n return (\n (op.kind === \"create_table\" && op.table.name === r.to) ||\n (op.kind === \"drop_table\" && op.table.name === r.from)\n );\n}\n\n/** Match a column-rename candidate against an op pair. */\nfunction isColumnRename(\n op: Operation,\n r: Extract<RenameCandidate, { kind: \"column\" }>,\n): boolean {\n return (\n (op.kind === \"add_column\" && op.table === r.table && op.column.name === r.to) ||\n (op.kind === \"drop_column\" && op.table === r.table && op.column.name === r.from)\n );\n}\n\n/**\n * Fold confirmed renames into an operation list: each confirmed candidate's\n * drop + add/create pair is removed and replaced by a single rename operation,\n * inserted at the position of the first op it replaces (preserving order).\n *\n * @param ops The forward operations from {@link diffSchema}.\n * @param confirmed The rename candidates the user accepted.\n * @returns A new operation list with renames applied.\n */\nexport function applyRenames(\n ops: readonly Operation[],\n confirmed: readonly RenameCandidate[],\n): Operation[] {\n const out: Operation[] = [];\n const emitted = new Set<RenameCandidate>();\n\n for (const op of ops) {\n const match = confirmed.find((r) =>\n r.kind === \"table\" ? isTableRename(op, r) : isColumnRename(op, r),\n );\n if (!match) {\n out.push(op);\n continue;\n }\n // Emit the rename once (at the first op of the pair); skip both members.\n if (!emitted.has(match)) {\n emitted.add(match);\n out.push(\n match.kind === \"table\"\n ? { kind: \"rename_table\", from: match.from, to: match.to }\n : { kind: \"rename_column\", table: match.table, from: match.from, to: match.to },\n );\n }\n }\n return out;\n}\n","/**\n * tempest-db-js — Phase 6: the migration runner.\n *\n * The `Op` facade records operations; the `MigrationRunner` renders them to SQL\n * (per dialect) and runs them through a sync driver, tracking applied revisions\n * in a `tempest_db_js_migrations` table. Upgrades/downgrades respect the revision DAG.\n *\n * SQLite execution is real (via `node:sqlite`); the same code path serves any\n * sync driver.\n */\n\nimport type { AsyncDriver, SyncDriver } from \"../engine.js\";\nimport type { Dialect } from \"../url.js\";\nimport { renderOperation } from \"./ddl.js\";\nimport { topoOrder } from \"./graph.js\";\nimport type { ColumnIR, TableIR } from \"./ir.js\";\nimport { type Operation, invertAll } from \"./operations.js\";\n\n/**\n * The facade injected into `up()`/`down()`. Each method records an operation;\n * the runner renders and executes them after the function returns.\n */\nexport class Op {\n readonly operations: Operation[] = [];\n\n /** Record a raw operation (used by autogenerated migrations). */\n run(operation: Operation): void {\n this.operations.push(operation);\n }\n\n createTable(table: TableIR): void {\n this.run({ kind: \"create_table\", table });\n }\n dropTable(table: TableIR): void {\n this.run({ kind: \"drop_table\", table });\n }\n renameTable(from: string, to: string): void {\n this.run({ kind: \"rename_table\", from, to });\n }\n addColumn(table: string, column: ColumnIR): void {\n this.run({ kind: \"add_column\", table, column });\n }\n dropColumn(table: string, column: ColumnIR): void {\n this.run({ kind: \"drop_column\", table, column });\n }\n alterColumn(table: string, name: string, from: ColumnIR, to: ColumnIR): void {\n this.run({ kind: \"alter_column\", table, name, from, to });\n }\n renameColumn(table: string, from: string, to: string): void {\n this.run({ kind: \"rename_column\", table, from, to });\n }\n /** Rebuild a table (SQLite batch-mode / PostgreSQL per-column alters). */\n recreateTable(from: TableIR, to: TableIR): void {\n this.run({ kind: \"recreate_table\", from, to });\n }\n /** Raw SQL escape hatch (e.g. a data migration). `down` may be `null`. */\n execute(up: string, down: string | null = null): void {\n this.run({ kind: \"execute\", up, down });\n }\n}\n\n/** A migration file's shape. */\nexport interface Migration {\n readonly revision: string;\n readonly downRevision: readonly string[];\n readonly label?: string;\n up(op: Op): void;\n down(op: Op): void;\n}\n\nconst VERSION_TABLE = \"tempest_db_js_migrations\";\n\n/** Runs migrations against a sync driver, tracking applied revisions. */\nexport class MigrationRunner {\n constructor(\n private readonly driver: SyncDriver,\n private readonly dialect: Dialect,\n ) {}\n\n /** Create the version-tracking table if it does not exist. */\n ensureVersionTable(): void {\n this.driver.execute(\n `CREATE TABLE IF NOT EXISTS \"${VERSION_TABLE}\" (revision TEXT PRIMARY KEY, applied_at TEXT NOT NULL, down_revision TEXT NOT NULL)`,\n [],\n );\n }\n\n /** The set of applied revision ids. */\n applied(): Set<string> {\n this.ensureVersionTable();\n const { rows } = this.driver.execute(`SELECT revision FROM \"${VERSION_TABLE}\"`, []);\n return new Set(rows.map((r) => String(r.revision)));\n }\n\n private runOps(ops: readonly Operation[]): void {\n for (const op of ops) {\n for (const stmt of renderOperation(op, this.dialect)) {\n const trimmed = stmt.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"--\")) continue;\n this.driver.execute(stmt, []);\n }\n }\n }\n\n private record(migration: Migration, appliedAt: string): void {\n this.driver.execute(\n `INSERT INTO \"${VERSION_TABLE}\" (revision, applied_at, down_revision) VALUES (?, ?, ?)`,\n [migration.revision, appliedAt, migration.downRevision.join(\",\")],\n );\n }\n\n private forget(revision: string): void {\n this.driver.execute(`DELETE FROM \"${VERSION_TABLE}\" WHERE revision = ?`, [revision]);\n }\n\n /**\n * Apply all pending migrations up to the head(s), in DAG order.\n *\n * @param migrations All known migrations.\n * @param appliedAt Timestamp string to stamp (pass one in — the runtime has no\n * wall clock of its own here).\n * @returns The revision ids that were applied this run.\n */\n upgrade(migrations: readonly Migration[], appliedAt: string): string[] {\n const done = this.applied();\n const ordered = topoOrder(migrations);\n const ran: string[] = [];\n for (const migration of ordered) {\n if (done.has(migration.revision)) continue;\n const op = new Op();\n migration.up(op);\n this.runOps(op.operations);\n this.record(migration, appliedAt);\n ran.push(migration.revision);\n }\n return ran;\n }\n\n /**\n * Revert the last `steps` applied migrations (default 1), newest first.\n *\n * @param migrations All known migrations.\n * @param steps How many applied revisions to roll back.\n * @returns The revision ids that were reverted.\n */\n downgrade(migrations: readonly Migration[], steps = 1): string[] {\n const done = this.applied();\n const ordered = topoOrder(migrations).filter((m) => done.has(m.revision));\n const toRevert = ordered.slice(-steps).reverse();\n const reverted: string[] = [];\n for (const migration of toRevert) {\n const op = new Op();\n // Prefer the migration's own down(); fall back to inverting up().\n if (migration.down.length >= 0) {\n try {\n migration.down(op);\n } catch {\n op.operations.length = 0;\n }\n }\n if (op.operations.length === 0) {\n const upOp = new Op();\n migration.up(upOp);\n op.operations.push(...invertAll(upOp.operations));\n }\n this.runOps(op.operations);\n this.forget(migration.revision);\n reverted.push(migration.revision);\n }\n return reverted;\n }\n}\n\n// ---------------------------------------------------------------------------\n// async runner (PostgreSQL / any async driver)\n// ---------------------------------------------------------------------------\n\n/** Quote an identifier for the dialect (backticks on MySQL, double-quotes else). */\nfunction quoteIdent(name: string, dialect: Dialect): string {\n return dialect === \"mysql\"\n ? `\\`${name.replace(/`/g, \"``\")}\\``\n : `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** The n-th (1-based) placeholder for the dialect (`$n` on PostgreSQL, `?` else). */\nfunction placeholder(index: number, dialect: Dialect): string {\n return dialect === \"postgresql\" ? `$${index}` : \"?\";\n}\n\n/**\n * Runs migrations against an **async** driver (PostgreSQL, or any async driver),\n * tracking applied revisions. Mirrors {@link MigrationRunner} but every statement\n * is awaited, and identifier quoting + placeholder style follow the dialect —\n * so the version table and its bookkeeping are portable across SQLite/PG/MySQL.\n */\nexport class AsyncMigrationRunner {\n private readonly vt: string;\n\n constructor(\n private readonly driver: AsyncDriver,\n private readonly dialect: Dialect,\n ) {\n this.vt = quoteIdent(VERSION_TABLE, dialect);\n }\n\n /** Create the version-tracking table if it does not exist. */\n async ensureVersionTable(): Promise<void> {\n await this.driver.execute(\n `CREATE TABLE IF NOT EXISTS ${this.vt} (revision ${this.textType()} PRIMARY KEY, applied_at ${this.textType()} NOT NULL, down_revision ${this.textType()} NOT NULL)`,\n [],\n );\n }\n\n /** A portable \"text\" column type for the version table. */\n private textType(): string {\n // MySQL cannot index an unbounded TEXT primary key; use VARCHAR there.\n return this.dialect === \"mysql\" ? \"VARCHAR(255)\" : \"TEXT\";\n }\n\n /** The set of applied revision ids. */\n async applied(): Promise<Set<string>> {\n await this.ensureVersionTable();\n const { rows } = await this.driver.execute(`SELECT revision FROM ${this.vt}`, []);\n return new Set(rows.map((r) => String(r.revision)));\n }\n\n private async runOps(ops: readonly Operation[]): Promise<void> {\n for (const op of ops) {\n for (const stmt of renderOperation(op, this.dialect)) {\n const trimmed = stmt.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"--\")) continue;\n await this.driver.execute(stmt, []);\n }\n }\n }\n\n private async record(migration: Migration, appliedAt: string): Promise<void> {\n const p = (i: number) => placeholder(i, this.dialect);\n await this.driver.execute(\n `INSERT INTO ${this.vt} (revision, applied_at, down_revision) VALUES (${p(1)}, ${p(2)}, ${p(3)})`,\n [migration.revision, appliedAt, migration.downRevision.join(\",\")],\n );\n }\n\n private async forget(revision: string): Promise<void> {\n await this.driver.execute(\n `DELETE FROM ${this.vt} WHERE revision = ${placeholder(1, this.dialect)}`,\n [revision],\n );\n }\n\n /**\n * Apply all pending migrations up to the head(s), in DAG order.\n *\n * @param migrations All known migrations.\n * @param appliedAt Timestamp string to stamp on each applied revision.\n * @returns The revision ids that were applied this run.\n */\n async upgrade(migrations: readonly Migration[], appliedAt: string): Promise<string[]> {\n const done = await this.applied();\n const ordered = topoOrder(migrations);\n const ran: string[] = [];\n for (const migration of ordered) {\n if (done.has(migration.revision)) continue;\n const op = new Op();\n migration.up(op);\n await this.runOps(op.operations);\n await this.record(migration, appliedAt);\n ran.push(migration.revision);\n }\n return ran;\n }\n\n /**\n * Revert the last `steps` applied migrations (default 1), newest first.\n *\n * @param migrations All known migrations.\n * @param steps How many applied revisions to roll back.\n * @returns The revision ids that were reverted.\n */\n async downgrade(migrations: readonly Migration[], steps = 1): Promise<string[]> {\n const done = await this.applied();\n const ordered = topoOrder(migrations).filter((m) => done.has(m.revision));\n const toRevert = ordered.slice(-steps).reverse();\n const reverted: string[] = [];\n for (const migration of toRevert) {\n const op = new Op();\n try {\n migration.down(op);\n } catch {\n op.operations.length = 0;\n }\n if (op.operations.length === 0) {\n const upOp = new Op();\n migration.up(upOp);\n op.operations.push(...invertAll(upOp.operations));\n }\n await this.runOps(op.operations);\n await this.forget(migration.revision);\n reverted.push(migration.revision);\n }\n return reverted;\n }\n}\n","/**\n * tempest-db-js — Phase 6: migration replay → virtual schema IR.\n *\n * Applies a migration's operations to an in-memory `SchemaIR`, building the\n * \"current\" schema without touching a database. This is the hybrid source of\n * truth for autogenerate: diff the replayed schema against the reflected models.\n */\n\nimport { topoOrder } from \"./graph.js\";\nimport { type SchemaIR, type TableIR, emptySchema } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\nimport { type Migration, Op } from \"./runner.js\";\n\n/** Apply one operation to a schema, returning the updated schema. */\nexport function applyOperation(schema: SchemaIR, op: Operation): SchemaIR {\n const tables: Record<string, TableIR> = { ...schema.tables };\n switch (op.kind) {\n case \"create_table\":\n tables[op.table.name] = op.table;\n break;\n case \"drop_table\":\n delete tables[op.table.name];\n break;\n case \"rename_table\": {\n const t = tables[op.from];\n if (t) {\n delete tables[op.from];\n tables[op.to] = { ...t, name: op.to };\n }\n break;\n }\n case \"recreate_table\":\n delete tables[op.from.name];\n tables[op.to.name] = op.to;\n break;\n case \"add_column\": {\n const t = tables[op.table];\n if (t) {\n tables[op.table] = {\n ...t,\n columns: { ...t.columns, [op.column.name]: op.column },\n };\n }\n break;\n }\n case \"drop_column\": {\n const t = tables[op.table];\n if (t) {\n const columns = { ...t.columns };\n delete columns[op.column.name];\n tables[op.table] = { ...t, columns };\n }\n break;\n }\n case \"alter_column\": {\n const t = tables[op.table];\n if (t) {\n tables[op.table] = {\n ...t,\n columns: { ...t.columns, [op.name]: op.to },\n };\n }\n break;\n }\n case \"rename_column\": {\n const t = tables[op.table];\n const col = t?.columns[op.from];\n if (t && col) {\n const columns = { ...t.columns };\n delete columns[op.from];\n columns[op.to] = { ...col, name: op.to };\n tables[op.table] = { ...t, columns };\n }\n break;\n }\n case \"execute\":\n // raw SQL is opaque to the IR\n break;\n }\n return { tables };\n}\n\n/**\n * Replay migrations (in DAG order) into a virtual `SchemaIR` — the \"current\"\n * schema, computed without a database.\n *\n * @param migrations All known migrations.\n * @returns The schema after applying every migration's `up()`.\n */\nexport function replaySchema(migrations: readonly Migration[]): SchemaIR {\n let schema = emptySchema();\n for (const migration of topoOrder(migrations)) {\n const op = new Op();\n migration.up(op);\n for (const operation of op.operations) {\n schema = applyOperation(schema, operation);\n }\n }\n return schema;\n}\n","/**\n * tempest-db-js — migration CLI (programmatic core).\n *\n * `runMigrationCli(argv, config)` dispatches Alembic-style commands against a\n * driver + a set of migrations + (optionally) the models. It returns lines and\n * an exit code rather than touching `process`, so it is fully testable; a thin\n * `bin` wrapper just maps `process.argv`/`process.exit` onto it.\n */\n\nimport type { SyncDriver } from \"../engine.js\";\nimport type { ModelClass } from \"../index.js\";\nimport type { Dialect } from \"../url.js\";\nimport { generateMigration, makeRevisionId } from \"./codegen.js\";\nimport { renderOperation } from \"./ddl.js\";\nimport { diffSchema } from \"./diff.js\";\nimport { heads as graphHeads, topoOrder } from \"./graph.js\";\nimport { checkDrift } from \"./introspect.js\";\nimport { reflectSchema } from \"./ir.js\";\nimport type { Operation } from \"./operations.js\";\nimport { type RenameCandidate, applyRenames, detectRenames } from \"./renames.js\";\nimport { replaySchema } from \"./replay.js\";\nimport { type Migration, MigrationRunner, Op } from \"./runner.js\";\n\n/** Configuration the CLI operates against. */\nexport interface CliConfig {\n readonly driver: SyncDriver;\n readonly dialect: Dialect;\n readonly migrations: readonly Migration[];\n readonly models?: readonly ModelClass[];\n /** Timestamp string stamped on applied revisions (no wall clock here). */\n readonly appliedAt?: string;\n}\n\n/** The result of a CLI run. */\nexport interface CliResult {\n readonly code: number;\n readonly lines: string[];\n}\n\n/**\n * Identity helper for authoring a typed migration config file. Gives editor\n * autocompletion and type-checking on the object the `tempest-db` bin loads.\n *\n * @example\n * ```ts\n * // tempest-db.config.mjs\n * import { defineMigrationConfig } from \"tempest-db-js/migrations\";\n * import { NodeSqliteDriver } from \"tempest-db-js\";\n * import { migrations } from \"./migrations/index.js\";\n * import { User } from \"./models.js\";\n *\n * export default defineMigrationConfig({\n * driver: NodeSqliteDriver.open(\"app.db\"),\n * dialect: \"sqlite\",\n * migrations,\n * models: [User],\n * });\n * ```\n *\n * @param config The migration config to pass through unchanged.\n * @returns The same config, typed as `CliConfig`.\n */\nexport function defineMigrationConfig(config: CliConfig): CliConfig {\n return config;\n}\n\nfunction ok(lines: string[]): CliResult {\n return { code: 0, lines };\n}\nfunction fail(lines: string[]): CliResult {\n return { code: 1, lines };\n}\n\n/**\n * Parse rename flags into explicit rename candidates.\n *\n * `--rename-table <from>:<to>` and `--rename-column <table>.<from>:<to>` may each\n * be repeated. Malformed specs are ignored (the safe drop + add stays).\n *\n * @param rest The command arguments.\n * @returns The explicitly requested renames.\n */\nfunction parseRenameFlags(rest: readonly string[]): RenameCandidate[] {\n const out: RenameCandidate[] = [];\n for (let i = 0; i < rest.length; i += 1) {\n const arg = rest[i];\n if (arg === \"--rename-table\") {\n const [from, to] = (rest[i + 1] ?? \"\").split(\":\");\n i += 1;\n if (from && to) out.push({ kind: \"table\", from, to });\n } else if (arg === \"--rename-column\") {\n const [left, to] = (rest[i + 1] ?? \"\").split(\":\");\n i += 1;\n const dot = left?.lastIndexOf(\".\") ?? -1;\n if (left && to && dot > 0) {\n out.push({\n kind: \"column\",\n table: left.slice(0, dot),\n from: left.slice(dot + 1),\n to,\n });\n }\n }\n }\n return out;\n}\n\n/** Pending migrations (DAG order) not yet applied. */\nfunction pending(config: CliConfig, runner: MigrationRunner): Migration[] {\n const done = runner.applied();\n return topoOrder(config.migrations).filter((m) => !done.has(m.revision));\n}\n\n/**\n * Run one CLI command.\n *\n * Commands: `current`, `history`, `heads`, `upgrade [--sql]`, `downgrade [N]`,\n * `check`, `revision -m <msg> [--autogenerate]`.\n *\n * @param argv The command and its arguments (without the program name).\n * @param config The driver, migrations, and models to operate on.\n * @returns Output lines and an exit code.\n */\nexport function runMigrationCli(argv: readonly string[], config: CliConfig): CliResult {\n const [command, ...rest] = argv;\n const runner = new MigrationRunner(config.driver, config.dialect);\n const appliedAt = config.appliedAt ?? \"1970-01-01T00:00:00.000Z\";\n\n switch (command) {\n case \"current\": {\n const applied = [...runner.applied()].sort();\n return ok(applied.length > 0 ? applied : [\"(no migrations applied)\"]);\n }\n\n case \"heads\":\n return ok(graphHeads(config.migrations));\n\n case \"history\": {\n const done = runner.applied();\n return ok(\n topoOrder(config.migrations).map(\n (m) =>\n `${done.has(m.revision) ? \"✓\" : \"·\"} ${m.revision}${m.label ? ` — ${m.label}` : \"\"}`,\n ),\n );\n }\n\n case \"upgrade\": {\n if (rest.includes(\"--sql\")) {\n const lines: string[] = [];\n for (const migration of pending(config, runner)) {\n const op = new Op();\n migration.up(op);\n lines.push(`-- ${migration.revision}`);\n for (const operation of op.operations) {\n for (const stmt of renderOperation(operation, config.dialect))\n lines.push(`${stmt};`);\n }\n }\n return ok(lines.length > 0 ? lines : [\"-- nothing to upgrade\"]);\n }\n const ran = runner.upgrade(config.migrations, appliedAt);\n return ok(ran.length > 0 ? ran.map((r) => `applied ${r}`) : [\"nothing to upgrade\"]);\n }\n\n case \"downgrade\": {\n const steps = rest[0] ? Number(rest[0]) : 1;\n const reverted = runner.downgrade(config.migrations, steps);\n return ok(\n reverted.length > 0\n ? reverted.map((r) => `reverted ${r}`)\n : [\"nothing to downgrade\"],\n );\n }\n\n case \"check\": {\n if (!config.models) return fail([\"check requires models in the config\"]);\n // Drift: live DB vs models (SQLite introspection).\n const drift =\n config.dialect === \"sqlite\" ? checkDrift(config.driver, config.models) : [];\n // Pending model changes not yet captured by a migration.\n const undiffed = diffSchema(\n replaySchema(config.migrations),\n reflectSchema(config.models),\n );\n const issues = [\n ...drift.map((d) => `drift: ${d}`),\n ...undiffed.map((o) => `uncaptured: ${o.kind}`),\n ];\n return issues.length > 0 ? fail(issues) : ok([\"no drift; models match migrations\"]);\n }\n\n case \"revision\": {\n if (!config.models)\n return fail([\"revision --autogenerate requires models in the config\"]);\n const msgIndex = rest.indexOf(\"-m\");\n const label = msgIndex >= 0 ? (rest[msgIndex + 1] ?? \"revision\") : \"revision\";\n const parents = graphHeads(config.migrations);\n let ops: Operation[] = rest.includes(\"--autogenerate\")\n ? diffSchema(replaySchema(config.migrations), reflectSchema(config.models))\n : [];\n if (rest.includes(\"--autogenerate\")) {\n // Fold add/drop pairs into renames: `--autorename` accepts every\n // detected candidate; otherwise only the explicit `--rename-*` flags.\n const confirmed = rest.includes(\"--autorename\")\n ? detectRenames(ops)\n : parseRenameFlags(rest);\n if (confirmed.length > 0) ops = applyRenames(ops, confirmed);\n }\n const source = generateMigration({\n revision: makeRevisionId(label, parents),\n downRevision: parents,\n label,\n operations: ops,\n });\n return ok(source.split(\"\\n\"));\n }\n\n default:\n return fail([\n `unknown command ${JSON.stringify(command)}`,\n \"commands: current | history | heads | upgrade [--sql] | downgrade [N] | check | revision -m <msg> [--autogenerate]\",\n ]);\n }\n}\n","#!/usr/bin/env node\n/**\n * tempest-db-js — `tempest-db` executable.\n *\n * A thin wrapper around {@link runMigrationCli}: it discovers a config module,\n * loads it, injects a real timestamp, dispatches the command, prints the output\n * lines, and maps the result code onto `process.exit`. All the migration logic\n * lives in the (fully testable) programmatic core — this file only touches\n * `process`, the filesystem, and the wall clock.\n *\n * @example\n * ```bash\n * tempest-db upgrade\n * tempest-db revision -m \"add users\" --autogenerate\n * tempest-db --config db/tempest.config.mjs current\n * ```\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport type { CliConfig } from \"./migrations/cli.js\";\nimport { runMigrationCli } from \"./migrations/cli.js\";\nimport { diffSchema } from \"./migrations/diff.js\";\nimport { reflectSchema } from \"./migrations/ir.js\";\nimport { type RenameCandidate, detectRenames } from \"./migrations/renames.js\";\nimport { replaySchema } from \"./migrations/replay.js\";\n\n/** Config file names looked up in the current directory, in order. */\nconst DEFAULT_CONFIG_NAMES: readonly string[] = [\n \"tempest-db.config.mjs\",\n \"tempest-db.config.js\",\n \"tempest-db.config.cjs\",\n];\n\n/**\n * Pull the `--config <path>` flag out of the argv, returning the path (if any)\n * and the remaining arguments for the CLI command itself.\n *\n * @param argv The process arguments (without node + script).\n * @returns The explicit config path (or `null`) and the leftover argv.\n */\nfunction extractConfigFlag(argv: readonly string[]): {\n configPath: string | null;\n rest: string[];\n} {\n const rest: string[] = [];\n let configPath: string | null = null;\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === \"--config\" || arg === \"-c\") {\n configPath = argv[i + 1] ?? null;\n i += 1;\n } else if (arg?.startsWith(\"--config=\")) {\n configPath = arg.slice(\"--config=\".length);\n } else if (arg !== undefined) {\n rest.push(arg);\n }\n }\n return { configPath, rest };\n}\n\n/**\n * Resolve the config file path: the explicit `--config` value, or the first of\n * the default names that exists in the current directory.\n *\n * @param explicit The `--config` value, or `null` to search defaults.\n * @returns The absolute config path, or `null` if none was found.\n */\nfunction resolveConfigPath(explicit: string | null): string | null {\n if (explicit) return resolve(process.cwd(), explicit);\n for (const name of DEFAULT_CONFIG_NAMES) {\n const candidate = resolve(process.cwd(), name);\n if (existsSync(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Dynamically import a config module and extract the `CliConfig` from its\n * `default` export (or a named `config` export as a fallback).\n *\n * @param path The absolute path to the config module.\n * @returns The loaded migration config.\n * @throws If the module has neither a default nor a `config` export.\n */\nasync function loadConfig(path: string): Promise<CliConfig> {\n const mod = (await import(pathToFileURL(path).href)) as {\n default?: CliConfig;\n config?: CliConfig;\n };\n const config = mod.default ?? mod.config;\n if (!config) {\n throw new Error(\n `config at ${path} must default-export (or export \\`config\\`) a CliConfig`,\n );\n }\n return config;\n}\n\n/** Turn a confirmed candidate into the `--rename-*` flag args the CLI parses. */\nfunction renameToFlags(r: RenameCandidate): string[] {\n return r.kind === \"table\"\n ? [\"--rename-table\", `${r.from}:${r.to}`]\n : [\"--rename-column\", `${r.table}.${r.from}:${r.to}`];\n}\n\n/**\n * When running `revision --autogenerate` at an interactive TTY, detect rename\n * candidates and ask the user to confirm each; return the `--rename-*` flags for\n * the accepted ones. No-op when not autogenerating, when `--autorename` or\n * explicit `--rename-*` flags are already present, when there are no models, or\n * when stdin is not a TTY (CI, pipes).\n *\n * @param config The loaded migration config.\n * @param rest The CLI command arguments.\n * @returns Extra `--rename-*` args to append before dispatching.\n */\nasync function promptRenames(\n config: CliConfig,\n rest: readonly string[],\n): Promise<string[]> {\n const decided =\n rest.includes(\"--autorename\") ||\n rest.includes(\"--rename-table\") ||\n rest.includes(\"--rename-column\");\n if (\n rest[0] !== \"revision\" ||\n !rest.includes(\"--autogenerate\") ||\n decided ||\n !config.models ||\n !process.stdin.isTTY\n ) {\n return [];\n }\n\n const ops = diffSchema(replaySchema(config.migrations), reflectSchema(config.models));\n const candidates = detectRenames(ops);\n if (candidates.length === 0) return [];\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const flags: string[] = [];\n try {\n for (const c of candidates) {\n const what =\n c.kind === \"table\"\n ? `table \"${c.from}\" → \"${c.to}\"`\n : `column \"${c.table}.${c.from}\" → \"${c.table}.${c.to}\"`;\n const answer = (await rl.question(`Rename ${what}? [y/N] `)).trim().toLowerCase();\n if (answer === \"y\" || answer === \"yes\") flags.push(...renameToFlags(c));\n }\n } finally {\n rl.close();\n }\n return flags;\n}\n\n/**\n * Run the `tempest-db` CLI end to end: discover + load the config, dispatch the\n * command, print output, and exit with the CLI's status code.\n *\n * @param argv The process arguments (without node + script).\n * @returns A promise resolving once the command has printed and exit is set.\n */\nexport async function main(argv: readonly string[]): Promise<void> {\n const { configPath, rest } = extractConfigFlag(argv);\n const resolved = resolveConfigPath(configPath);\n if (!resolved) {\n process.stderr.write(\n `tempest-db: no config found. Create one of ${DEFAULT_CONFIG_NAMES.join(\n \", \",\n )} or pass --config <path>.\\n`,\n );\n process.exitCode = 1;\n return;\n }\n\n let config: CliConfig;\n try {\n config = await loadConfig(resolved);\n } catch (error) {\n process.stderr.write(`tempest-db: ${(error as Error).message}\\n`);\n process.exitCode = 1;\n return;\n }\n\n const withClock: CliConfig = {\n ...config,\n appliedAt: config.appliedAt ?? new Date().toISOString(),\n };\n const renameFlags = await promptRenames(withClock, rest);\n const result = runMigrationCli([...rest, ...renameFlags], withClock);\n const sink = result.code === 0 ? process.stdout : process.stderr;\n for (const line of result.lines) sink.write(`${line}\\n`);\n process.exitCode = result.code;\n}\n\n// Only auto-run when invoked as a program (not when imported by a test).\nif (import.meta.url === pathToFileURL(process.argv[1] ?? \"\").href) {\n void main(process.argv.slice(2));\n}\n"]}