@forinda/kickjs-db 8.0.0 → 8.2.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/README.md +16 -45
- package/dist/cli.d.mts +16 -2
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +4 -3
- package/dist/cli.mjs.map +1 -1
- package/dist/create-BaiUxRiE.mjs +29 -0
- package/dist/create-BaiUxRiE.mjs.map +1 -0
- package/dist/custom-type-DoPt91ZM.mjs +12 -0
- package/dist/custom-type-DoPt91ZM.mjs.map +1 -0
- package/dist/devtools-events.d.mts +1 -1
- package/dist/devtools-events.mjs +1 -1
- package/dist/{index-BQQWKybR.d.mts → index-BJYFXCB4.d.mts} +702 -167
- package/dist/index-BJYFXCB4.d.mts.map +1 -0
- package/dist/index.d.mts +6 -4
- package/dist/index.mjs +2 -2
- package/dist/mysql.d.mts +41 -37
- package/dist/mysql.d.mts.map +1 -1
- package/dist/mysql.mjs +8 -8
- package/dist/mysql.mjs.map +1 -1
- package/dist/pg-CuKSRK4C.mjs +12 -0
- package/dist/pg-CuKSRK4C.mjs.map +1 -0
- package/dist/pg.d.mts +74 -8
- package/dist/pg.d.mts.map +1 -1
- package/dist/pg.mjs +8 -7
- package/dist/pg.mjs.map +1 -1
- package/dist/schema-BjGAg-s1.d.mts +95 -0
- package/dist/schema-BjGAg-s1.d.mts.map +1 -0
- package/dist/schema-types-DH-d43Pf.d.mts +51 -0
- package/dist/schema-types-DH-d43Pf.d.mts.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +2 -2
- package/dist/schema.mjs.map +1 -1
- package/dist/split-statements-DFaB7cus.mjs +14 -0
- package/dist/split-statements-DFaB7cus.mjs.map +1 -0
- package/dist/sqlite.d.mts +86 -6
- package/dist/sqlite.d.mts.map +1 -1
- package/dist/sqlite.mjs +13 -7
- package/dist/sqlite.mjs.map +1 -1
- package/dist/src-CXdCpvjp.mjs +199 -0
- package/dist/src-CXdCpvjp.mjs.map +1 -0
- package/dist/table-CGPsm5i7.d.mts +221 -0
- package/dist/table-CGPsm5i7.d.mts.map +1 -0
- package/dist/testing.d.mts +53 -0
- package/dist/testing.d.mts.map +1 -0
- package/dist/testing.mjs +12 -0
- package/dist/testing.mjs.map +1 -0
- package/dist/{types-DtvYnaXL.d.mts → types-BnYMhgYq.d.mts} +352 -9
- package/dist/types-BnYMhgYq.d.mts.map +1 -0
- package/dist/{schema-DDMkteEP.d.mts → types-DNAKmwPO.d.mts} +174 -159
- package/dist/types-DNAKmwPO.d.mts.map +1 -0
- package/package.json +16 -6
- package/dist/custom-type-CZdUgkPT.mjs +0 -12
- package/dist/custom-type-CZdUgkPT.mjs.map +0 -1
- package/dist/index-BQQWKybR.d.mts.map +0 -1
- package/dist/pg-CwNv938J.mjs +0 -12
- package/dist/pg-CwNv938J.mjs.map +0 -1
- package/dist/schema-DDMkteEP.d.mts.map +0 -1
- package/dist/src-BEJ33yHI.mjs +0 -166
- package/dist/src-BEJ33yHI.mjs.map +0 -1
- package/dist/types-DtvYnaXL.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-CXdCpvjp.mjs","names":["DEFAULT_EXCLUDED","readColumns","readIndexes","readForeignKeys","normalizeType","mapFkAction","DEFAULT_EXCLUDED","rows","readColumns","readIndexes","readForeignKeys","normalizeType","mapFkAction","ColumnBuilderClass","_exhaustive"],"sources":["../src/snapshot/render.ts","../src/diff/invert.ts","../src/diff/composite-detect.ts","../src/migrate/schema.ts","../src/migrate/memory-adapter.ts","../src/migrate/introspect-pg.ts","../src/migrate/introspect-sqlite.ts","../src/migrate/introspect-mysql.ts","../src/adapter.ts","../src/tokens.ts","../src/client/plugins.ts","../src/migrate/tenants.ts","../src/migrate/review.ts","../src/cli/config.ts","../src/cli/generate.ts","../src/cli/check.ts","../src/cli/seed.ts","../src/dsl/columns/builders.ts","../src/dsl/pg-schema.ts","../src/dsl/table-forms.ts","../src/dsl/constraints.ts","../src/dsl/alias.ts","../src/query/operators.ts","../src/dsl/relations.ts","../src/query/like.ts","../src/query/order.ts"],"sourcesContent":["import { derivedFkName, derivedUniqueName } from './name'\nimport type {\n ColumnSnapshot,\n EnumSnapshot,\n ForeignKeySnapshot,\n IndexSnapshot,\n SchemaSnapshot,\n PolicySnapshot,\n TableSnapshot,\n ViewSnapshot,\n} from './types'\n\n/**\n * Render a SchemaSnapshot to TypeScript source matching the kickjs-db DSL.\n * Inverse of extractSnapshot().\n *\n * Naming: tables become exported `const`s with the same name. Constants\n * starting with digits get an underscore prefix to stay JS-valid.\n *\n * Limits (M1 — refined in M2/M3):\n * - No relations() emission. Adopter adds them manually post-introspect.\n * - No checks (M1 doesn't model CHECK constraints in the snapshot).\n * - Default values pass through as-is. The DSL accepts string defaults,\n * so 'true' / 'CURRENT_TIMESTAMP' / \"'foo'\" all round-trip.\n * - Auto-derived constraint names (`<table>_<col>_unique`, `<table>_<col>_fk`)\n * are detected and rendered as the chained .unique() / .references() form.\n * Custom-named constraints fall back to the third-arg callback / FK helper.\n */\nexport function renderSchemaSource(snapshot: SchemaSnapshot): string {\n const usedColumnHelpers = new Set<string>()\n const tableSources: string[] = []\n\n // An enum column's SQL type IS the type's name, so the renderer needs to know\n // which names are enums to reach for the factory instead of a column helper.\n const enums = snapshot.enums ?? {}\n\n // First pass: render every table, accumulating which column helpers we used.\n for (const table of Object.values(snapshot.tables)) {\n tableSources.push(renderTable(table, usedColumnHelpers, enums))\n }\n const views = Object.values(snapshot.views ?? {})\n for (const v of views) tableSources.push(renderView(v, usedColumnHelpers, enums))\n\n const helpers = ['table', ...Array.from(usedColumnHelpers).toSorted()]\n if (views.some((v) => !v.materialized)) helpers.push('view')\n const viewIndexes = views.flatMap((v) => v.indexes ?? [])\n if (viewIndexes.some((i) => !i.unique) && !helpers.includes('index')) helpers.push('index')\n if (viewIndexes.some((i) => i.unique) && !helpers.includes('unique')) helpers.push('unique')\n // Common constraint helpers used by tables with secondary objects.\n const needsIndex = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => !isAutoUniqueName(t.name, i)),\n )\n if (needsIndex) helpers.push('index')\n const needsUnique = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => i.unique && !isAutoUniqueName(t.name, i)),\n )\n if (needsUnique && !helpers.includes('unique')) helpers.push('unique')\n\n const lines = [`import { ${helpers.join(', ')} } from '@forinda/kickjs-db'`]\n\n // `pgEnum` and `materializedView` live on the dialect subpath.\n const enumDecls = Object.values(enums)\n const pgImports = [\n ...(enumDecls.length > 0 ? ['pgEnum'] : []),\n ...(views.some((v) => v.materialized) ? ['materializedView'] : []),\n ...(Object.values(snapshot.tables).some((t) => t.policies?.length) ? ['policy'] : []),\n ]\n if (pgImports.length > 0) {\n lines.push(`import { ${pgImports.join(', ')} } from '@forinda/kickjs-db/pg'`)\n }\n\n const body: string[] = []\n if (enumDecls.length > 0) {\n // Declared before the tables that use them: these are plain consts, and a\n // column reads the factory at table-definition time.\n for (const e of enumDecls.toSorted((a, b) => a.name.localeCompare(b.name))) {\n const values = e.values.map((v) => `'${v.replace(/'/g, \"\\\\'\")}'`).join(', ')\n body.push(`export const ${enumIdent(e.name)} = pgEnum('${e.name}', ${values})`)\n }\n body.push('')\n }\n\n return [...lines, '', ...body, ...tableSources].join('\\n').trimEnd() + '\\n'\n}\n\n/**\n * A view as `view(name, columns, { as })` — or `materializedView` with its\n * indexes. The columns are what introspection reported; the SQL is the\n * database's own rewrite of it.\n */\nfunction renderView(\n v: ViewSnapshot,\n helpers: Set<string>,\n enums: Record<string, EnumSnapshot>,\n): string {\n const columns = Object.values(v.columns ?? {}).map(\n (c) => ` ${jsKey(c.name)}: ${renderColumn(c, helpers, undefined, false, v.name, enums)},`,\n )\n const sql =\n '`' + v.definition.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${') + '`'\n const opts = [`as: ${sql}`]\n if (v.indexes?.length) {\n const calls = v.indexes.map((i) => ` ${jsKey(i.name)}: ${renderIndexCall(i)}`).join(',\\n')\n opts.push(`constraints: (t) => ({\\n${calls},\\n })`)\n }\n const factory = v.materialized ? 'materializedView' : 'view'\n return `export const ${jsIdent(v.name)} = ${factory}(${strLit(v.name)}, {\\n${columns.join('\\n')}\\n}, { ${opts.join(', ')} })`\n}\n\n/** `policy('name').for(...).to(...).using(...)`, leaving defaults out. */\nfunction renderPolicyCall(p: PolicySnapshot): string {\n let s = `policy(${strLit(p.name)})`\n if (p.as !== 'permissive') s += `.as('${p.as}')`\n if (p.command !== 'all') s += `.for('${p.command}')`\n if (p.to.join() !== 'public') s += `.to(${p.to.map(strLit).join(', ')})`\n if (p.using) s += `.using(${strLit(p.using)})`\n if (p.withCheck) s += `.withCheck(${strLit(p.withCheck)})`\n return s\n}\n\n/**\n * The const name for an enum declaration.\n *\n * Postgres puts types and tables in one namespace, so an enum can never share a\n * name with a table and `jsIdent` alone is unambiguous.\n */\nfunction enumIdent(enumName: string): string {\n return jsIdent(enumName)\n}\n\nfunction renderTable(\n table: TableSnapshot,\n helpers: Set<string>,\n enums: Record<string, EnumSnapshot>,\n): string {\n const ident = jsIdent(table.name)\n const columns: string[] = []\n\n // Grouped so a column with more than one foreign key is visible as such.\n const singleColumnFks = new Map<string, ForeignKeySnapshot[]>()\n for (const f of table.foreignKeys) {\n if (f.columns.length !== 1) continue\n const list = singleColumnFks.get(f.columns[0]) ?? []\n list.push(f)\n singleColumnFks.set(f.columns[0], list)\n }\n /** The ones actually rendered on a column; everything else is deferred. */\n const inlined = new Set<ForeignKeySnapshot>()\n for (const col of Object.values(table.columns)) {\n // Match on SHAPE — one column, this column — not on the constraint's name.\n //\n // Matching by name meant only `<table>_<col>_fk` was ever inlined, which is\n // the name this DSL derives. A real database names constraints itself:\n // Postgres' default is `<table>_<col>_fkey`, and a DBA may have chosen\n // anything at all. So introspecting a live schema matched nothing and every\n // foreign key fell through to a TODO comment — 1,330 of them on a\n // 242-table schema (#643). The name is preserved separately below.\n //\n // Exactly one, or none: `.references()` says \"this column points at X\", and\n // a column carrying two constraints cannot say both. Inlining the first\n // would make the file look complete while the second lived only in a\n // comment, so neither is inlined and both are reported below.\n const candidates = singleColumnFks.get(col.name) ?? []\n const fk = candidates.length === 1 ? candidates[0] : undefined\n if (fk) inlined.add(fk)\n const inlineUnique =\n table.indexes.find(\n (i) =>\n i.unique &&\n i.columns.length === 1 &&\n i.columns[0] === col.name &&\n isAutoUniqueName(table.name, i),\n ) !== undefined\n columns.push(\n ` ${jsKey(col.name)}: ${renderColumn(col, helpers, fk, inlineUnique, table.name, enums)},`,\n )\n }\n\n // Constraints that don't fit on a column chain.\n const explicitIndexes = table.indexes.filter((i) => !isAutoUniqueName(table.name, i))\n // Whatever did not render on a column: composite keys, which have no\n // column-level form, and the members of any column carrying more than one.\n const deferredFks = table.foreignKeys.filter((f) => !inlined.has(f))\n\n const tableArgs: string[] = [strLit(table.name), `{\\n${columns.join('\\n')}\\n}`]\n\n const callbacks = [\n ...explicitIndexes.map((i) => ` ${jsKey(i.name)}: ${renderIndexCall(i)}`),\n ...(table.policies ?? []).map((p) => ` ${jsKey(p.name)}: ${renderPolicyCall(p)}`),\n ].join(',\\n')\n const constraints = callbacks ? `(t) => ({\\n${callbacks},\\n })` : undefined\n // A policy turns row-level security on by itself; say so only when it doesn't.\n const rls = table.rls?.force\n ? '{ force: true }'\n : table.rls && !table.policies?.length\n ? 'true'\n : undefined\n if (table.comment !== undefined || rls) {\n const parts: string[] = []\n if (table.comment !== undefined) parts.push(`comment: ${strLit(table.comment)}`)\n if (rls) parts.push(`rls: ${rls}`)\n if (constraints) parts.push(`constraints: ${constraints}`)\n tableArgs.push(`{ ${parts.join(', ')} }`)\n } else if (constraints) {\n tableArgs.push(constraints)\n }\n\n let src = `export const ${ident} = table(${tableArgs.join(', ')})`\n\n // Foreign keys with no column-level form in the DSL are logged as TODO\n // comments for the adopter to handle. M3 may upgrade this to emit a separate\n // ALTER snippet.\n if (deferredFks.length > 0) {\n src +=\n '\\n// TODO: kick db introspect — composite foreign keys, and columns with more than one, not auto-rendered:\\n'\n for (const f of deferredFks) {\n src += `// ${f.name}: (${f.columns.join(', ')}) → ${f.refTable}(${f.refColumns.join(', ')})\\n`\n }\n }\n\n return src\n}\n\nfunction renderColumn(\n col: ColumnSnapshot,\n helpers: Set<string>,\n fk: ForeignKeySnapshot | undefined,\n inlineUnique: boolean,\n tableName: string,\n enums: Record<string, EnumSnapshot>,\n): string {\n // An enum column calls the factory declared above rather than a helper\n // imported from the package, so nothing is added to the import line.\n if (enums[col.type]) {\n return chainSuffix(`${enumIdent(col.type)}()`, col, fk, inlineUnique, tableName)\n }\n\n const { helperName, args, isArray } = pickColumnHelper(col)\n helpers.add(helperName)\n // `.array()` goes first in the chain: it rewrites the column's type, and\n // reads as part of the type rather than as a constraint on it.\n const base = `${helperName}(${args})${isArray ? '.array()' : ''}`\n return chainSuffix(base, col, fk, inlineUnique, tableName)\n}\n\n/**\n * Append the modifier chain — nullability, default, unique, references — to a\n * column expression.\n *\n * Shared so an enum column, whose expression comes from a declared factory\n * rather than an imported helper, gets exactly the same modifiers in exactly\n * the same order.\n */\nfunction chainSuffix(\n base: string,\n col: ColumnSnapshot,\n fk: ForeignKeySnapshot | undefined,\n inlineUnique: boolean,\n tableName: string,\n): string {\n let chain = base\n if (col.primaryKey) chain += '.primaryKey()'\n if (!col.primaryKey && !col.nullable) chain += '.notNull()'\n if (col.default !== null) chain += `.default(${JSON.stringify(col.default)})`\n if (col.identity === 'always') chain += '.generatedAlwaysAsIdentity()'\n if (col.identity === 'byDefault') chain += '.generatedByDefaultAsIdentity()'\n if (col.generated) {\n const virtual = col.generated.stored ? '' : ', { stored: false }'\n chain += `.generatedAlwaysAs(${strLit(col.generated.expression)}${virtual})`\n }\n if (inlineUnique) chain += '.unique()'\n if (col.comment !== undefined) chain += `.comment(${strLit(col.comment)})`\n if (fk) {\n const ref = `${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`\n const opts: string[] = []\n if (fk.onDelete !== 'no_action') opts.push(`onDelete: '${fk.onDelete}'`)\n if (fk.onUpdate !== undefined && fk.onUpdate !== 'no_action') {\n opts.push(`onUpdate: '${fk.onUpdate}'`)\n }\n // Carry the real constraint name whenever it isn't the one the DSL would\n // derive, so re-extracting this file reproduces the database rather than\n // proposing a rename of every key.\n if (fk.name !== derivedFkName(tableName, col.name)) opts.push(`name: ${strLit(fk.name)}`)\n const optArg = opts.length > 0 ? `, { ${opts.join(', ')} }` : ''\n chain += `.references(() => ${ref}${optArg})`\n }\n return chain\n}\n\nfunction pickColumnHelper(col: ColumnSnapshot): {\n helperName: string\n args: string\n isArray: boolean\n} {\n // An array type is its element type plus `.array()`. Introspect already\n // reports `integer[]`, but every such column used to miss every branch below\n // and land on the `text(/* TODO */)` fallback, losing the element type and\n // the array-ness together (#648).\n const isArray = col.type.endsWith('[]')\n const t = isArray ? col.type.slice(0, -2) : col.type\n\n if (t === 'serial') return { helperName: 'serial', args: '', isArray }\n if (t === 'bigserial') return { helperName: 'bigSerial', args: '', isArray }\n if (t === 'smallserial') return { helperName: 'serial', args: '', isArray }\n if (t === 'integer') return { helperName: 'integer', args: '', isArray }\n if (t === 'bigint') return { helperName: 'bigint', args: '', isArray }\n if (t === 'smallint') return { helperName: 'smallint', args: '', isArray }\n if (t === 'real') return { helperName: 'real', args: '', isArray }\n if (t === 'double precision') return { helperName: 'doublePrecision', args: '', isArray }\n if (/^numeric(\\(.+\\))?$/.test(t))\n return { helperName: 'numeric', args: extractParens(t), isArray }\n if (/^varchar(\\(\\d+\\))?$/.test(t))\n return { helperName: 'varchar', args: extractParens(t), isArray }\n if (/^char(\\(\\d+\\))?$/.test(t)) return { helperName: 'char', args: extractParens(t), isArray }\n if (t === 'text') return { helperName: 'text', args: '', isArray }\n if (t === 'boolean') return { helperName: 'boolean', args: '', isArray }\n if (t === 'timestamp') return { helperName: 'timestamp', args: '', isArray }\n if (t === 'timestamptz') return { helperName: 'timestamptz', args: '', isArray }\n if (t === 'date') return { helperName: 'date', args: '', isArray }\n if (t === 'time') return { helperName: 'time', args: '', isArray }\n if (t === 'interval') return { helperName: 'interval', args: '', isArray }\n if (t === 'uuid') return { helperName: 'uuid', args: '', isArray }\n if (t === 'jsonb') return { helperName: 'jsonb', args: '', isArray }\n if (t === 'json') return { helperName: 'json', args: '', isArray }\n if (t === 'bytea') return { helperName: 'bytea', args: '', isArray }\n\n // Fallback: emit as a comment + placeholder text() so the file still\n // parses. Adopter edits to the right helper. `isArray` still rides along, so\n // an array of an unmapped element type keeps at least its array-ness.\n return { helperName: 'text', args: `/* TODO: ${t} */`, isArray }\n}\n\nfunction extractParens(t: string): string {\n const m = t.match(/\\(([^)]+)\\)/)\n return m ? m[1] : ''\n}\n\nfunction renderIndexCall(idx: IndexSnapshot): string {\n const helper = idx.unique ? 'unique' : 'index'\n // An expression key renders as the SQL string `on()` takes, without the\n // parentheses the snapshot stores it in.\n const key = (c: string) => (c.startsWith('(') ? strLit(c.slice(1, -1)) : `t.${jsIdent(c)}`)\n let call = `${helper}(${strLit(idx.name)}).on(${idx.columns.map(key).join(', ')})`\n if (idx.using) call += `.using(${strLit(idx.using)})`\n for (const [k, op] of Object.entries(idx.opclasses ?? {})) call += `.op(${key(k)}, ${strLit(op)})`\n if (idx.include?.length)\n call += `.include(${idx.include.map((c) => `t.${jsIdent(c)}`).join(', ')})`\n if (idx.where) call += `.where(${strLit(idx.where)})`\n if (idx.concurrently) call += '.concurrently()'\n return call\n}\n\nfunction isAutoUniqueName(tableName: string, idx: IndexSnapshot): boolean {\n return (\n idx.unique &&\n idx.columns.length === 1 &&\n idx.name === derivedUniqueName(tableName, idx.columns[0])\n )\n}\n\n/**\n * Render a database-supplied string as a JS literal.\n *\n * Table, index and constraint names come from the database, and a quoted\n * Postgres identifier may legally contain a quote or a backslash —\n * `\"customer'fk\"` is a valid constraint name. Interpolating one straight into a\n * single-quoted literal produced a schema file that did not parse.\n *\n * Single quotes are kept for everything that can hold them verbatim, so\n * ordinary names render exactly as they always have; anything else falls back\n * to JSON, which escapes quotes, backslashes and line terminators alike.\n */\nfunction strLit(value: string): string {\n return /^[^'\\\\\\r\\n\\u2028\\u2029]*$/.test(value) ? `'${value}'` : JSON.stringify(value)\n}\n\n/** Make a JS-safe identifier from a snake_case column/table name. */\nfunction jsIdent(raw: string): string {\n if (/^[A-Za-z_$][\\w$]*$/.test(raw)) return raw\n // Prefix digits-leading names with underscore.\n return `_${raw.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Render a record key — quoted if not a valid identifier. */\nfunction jsKey(raw: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(raw) ? raw : JSON.stringify(raw)\n}\n","import { snapshotTableName } from '../snapshot/name'\nimport type { Change, ChangeSet, CreateSchema } from './types'\n\n/**\n * Reverse a forward ChangeSet so emitting it produces the SQL that undoes\n * the forward migration.\n *\n * The reverse of an *unambiguous* change is exact (rename → rename swapped,\n * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,\n * drop table, type widen, NOT NULL gain without default) is a defensible\n * best-effort derived from the snapshot the forward change carried — the\n * runner refuses to apply a non-reviewed migration in non-dev so the operator\n * always sees the draft before it touches a DB.\n *\n * The order is reversed too: drop FK before drop index before drop table is\n * the safe sequence for tearing down what create-FK / create-index / create-\n * table built up.\n */\nexport function invertChanges(forward: ChangeSet): ChangeSet {\n const reversed: Change[] = []\n for (const change of forward) {\n // `createSchema` has no inverse by design. A schema can hold objects this\n // app never declared, so a generated DROP SCHEMA could destroy data the\n // diff never saw; the down migration leaves the (now empty) schema behind\n // for an operator to remove deliberately. See CreateSchema in ./types.\n if (change.kind === 'createSchema') continue\n // Roles are the server's, not this database's: a down migration leaves them.\n if (change.kind === 'createRole' || change.kind === 'alterRole') continue\n reversed.push(invert(change))\n }\n const ordered = reversed.toReversed()\n\n // Prune redundant teardown: when the inverted set drops a table\n // outright, its dropForeignKey / dropIndex entries are no-ops — the\n // DROP TABLE removes both. On SQLite they're actively fatal: FK/index\n // drops compile to a table rebuild against the post-state snapshot,\n // which no longer contains the table when the inversion of a\n // createTable is in the same set (every first migration of an\n // FK-bearing schema hit `SqliteRebuildRequiredError`).\n // Qualified on both sides: `dropTable` carries a TableSnapshot (bare name +\n // schema) while `dropForeignKey`/`dropIndex` carry the qualified snapshot\n // key, so comparing raw `.name` would never match a schema-qualified table\n // and the prune below would silently stop firing for it.\n const droppedTables = new Set(\n ordered.filter((c) => c.kind === 'dropTable').map((c) => snapshotTableName(c.table)),\n )\n return ordered.filter((c) => {\n if (\n c.kind === 'dropForeignKey' ||\n c.kind === 'dropIndex' ||\n c.kind === 'dropCheck' ||\n c.kind === 'dropPolicy' ||\n c.kind === 'setRowLevelSecurity'\n ) {\n return !droppedTables.has(c.table)\n }\n return true\n })\n}\n\n// `CreateSchema` is filtered out above rather than inverted, so excluding it\n// here keeps the switch exhaustive without a dead default branch.\nfunction invert(\n change: Exclude<Change, CreateSchema | { kind: 'createRole' } | { kind: 'alterRole' }>,\n): Change {\n switch (change.kind) {\n case 'createTable':\n return { kind: 'dropTable', table: change.table }\n case 'dropTable':\n return { kind: 'createTable', table: change.table }\n case 'renameTable':\n return { kind: 'renameTable', from: change.to, to: change.from }\n case 'addColumn':\n return { kind: 'dropColumn', table: change.table, column: change.column }\n case 'dropColumn':\n return { kind: 'addColumn', table: change.table, column: change.column }\n case 'renameColumn':\n return {\n kind: 'renameColumn',\n table: change.table,\n from: change.to,\n to: change.from,\n }\n case 'alterColumn':\n return {\n kind: 'alterColumn',\n table: change.table,\n column: change.column,\n before: change.after,\n after: change.before,\n }\n case 'addIndex':\n return { kind: 'dropIndex', table: change.table, index: change.index }\n case 'dropIndex':\n return { kind: 'addIndex', table: change.table, index: change.index }\n case 'addForeignKey':\n return { kind: 'dropForeignKey', table: change.table, fk: change.fk }\n case 'dropForeignKey':\n return { kind: 'addForeignKey', table: change.table, fk: change.fk }\n case 'createEnum':\n return { kind: 'dropEnum', enum: change.enum }\n case 'dropEnum':\n return { kind: 'createEnum', enum: change.enum }\n case 'addEnumValue':\n // PG can't ALTER TYPE … DROP VALUE without recreating the type +\n // touching every column that uses it. Down-migrations carry the\n // forward change verbatim; the operator gets a draft + a clear\n // signal that the down won't auto-revert.\n return change\n case 'alterPrimaryKey':\n return {\n kind: 'alterPrimaryKey',\n table: change.table,\n before: change.after,\n after: change.before,\n }\n case 'addCheck':\n return { kind: 'dropCheck', table: change.table, check: change.check }\n case 'dropCheck':\n return { kind: 'addCheck', table: change.table, check: change.check }\n case 'createPolicy':\n return { kind: 'dropPolicy', table: change.table, policy: change.policy }\n case 'dropPolicy':\n return { kind: 'createPolicy', table: change.table, policy: change.policy }\n case 'setRowLevelSecurity':\n return { ...change, from: change.to, to: change.from }\n case 'createView':\n return { kind: 'dropView', view: change.view }\n case 'dropView':\n return { kind: 'createView', view: change.view }\n case 'setTableComment':\n return { ...change, from: change.to, to: change.from }\n case 'setColumnComment':\n return {\n ...change,\n column: { ...change.column, comment: change.from ?? undefined },\n from: change.to,\n to: change.from,\n }\n case 'removeEnumValue':\n // The forward direction of a value removal is itself an\n // advisory + manual operation; the reverse is symmetric. Carry\n // the change verbatim so the down draft surfaces the same\n // SQL-comment guidance, with `removed` listing the values that\n // would need to be re-added.\n return change\n }\n}\n\n/**\n * Returns the change kinds that produce ambiguous reverses — drop column,\n * drop table, type widen — so the generator can flag the down.sql as a draft\n * even if every individual statement is technically valid SQL.\n */\nconst AMBIGUOUS_REVERSE_KINDS = new Set<Change['kind']>([\n 'dropTable',\n 'dropColumn',\n 'alterColumn',\n // PG enum value additions can't auto-reverse — drop-value isn't\n // supported without recreating the type. The down draft surfaces\n // the forward statement so the operator manually rewrites it.\n 'addEnumValue',\n // Removed values can't auto-reverse for the symmetric reason: the\n // value(s) that disappeared from the schema may have been held by\n // existing rows whose state is already gone. Down draft preserves\n // the advisory comment.\n 'removeEnumValue',\n])\n\nexport function hasAmbiguousReverse(forward: ChangeSet): boolean {\n return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind))\n}\n","/**\n * PG composite-type detection for `removeEnumValue` migrations (M4.C).\n *\n * The M3.B rename-recreate dance assumes the enum is referenced only by\n * table columns — each affected column gets a single `ALTER TABLE …\n * ALTER COLUMN … TYPE foo USING column::text::foo` clause. PG composite\n * types / arrays-of-composite / domains containing the enum break that\n * approach: the USING clause can't reach into composite fields, so the\n * migration fails opaquely at apply time with `type X is being used by\n * table Y`.\n *\n * `detectCompositeReferences` queries `pg_type` + `pg_attribute` to\n * surface those references at generate time. The CLI `kick db generate`\n * command then refuses to emit a migration when any are found, telling\n * the operator to drop or restructure the composite first.\n *\n * Driver-agnostic: takes a structural query runner (any pg-protocol-\n * compatible client). The CLI wires this against the same pool used for\n * `kick db migrate` so adopters don't configure a second connection.\n */\n\nimport { KickDbError } from '../errors'\n\n/**\n * One composite-type field that holds the target enum. The composite\n * may itself be referenced by table columns; that second level is not\n * surfaced — the goal here is to refuse the rename-recreate, not to\n * map the full dependency graph.\n */\nexport interface CompositeRef {\n /** Schema-qualified composite type name, e.g. `\"public.address_t\"`. */\n composite: string\n /** Attribute (field) within the composite that holds the enum. */\n attribute: string\n /** Schema-qualified enum type name. */\n enum: string\n}\n\n/**\n * Slim contract for a pg-protocol-compatible query function. Both\n * `pg.Pool` and `@neondatabase/serverless`'s Pool match this shape, as\n * does the `query` method on a pooled client.\n */\nexport interface CompositeQueryRunner {\n query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: R[] }>\n}\n\ninterface CompositeRow {\n composite_schema: string\n composite_name: string\n attribute_name: string\n enum_schema: string\n enum_name: string\n}\n\n/**\n * Find every PG composite type whose attribute(s) hold the given enum\n * type. `enumName` may be unqualified (treated as `public.<name>`) or\n * schema-qualified (`schema.name`).\n *\n * Returns an empty array when:\n * - the enum doesn't exist in the live DB (the diff engine raised it\n * against a snapshot, but the DB hasn't applied the prior migration\n * yet — generate-time refusal would be a false alarm), or\n * - no composite references the enum (the M3.B path is safe).\n */\nexport async function detectCompositeReferences(\n runner: CompositeQueryRunner,\n enumName: string,\n): Promise<CompositeRef[]> {\n const { schema, name } = splitQualifiedName(enumName)\n\n const sql = `\n SELECT\n ns_comp.nspname AS composite_schema,\n t_comp.typname AS composite_name,\n a.attname AS attribute_name,\n ns_enum.nspname AS enum_schema,\n t_enum.typname AS enum_name\n FROM pg_type t_comp\n JOIN pg_namespace ns_comp ON ns_comp.oid = t_comp.typnamespace\n JOIN pg_class c ON c.oid = t_comp.typrelid\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped\n JOIN pg_type t_enum_or_arr ON t_enum_or_arr.oid = a.atttypid\n JOIN pg_type t_enum ON t_enum.oid = COALESCE(NULLIF(t_enum_or_arr.typelem, 0), t_enum_or_arr.oid)\n JOIN pg_namespace ns_enum ON ns_enum.oid = t_enum.typnamespace\n WHERE t_comp.typtype = 'c'\n AND c.relkind = 'c'\n AND t_enum.typtype = 'e'\n AND t_enum.typname = $1\n AND ($2::text IS NULL OR ns_enum.nspname = $2)\n `\n\n const result = await runner.query<CompositeRow>(sql, [name, schema])\n return result.rows.map((r) => ({\n composite: `${r.composite_schema}.${r.composite_name}`,\n attribute: r.attribute_name,\n enum: `${r.enum_schema}.${r.enum_name}`,\n }))\n}\n\nfunction splitQualifiedName(qualified: string): { schema: string | null; name: string } {\n const dot = qualified.indexOf('.')\n if (dot === -1) return { schema: null, name: qualified }\n return { schema: qualified.slice(0, dot), name: qualified.slice(dot + 1) }\n}\n\n/**\n * Thrown by `kick db generate` when the diff would emit one or more\n * `removeEnumValue` changes against an enum that is referenced by a\n * PG composite type. The rename-recreate dance can't reach into\n * composite fields, so the generator refuses to write the migration\n * rather than letting it fail at apply time.\n *\n * The operator's options: drop the composite, restructure it not to\n * use the enum, or keep the value and ship the change later.\n */\nexport class CompositeEnumReferenceError extends KickDbError {\n readonly refs: readonly CompositeRef[]\n\n constructor(refs: readonly CompositeRef[]) {\n const summary = refs.map((r) => `${r.composite}.${r.attribute} → ${r.enum}`).join(', ')\n super(\n 'composite_enum_reference',\n `Cannot generate migration: the enum value(s) being removed are reachable through ` +\n `composite type field(s) [${summary}]. PostgreSQL's USING-cast in the rename-recreate ` +\n `path can't reach into composite fields, so the migration would fail at apply time. ` +\n `Drop or restructure the composite type(s) first, then re-run \\`kick db generate\\`.`,\n )\n this.refs = refs\n }\n}\n","import type { Dialect } from '../snapshot/types'\n\nexport const KICK_MIGRATIONS_TABLE = 'kick_migrations'\nexport const KICK_LOCK_TABLE = 'kick_migrations_lock'\n\n/** The lock table that goes with a migrations table. */\nexport function lockTableName(table: string): string {\n return `${table}_lock`\n}\n\n/**\n * A table name quoted for the dialect. A dotted name is schema-qualified on\n * Postgres (`meta.kick_migrations`); elsewhere a dot is part of the name.\n */\nexport function quoteTable(dialect: Dialect, name: string): string {\n if (dialect === 'mysql') return `\\`${name.replaceAll('`', '``')}\\``\n const parts = dialect === 'postgres' ? name.split('.') : [name]\n return parts.map((p) => `\"${p.replaceAll('\"', '\"\"')}\"`).join('.')\n}\n\n/** The bare table name, for names derived from it (an index can't be schema-qualified). */\nfunction bareName(name: string): string {\n return name.slice(name.lastIndexOf('.') + 1)\n}\n\nexport function migrationsTableDdl(\n dialect: Dialect,\n table: string = KICK_MIGRATIONS_TABLE,\n): string {\n const T = quoteTable(dialect, table)\n const idx = quoteTable(dialect, `${bareName(table)}_batch_idx`)\n switch (dialect) {\n case 'postgres':\n // A schema-qualified table needs its schema; created if missing.\n return `${table.includes('.') ? `CREATE SCHEMA IF NOT EXISTS ${quoteTable(dialect, table.slice(0, table.lastIndexOf('.')))};\\n ` : ''}CREATE TABLE IF NOT EXISTS ${T} (\n \"id\" varchar(128) PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \"direction\" varchar(8) NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS ${idx} ON ${T} (\"batch\");`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS ${T} (\n \"id\" text PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" text NOT NULL DEFAULT (datetime('now')),\n \"direction\" text NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS ${idx} ON ${T} (\"batch\");`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS ${T} (\n \\`id\\` varchar(128) PRIMARY KEY,\n \\`name\\` text NOT NULL,\n \\`hash\\` text NOT NULL,\n \\`batch\\` int NOT NULL,\n \\`applied_at\\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \\`direction\\` varchar(8) NOT NULL DEFAULT 'up',\n INDEX ${idx} (\\`batch\\`)\n );`\n }\n}\n\nexport function lockTableDdl(dialect: Dialect, table: string = KICK_MIGRATIONS_TABLE): string {\n const L = quoteTable(dialect, lockTableName(table))\n switch (dialect) {\n case 'postgres':\n return `CREATE TABLE IF NOT EXISTS ${L} (\n \"id\" smallint PRIMARY KEY,\n \"locked_at\" timestamptz,\n \"locked_by\" text\n );\n INSERT INTO ${L} (\"id\") VALUES (1) ON CONFLICT DO NOTHING;`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS ${L} (\n \"id\" integer PRIMARY KEY,\n \"locked_at\" text,\n \"locked_by\" text\n );\n INSERT OR IGNORE INTO ${L} (\"id\") VALUES (1);`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS ${L} (\n \\`id\\` smallint PRIMARY KEY,\n \\`locked_at\\` timestamp NULL,\n \\`locked_by\\` text\n );\n INSERT IGNORE INTO ${L} (\\`id\\`) VALUES (1);`\n }\n}\n","import type { Dialect, SchemaSnapshot } from '../snapshot/types'\nimport type { MigrationAdapter, MigrationBookkeeping, MigrationRow } from './adapter'\n\n/**\n * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-\n * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as\n * test-only stubs — the real DB-bound semantics are validated in db-pg's\n * integration tests, not here.\n */\nexport class MemoryMigrationAdapter implements MigrationAdapter {\n readonly dialect: Dialect = 'postgres'\n\n private rows: MigrationRow[] = []\n private locked: { by: string; at: string } | null = null\n private appliedSql: string[] = []\n private currentSchema: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n\n async ensureMigrationTables(): Promise<void> {\n /* no-op */\n }\n\n async listApplied(): Promise<MigrationRow[]> {\n return [...this.rows]\n }\n\n async recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void> {\n this.rows.push({ ...row, appliedAt: new Date().toISOString() })\n }\n\n async removeApplied(id: string): Promise<void> {\n this.rows = this.rows.filter((r) => r.id !== id)\n }\n\n async acquireLock(owner: string): Promise<boolean> {\n if (this.locked) return false\n this.locked = { by: owner, at: new Date().toISOString() }\n return true\n }\n\n async releaseLock(): Promise<void> {\n this.locked = null\n }\n\n async applySqlInTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async applyMigrationInTx(sql: string, bookkeeping: MigrationBookkeeping | null): Promise<void> {\n this.appliedSql.push(sql)\n if (bookkeeping && 'record' in bookkeeping) await this.recordApplied(bookkeeping.record)\n else if (bookkeeping) await this.removeApplied(bookkeeping.remove)\n }\n\n async applySqlNoTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async introspect(): Promise<SchemaSnapshot> {\n return this.currentSchema\n }\n\n async close(): Promise<void> {\n /* no-op */\n }\n\n /** Test-only setter — let drift tests stage a \"live\" schema state. */\n __setIntrospectedSchema(snap: SchemaSnapshot): void {\n this.currentSchema = snap\n }\n\n /** Test-only inspector — what SQL we received. */\n __appliedSql(): readonly string[] {\n return this.appliedSql\n }\n}\n","import type {\n ColumnSnapshot,\n EnumSnapshot,\n ForeignKeySnapshot,\n FkAction,\n IndexSnapshot,\n SchemaSnapshot,\n PolicySnapshot,\n TableSnapshot,\n ViewSnapshot,\n} from '../snapshot/types'\nimport type { IntrospectPgOptions, PgQueryRunner } from './introspect-types'\n\nconst DEFAULT_EXCLUDED = ['kick_migrations', 'kick_migrations_lock']\n\ninterface ColumnRow {\n column_name: string\n is_identity: 'YES' | 'NO'\n identity_generation: 'ALWAYS' | 'BY DEFAULT' | null\n generation_expression: string | null\n /** pg_attribute.attgenerated: 's' stored, 'v' virtual, '' not generated. */\n attgenerated: string\n /** col_description(): the column's comment, or null. */\n comment: string | null\n data_type: string\n udt_name: string\n is_nullable: 'YES' | 'NO'\n column_default: string | null\n character_maximum_length: number | null\n numeric_precision: number | null\n numeric_scale: number | null\n /**\n * The sequence this column OWNS, or null. `pg_get_serial_sequence` answers\n * only for an owned sequence — the thing `serial` creates.\n */\n owned_sequence: string | null\n /**\n * The sequence this column's DEFAULT actually draws from, or null.\n *\n * Ownership and use are separate facts, and `SET DEFAULT nextval(...)` can\n * repoint a former serial at another sequence while it keeps owning its\n * original one. Both are normalised through `regclass::text` so they are\n * comparable — `pg_get_serial_sequence` always schema-qualifies while a\n * regclass renders bare when the object is on the search path.\n */\n default_sequence: string | null\n}\n\ninterface EnumRow {\n enum_name: string\n enum_value: string\n}\n\ninterface IndexRow {\n index_name: string\n /** The column, or for an expression key part its SQL text. */\n key: string\n is_expression: boolean\n /** True for an INCLUDE column rather than a key part. */\n is_included: boolean\n is_unique: boolean\n is_primary: boolean\n method: string\n predicate: string | null\n}\n\ninterface FkRow {\n constraint_name: string\n column_name: string\n ref_table: string\n ref_column: string\n delete_rule: string\n update_rule: string\n}\n\nexport async function introspectPg(\n client: PgQueryRunner,\n opts: IntrospectPgOptions = {},\n): Promise<SchemaSnapshot> {\n const schema = opts.schema ?? 'public'\n const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED\n\n const tableRows = await client.query<{ table_name: string; comment: string | null }>(\n `SELECT table_name,\n obj_description(format('%I.%I', table_schema, table_name)::regclass, 'pg_class')\n AS comment\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type = 'BASE TABLE'\n ORDER BY table_name`,\n [schema],\n )\n\n const tables: Record<string, TableSnapshot> = {}\n for (const t of tableRows.rows) {\n if (excluded.includes(t.table_name)) continue\n tables[t.table_name] = {\n name: t.table_name,\n columns: await readColumns(client, schema, t.table_name),\n indexes: await readIndexes(client, schema, t.table_name),\n foreignKeys: await readForeignKeys(client, schema, t.table_name),\n checks: [],\n ...(t.comment !== null ? { comment: t.comment } : {}),\n ...(await readRowLevelSecurity(client, schema, t.table_name)),\n }\n }\n const enums = await readEnums(client, schema)\n\n const snapshot: SchemaSnapshot = { version: 1, dialect: 'postgres', tables }\n const views = await readViews(client, schema)\n if (Object.keys(views).length > 0) snapshot.views = views\n // Only carry `enums` when the database has some, matching what\n // `extractSnapshot` does — an empty `enums: {}` would change the serialized\n // snapshot and invalidate every existing migration hash.\n if (Object.keys(enums).length > 0) snapshot.enums = enums\n return snapshot\n}\n\n/** A table's row-level security switch and its policies, as snapshot fields. */\nasync function readRowLevelSecurity(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<Pick<TableSnapshot, 'rls' | 'policies'>> {\n const flags = await client.query<{ on: boolean; force: boolean }>(\n `SELECT relrowsecurity AS on, relforcerowsecurity AS force FROM pg_class\n WHERE oid = format('%I.%I', $1::text, $2::text)::regclass`,\n [schema, table],\n )\n const rows = await client.query<{\n name: string\n permissive: string\n roles: string[]\n cmd: string\n qual: string | null\n with_check: string | null\n }>(\n `SELECT policyname AS name, permissive, array_to_json(roles) AS roles, cmd, qual, with_check\n FROM pg_policies WHERE schemaname = $1 AND tablename = $2 ORDER BY policyname`,\n [schema, table],\n )\n const out: Pick<TableSnapshot, 'rls' | 'policies'> = {}\n if (flags.rows[0]?.on) out.rls = flags.rows[0].force ? { force: true } : {}\n if (rows.rows.length > 0) {\n out.policies = rows.rows.map((r) => ({\n name: r.name,\n as: r.permissive === 'RESTRICTIVE' ? 'restrictive' : 'permissive',\n command: r.cmd.toLowerCase() as PolicySnapshot['command'],\n to: r.roles,\n ...(r.qual !== null ? { using: r.qual } : {}),\n ...(r.with_check !== null ? { withCheck: r.with_check } : {}),\n }))\n }\n return out\n}\n\n/** Views and materialized views, with their SQL, columns and (materialized) indexes. */\nasync function readViews(\n client: PgQueryRunner,\n schema: string,\n): Promise<Record<string, ViewSnapshot>> {\n const rows = await client.query<{ name: string; definition: string; materialized: boolean }>(\n `SELECT viewname AS name, definition, false AS materialized\n FROM pg_views WHERE schemaname = $1\n UNION ALL\n SELECT matviewname, definition, true FROM pg_matviews WHERE schemaname = $1\n ORDER BY name`,\n [schema],\n )\n const out: Record<string, ViewSnapshot> = {}\n for (const r of rows.rows) {\n const cols = await client.query<{ name: string; type: string; notnull: boolean }>(\n `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type,\n a.attnotnull AS notnull\n FROM pg_attribute a\n WHERE a.attrelid = format('%I.%I', $1::text, $2::text)::regclass\n AND a.attnum > 0 AND NOT a.attisdropped\n ORDER BY a.attnum`,\n [schema, r.name],\n )\n const columns: Record<string, ColumnSnapshot> = {}\n for (const c of cols.rows) {\n columns[c.name] = {\n name: c.name,\n type: viewColumnType(c.type),\n nullable: !c.notnull,\n default: null,\n primaryKey: false,\n }\n }\n const v: ViewSnapshot = {\n name: r.name,\n definition: r.definition.trim().replace(/;$/, ''),\n columns,\n }\n if (r.materialized) {\n v.materialized = true\n const indexes = await readIndexes(client, schema, r.name)\n if (indexes.length > 0) v.indexes = indexes\n }\n out[r.name] = v\n }\n return out\n}\n\n/** `format_type()` spelling → the DSL's, for the types a view usually returns. */\nfunction viewColumnType(type: string): string {\n return type\n .replace(/^character varying/, 'varchar')\n .replace(/^character\\b/, 'char')\n .replace(/^timestamp(\\(\\d+\\))? without time zone$/, 'timestamp')\n .replace(/^timestamp(\\(\\d+\\))? with time zone$/, 'timestamptz')\n .replace(/^time(\\(\\d+\\))? without time zone$/, 'time')\n .replace(/,(\\S)/g, ', $1')\n}\n\n/**\n * Read every enum type declared in the schema.\n *\n * Enum columns were already introspected as their type name — `status\n * enum_grading_systems_type` — but the type itself was never read, so a\n * generated schema referenced 37 types it did not declare and the renderer had\n * nothing to build them from (#644). `enumsortorder` is what preserves the\n * declaration order, which for an enum is part of its meaning: comparisons and\n * ORDER BY follow it.\n */\nasync function readEnums(\n client: PgQueryRunner,\n schema: string,\n): Promise<Record<string, EnumSnapshot>> {\n const rows = await client.query<EnumRow>(\n `SELECT t.typname AS enum_name, e.enumlabel AS enum_value\n FROM pg_type t\n JOIN pg_enum e ON e.enumtypid = t.oid\n JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = $1\n ORDER BY t.typname, e.enumsortorder`,\n [schema],\n )\n\n const out: Record<string, EnumSnapshot> = {}\n for (const r of rows.rows) {\n const entry = out[r.enum_name]\n if (entry) (entry.values as string[]).push(r.enum_value)\n else out[r.enum_name] = { name: r.enum_name, values: [r.enum_value] }\n }\n return out\n}\n\nasync function readColumns(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<TableSnapshot['columns']> {\n const cols = await client.query<ColumnRow>(\n `SELECT column_name, data_type, udt_name, is_nullable, column_default,\n character_maximum_length, numeric_precision, numeric_scale,\n pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name)\n ::regclass::text AS owned_sequence,\n to_regclass(\n (regexp_match(column_default, 'nextval\\\\(''([^'']+)''(::regclass)?\\\\)'))[1]\n )::text AS default_sequence,\n is_identity, identity_generation, generation_expression,\n (SELECT a.attgenerated FROM pg_attribute a\n WHERE a.attrelid = format('%I.%I', table_schema, table_name)::regclass\n AND a.attname = column_name) AS attgenerated,\n col_description(\n format('%I.%I', table_schema, table_name)::regclass, ordinal_position::int\n ) AS comment\n FROM information_schema.columns\n WHERE table_schema = $1 AND table_name = $2\n ORDER BY ordinal_position`,\n [schema, table],\n )\n\n const pkCols = await client.query<{ column_name: string }>(\n `SELECT k.column_name\n FROM information_schema.table_constraints c\n JOIN information_schema.key_column_usage k\n ON k.constraint_name = c.constraint_name\n AND k.table_schema = c.table_schema\n WHERE c.table_schema = $1 AND c.table_name = $2 AND c.constraint_type = 'PRIMARY KEY'\n ORDER BY k.ordinal_position`,\n [schema, table],\n )\n const pkSet = new Set(pkCols.rows.map((r) => r.column_name))\n\n const out: TableSnapshot['columns'] = {}\n for (const r of cols.rows) {\n const isSerial = isSerialColumn(r)\n out[r.column_name] = {\n name: r.column_name,\n type: isSerial ? serialTypeFor(r) : normalizeType(r),\n nullable: r.is_nullable === 'YES',\n // serial columns own their nextval default; collapse it to keep round-\n // trips (DSL → emit → introspect) idempotent.\n default: isSerial ? null : normalizeDefault(r.column_default),\n primaryKey: pkSet.has(r.column_name),\n }\n if (r.is_identity === 'YES') {\n out[r.column_name].identity = r.identity_generation === 'ALWAYS' ? 'always' : 'byDefault'\n }\n if (r.comment !== null) out[r.column_name].comment = r.comment\n if (r.attgenerated && r.generation_expression) {\n out[r.column_name].generated = {\n expression: r.generation_expression,\n stored: r.attgenerated === 's',\n }\n }\n }\n return out\n}\n\n/**\n * Is this column a `serial`, as opposed to an integer that happens to default\n * from a sequence?\n *\n * A `nextval(...)` default alone does not answer it. `CREATE SEQUENCE s` then\n * `ALTER TABLE t ALTER c SET DEFAULT nextval('s')` produces exactly that\n * default while the sequence is standalone — shared between tables, or kept\n * deliberately independent of the column's lifetime.\n *\n * Treating those as `serial` was wrong twice over: `serial` implies NOT NULL,\n * so a nullable column came back non-nullable, and the default is collapsed to\n * null on the way out, so the link to the sequence was dropped entirely (#649).\n *\n * Three extra conditions settle it:\n *\n * - The column OWNS a sequence — what `serial` creates and what `DROP TABLE`\n * takes with it. `pg_get_serial_sequence` answers only for those.\n * - It owns the sequence its default actually draws from. Ownership and use are\n * separate facts: `ALTER COLUMN id SET DEFAULT nextval('shared_ids')` repoints\n * a former serial at another sequence while it keeps owning its original one.\n * Calling that `serial` discards the active default and would silently point\n * the column back at the sequence it no longer uses.\n * - The column is NOT NULL. An owned sequence whose column has had its NOT NULL\n * dropped is no longer expressible as `serial`, and restoring the constraint\n * on the next migration would reject the rows that made someone drop it.\n */\nfunction isSerialColumn(r: ColumnRow): boolean {\n if (!r.column_default) return false\n if (!r.column_default.startsWith('nextval(')) return false\n if (r.owned_sequence === null) return false\n if (r.owned_sequence !== r.default_sequence) return false\n if (r.is_nullable === 'YES') return false\n return r.udt_name === 'int2' || r.udt_name === 'int4' || r.udt_name === 'int8'\n}\n\nfunction serialTypeFor(r: ColumnRow): string {\n if (r.udt_name === 'int8') return 'bigserial'\n if (r.udt_name === 'int2') return 'smallserial'\n return 'serial'\n}\n\nfunction normalizeType(r: ColumnRow): string {\n // Map PG's information_schema data_type back to the DSL surface.\n if (r.data_type === 'character varying') {\n return r.character_maximum_length ? `varchar(${r.character_maximum_length})` : 'varchar'\n }\n if (r.data_type === 'character') {\n return r.character_maximum_length ? `char(${r.character_maximum_length})` : 'char(1)'\n }\n if (r.data_type === 'numeric') {\n if (r.numeric_precision !== null && r.numeric_scale !== null) {\n return `numeric(${r.numeric_precision}, ${r.numeric_scale})`\n }\n if (r.numeric_precision !== null) return `numeric(${r.numeric_precision})`\n return 'numeric'\n }\n if (r.data_type === 'timestamp with time zone') return 'timestamptz'\n if (r.data_type === 'timestamp without time zone') return 'timestamp'\n if (r.data_type === 'time without time zone') return 'time'\n if (r.data_type === 'double precision') return 'double precision'\n if (r.data_type === 'USER-DEFINED') return r.udt_name\n if (r.data_type === 'ARRAY') {\n // For an array, `data_type` is just 'ARRAY' and the element lives in\n // `udt_name` as `_<pg internal name>`. Those internal names are not the\n // DSL's: int4, float8, bool, bpchar. Stripping the underscore alone gave\n // `int4[]`, which then matched no column helper and rendered as\n // text(/* TODO */) — the array and its element type both lost (#648).\n return `${dslTypeForUdt(r.udt_name.replace(/^_/, ''))}[]`\n }\n // bigint, integer, smallint, text, boolean, date, json, jsonb, bytea, uuid,\n // interval, etc — pass through as data_type when it matches the DSL.\n return r.data_type\n}\n\n/**\n * PG's internal type name → the name the schema DSL uses.\n *\n * Only needed for arrays: for a scalar column `information_schema` reports a\n * usable `data_type` ('integer', 'boolean'), but for an array it reports\n * 'ARRAY' and leaves the element in `udt_name`, which is always the internal\n * spelling. Anything unmapped passes through — text, uuid, json, jsonb, bytea,\n * numeric, interval and every user-defined type already share both names.\n */\nconst UDT_TO_DSL: Record<string, string> = {\n int2: 'smallint',\n int4: 'integer',\n int8: 'bigint',\n float4: 'real',\n float8: 'double precision',\n bool: 'boolean',\n bpchar: 'char',\n // Element length/precision is not reported for array columns, so these come\n // back unparameterised — `varchar[]`, not `varchar(255)[]`.\n varchar: 'varchar',\n timestamp: 'timestamp',\n timestamptz: 'timestamptz',\n time: 'time',\n date: 'date',\n}\n\nfunction dslTypeForUdt(udt: string): string {\n return UDT_TO_DSL[udt] ?? udt\n}\n\nfunction normalizeDefault(raw: string | null): string | null {\n if (!raw) return null\n // Strip PG's :: cast suffixes: 'true'::boolean → true, 'foo'::text → 'foo'\n const stripped = raw.replace(/::[\\w\" ]+(\\([^)]*\\))?$/, '')\n // Normalize CURRENT_TIMESTAMP / now() to the DSL canonical token.\n const upper = stripped.toUpperCase()\n if (upper === 'NOW()' || upper === 'CURRENT_TIMESTAMP') return 'CURRENT_TIMESTAMP'\n if (upper === 'GEN_RANDOM_UUID()') return 'gen_random_uuid()'\n // 'foo' literal → foo. true / false / numeric pass through.\n return stripped.replace(/^'(.*)'$/, '$1')\n}\n\nasync function readIndexes(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<IndexSnapshot[]> {\n const rows = await client.query<IndexRow>(\n `SELECT i.relname AS index_name,\n COALESCE(a.attname, pg_get_indexdef(ix.indexrelid, k.ord::int, true)) AS key,\n k.attnum = 0 AS is_expression,\n k.ord > ix.indnkeyatts AS is_included,\n ix.indisunique AS is_unique,\n ix.indisprimary AS is_primary,\n am.amname AS method,\n pg_get_expr(ix.indpred, ix.indrelid, true) AS predicate\n FROM pg_class t\n JOIN pg_namespace n ON n.oid = t.relnamespace\n JOIN pg_index ix ON ix.indrelid = t.oid\n JOIN pg_class i ON i.oid = ix.indexrelid\n JOIN pg_am am ON am.oid = i.relam\n JOIN unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND k.attnum <> 0\n WHERE n.nspname = $1 AND t.relname = $2 AND t.relkind IN ('r', 'm')\n ORDER BY i.relname, k.ord`,\n [schema, table],\n )\n\n // Group rows by index_name, preserve key order.\n type Tagged = IndexSnapshot & { _isPrimary: boolean }\n const byIndex = new Map<string, Tagged>()\n for (const r of rows.rows) {\n let entry = byIndex.get(r.index_name)\n if (!entry) {\n entry = { name: r.index_name, columns: [], unique: r.is_unique, _isPrimary: r.is_primary }\n if (r.method !== 'btree') entry.using = r.method\n if (r.predicate) entry.where = r.predicate\n byIndex.set(r.index_name, entry)\n }\n if (r.is_included) entry.include = [...(entry.include ?? []), r.key]\n else entry.columns.push(r.is_expression ? `(${r.key})` : r.key)\n }\n\n // Drop PK-backing indexes — primaryKey is recorded on the column itself.\n return [...byIndex.values()]\n .filter((i) => !i._isPrimary)\n .map(({ _isPrimary, ...rest }) => rest)\n .toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nasync function readForeignKeys(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<ForeignKeySnapshot[]> {\n const rows = await client.query<FkRow>(\n `SELECT tc.constraint_name,\n kcu.column_name,\n ccu.table_name AS ref_table,\n ccu.column_name AS ref_column,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON kcu.constraint_name = tc.constraint_name\n AND kcu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = rc.unique_constraint_name\n AND ccu.constraint_schema = rc.unique_constraint_schema\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, table],\n )\n\n const byName = new Map<string, ForeignKeySnapshot>()\n for (const r of rows.rows) {\n let fk = byName.get(r.constraint_name)\n if (!fk) {\n fk = {\n name: r.constraint_name,\n columns: [],\n refTable: r.ref_table,\n refColumns: [],\n onDelete: mapFkAction(r.delete_rule),\n onUpdate: mapFkAction(r.update_rule),\n }\n byName.set(r.constraint_name, fk)\n }\n fk.columns.push(r.column_name)\n fk.refColumns.push(r.ref_column)\n }\n return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nfunction mapFkAction(raw: string): FkAction {\n switch (raw.toUpperCase()) {\n case 'CASCADE':\n return 'cascade'\n case 'RESTRICT':\n return 'restrict'\n case 'SET NULL':\n return 'set_null'\n case 'SET DEFAULT':\n return 'set_default'\n case 'NO ACTION':\n default:\n return 'no_action'\n }\n}\n","import type {\n ColumnSnapshot,\n ForeignKeySnapshot,\n FkAction,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n ViewSnapshot,\n} from '../snapshot/types'\n\nconst DEFAULT_EXCLUDED = ['kick_migrations', 'kick_migrations_lock']\n\n/**\n * Minimal better-sqlite3 surface introspection needs (sync `.all()`).\n *\n * `all` is deliberately NOT method-generic: better-sqlite3 v12's own\n * `Statement.all(...params): Result[]` is non-generic, so a generic\n * method here would make a real `Database` instance structurally\n * incompatible (callers had to cast). Row typing happens inside this\n * module via per-call assertions instead.\n */\nexport interface SqliteIntrospectDb {\n prepare(sql: string): { all(...params: unknown[]): unknown[] }\n}\n\nexport interface IntrospectSqliteOptions {\n excludeTables?: string[]\n}\n\ninterface TableInfoRow {\n cid: number\n name: string\n type: string\n notnull: 0 | 1\n dflt_value: string | null\n pk: number\n /** table_xinfo: 2 a virtual generated column, 3 a stored one. */\n hidden?: number\n}\n\ninterface IndexListRow {\n seq: number\n name: string\n unique: 0 | 1\n origin: string // 'c' = CREATE INDEX, 'u' = UNIQUE constraint, 'pk' = primary key\n partial: 0 | 1\n}\n\ninterface IndexInfoRow {\n seqno: number\n cid: number\n name: string | null\n}\n\ninterface FkListRow {\n id: number\n seq: number\n table: string\n from: string\n to: string\n on_update: string\n on_delete: string\n match: string\n}\n\n/** One query introspection needs: the caller runs it and sends back the rows. */\ntype Step = { sql: string; params: unknown[] }\ntype Steps<T> = Generator<Step, T, unknown[]>\n\n/** Run a query; the rows come back from whoever drives the walk. */\nfunction* rows<T>(sql: string, ...params: unknown[]): Steps<T[]> {\n return (yield { sql, params }) as T[]\n}\n\n/**\n * The introspection walk, written once: it yields each query it needs, so the\n * same code runs over a sync handle (better-sqlite3, `bun:sqlite`) and an\n * async driver (libsql, D1). Counts are read with `Number()` because some\n * drivers return them as bigints.\n */\nfunction* introspectSteps(opts: IntrospectSqliteOptions): Steps<SchemaSnapshot> {\n const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED\n // `_cf_*` tables are Cloudflare D1's own.\n const tableRows = yield* rows<{ name: string }>(\n `SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\'\n ORDER BY name`,\n )\n\n const tables: Record<string, TableSnapshot> = {}\n for (const { name } of tableRows) {\n if (excluded.includes(name)) continue\n tables[name] = {\n name,\n columns: yield* readColumns(name),\n indexes: yield* readIndexes(name),\n foreignKeys: yield* readForeignKeys(name),\n checks: [],\n }\n }\n const snapshot: SchemaSnapshot = { version: 1, dialect: 'sqlite', tables }\n const viewRows = yield* rows<{ name: string; sql: string }>(\n `SELECT name, sql FROM sqlite_master WHERE type = 'view' ORDER BY name`,\n )\n if (viewRows.length > 0) {\n const views: Record<string, ViewSnapshot> = {}\n for (const v of viewRows) {\n views[v.name] = {\n name: v.name,\n definition: viewSelect(v.sql),\n columns: yield* readColumns(v.name),\n }\n }\n snapshot.views = views\n }\n return snapshot\n}\n\n/**\n * Read a live SQLite database into a {@link SchemaSnapshot} via\n * `sqlite_master` + `PRAGMA` walks. Type strings come back as the\n * column's *declared* affinity (`TEXT`, `INTEGER`, …) lowercased — SQLite\n * doesn't preserve the original DSL type (a `uuid()` column reads back as\n * `text`), so this is primarily for `kick db introspect` (reverse-engineer\n * a schema), not byte-exact drift against a code-first snapshot.\n */\nexport function introspectSqlite(\n db: SqliteIntrospectDb,\n opts: IntrospectSqliteOptions = {},\n): SchemaSnapshot {\n const walk = introspectSteps(opts)\n let step = walk.next()\n while (!step.done) step = walk.next(db.prepare(step.value.sql).all(...step.value.params))\n return step.value\n}\n\n/**\n * {@link introspectSqlite} over an async driver (libsql/Turso, Cloudflare D1):\n * `query` runs one statement and resolves with its rows.\n */\nexport async function introspectSqliteAsync(\n query: (sql: string, params: unknown[]) => Promise<unknown[]>,\n opts: IntrospectSqliteOptions = {},\n): Promise<SchemaSnapshot> {\n const walk = introspectSteps(opts)\n let step = walk.next()\n while (!step.done) step = walk.next(await query(step.value.sql, step.value.params))\n return step.value\n}\n\n/**\n * The SELECT of a `CREATE VIEW` statement, which SQLite stores whole: past\n * `CREATE [TEMP] VIEW [IF NOT EXISTS]`, the (possibly quoted, possibly\n * qualified) name and an optional column list — a quoted name may contain `as`.\n */\nexport function viewSelect(statement: string): string {\n let i = 0\n const s = statement\n const space = () => {\n while (i < s.length && /\\s/.test(s[i]!)) i++\n }\n const word = (w: string) => {\n space()\n if (s.slice(i, i + w.length).toUpperCase() === w && !/\\w/.test(s[i + w.length] ?? '')) {\n i += w.length\n return true\n }\n return false\n }\n const close: Record<string, string> = { '\"': '\"', '`': '`', '[': ']', \"'\": \"'\" }\n const identifier = () => {\n space()\n const end = close[s[i]!]\n if (end) {\n // Quoted: up to the closing quote; a doubled one is part of the name.\n for (i++; i < s.length; i++) {\n if (s[i] === end) {\n if (s[i + 1] === end && end !== ']') i++\n else return void i++\n }\n }\n return\n }\n while (i < s.length && /[\\w$]/.test(s[i]!)) i++\n }\n word('CREATE')\n if (!word('TEMPORARY')) word('TEMP')\n word('VIEW')\n if (word('IF')) {\n word('NOT')\n word('EXISTS')\n }\n identifier()\n space()\n if (s[i] === '.') {\n i++\n identifier()\n }\n space()\n if (s[i] === '(') {\n // The column list: up to its closing parenthesis, skipping quoted names.\n for (let depth = 0; i < s.length; i++) {\n const end = close[s[i]!]\n if (end) {\n // A quoted name: up to its closing quote; a doubled one is part of it.\n for (i++; i < s.length; i++) {\n if (s[i] !== end) continue\n if (s[i + 1] === end && end !== ']') i++\n else break\n }\n continue\n }\n if (s[i] === '(') depth++\n else if (s[i] === ')' && --depth === 0) {\n i++\n break\n }\n }\n }\n word('AS')\n return s.slice(i).trim().replace(/;$/, '')\n}\n\nfunction* readColumns(table: string): Steps<Record<string, ColumnSnapshot>> {\n // table_xinfo, unlike table_info, lists generated columns too.\n const list = yield* rows<TableInfoRow>(`PRAGMA table_xinfo(${quote(table)})`)\n const out: Record<string, ColumnSnapshot> = {}\n let createSql: string | undefined\n for (const r of list) {\n out[r.name] = {\n name: r.name,\n // SQLite reports a generated column's type with the clause appended.\n type: normalizeType(r.type.replace(/\\s+GENERATED\\s+ALWAYS\\b.*$/i, '')),\n nullable: Number(r.notnull) === 0,\n default: r.dflt_value,\n primaryKey: Number(r.pk) > 0,\n }\n const hidden = Number(r.hidden ?? 0)\n if (hidden === 2 || hidden === 3) {\n createSql ??= (yield* rows<{ sql: string }>(\n `SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,\n table,\n ))[0]?.sql\n out[r.name].generated = {\n expression: generatedExpression(createSql ?? '', r.name),\n stored: hidden === 3,\n }\n }\n }\n return out\n}\n\nfunction* readIndexes(table: string): Steps<IndexSnapshot[]> {\n const list = yield* rows<IndexListRow>(`PRAGMA index_list(${quote(table)})`)\n const out: IndexSnapshot[] = []\n for (const idx of list) {\n // Skip auto-indexes SQLite creates for UNIQUE / PK constraints — those\n // belong to the column/constraint definitions, not standalone indexes.\n if (idx.origin !== 'c') continue\n const cols = (yield* rows<IndexInfoRow>(`PRAGMA index_info(${quote(idx.name)})`))\n .filter((c) => c.name !== null)\n .map((c) => c.name as string)\n const entry: IndexSnapshot = { name: idx.name, columns: cols, unique: Number(idx.unique) === 1 }\n if (Number(idx.partial) === 1) {\n // SQLite keeps only the statement; WHERE is its last clause.\n const row = (yield* rows<{ sql: string | null }>(\n `SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?`,\n idx.name,\n ))[0]\n const where = row?.sql?.match(/\\bWHERE\\b([\\s\\S]*)$/i)?.[1].trim()\n if (where) entry.where = where\n }\n out.push(entry)\n }\n return out\n}\n\nfunction* readForeignKeys(table: string): Steps<ForeignKeySnapshot[]> {\n const list = yield* rows<FkListRow>(`PRAGMA foreign_key_list(${quote(table)})`)\n // Group multi-column FKs by their `id`.\n const byId = new Map<number, FkListRow[]>()\n for (const r of list) {\n const g = byId.get(Number(r.id)) ?? []\n g.push(r)\n byId.set(Number(r.id), g)\n }\n const out: ForeignKeySnapshot[] = []\n for (const [id, group] of byId) {\n group.sort((a, b) => Number(a.seq) - Number(b.seq))\n const first = group[0]\n out.push({\n // SQLite doesn't name FKs — synthesize a stable name.\n name: `${table}_${group.map((g) => g.from).join('_')}_fk_${id}`,\n columns: group.map((g) => g.from),\n refTable: first.table,\n refColumns: group.map((g) => g.to),\n onDelete: mapFkAction(first.on_delete),\n onUpdate: mapFkAction(first.on_update),\n })\n }\n return out\n}\n\nfunction mapFkAction(action: string): FkAction {\n switch (action.toUpperCase()) {\n case 'CASCADE':\n return 'cascade'\n case 'RESTRICT':\n return 'restrict'\n case 'SET NULL':\n return 'set_null'\n case 'SET DEFAULT':\n return 'set_default'\n default:\n return 'no_action'\n }\n}\n\n/** Lowercase the declared type, preserving any `(length)` qualifier. */\nfunction normalizeType(declared: string): string {\n return declared.trim().toLowerCase() || 'text'\n}\n\n/** Quote a SQLite identifier for interpolation into a PRAGMA (no binding). */\nfunction quote(name: string): string {\n return '\"' + name.replace(/\"/g, '\"\"') + '\"'\n}\n\n/**\n * The expression of a generated column, read out of the table's CREATE\n * statement: the balanced parentheses after `GENERATED ALWAYS AS` in that\n * column's definition. Empty when it can't be found.\n */\nfunction generatedExpression(createSql: string, column: string): string {\n const name = column.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const start = new RegExp(\n `[\"\\`\\\\[]?${name}[\"\\`\\\\]]?\\\\s[^,]*?GENERATED\\\\s+ALWAYS\\\\s+AS\\\\s*\\\\(`,\n 'i',\n ).exec(createSql)\n if (!start) return ''\n let depth = 1\n const from = start.index + start[0].length\n for (let i = from; i < createSql.length; i++) {\n if (createSql[i] === '(') depth++\n else if (createSql[i] === ')' && --depth === 0) return createSql.slice(from, i).trim()\n }\n return ''\n}\n","import type {\n ColumnSnapshot,\n ForeignKeySnapshot,\n FkAction,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n ViewSnapshot,\n} from '../snapshot/types'\n\nconst DEFAULT_EXCLUDED = ['kick_migrations', 'kick_migrations_lock']\n\n/** Minimal mysql2 surface introspection needs. Returns `[rows, fields]`. */\nexport interface MysqlIntrospectDb {\n query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<[R, unknown]>\n}\n\nexport interface IntrospectMysqlOptions {\n excludeTables?: string[]\n}\n\ninterface ColumnRow {\n COLUMN_NAME: string\n DATA_TYPE: string\n COLUMN_TYPE: string\n IS_NULLABLE: 'YES' | 'NO'\n COLUMN_DEFAULT: string | null\n COLUMN_KEY: string\n /** '' when the column has none: MySQL doesn't distinguish no comment from an empty one. */\n COLUMN_COMMENT: string\n EXTRA: string\n}\n\ninterface IndexRow {\n INDEX_NAME: string\n /** Null for a functional key part. */\n COLUMN_NAME: string | null\n EXPRESSION: string | null\n NON_UNIQUE: number\n SEQ_IN_INDEX: number\n INDEX_TYPE: string\n}\n\ninterface FkRow {\n CONSTRAINT_NAME: string\n COLUMN_NAME: string\n REF_TABLE: string\n REF_COLUMN: string\n DELETE_RULE: string\n UPDATE_RULE: string\n ORDINAL_POSITION: number\n}\n\nasync function rows<R>(db: MysqlIntrospectDb, sql: string, params: unknown[]): Promise<R[]> {\n const [result] = await db.query<R[]>(sql, params)\n return result\n}\n\n/**\n * Read the current MySQL database into a {@link SchemaSnapshot} via\n * `information_schema`. Types come back as the column's declared\n * `COLUMN_TYPE` (`varchar(200)`, `tinyint(1)`, …) lowercased — MySQL\n * doesn't preserve the original DSL type, so this powers `kick db\n * introspect` rather than byte-exact drift against a code-first snapshot.\n */\nexport async function introspectMysql(\n db: MysqlIntrospectDb,\n opts: IntrospectMysqlOptions = {},\n): Promise<SchemaSnapshot> {\n const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED\n\n const tableRows = await rows<{ TABLE_NAME: string; TABLE_COMMENT: string }>(\n db,\n `SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.TABLES\n WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'\n ORDER BY TABLE_NAME`,\n [],\n )\n\n const tables: Record<string, TableSnapshot> = {}\n for (const t of tableRows) {\n if (excluded.includes(t.TABLE_NAME)) continue\n tables[t.TABLE_NAME] = {\n name: t.TABLE_NAME,\n columns: await readColumns(db, t.TABLE_NAME),\n indexes: await readIndexes(db, t.TABLE_NAME),\n foreignKeys: await readForeignKeys(db, t.TABLE_NAME),\n checks: [],\n ...(t.TABLE_COMMENT ? { comment: t.TABLE_COMMENT } : {}),\n }\n }\n const snapshot: SchemaSnapshot = { version: 1, dialect: 'mysql', tables }\n const viewRows = await rows<{ TABLE_NAME: string; VIEW_DEFINITION: string }>(\n db,\n `SELECT TABLE_NAME, VIEW_DEFINITION FROM information_schema.VIEWS\n WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME`,\n [],\n )\n if (viewRows.length > 0) {\n const views: Record<string, ViewSnapshot> = {}\n for (const v of viewRows) {\n views[v.TABLE_NAME] = {\n name: v.TABLE_NAME,\n definition: v.VIEW_DEFINITION,\n columns: await readColumns(db, v.TABLE_NAME),\n }\n }\n snapshot.views = views\n }\n return snapshot\n}\n\nasync function readColumns(\n db: MysqlIntrospectDb,\n table: string,\n): Promise<Record<string, ColumnSnapshot>> {\n const cols = await rows<ColumnRow>(\n db,\n `SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA,\n COLUMN_COMMENT\n FROM information_schema.COLUMNS\n WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?\n ORDER BY ORDINAL_POSITION`,\n [table],\n )\n const out: Record<string, ColumnSnapshot> = {}\n for (const c of cols) {\n out[c.COLUMN_NAME] = {\n name: c.COLUMN_NAME,\n type: normalizeType(c),\n nullable: c.IS_NULLABLE === 'YES',\n default: c.COLUMN_DEFAULT,\n primaryKey: c.COLUMN_KEY === 'PRI',\n ...(c.COLUMN_COMMENT ? { comment: c.COLUMN_COMMENT } : {}),\n }\n }\n return out\n}\n\nasync function readIndexes(db: MysqlIntrospectDb, table: string): Promise<IndexSnapshot[]> {\n const stats = await rows<IndexRow>(\n db,\n `SELECT INDEX_NAME, COLUMN_NAME, EXPRESSION, NON_UNIQUE, SEQ_IN_INDEX, INDEX_TYPE\n FROM information_schema.STATISTICS\n WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME <> 'PRIMARY'\n ORDER BY INDEX_NAME, SEQ_IN_INDEX`,\n [table],\n )\n const byName = new Map<string, IndexSnapshot>()\n for (const r of stats) {\n let e = byName.get(r.INDEX_NAME)\n if (!e) {\n e = { name: r.INDEX_NAME, columns: [], unique: r.NON_UNIQUE === 0 }\n if (r.INDEX_TYPE === 'HASH') e.using = 'hash'\n byName.set(r.INDEX_NAME, e)\n }\n // A functional key part has no column; its expression is in EXPRESSION.\n e.columns.push(r.COLUMN_NAME ?? `(${r.EXPRESSION})`)\n }\n return [...byName.values()]\n}\n\nasync function readForeignKeys(\n db: MysqlIntrospectDb,\n table: string,\n): Promise<ForeignKeySnapshot[]> {\n const fkRows = await rows<FkRow>(\n db,\n `SELECT k.CONSTRAINT_NAME, k.COLUMN_NAME,\n k.REFERENCED_TABLE_NAME AS REF_TABLE, k.REFERENCED_COLUMN_NAME AS REF_COLUMN,\n r.DELETE_RULE, r.UPDATE_RULE, k.ORDINAL_POSITION\n FROM information_schema.KEY_COLUMN_USAGE k\n JOIN information_schema.REFERENTIAL_CONSTRAINTS r\n ON r.CONSTRAINT_SCHEMA = k.TABLE_SCHEMA AND r.CONSTRAINT_NAME = k.CONSTRAINT_NAME\n WHERE k.TABLE_SCHEMA = DATABASE() AND k.TABLE_NAME = ?\n AND k.REFERENCED_TABLE_NAME IS NOT NULL\n ORDER BY k.CONSTRAINT_NAME, k.ORDINAL_POSITION`,\n [table],\n )\n const byName = new Map<string, FkRow[]>()\n for (const r of fkRows) {\n const g = byName.get(r.CONSTRAINT_NAME) ?? []\n g.push(r)\n byName.set(r.CONSTRAINT_NAME, g)\n }\n const out: ForeignKeySnapshot[] = []\n for (const [name, group] of byName) {\n const first = group[0]\n out.push({\n name,\n columns: group.map((g) => g.COLUMN_NAME),\n refTable: first.REF_TABLE,\n refColumns: group.map((g) => g.REF_COLUMN),\n onDelete: mapFkAction(first.DELETE_RULE),\n onUpdate: mapFkAction(first.UPDATE_RULE),\n })\n }\n return out\n}\n\nfunction mapFkAction(action: string): FkAction {\n switch (action.toUpperCase()) {\n case 'CASCADE':\n return 'cascade'\n case 'RESTRICT':\n return 'restrict'\n case 'SET NULL':\n return 'set_null'\n case 'SET DEFAULT':\n return 'set_default'\n default:\n return 'no_action'\n }\n}\n\n/**\n * Use the declared `COLUMN_TYPE` (carries length), lowercased — except an\n * enum's or set's values, which keep their case.\n */\nfunction normalizeType(c: ColumnRow): string {\n const type = (c.COLUMN_TYPE || c.DATA_TYPE).trim()\n const values = /^(enum|set)\\s*(\\(.*\\))$/is.exec(type)\n if (values) return `${values[1]!.toLowerCase()}${values[2]}`\n return type.toLowerCase() || 'text'\n}\n","import { defineAdapter } from '@forinda/kickjs'\nimport type { InjectionToken } from '@forinda/kickjs'\n\nimport { migrateLatest, migrateStatus } from './migrate/runner'\nimport type { MigrationAdapter } from './migrate/adapter'\nimport type { DriftBehavior } from './migrate/drift'\n\nexport type MigrationsOnBoot = 'fail-if-pending' | 'apply' | 'ignore'\n\nexport interface KickDbAdapterConfig {\n /** The driver-bound MigrationAdapter — pgAdapter() in @forinda/kickjs-db/pg, etc. */\n migrationAdapter: MigrationAdapter\n /** Directory containing the generated migrations + _journal.json — or several, run as one history. */\n migrationsDir: string | readonly string[]\n /** Boot policy. Default 'fail-if-pending' — mirror the operator-explicit philosophy. */\n migrationsOnBoot?: MigrationsOnBoot\n /** Drift detection mode. Default 'error' outside dev. */\n driftCheck?: DriftBehavior\n /** Default true outside dev. */\n requireReviewed?: boolean\n /** Optional DI token to register the migrationAdapter under, for adopters who need direct access. */\n token?: InjectionToken<MigrationAdapter>\n /**\n * Optional KickEventBus the adapter publishes migration events to.\n * When set, `db:migration-applied` fires after a successful\n * `migrateLatest()` on boot (apply policy only). Pair with\n * `DEVTOOLS_BUS` so the events surface in the DevTools panel:\n *\n * import { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\n * // Resolve only when devtools is actually wired — adopters who\n * // skip @forinda/kickjs-devtools never register the token, and\n * // resolve() throws on missing tokens.\n * const adapter = kickDbAdapter({\n * ...,\n * bus: container.has(DEVTOOLS_BUS) ? container.resolve(DEVTOOLS_BUS) : undefined,\n * })\n *\n * Type imported via `import type` so kickjs-db keeps devtools-kit\n * as an optional peer.\n */\n bus?: import('@forinda/kickjs-devtools-kit/bus').KickEventBus\n}\n\n/**\n * KickJS lifecycle adapter for kickjs-db. Three jobs:\n *\n * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.\n * - 'fail-if-pending' (default): throw if any pending exists. Operators\n * run `kick db migrate latest` explicitly before deploys land. Avoids\n * the prisma footgun where migrations silently apply on deploy.\n * - 'apply': run migrateLatest() automatically. Useful for dev / preview\n * environments where convenience matters more than safety.\n * - 'ignore': boot regardless. Last-resort escape hatch.\n * 2. On shutdown, close the migrationAdapter (ends its pool only when created with `endPoolOnClose`).\n * 3. Register the migrationAdapter under an optional DI token so adopters\n * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers\n * separately under DB_PRIMARY.\n */\nexport const kickDbAdapter = defineAdapter<KickDbAdapterConfig>({\n name: 'kickjs-db',\n build: (config) => ({\n async beforeStart({ container }) {\n const policy = config.migrationsOnBoot ?? 'fail-if-pending'\n const status = await migrateStatus({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n })\n const pending = status.filter((s) => s.state === 'pending')\n\n if (pending.length > 0) {\n if (policy === 'fail-if-pending') {\n throw new Error(\n `kickjs-db: ${pending.length} pending migration(s); run \\`kick db migrate latest\\` before boot`,\n )\n }\n if (policy === 'apply') {\n const result = await migrateLatest({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n requireReviewed: config.requireReviewed,\n driftCheck: config.driftCheck,\n })\n // Republish to DevTools when a bus is wired so the panel\n // can surface \"migrations ran on boot\" without polling.\n // `applied` is the list of migration ids the runner ran;\n // `batch` is the batch number the journal stamped them with.\n if (config.bus) {\n config.bus.emit('db:migration-applied', {\n applied: result.applied,\n batch: result.batch,\n })\n }\n }\n // 'ignore' falls through.\n }\n\n if (config.token) {\n container.registerFactory(config.token, () => config.migrationAdapter)\n }\n },\n async shutdown() {\n await config.migrationAdapter.close()\n },\n }),\n})\n","import { createToken, type InjectionToken } from '@forinda/kickjs'\n\nimport type { KickDbClient } from './client/types'\n\n// First-party tokens own the reserved `kick/` namespace. Adopter-defined\n// tokens (e.g. additional shards / read replicas beyond the default pair)\n// should use the adopter's own scope (e.g. `app/db/tenants`).\nexport const DB_PRIMARY: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/primary')\nexport const DB_REPLICA: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/replica')\n\n/**\n * Alias for the default DB. Adopters who only have one database can inject\n * `DB_CLIENT` instead of remembering whether it's primary/replica.\n */\nexport const DB_CLIENT = DB_PRIMARY\n","import {\n BinaryOperationNode,\n OperationNodeTransformer,\n OperatorNode,\n ValueNode,\n type KyselyPlugin,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type QueryResult,\n type RootOperationNode,\n type UnknownRow,\n} from 'kysely'\n\n// M5 follow-up — kickjs-side workaround for the broken\n// SafeNullComparisonPlugin shipped in Kysely 0.29\n// (kysely/dist/plugin/safe-null-comparison/safe-null-comparison-transformer.js).\n//\n// The upstream transformer rewrites `=` / `!=` / `<>` against\n// literal `null` to `IS` / `IS NOT` at AST level but keeps the null\n// operand as a `ValueNode(null)`, which the PG compiler then\n// parameterises. Result: `WHERE \"col\" IS $1` with `$1=null` —\n// invalid PostgreSQL syntax. PG's `IS` predicate grammar requires\n// specific predicates (`NULL`, `TRUE`, `FALSE`, `UNKNOWN`,\n// `DISTINCT FROM ...`), not an arbitrary parameter placeholder.\n//\n// Verified empirically against postgres:16-alpine in\n// `packages/db-pg/__tests__/integration/kysely-safe-null-broken-pg.test.ts`.\n// Tracked for upstream follow-up at #220.\n//\n// Fix: identical AST rewrite, but replace the null `ValueNode` with\n// `ValueNode.createImmediate(null)` so the PG compiler emits the\n// bare SQL keyword `null` inline (no parameter binding). Output is\n// `WHERE \"col\" IS NULL` / `WHERE \"col\" IS NOT NULL` — valid PG and\n// semantically correct under three-valued logic.\n//\n// When upstream Kysely fixes their transformer (issue #220), this\n// wrapper can collapse to a one-line re-export of\n// `kysely`'s plugin. The unit test in\n// `__tests__/unit/safe-null-comparison.test.ts` and the PG\n// integration test pin the current output, so the diff will surface\n// loudly at upgrade time.\n\nclass SafeNullComparisonTransformer extends OperationNodeTransformer {\n protected override transformBinaryOperation(node: BinaryOperationNode): BinaryOperationNode {\n const transformed = super.transformBinaryOperation(node)\n const { operator, leftOperand, rightOperand } = transformed\n\n if (!OperatorNode.is(operator)) return transformed\n if (!ValueNode.is(rightOperand) || rightOperand.value !== null) return transformed\n\n const op = operator.operator\n if (op !== '=' && op !== '!=' && op !== '<>') return transformed\n\n return BinaryOperationNode.create(\n leftOperand,\n OperatorNode.create(op === '=' ? 'is' : 'is not'),\n // KEY DIFFERENCE vs Kysely's upstream transformer — `createImmediate`\n // marks the value for inline emission, so the compiler writes the\n // SQL keyword `null` instead of binding the value as a `$N` parameter.\n ValueNode.createImmediate(null),\n )\n }\n}\n\nclass SafeNullComparisonPlugin implements KyselyPlugin {\n readonly #transformer = new SafeNullComparisonTransformer()\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n return this.#transformer.transformNode(args.node)\n }\n\n async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> {\n return args.result\n }\n}\n\n/**\n * Pass this to `createDbClient({ plugins: [...] })` so\n * `eb('col', '=', null)` (plus `!=` / `<>`) compiles to `IS NULL` /\n * `IS NOT NULL` instead of the silently-false `= NULL` default.\n *\n * Without the plugin, Kysely passes `null` through as a bound\n * parameter — the resulting `col = $1` evaluates to UNKNOWN under\n * three-valued logic, which filters out every row including the\n * ones the adopter intended to match. The plugin rewrites the AST\n * before compilation so the operator becomes `IS` / `IS NOT` and\n * the null literal flows inline (no `$N` parameter binding).\n *\n * ```ts\n * import { createDbClient, safeNullComparison } from '@forinda/kickjs-db'\n *\n * const db = createDbClient({\n * schema,\n * dialect: pgDialect({ pool }),\n * plugins: [safeNullComparison()],\n * })\n *\n * await db.selectFrom('users').where('deletedAt', '=', null).selectAll().execute()\n * // → SQL: select * from \"users\" where \"deletedAt\" is null\n * ```\n *\n * Opt-in; default `createDbClient` chains stay byte-identical so\n * existing repos that work around the gotcha manually don't see a\n * behaviour change.\n *\n * **Why a kickjs-side helper rather than re-exporting Kysely's?**\n * Kysely 0.29's own `SafeNullComparisonPlugin` ships broken on PG —\n * it rewrites the operator but keeps the null operand parameterised,\n * producing `WHERE \"col\" IS $1` with `$1=null`, which PG rejects\n * with `syntax error at or near \"$1\"`. The kickjs version emits the\n * literal `null` keyword inline so PG accepts it. Tracked upstream\n * at <https://github.com/forinda/kick-js/issues/220>.\n */\nexport function safeNullComparison(): KyselyPlugin {\n return new SafeNullComparisonPlugin()\n}\n","import type { MigrationAdapter } from './adapter'\nimport { migrateLatest, type AppliedSummary, type RunnerOptions } from './runner'\n\nexport interface MigrateTenantsOptions extends Omit<RunnerOptions, 'adapter'> {\n /** The tenants to migrate, or a function returning them (read from the central database). */\n tenants: readonly string[] | (() => readonly string[] | Promise<readonly string[]>)\n /**\n * The migration adapter for one tenant: its database (`'database'`), or a\n * connection whose `search_path` is its schema (`'schema'`). Closed after\n * that tenant is migrated.\n */\n adapterFor: (tenantId: string) => MigrationAdapter | Promise<MigrationAdapter>\n /** Tenants migrated at once. Default 1. */\n concurrency?: number\n /** Stop at the first failure. Default false: migrate the rest and report every failure. */\n stopOnError?: boolean\n /** Called as each tenant finishes. */\n onTenant?: (result: TenantMigrationResult) => void\n}\n\nexport interface TenantMigrationResult {\n tenant: string\n /** What was applied, when it succeeded. */\n summary?: AppliedSummary\n error?: unknown\n}\n\nexport interface MigrateTenantsResult {\n results: TenantMigrationResult[]\n /** The tenants whose migration failed. */\n failed: string[]\n}\n\n/**\n * Run the same migrations for every tenant — schema- or database-per-tenant.\n * Each tenant keeps its own `kick_migrations`, so a tenant added later (or\n * one that failed) catches up on the next run.\n */\nexport async function migrateTenants(opts: MigrateTenantsOptions): Promise<MigrateTenantsResult> {\n const { tenants, adapterFor, concurrency = 1, stopOnError = false, onTenant, ...runner } = opts\n const queue = [...(typeof tenants === 'function' ? await tenants() : tenants)]\n const results: TenantMigrationResult[] = []\n let stop = false\n\n const migrateOne = async (tenant: string) => {\n let result: TenantMigrationResult\n let adapter: MigrationAdapter | undefined\n try {\n adapter = await adapterFor(tenant)\n result = { tenant, summary: await migrateLatest({ ...runner, adapter }) }\n } catch (error) {\n result = { tenant, error }\n if (stopOnError) stop = true\n } finally {\n await adapter?.close().catch(() => {})\n }\n results.push(result)\n onTenant?.(result)\n }\n\n const worker = async () => {\n for (;;) {\n // `stop` is set by another worker's failure (stopOnError).\n const tenant = stop ? undefined : queue.shift()\n if (tenant === undefined) return\n await migrateOne(tenant)\n }\n }\n await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker))\n return { results, failed: results.filter((r) => r.error !== undefined).map((r) => r.tenant) }\n}\n","import path from 'node:path'\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\n\nimport { computeMigrationHash } from './journal'\nimport type { Journal } from './journal'\n\nexport interface ReviewResult {\n id: string\n /** True when the migration was already reviewed — its hash is re-recorded. */\n alreadyReviewed: boolean\n}\n\n/**\n * Mark a migration as reviewed: flip `meta.json.reviewed` to `true` —\n * the review state the runner checks — and record the hash of the files\n * as reviewed in the journal, so hand-written or edited SQL applies and a\n * later edit doesn't.\n *\n * Legacy migrations (generated before the provenance banner) still carry\n * `-- REVIEWED: false` markers inside the hashed files; those are swapped\n * first, so the recorded hash covers them.\n */\nexport async function reviewMigration(migrationsDir: string, id: string): Promise<ReviewResult> {\n const dir = path.join(migrationsDir, id)\n const metaPath = path.join(dir, 'meta.json')\n if (!existsSync(metaPath)) {\n throw new Error(`kickjs-db: migration '${id}' not found under ${migrationsDir}`)\n }\n\n const meta = JSON.parse(await readFile(metaPath, 'utf8')) as { reviewed?: boolean }\n // Reviewing again re-records the hash — how an edit made after review is\n // signed off.\n const alreadyReviewed = meta.reviewed === true\n\n // 1. Legacy marker migration: swap `-- REVIEWED: false` if present.\n // New-style files (immutable banner) are left untouched.\n for (const file of ['up.sql', 'down.sql']) {\n const p = path.join(dir, file)\n if (!existsSync(p)) continue\n const sql = await readFile(p, 'utf8')\n const next = sql.replace(/^-- REVIEWED: false$/m, '-- REVIEWED: true')\n if (next !== sql) await writeFile(p, next, 'utf8')\n }\n\n // 2. Flip the gate in meta.json (the value the runner actually checks).\n if (!alreadyReviewed) {\n meta.reviewed = true\n await writeFile(metaPath, JSON.stringify(meta, null, 2) + '\\n', 'utf8')\n }\n\n // 3. Record the hash of what was reviewed. Generated SQL is a draft:\n // filling in an `--empty` migration or editing a generated one before\n // review is the point of reviewing, so the journal takes the reviewed\n // bytes. An edit after this is what the runner refuses.\n const journalPath = path.join(migrationsDir, '_journal.json')\n const journal = JSON.parse(await readFile(journalPath, 'utf8')) as Journal\n const entry = journal.entries.find((e) => e.id === id)\n if (entry) {\n entry.hash = await computeMigrationHash(dir)\n await writeFile(journalPath, JSON.stringify(journal, null, 2) + '\\n', 'utf8')\n }\n\n return { id, alreadyReviewed }\n}\n","import path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Dialect } from '../snapshot/types'\nimport type { MigrationAdapter } from '../migrate/adapter'\nimport type { DriftBehavior } from '../migrate/drift'\n\nexport type MigrationAdapterFactory = () => MigrationAdapter | Promise<MigrationAdapter>\n\nexport interface DbConfig {\n schemaPath: string\n migrationsDir: string\n /** Where `kick db seed` finds seed files. Default `db/seeds`. */\n seedsDir?: string\n dialect: Dialect\n /**\n * How `kick db migrate` reacts when the live DB has schema not recorded\n * in the migrations (someone ran DDL out of band): `'error'` (default —\n * refuse), `'warn'` (log + continue), `'ignore'` (skip the check). The\n * check is dialect-normalised, so SQLite/MySQL's lossy introspection\n * doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n /**\n * `'snake_case'`: migrations name tables and columns in snake_case while\n * the schema's keys stay camelCase. Pass the same `casing` to `createDbClient`.\n */\n casing?: 'snake_case'\n /**\n * The table migrations are recorded in (default `kick_migrations`) — for\n * the built-in Postgres adapter. An `adapter()` factory passes it itself:\n * `pgAdapter({ pool, migrationsTable })`.\n */\n migrationsTable?: string\n /** More migration folders, run with `migrationsDir` as one history. */\n migrationsDirs?: string[]\n /**\n * Postgres connection string for the built-in pgAdapter path. Read from\n * `db.connectionString` in kick.config.ts, or falls back to the\n * DATABASE_URL env var. The CLI uses this when no `adapter` factory is\n * provided.\n */\n connectionString?: string\n /**\n * Escape hatch: a factory returning a fully-constructed MigrationAdapter.\n * Takes precedence over `connectionString` when both are set. Use this\n * for non-default adapter wiring (custom pool, neon-serverless, etc).\n */\n adapter?: MigrationAdapterFactory\n /**\n * Schema- or database-per-tenant: the tenants, and the adapter for one —\n * what `kick db migrate latest --tenants` runs with.\n */\n tenants?: TenantsConfig\n}\n\nexport interface TenantsConfig {\n /** Every tenant's id — typically read from the central database. */\n list: () => readonly string[] | Promise<readonly string[]>\n /** The migration adapter for one tenant (closed after it's migrated). */\n adapter: (tenantId: string) => MigrationAdapter | Promise<MigrationAdapter>\n /** Tenants migrated at once. Default 1. */\n concurrency?: number\n}\n\nexport async function resolveDbConfig(opts: { configPath: string }): Promise<DbConfig> {\n const abs = path.resolve(opts.configPath)\n const mod = await import(pathToFileURL(abs).href)\n const cfg = mod.default ?? mod\n const db = cfg?.db ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n seedsDir: db.seedsDir ?? 'db/seeds',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\n }\n}\n","import path from 'node:path'\nimport { loadModule } from './load-module'\nimport { mkdir, readFile, writeFile, readdir } from 'node:fs/promises'\nimport { fileURLToPath } from 'node:url'\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { extractSnapshot } from '../snapshot/extract'\nimport { snapshotTableName } from '../snapshot/name'\nimport {\n diff,\n findRenameCandidates,\n withTableRenames,\n type DiffOptions,\n type RenameCandidates,\n type RenameHints,\n} from '../diff/engine'\nimport { invertChanges, hasAmbiguousReverse } from '../diff/invert'\nimport { CompositeEnumReferenceError, type CompositeRef } from '../diff/composite-detect'\nimport { emitPg } from '../emit/pg'\nimport { emitSqlite } from '../emit/sqlite'\nimport { emitMysql } from '../emit/mysql'\nimport { appendJournalEntry, computeMigrationHash } from '../migrate/journal'\nimport type { DbConfig } from './config'\nimport type { ChangeSet } from '../diff/types'\nimport type { Dialect, SchemaSnapshot } from '../snapshot/types'\nimport type { Change, RemoveEnumValue } from '../diff/types'\n\n/**\n * Emit migration DDL for the dialect. `from`/`to` are the schema snapshots\n * before/after the changes apply — the SQLite emitter uses them to build\n * table rebuilds (column alters, FK add/drop) it can't express via\n * `ALTER TABLE`. Postgres/MySQL ignore them.\n */\nfunction emitDdl(\n dialect: Dialect,\n changes: ChangeSet,\n from: SchemaSnapshot,\n to: SchemaSnapshot,\n): string {\n switch (dialect) {\n case 'sqlite':\n return emitSqlite(changes, { from, to })\n case 'mysql':\n return emitMysql(changes)\n case 'postgres':\n return emitPg(changes)\n }\n}\n\nexport interface GenerateOptions {\n name: string\n config: DbConfig\n cwd: string\n now?: () => Date\n /**\n * When true, skip the schema diff and emit an empty migration shell\n * (up.sql / down.sql with just the generated-by banner, snapshot.json copying\n * the prior schema state). Used for data migrations, seed inserts, or any\n * change the diff engine can't author. Matches knex's `migrate:make`.\n */\n empty?: boolean\n /**\n * Write the migration in TypeScript: a `migration.ts` exporting\n * `up(db)` / `down(db)` instead of SQL, for data changes that need code.\n * Like `empty`, the schema diff is skipped and the snapshot carried over.\n */\n typescript?: boolean\n /**\n * M4.C — generate-time gate for `removeEnumValue` changes. When the\n * diff produces one or more, this callback is invoked once per\n * affected enum to surface PG composite-type references. A non-empty\n * result aborts generate with `CompositeEnumReferenceError` (the\n * rename-recreate USING-cast can't reach into composite fields).\n *\n * Optional: when omitted, generate skips the check (no DB connection\n * required). The CLI wires this for `dialect=postgres` workflows.\n */\n detectCompositeRefs?: (enumName: string) => Promise<readonly CompositeRef[]>\n /** Renames known up front — `--rename-table` / `--rename-column`. */\n renames?: RenameHints\n /**\n * Asked which dropped tables and columns are really renames, when the diff\n * has a drop and an add that could be one. Called first with table\n * candidates, then with column candidates (inside renamed tables too). What\n * it doesn't name is dropped. Without it, only `renames` and the\n * one-drop-one-add guess pair them.\n */\n askRenames?: (candidates: RenameCandidates) => Promise<RenameHints>\n /**\n * Told about each table or column the migration drops that could have been\n * a rename, when `askRenames` isn't given — so a non-interactive run can\n * still warn. `flag` is the `--rename-…` that would keep it.\n */\n onPossibleRename?: (drop: { what: string; flag: string }) => void\n}\n\nexport interface GenerateResult {\n status: 'created' | 'no-changes'\n migrationDir?: string\n changeCount: number\n empty?: boolean\n}\n\nexport async function generate(opts: GenerateOptions): Promise<GenerateResult> {\n const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir)\n const { snapshot: prev, id: previousId } = await readLatestSnapshotEntry(\n migrationsAbs,\n opts.config.dialect,\n )\n\n if (opts.empty || opts.typescript) {\n return await writeMigration({\n opts,\n migrationsAbs,\n previousId,\n // Empty migrations don't change schema state — keep the prior snapshot\n // so the next diff-based generate stays consistent.\n target: prev,\n upBody: '',\n downBody: '',\n changeCount: 0,\n draft: false,\n empty: true,\n code: opts.typescript ? CODE_MIGRATION_TEMPLATE : undefined,\n })\n }\n\n const schemaAbs = path.resolve(opts.cwd, opts.config.schemaPath)\n // Fresh: a second generate() in the same process must see the edited schema.\n const schemaModule = await loadModule(schemaAbs, { fresh: true })\n const target = extractSnapshot(schemaModule, opts.config.dialect, { casing: opts.config.casing })\n const renames = await resolveRenames(prev, target, opts)\n const changes = diff(prev, target, renames)\n if (!opts.askRenames && opts.onPossibleRename)\n warnPossibleRenames(prev, target, changes, renames, opts.onPossibleRename)\n\n if (changes.length === 0) {\n return { status: 'no-changes', changeCount: 0 }\n }\n\n await assertNoCompositeReferences(changes, opts.detectCompositeRefs)\n\n const dialect = opts.config.dialect\n // CONCURRENTLY can't run in a transaction, nor beside another statement\n // (Postgres runs a multi-statement query as one implicit transaction). So\n // each concurrent index change gets a migration of its own, after one\n // holding everything else; each migration records the schema as it leaves it.\n const concurrent = changes.filter(isConcurrentIndexChange)\n const rest = changes.filter((c) => !concurrent.includes(c))\n const stages = [\n ...(rest.length > 0 ? [{ changes: rest, pending: concurrent }] : []),\n ...concurrent.map((c, i) => ({ changes: [c], pending: concurrent.slice(i + 1) })),\n ]\n\n let from = prev\n let previous = previousId\n let result: GenerateResult | undefined\n for (const [n, { changes: stage, pending }] of stages.entries()) {\n const to = snapshotAfter(target, pending)\n result = await writeMigration({\n opts: n === 0 ? opts : withStageName(opts, n),\n migrationsAbs,\n previousId: previous,\n target: to,\n // up: from -> to. down: invert applied to to -> from.\n upBody: emitDdl(dialect, stage, from, to),\n downBody: emitDdl(dialect, invertChanges(stage), to, from),\n changeCount: stage.length,\n draft: hasAmbiguousReverse(stage),\n empty: false,\n transaction: isConcurrentIndexChange(stage[0]) ? false : undefined,\n })\n from = to\n previous = path.basename(result.migrationDir!)\n }\n return { ...result!, changeCount: changes.length }\n}\n\nfunction warnPossibleRenames(\n prev: SchemaSnapshot,\n target: SchemaSnapshot,\n changes: ChangeSet,\n { renames = {} }: DiffOptions,\n warn: NonNullable<GenerateOptions['onPossibleRename']>,\n): void {\n const options = (to: string[]) => (to.length === 1 ? to[0] : `<${to.join('|')}>`)\n const candidates = findRenameCandidates(\n withTableRenames(prev, target, renames.tables ?? {}),\n target,\n )\n for (const c of candidates.tables) {\n if (!changes.some((x) => x.kind === 'dropTable' && snapshotTableName(x.table) === c.from))\n continue\n warn({ what: `table ${c.from}`, flag: `--rename-table ${c.from}=${options(c.to)}` })\n }\n for (const c of candidates.columns) {\n const dropped = changes.some(\n (x) => x.kind === 'dropColumn' && x.table === c.table && x.column.name === c.from,\n )\n if (!dropped) continue\n warn({\n what: `column ${c.table}.${c.from}`,\n flag: `--rename-column ${c.table}.${c.from}=${options(c.to)}`,\n })\n }\n}\n\nasync function resolveRenames(\n prev: SchemaSnapshot,\n target: SchemaSnapshot,\n opts: GenerateOptions,\n): Promise<DiffOptions> {\n const given = opts.renames ?? {}\n if (!opts.askRenames) return { renames: given }\n\n // A name a flag already claimed isn't offered again; a drop is only left\n // out when a flag named it or nothing is left for it to become.\n const tables = { ...given.tables }\n const claimedTables = new Set(Object.values(tables))\n const tableCandidates = findRenameCandidates(prev, target)\n .tables.filter((c) => !(c.from in tables))\n .map((c) => Object.assign(c, { to: c.to.filter((t) => !claimedTables.has(t)) }))\n .filter((c) => c.to.length > 0)\n if (tableCandidates.length > 0) {\n Object.assign(tables, (await opts.askRenames({ tables: tableCandidates, columns: [] })).tables)\n }\n\n const columns = { ...given.columns }\n const claimedColumns = new Set(\n Object.entries(columns).map(([key, to]) => `${key.slice(0, key.lastIndexOf('.'))}.${to}`),\n )\n const renamed = withTableRenames(prev, target, tables)\n const columnCandidates = findRenameCandidates(renamed, target)\n .columns.filter((c) => !(`${c.table}.${c.from}` in columns))\n .map((c) =>\n Object.assign(c, { to: c.to.filter((t) => !claimedColumns.has(`${c.table}.${t}`)) }),\n )\n .filter((c) => c.to.length > 0)\n if (columnCandidates.length > 0) {\n Object.assign(\n columns,\n (await opts.askRenames({ tables: [], columns: columnCandidates })).columns,\n )\n }\n return { renames: { tables, columns }, explicitRenames: true }\n}\n\nfunction isConcurrentIndexChange(c: Change): boolean {\n return (c.kind === 'addIndex' || c.kind === 'dropIndex') && c.index.concurrently === true\n}\n\n/**\n * `target` with the given concurrent index changes not yet applied: their\n * added indexes taken out, their dropped ones put back.\n */\nfunction snapshotAfter(target: SchemaSnapshot, pending: Change[]): SchemaSnapshot {\n if (pending.length === 0) return target\n const tables = structuredClone(target.tables)\n // Undone latest first, so a rebuild (drop, then add, of one name) ends on the old index.\n for (const c of pending.toReversed()) {\n if (c.kind !== 'addIndex' && c.kind !== 'dropIndex') continue\n const t = tables[c.table]\n const others = t.indexes.filter((i) => i.name !== c.index.name)\n t.indexes = c.kind === 'addIndex' ? others : [...others, c.index]\n }\n return { ...target, tables }\n}\n\n/** A later migration from the same generate: one second on, so ids stay ordered. */\nfunction withStageName(opts: GenerateOptions, n: number): GenerateOptions {\n const at = (opts.now?.() ?? new Date()).getTime() + n * 1000\n return { ...opts, name: `${opts.name}_concurrently_${n}`, now: () => new Date(at) }\n}\n\ninterface WriteMigrationParams {\n opts: GenerateOptions\n migrationsAbs: string\n previousId: string | null\n target: SchemaSnapshot\n upBody: string\n downBody: string\n changeCount: number\n draft: boolean\n empty: boolean\n /** `false` runs the migration outside a transaction. */\n transaction?: false\n /** The `migration.ts` source, for a migration written in TypeScript. */\n code?: string\n}\n\nconst CODE_MIGRATION_TEMPLATE = `import type { MigrationDb } from '@forinda/kickjs-db'\n\n// Runs inside the migration's transaction. \\`db\\` is Kysely over the live\n// schema — untyped on purpose, since the schema keeps changing after this\n// migration is written.\nexport async function up(db: MigrationDb): Promise<void> {\n // await db.updateTable('users').set({ status: 'active' }).where('status', 'is', null).execute()\n}\n\nexport async function down(db: MigrationDb): Promise<void> {\n // Reverse up(), or throw if it can't be.\n}\n`\n\n/**\n * Immutable provenance banner for generated SQL files. Replaces the old\n * mutable `-- REVIEWED: false` marker — review state lives ONLY in\n * `meta.json` (which the integrity hash does not cover), so reviewing a\n * migration never invalidates its journal hash. The old marker invited\n * hand-edits that broke the hash with an opaque mismatch error.\n */\nfunction generatedBanner(): string {\n return `-- Generated by @forinda/kickjs-db v${ownPackageVersion()} — review state lives in meta.json\\n`\n}\n\nlet cachedVersion: string | null = null\nfunction ownPackageVersion(): string {\n if (cachedVersion) return cachedVersion\n // dist layout: dist/*.mjs → '../package.json'; source layout (vitest):\n // src/cli/generate.ts → '../../package.json'. Probe both.\n const here = path.dirname(fileURLToPath(import.meta.url))\n for (const rel of ['../package.json', '../../package.json']) {\n try {\n const pkg = JSON.parse(readFileSync(path.resolve(here, rel), 'utf8')) as {\n name?: string\n version?: string\n }\n if (pkg.name === '@forinda/kickjs-db' && pkg.version) {\n cachedVersion = pkg.version\n return cachedVersion\n }\n } catch {\n // keep probing\n }\n }\n cachedVersion = 'unknown'\n return cachedVersion\n}\n\nasync function writeMigration(p: WriteMigrationParams): Promise<GenerateResult> {\n const id = formatId(p.opts.now?.() ?? new Date(), p.opts.name)\n const dir = path.join(p.migrationsAbs, id)\n await mkdir(dir, { recursive: true })\n\n const upHeader = generatedBanner()\n const upHint = p.code\n ? '-- Written in TypeScript: migration.ts runs instead of this file.\\n'\n : p.empty\n ? '-- Empty migration — author SQL below (data migration, seed, etc).\\n'\n : ''\n const upSql = upHeader + upHint + p.upBody + (p.upBody ? '\\n' : '')\n await writeFile(path.join(dir, 'up.sql'), upSql, 'utf8')\n\n const downHeader = generatedBanner()\n const downDraft = p.draft\n ? '-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.\\n'\n : ''\n const downHint = p.code\n ? '-- Written in TypeScript: migration.ts runs instead of this file.\\n'\n : p.empty\n ? '-- Empty migration — author the reverse SQL here.\\n'\n : ''\n const downSql = downHeader + downDraft + downHint + p.downBody + (p.downBody ? '\\n' : '')\n await writeFile(path.join(dir, 'down.sql'), downSql, 'utf8')\n\n await writeFile(path.join(dir, 'snapshot.json'), JSON.stringify(p.target, null, 2) + '\\n', 'utf8')\n if (p.code) await writeFile(path.join(dir, 'migration.ts'), p.code, 'utf8')\n\n await writeFile(\n path.join(dir, 'meta.json'),\n JSON.stringify(\n {\n id,\n name: p.opts.name,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n reviewed: false,\n dialect: p.opts.config.dialect,\n previousId: p.previousId,\n downIsDraft: p.draft,\n empty: p.empty,\n ...(p.transaction === false ? { transaction: false } : {}),\n },\n null,\n 2,\n ) + '\\n',\n 'utf8',\n )\n\n // Append to _journal.json so the runner has the canonical applied-order\n // and integrity hash. Hash includes up + down + snapshot, so any later\n // hand-edit of those files will surface as a MigrationHashError at apply.\n const hash = await computeMigrationHash(dir)\n await appendJournalEntry(p.migrationsAbs, p.opts.config.dialect, {\n id,\n tag: p.opts.name,\n hash,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n })\n\n return { status: 'created', migrationDir: dir, changeCount: p.changeCount, empty: p.empty }\n}\n\ninterface LatestEntry {\n snapshot: SchemaSnapshot\n id: string | null\n}\n\nexport async function readLatestSnapshotEntry(\n migrationsDir: string,\n dialect: Dialect,\n): Promise<LatestEntry> {\n const empty: SchemaSnapshot = { version: 1, dialect, tables: {} }\n if (!existsSync(migrationsDir)) {\n return { snapshot: empty, id: null }\n }\n const entries = await readdir(migrationsDir)\n const dirs = entries.filter((e) => /^\\d{8}_\\d{6}_/.test(e)).toSorted()\n if (dirs.length === 0) {\n return { snapshot: empty, id: null }\n }\n const latest = dirs[dirs.length - 1]\n const file = path.join(migrationsDir, latest, 'snapshot.json')\n const snapshot = JSON.parse(await readFile(file, 'utf8')) as SchemaSnapshot\n return { snapshot, id: latest }\n}\n\n/**\n * M4.C gate. Walk the diff for `removeEnumValue` changes; if any are\n * present and the caller supplied a composite-detector, run it once\n * per enum and aggregate the references. Throws\n * `CompositeEnumReferenceError` when any references are found so the\n * operator restructures the composite before the migration is\n * committed to disk.\n */\nasync function assertNoCompositeReferences(\n changes: readonly Change[],\n detect: ((enumName: string) => Promise<readonly CompositeRef[]>) | undefined,\n): Promise<void> {\n if (!detect) return\n const removals = changes.filter((c): c is RemoveEnumValue => c.kind === 'removeEnumValue')\n if (removals.length === 0) return\n\n const allRefs: CompositeRef[] = []\n // Detect once per distinct enum — multiple removals on the same enum\n // collapse into a single check; the caller probably batched them.\n const seen = new Set<string>()\n for (const r of removals) {\n if (seen.has(r.enum)) continue\n seen.add(r.enum)\n const refs = await detect(r.enum)\n allRefs.push(...refs)\n }\n if (allRefs.length > 0) {\n throw new CompositeEnumReferenceError(allRefs)\n }\n}\n\nfunction formatId(date: Date, name: string): string {\n const pad = (n: number) => n.toString().padStart(2, '0')\n const ts =\n date.getUTCFullYear().toString() +\n pad(date.getUTCMonth() + 1) +\n pad(date.getUTCDate()) +\n '_' +\n pad(date.getUTCHours()) +\n pad(date.getUTCMinutes()) +\n pad(date.getUTCSeconds())\n const slug = name.replace(/[^a-z0-9]+/gi, '_').toLowerCase()\n return `${ts}_${slug}`\n}\n","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { loadModule } from './load-module'\n\nimport type { DbConfig } from './config'\nimport { diff } from '../diff/engine'\nimport { computeMigrationHash, readJournal } from '../migrate/journal'\nimport { extractSnapshot } from '../snapshot/extract'\nimport { readLatestSnapshotEntry } from './generate'\n\nexport interface CheckResult {\n /** Changes in the schema that no migration covers yet — run `kick db generate`. */\n unmigratedChanges: number\n /** Migrations not marked reviewed — the runner refuses them outside development. */\n unreviewed: string[]\n /** Reviewed migrations whose files changed after review — the runner refuses them. */\n modified: string[]\n ok: boolean\n}\n\n/**\n * Everything `migrate latest` would refuse, found without a database — for\n * CI, before a deploy reaches one: the schema has changes no migration\n * covers, a migration is unreviewed, or a migration was edited after review.\n */\nexport async function checkMigrations(opts: {\n config: DbConfig\n cwd: string\n}): Promise<CheckResult> {\n const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir)\n const { snapshot: prev } = await readLatestSnapshotEntry(migrationsAbs, opts.config.dialect)\n const schemaModule = await loadModule(path.resolve(opts.cwd, opts.config.schemaPath), {\n fresh: true,\n })\n const unmigratedChanges = diff(\n prev,\n extractSnapshot(schemaModule, opts.config.dialect, { casing: opts.config.casing }),\n ).length\n\n // Every folder the runner applies is checked for unreviewed or edited\n // migrations. The schema is compared with `migrationsDir` only: the other\n // folders belong to schemas of their own.\n const unreviewed: string[] = []\n const modified: string[] = []\n const folders = [opts.config.migrationsDir, ...(opts.config.migrationsDirs ?? [])].map((d) =>\n path.resolve(opts.cwd, d),\n )\n for (const folder of folders) {\n if (!existsSync(folder)) continue\n for (const entry of (await readJournal(folder, opts.config.dialect)).entries) {\n const dir = path.join(folder, entry.id)\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8')) as {\n reviewed?: boolean\n }\n // An unreviewed migration is a draft — edits are expected until review.\n if (meta.reviewed !== true) unreviewed.push(entry.id)\n else if ((await computeMigrationHash(dir)) !== entry.hash) modified.push(entry.id)\n }\n }\n\n return {\n unmigratedChanges,\n unreviewed,\n modified,\n ok: unmigratedChanges === 0 && unreviewed.length === 0 && modified.length === 0,\n }\n}\n","/**\n * `kick db seed` — run the seed files in `seedsDir`: data a fresh database\n * needs (roles, a first admin, reference rows) or a developer wants (sample\n * data). Each file default-exports an async function, imports whatever client\n * it needs, and should be safe to run again — `db.upsert()` and\n * `db.findOrCreate()` make that easy. Nothing is recorded: seeds aren't\n * migrations.\n */\nimport { existsSync } from 'node:fs'\nimport { readdir } from 'node:fs/promises'\nimport path from 'node:path'\nimport { loadModule } from './load-module'\n\nimport { KickDbError } from '../errors'\n\nconst SEED_FILE = /\\.(?:[cm]?[jt]s)$/\n\nexport interface SeedResult {\n /** The seed files run, in order. */\n ran: string[]\n}\n\n/** The seed files in `dir`, sorted by name — prefix them (`01_roles.ts`) to order them. */\nexport async function listSeeds(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return []\n return (await readdir(dir))\n .filter((f) => SEED_FILE.test(f) && !f.endsWith('.d.ts') && !/\\.test\\.[cm]?[jt]s$/.test(f))\n .toSorted()\n}\n\n/**\n * Run every seed in `dir`, or only `names` (file names, with or without the\n * extension), in name order. A seed that throws stops the run: the error\n * names the file and keeps the original as `cause`.\n */\nexport async function runSeeds(opts: { dir: string; names?: string[] }): Promise<SeedResult> {\n const all = await listSeeds(opts.dir)\n const strip = (f: string) => f.replace(SEED_FILE, '')\n // `01_users.ts` and `01_users.js` side by side — usually a stale build output —\n // would both run, and a name couldn't pick one. Refuse before running anything.\n const byBase = new Map<string, string[]>()\n for (const f of all) byBase.set(strip(f), [...(byBase.get(strip(f)) ?? []), f])\n const clashes = [...byBase.values()].filter((files) => files.length > 1)\n if (clashes.length > 0) {\n throw new KickDbError(\n 'KICK_DB_SEED_DUPLICATE',\n `Seeds share a name: ${clashes.map((c) => c.join(' and ')).join('; ')} in ${opts.dir} — keep one of each`,\n )\n }\n const wanted = opts.names?.length ? new Set(opts.names.map(strip)) : null\n const files = wanted ? all.filter((f) => wanted.has(strip(f))) : all\n\n if (wanted) {\n const missing = [...wanted].filter((n) => !files.some((f) => strip(f) === n))\n if (missing.length > 0) {\n throw new KickDbError(\n 'KICK_DB_SEED_NOT_FOUND',\n `No seed named ${missing.join(', ')} in ${opts.dir}`,\n )\n }\n }\n\n const ran: string[] = []\n for (const file of files) {\n let mod: { default?: unknown }\n try {\n mod = (await loadModule(path.join(opts.dir, file))) as { default?: unknown }\n } catch (cause) {\n // A syntax error or an import that doesn't resolve — still name the seed.\n const err = new KickDbError(\n 'KICK_DB_SEED_FAILED',\n `Seed ${file} failed to load: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n err.cause = cause\n throw err\n }\n if (typeof mod.default !== 'function') {\n throw new KickDbError(\n 'KICK_DB_SEED_INVALID',\n `Seed ${file} must default-export a function: export default async function seed() { … }`,\n )\n }\n try {\n await mod.default()\n } catch (cause) {\n const err = new KickDbError(\n 'KICK_DB_SEED_FAILED',\n `Seed ${file} failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n err.cause = cause\n throw err\n }\n ran.push(file)\n }\n return { ran }\n}\n","import { ColumnBuilder, type GeneratedBrand, type NotNullBrand } from './types'\n\n// ── helpers ───────────────────────────────────────────────────────────────\n\n/**\n * Type-level brand stamps. Runtime is identity; the cast attaches the\n * relevant brand so `SchemaToTypes<S>` reads them per column.\n */\nfunction brandGenerated<C>(col: C): C & GeneratedBrand {\n return col as C & GeneratedBrand\n}\n\nfunction brandNotNull<C>(col: C): C & NotNullBrand {\n return col as C & NotNullBrand\n}\n\nfunction formatNumeric(base: string, precision?: number, scale?: number): string {\n if (precision === undefined) return base\n if (scale === undefined) return `${base}(${precision})`\n return `${base}(${precision}, ${scale})`\n}\n\n// ── auto-assigned identity columns (DB picks the value) ───────────────────\n//\n// Auto-identity columns are always NOT NULL by SQL semantics, so we stamp\n// both NotNullBrand (drop the `| null`) and GeneratedBrand (wrap in\n// Generated<T>) at the constructor.\n\nexport function serial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('serial', { nullable: false })))\n}\n\n/** How `bigint` / `numeric` values are read back, and the type they get. */\nexport interface NumberModes {\n bigint: bigint\n number: number\n string: string\n}\n\nexport function bigSerial(): ColumnBuilder<bigint> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<bigint>('bigserial', { nullable: false })))\n}\n\nexport function smallSerial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('smallserial', { nullable: false })))\n}\n\n// ── numeric ───────────────────────────────────────────────────────────────\n\nexport function integer(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('integer')\n}\n\n/**\n * A 64-bit integer. Drivers return it differently (`pg` a string,\n * better-sqlite3 a number), so pick how it reads back with `mode`:\n * `'bigint'` (exact), `'number'` (safe up to 2^53) or `'string'`. Without\n * `mode` the driver's value is returned, typed `bigint`.\n */\nexport function bigint(): ColumnBuilder<bigint>\nexport function bigint<M extends keyof NumberModes>(options: {\n mode: M\n}): ColumnBuilder<NumberModes[M]>\nexport function bigint(options?: { mode: keyof NumberModes }): ColumnBuilder<unknown> {\n return new ColumnBuilder('bigint', options ? { mode: options.mode } : {})\n}\n\nexport function smallint(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('smallint')\n}\n\n/**\n * An optimistic-locking counter: an integer, not null, starting at 0, that\n * every update increments. Read it with the row, then update\n * `.where('version', '=', read)` — no row updated means someone else changed\n * it first.\n */\nexport function version(): ColumnBuilder<number> & NotNullBrand & GeneratedBrand {\n const col = integer().notNull().default(0) as ColumnBuilder<number> &\n NotNullBrand &\n GeneratedBrand\n ;(col as unknown as { state: { managed: string } }).state.managed = 'version'\n return col\n}\n\ntype DecimalMode = { mode: 'number' | 'string' }\n\n/**\n * An exact decimal, read back as a string by default so no precision is lost.\n * `{ mode: 'number' }` reads it as a JS number: exact up to 15 significant\n * digits, which validators enforce on input (more is refused, not rounded).\n */\nexport function decimal(precision?: number, scale?: number): ColumnBuilder<string>\nexport function decimal<M extends DecimalMode['mode']>(\n precision: number | undefined,\n scale: number | undefined,\n options: { mode: M },\n): ColumnBuilder<NumberModes[M]>\nexport function decimal(\n precision?: number,\n scale?: number,\n options?: DecimalMode,\n): ColumnBuilder<unknown> {\n return new ColumnBuilder(\n formatNumeric('decimal', precision, scale),\n options ? { mode: options.mode } : {},\n )\n}\n\n/** Same as {@link decimal}. */\nexport function numeric(precision?: number, scale?: number): ColumnBuilder<string>\nexport function numeric<M extends DecimalMode['mode']>(\n precision: number | undefined,\n scale: number | undefined,\n options: { mode: M },\n): ColumnBuilder<NumberModes[M]>\nexport function numeric(\n precision?: number,\n scale?: number,\n options?: DecimalMode,\n): ColumnBuilder<unknown> {\n return new ColumnBuilder(\n formatNumeric('numeric', precision, scale),\n options ? { mode: options.mode } : {},\n )\n}\n\nexport function real(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('real')\n}\n\nexport function doublePrecision(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('double precision')\n}\n\n// ── string-shaped ─────────────────────────────────────────────────────────\n\nexport function varchar(length = 255): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`varchar(${length})`)\n}\n\nexport function char(length = 1): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`char(${length})`)\n}\n\nexport function text(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('text')\n}\n\n// ── boolean ───────────────────────────────────────────────────────────────\n\nexport function boolean(): ColumnBuilder<boolean> {\n return new ColumnBuilder<boolean>('boolean')\n}\n\n// ── date / time ───────────────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultNow()` can mark the resulting column as\n * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter\n * omits the column on insert. Returns `this & GeneratedBrand` so the\n * subclass identity is preserved through the chain.\n */\nexport class TimestampBuilder extends ColumnBuilder<Date> {\n constructor(typeName: string = 'timestamp') {\n super(typeName)\n }\n\n defaultNow(): this & GeneratedBrand {\n this.state.default = 'CURRENT_TIMESTAMP'\n return brandGenerated(this)\n }\n}\n\nexport function timestamp(): TimestampBuilder {\n return new TimestampBuilder('timestamp')\n}\n\nexport function timestamptz(): TimestampBuilder {\n return new TimestampBuilder('timestamptz')\n}\n\nexport function date(): ColumnBuilder<Date> {\n return new ColumnBuilder<Date>('date')\n}\n\nexport function time(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('time')\n}\n\nexport function interval(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('interval')\n}\n\n// ── identity-shaped (uuid) ────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultRandom()` can mark the resulting column as\n * generated — when the DB fills in `gen_random_uuid()` for omitted columns.\n * Returns `this & GeneratedBrand` so chaining works in either order:\n * uuid().defaultRandom().primaryKey()\n * uuid().primaryKey().defaultRandom() ← also works\n */\nexport class UuidBuilder extends ColumnBuilder<string> {\n constructor() {\n super('uuid')\n }\n\n defaultRandom(): this & GeneratedBrand {\n this.state.default = 'gen_random_uuid()'\n return brandGenerated(this)\n }\n}\n\nexport function uuid(): UuidBuilder {\n return new UuidBuilder()\n}\n\n// ── structured / binary ───────────────────────────────────────────────────\n\n/**\n * The `T` generic exists so adopters can declare their JSON shape:\n *\n * meta: jsonb<{ tags: string[] }>()\n *\n * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the\n * row type narrows to `{ tags: string[] } | null`.\n */\nexport function json<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('json')\n}\n\nexport function jsonb<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('jsonb')\n}\n\nexport function bytea(): ColumnBuilder<Uint8Array> {\n return new ColumnBuilder<Uint8Array>('bytea')\n}\n","import type { ColumnBuilder, TypedColumnRefs } from './columns/types'\nimport { buildTable, type TableDecl, type TableOptions } from './table'\n\n/**\n * PostgreSQL named-schema namespace.\n *\n * ```ts\n * const billing = pgSchema('billing')\n *\n * const invoices = billing.table('invoices', {\n * id: uuid().primaryKey().defaultRandom(),\n * total: numeric().notNull(),\n * })\n * ```\n *\n * Emits `CREATE SCHEMA IF NOT EXISTS \"billing\"` ahead of the tables that need\n * it, qualifies every generated statement (`\"billing\".\"invoices\"`), and keys\n * the row type as `KickDbSchema['billing.invoices']` so Kysely resolves the\n * qualified table without a `withSchema()` call.\n *\n * Tables declared through the bare `table()` factory are untouched: no schema\n * field, bare identifiers, same snapshot bytes and migration hashes as before.\n *\n * PostgreSQL only. A schema is a true namespace only on PG — on MySQL the\n * word means \"database\" and on SQLite it means an `ATTACH` alias, both of\n * which have different lifecycles than `CREATE SCHEMA`. Declaring one and\n * then diffing against MySQL/SQLite throws rather than emitting DDL that\n * looks right and means something else.\n */\nexport interface PgSchema<TSchema extends string | undefined = string | undefined> {\n readonly __isPgSchema: true\n /** The schema name as declared, e.g. `billing`. */\n readonly name: string\n\n table<TName extends string, C extends Record<string, ColumnBuilder>>(\n name: TName,\n columns: C,\n options?: TableOptions<C>,\n ): TableDecl<TName, C, TSchema> & TypedColumnRefs<C>\n}\n\n/**\n * `public` resolves to \"no schema\" rather than to itself.\n *\n * PG creates `public` for every database and puts it on the default\n * search_path, so `pgSchema('public').table('users', …)` and\n * `table('users', …)` name the same physical table. If the former stamped\n * `schema: 'public'`, its snapshot key would be `public.users` while the\n * latter's is `users` — the diff engine would read that as \"drop `users`,\n * create `public.users`\" and emit a DROP TABLE. Collapsing to `undefined`\n * keeps the two spellings interchangeable, and the conditional return type\n * below keeps the static key in step with the runtime one.\n */\ntype EffectiveSchema<TName extends string> = TName extends 'public' ? undefined : TName\n\n/** Reject names that would need quoting gymnastics or inject into DDL. */\nconst SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/\n\n/**\n * Declare a PostgreSQL schema namespace. See {@link PgSchema}.\n *\n * `pgSchema('public')` is accepted and collapses to \"no schema\" — see\n * {@link EffectiveSchema} for why that matters.\n */\nexport function pgSchema<TName extends string>(name: TName): PgSchema<EffectiveSchema<TName>> {\n // The typeof check is load-bearing, not belt-and-braces: `RegExp.test(x)`\n // stringifies its argument, so the regex alone accepts `undefined`\n // ('undefined'), `null` ('null'), `true` ('true') and `['a']` ('a'). Each\n // fails differently downstream — `undefined` yields a silently unqualified\n // table, `null` serializes `\"schema\": null` into the snapshot, and the\n // others key a table `\"true.x\"` / `\"a.x\"` and emit DDL creating a schema by\n // that name. TS forbids all of them; JS callers and `any` do not.\n if (typeof name !== 'string' || !SCHEMA_NAME.test(name)) {\n throw new Error(\n `pgSchema: invalid schema name ${JSON.stringify(name)}. ` +\n `Expected an unquoted PostgreSQL identifier matching ${SCHEMA_NAME.source}.`,\n )\n }\n const effective = (name === 'public' ? undefined : name) as EffectiveSchema<TName>\n\n return {\n __isPgSchema: true,\n name,\n table<TName2 extends string, C extends Record<string, ColumnBuilder>>(\n tableName: TName2,\n columns: C,\n options?: TableOptions<C>,\n ) {\n return buildTable(tableName, columns, options, effective)\n },\n }\n}\n\nexport function isPgSchema(value: unknown): value is PgSchema<string> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __isPgSchema?: unknown }).__isPgSchema === true\n )\n}\n","/**\n * Other ways to declare a table. Each one hands the same builders to\n * `table()` / `pgSchema(schema).table()`, so what comes out is an ordinary\n * table: snapshots, migrations, the query client and `insertSchema` can't\n * tell which form declared it.\n *\n * // builder fields — plain thunks even for self-references and cycles\n * class Users {\n * static readonly tableName = 'users'\n * id = uuid().primaryKey().defaultRandom()\n * @Rule({ format: 'email' }) email = varchar(120).notNull()\n * }\n * export const users = tableFromClass(Users)\n *\n * // base class — the class is the row type and can carry methods\n * export class User extends TableBase('users', { id: uuid().primaryKey(), email: varchar(120).notNull() }) {}\n *\n * // fluent — typed self-references, duplicate columns rejected\n * export const users = defineTable('users').column('id', uuid().primaryKey()).build()\n *\n * Validation rules declared with a form (`@Rule`, `rules`, `.column(k, b, rule)`)\n * travel with the table: `insertSchema(users)` applies them.\n */\nimport type { ColumnRule, SchemaLike } from '../schema'\nimport type {\n ColumnBuilder,\n ColumnRef,\n NotNullBrand,\n TypedColumnRef,\n TypedColumnRefs,\n} from './columns/types'\nimport { ColumnBuilder as ColumnBuilderClass } from './columns/types'\nimport type { TableConstraint } from './constraints'\nimport { pgSchema } from './pg-schema'\nimport { table, type TableDecl } from './table'\n\ntype ColumnsRecord = Record<string, ColumnBuilder>\ntype Constraints = (refs: never) => Record<string, TableConstraint>\ntype Rules = Record<string, ColumnRule | SchemaLike>\n\n/** The Postgres schema of a table: `undefined` for none or `public`. */\ntype SchemaOf<S> = S extends string ? (S extends 'public' ? undefined : `${S}`) : undefined\n\n/**\n * Build through `table()` / `pgSchema(schema).table()` — the one place every\n * form turns into a table — and attach the form's validation rules, which\n * `insertSchema` / `selectSchema` / `updateSchema` read.\n */\nfunction build(\n name: string,\n columns: ColumnsRecord,\n schema: string | undefined,\n constraints: Constraints | undefined,\n rules: Rules,\n) {\n const decl = schema\n ? pgSchema(schema).table(name, columns, constraints as never)\n : table(name, columns, constraints as never)\n // Not enumerable: a table's own keys are its column refs.\n if (Object.keys(rules).length > 0) {\n Object.defineProperty(decl, '__rules', { value: { ...rules }, enumerable: false })\n }\n return decl\n}\n\n// ── Rules ───────────────────────────────────────────────────────────────\n\n/** Rules for a string column. */\nexport type StringRule = Pick<ColumnRule, 'format' | 'minLength' | 'maxLength' | 'pattern'>\n/** Rules for a numeric column. */\nexport type NumberRule = Pick<ColumnRule, 'minimum' | 'maximum'>\n\n/** The rules a column of this builder may take — a string rule on a number column fails to compile. */\nexport type RuleFor<B> =\n | SchemaLike\n | (B extends ColumnBuilder<infer T>\n ? [T] extends [string]\n ? StringRule\n : [T] extends [number]\n ? NumberRule\n : never\n : never)\n\n// ── Builder fields ──────────────────────────────────────────────────────\n\ntype BuilderKeys<I> = { [K in keyof I]: I[K] extends ColumnBuilder ? K : never }[keyof I]\ntype BuilderFields<I> = { [K in BuilderKeys<I>]: I[K] extends ColumnBuilder ? I[K] : never }\n\n/** A class whose fields are column builders — the input to {@link tableFromClass}. */\nexport interface TableClass {\n new (): object\n /** The table's name. */\n readonly tableName: string\n /** Postgres schema the table lives in — `pgSchema(schema).table(...)`. */\n readonly schema?: string\n /** Indexes, unique constraints, `primaryKey()` and `check()`, over {@link ClassRefs} of the class. */\n readonly indexes?: (refs: never) => Record<string, TableConstraint>\n}\n\n/** Column refs of a builder-field class, for its `static indexes`. */\nexport type ClassRefs<C extends new () => object> = TypedColumnRefs<BuilderFields<InstanceType<C>>>\n\nconst FIELD_RULES = Symbol.for('@forinda/kickjs-db/field-rules')\nconst CLASS_TABLE = Symbol.for('@forinda/kickjs-db/class-table')\n\n/**\n * Validation a column's SQL type can't express, on a builder field. The rule\n * has to fit the column: `@Rule({ minLength: 2 })` on an integer column is a\n * type error.\n */\nexport function Rule(\n rule: StringRule,\n): <K extends string>(prototype: { [P in K]: ColumnBuilder<string> }, key: K) => void\nexport function Rule(\n rule: NumberRule,\n): <K extends string>(prototype: { [P in K]: ColumnBuilder<number> }, key: K) => void\nexport function Rule(rule: SchemaLike): (prototype: object, key: string) => void\nexport function Rule(rule: ColumnRule | SchemaLike) {\n return (prototype: object, key: string): void => {\n const ctor = prototype.constructor as unknown as Record<symbol, Rules>\n if (!Object.hasOwn(ctor, FIELD_RULES)) ctor[FIELD_RULES] = { ...ctor[FIELD_RULES] }\n ctor[FIELD_RULES]![key] = rule\n }\n}\n\n/**\n * The table a builder-field class declares — built once, then the same\n * object on every call. Fields that aren't column builders are ignored.\n */\nexport function tableFromClass<C extends TableClass>(\n cls: C,\n): TableDecl<\n // Re-stated as a template literal: `static readonly x = 'users'` is a\n // *widening* literal, which becomes `string` the moment the table goes\n // through a generic function (relations(), the client) — losing the key.\n `${C['tableName']}`,\n BuilderFields<InstanceType<C>>,\n C extends { schema: infer S } ? SchemaOf<S> : undefined\n> &\n TypedColumnRefs<BuilderFields<InstanceType<C>>> {\n const meta = cls as unknown as Record<symbol, unknown>\n if (!Object.hasOwn(meta, CLASS_TABLE)) {\n // One instance, to read the initializers. The builders are the column\n // declarations themselves, so the table owns them from here on.\n const instance = new cls() as Record<string, unknown>\n const columns: ColumnsRecord = {}\n for (const [key, value] of Object.entries(instance)) {\n if (value instanceof ColumnBuilderClass) columns[key] = value\n }\n if (Object.keys(columns).length === 0) throw new Error(`${cls.name} has no column fields`)\n const rules = (meta[FIELD_RULES] as Rules | undefined) ?? {}\n meta[CLASS_TABLE] = build(cls.tableName, columns, cls.schema, cls.indexes, rules)\n }\n return meta[CLASS_TABLE] as never\n}\n\n// ── Base class ──────────────────────────────────────────────────────────\n\ntype RowOf<C extends ColumnsRecord> = {\n [K in keyof C]: C[K] extends ColumnBuilder<infer T>\n ? C[K] extends NotNullBrand\n ? T\n : T | null\n : never\n}\n\n/**\n * A class for a table: `class User extends TableBase('users', { ... }) {}`.\n * The columns are an object literal, so types infer exactly as with\n * `table()`. The class is the row type and can hold methods; `User.table` is\n * the table, and exporting the class is enough for `kick db generate` and\n * `createDbClient({ schema })`.\n */\nexport function TableBase<\n const N extends string,\n C extends ColumnsRecord,\n const S extends string | undefined = undefined,\n>(\n name: N,\n columns: C,\n options: {\n schema?: S\n rules?: { [K in keyof C]?: RuleFor<C[K]> }\n indexes?: (refs: TypedColumnRefs<C>) => Record<string, TableConstraint>\n } = {},\n) {\n const decl = build(\n name,\n columns,\n options.schema,\n options.indexes as Constraints | undefined,\n (options.rules ?? {}) as Rules,\n ) as TableDecl<N, C, SchemaOf<S>> & TypedColumnRefs<C>\n\n abstract class Base {\n static readonly table = decl\n /** A subclass instance holding `row` — for methods over a row. */\n static from<T extends Base>(this: new () => T, row: RowOf<C>): T {\n return Object.assign(new this(), row)\n }\n }\n // One construct signature, returning the row. The class's own would make\n // a second, and `extends` rejects two (\"Base constructors must all have the\n // same return type\").\n return Base as unknown as (abstract new () => RowOf<C>) & {\n readonly table: typeof decl\n from<T>(this: new () => T, row: RowOf<C>): T\n }\n}\n\n// ── Fluent ──────────────────────────────────────────────────────────────\n\n/** A table being declared column by column — see {@link defineTable}. */\nexport class TableDefinition<\n N extends string,\n C extends ColumnsRecord,\n S extends string | undefined,\n> {\n constructor(\n private readonly name: N,\n private readonly schema: S,\n private readonly columns: C,\n private readonly columnRules: Rules,\n private readonly constraints: Constraints | undefined,\n /** Shared by every step of one chain; `build()` fills it in. */\n private readonly built: { decl?: Record<string, ColumnRef> },\n ) {}\n\n /**\n * Add a column. A name already declared is a type error, and `rule` must\n * fit the column. `builder` may be a function of the columns declared so\n * far — a self-reference with no annotation, key and type checked:\n * `.column('parentId', (t) => fk(uuid(), () => t.id))`.\n */\n column<const K extends string, B extends ColumnBuilder>(\n key: K extends keyof C ? never : K,\n builder: B | ((refs: TypedColumnRefs<C>) => B),\n rule?: RuleFor<B>,\n ): TableDefinition<N, C & { [P in K]: B }, S> {\n const resolved =\n typeof builder === 'function' ? builder(this.lazyRefs() as TypedColumnRefs<C>) : builder\n return new TableDefinition(\n this.name,\n this.schema,\n { ...this.columns, [key]: resolved } as C & { [P in K]: B },\n rule ? { ...this.columnRules, [key]: rule as ColumnRule | SchemaLike } : this.columnRules,\n this.constraints,\n this.built,\n )\n }\n\n /** Indexes / unique constraints over the columns declared so far. Calls add up. */\n index(\n constraints: (refs: TypedColumnRefs<C>) => Record<string, TableConstraint>,\n ): TableDefinition<N, C, S> {\n const previous = this.constraints\n const next = constraints as Constraints\n const combined: Constraints = previous ? (refs) => ({ ...previous(refs), ...next(refs) }) : next\n return new TableDefinition(\n this.name,\n this.schema,\n this.columns,\n this.columnRules,\n combined,\n this.built,\n )\n }\n\n build(): TableDecl<N, C, SchemaOf<S>> & TypedColumnRefs<C> {\n const decl = build(this.name, this.columns, this.schema, this.constraints, this.columnRules)\n this.built.decl = decl as unknown as Record<string, ColumnRef>\n return decl as never\n }\n\n /**\n * Refs for `.column(key, (t) => ...)` callbacks. The table doesn't exist\n * yet, so each ref resolves when a foreign-key thunk runs — after `build()`.\n */\n private lazyRefs(): Record<string, ColumnRef> {\n const built = this.built\n const owner =\n this.schema && this.schema !== 'public' ? `${this.schema}.${this.name}` : this.name\n return new Proxy({} as Record<string, ColumnRef>, {\n get: (_, key: string) =>\n ({\n __tableName: owner,\n __name: key,\n get __builder() {\n return built.decl![key]!.__builder\n },\n __state: () => built.decl![key]!.__state(),\n }) as ColumnRef,\n })\n }\n}\n\n/**\n * Declare a table column by column:\n * `defineTable('users').column('id', uuid().primaryKey()).build()`.\n */\nexport function defineTable<const N extends string, const S extends string | undefined = undefined>(\n name: N,\n options: { schema?: S } = {},\n): TableDefinition<N, {}, S> {\n return new TableDefinition(name, options.schema as S, {}, {}, undefined, {})\n}\n\n// ── Typed foreign keys ──────────────────────────────────────────────────\n\n/**\n * A foreign key whose target must hold the same type:\n * `authorId: fk(uuid().notNull(), () => users.id)` — a uuid column pointing\n * at a serial key is a type error. Same as `.references()` at runtime.\n */\nexport function fk<T, B extends ColumnBuilder<T>>(\n builder: B & ColumnBuilder<T>,\n target: () => TypedColumnRef<NoInfer<T>>,\n options: Parameters<ColumnBuilder['references']>[1] = {},\n): B {\n return builder.references(target, options) as B\n}\n\n/**\n * Add a foreign key to a column after both tables exist — how two tables\n * reference each other without an annotation:\n *\n * const users = table('users', { id: uuid().primaryKey(), featuredPostId: integer() })\n * const posts = table('posts', { id: serial().primaryKey(), authorId: fk(uuid(), () => users.id) })\n * link(users.featuredPostId, () => posts.id)\n *\n * Declared inside the initializers, each table's type would wait on the\n * other's (TS7022). References are read at snapshot time, so adding one\n * afterwards is the same as declaring it.\n */\nexport function link<T>(\n column: TypedColumnRef<T>,\n target: () => TypedColumnRef<NoInfer<T>>,\n options: Parameters<ColumnBuilder['references']>[1] = {},\n): void {\n column.__builder.references(target, options)\n}\n","import type { IndexSnapshot } from '../snapshot/types'\nimport type { PolicyDecl } from './rls'\n\ninterface ColRef {\n __name: string\n}\n\n/** An index key part: a column, or an SQL expression such as `'lower(email)'`. */\nexport type IndexKey = ColRef | string\n\nfunction keyName(key: IndexKey): string {\n return typeof key === 'string' ? `(${key})` : key.__name\n}\n\n/**\n * An index declared in a table's constraint builder. Chain the options;\n * each returns the same declaration:\n *\n * index('users_active_email').on(t.email).where('\"deletedAt\" IS NULL')\n * index('users_email_lower').on('lower(email)')\n * index('docs_embedding').on(t.embedding).using('hnsw').op(t.embedding, 'vector_cosine_ops')\n * index('orders_customer').on(t.customerId).include(t.total).concurrently()\n */\nexport class IndexDecl {\n /** The index as recorded in the snapshot. */\n readonly __index: IndexSnapshot\n\n constructor(name: string, keys: IndexKey[], unique: boolean) {\n this.__index = { name, columns: keys.map(keyName), unique }\n }\n\n /** Make it a partial index over the rows matching `predicate` (Postgres, SQLite). */\n where(predicate: string): this {\n this.__index.where = predicate\n return this\n }\n\n /** The index method: `gin`, `gist`, `brin`, `hash`, `hnsw`, `ivfflat` … (MySQL: `btree` / `hash`). */\n using(method: string): this {\n this.__index.using = method\n return this\n }\n\n /** Store these columns in the index without making them part of the key (Postgres). */\n include(...cols: ColRef[]): this {\n this.__index.include = cols.map((c) => c.__name)\n return this\n }\n\n /** The operator class for one key part, e.g. `vector_cosine_ops` or `gin_trgm_ops` (Postgres). */\n op(key: IndexKey, opclass: string): this {\n const name = keyName(key)\n if (!this.__index.columns.includes(name)) {\n throw new Error(`kickjs-db: index '${this.__index.name}' has no key ${name} to give op()`)\n }\n this.__index.opclasses = { ...this.__index.opclasses, [name]: opclass }\n return this\n }\n\n /**\n * Build and drop it with `CONCURRENTLY`, without blocking writes (Postgres).\n * `kick db generate` puts each such change in a migration of its own that\n * runs outside a transaction, as `CONCURRENTLY` requires.\n */\n concurrently(): this {\n this.__index.concurrently = true\n return this\n }\n}\n\nexport function index(name: string) {\n return {\n on(...keys: IndexKey[]): IndexDecl {\n return new IndexDecl(name, keys, false)\n },\n }\n}\n\nexport function unique(name: string) {\n return {\n on(...keys: IndexKey[]): IndexDecl {\n return new IndexDecl(name, keys, true)\n },\n }\n}\n\n/** A table's primary key, declared on its own — required for a composite or named key. */\nexport interface PrimaryKeyDecl {\n kind: 'primaryKey'\n /** Constraint name; Postgres otherwise names it `<table>_pkey`. MySQL and SQLite ignore it. */\n name?: string\n columns: string[]\n}\n\n/** A CHECK constraint. */\nexport interface CheckDecl {\n kind: 'check'\n name: string\n /** SQL boolean expression, written for the target dialect. */\n expression: string\n}\n\n/** Anything a table's constraint builder may return. */\nexport type TableConstraint = IndexDecl | PrimaryKeyDecl | CheckDecl | PolicyDecl\n\n/**\n * The table's primary key, over one or more columns, in key order:\n *\n * table('memberships', { teamId: integer(), userId: integer() }, (t) => ({\n * pk: primaryKey('memberships_pk').on(t.teamId, t.userId),\n * }))\n *\n * Use this or a column's `.primaryKey()`, not both.\n */\nexport function primaryKey(name?: string) {\n return {\n on(...cols: ColRef[]): PrimaryKeyDecl {\n return name === undefined\n ? { kind: 'primaryKey', columns: cols.map((c) => c.__name) }\n : { kind: 'primaryKey', name, columns: cols.map((c) => c.__name) }\n },\n }\n}\n\n/**\n * A CHECK constraint — `check('price_positive', 'price > 0')`. The\n * expression is SQL, passed through as written.\n */\nexport function check(name: string, expression: string): CheckDecl {\n return { kind: 'check', name, expression }\n}\n","import type { ColumnBuilder, TypedColumnRefs } from './columns/types'\nimport { qualifiedTableName, type TableDecl } from './table'\n\ntype Qualified<TName extends string, TSchema> = TSchema extends string\n ? `${TSchema}.${TName}`\n : TName\n\n/** A table under a second name: its columns, plus `$from` for `selectFrom` / joins. */\nexport type AliasedTable<\n TName extends string,\n C extends Record<string, ColumnBuilder>,\n TSchema extends string | undefined,\n A extends string,\n> = TypedColumnRefs<C> & {\n /** `'<table> as <alias>'` — what `selectFrom` and the joins take. */\n readonly $from: `${Qualified<TName, TSchema>} as ${A}`\n}\n\n/**\n * The same table under another name, for self-joins and reading a table twice.\n * Its columns work with the condition helpers:\n *\n * const manager = alias(users, 'manager')\n * db.selectFrom('users')\n * .innerJoin(manager.$from, (j) => j.on(eq(manager.id, users.managerId)))\n * .select(['users.name', 'manager.name as managerName'])\n */\nexport function alias<\n TName extends string,\n C extends Record<string, ColumnBuilder>,\n TSchema extends string | undefined,\n A extends string,\n>(table: TableDecl<TName, C, TSchema>, name: A): AliasedTable<TName, C, TSchema, A> {\n const refs: Record<string, unknown> = {}\n for (const [key, builder] of Object.entries(table.__columns)) {\n refs[key] = {\n __tableName: name,\n __name: key,\n __builder: builder,\n __state: () => builder.__state(),\n }\n }\n refs.$from = `${qualifiedTableName(table)} as ${name}`\n return refs as AliasedTable<TName, C, TSchema, A>\n}\n","/**\n * Standalone condition helpers — `eq(users.email, x)`, `and(…)`, `or(…)` —\n * for anyone who prefers them to Kysely's `eb('col', '=', x)`. Each returns\n * a Kysely `Expression<SqlBool>`, so it goes wherever one is taken:\n * `.where(…)`, `.on(…)` in a join, `having`, and `db.query`'s `where`.\n *\n * An operand is one of:\n * - a column of a schema table (`users.email`) or of an `alias()`;\n * - the row argument of a `db.query` callback (`(u) => eq(u.email, x)`);\n * - any Kysely expression (`eb.ref('email')`, `sql\\`lower(email)\\``);\n * - otherwise a value, sent as a bound parameter.\n */\nimport { sql, type Expression, type RawBuilder, type SelectType, type SqlBool } from 'kysely'\nimport type { ColumnRef, TypedColumnRef } from '../dsl/columns/types'\n\n/** The value type an operand stands for. */\ntype ValueOf<O> = O extends TypedColumnRef<infer T> ? T : O extends Expression<infer T> ? T : O\n\n/** What may sit across from `O`: a value of its type, or anything standing for one. */\ntype Comparable<O> = Operand<SelectType<ValueOf<O>>>\n\n/** A column, a Kysely expression, or a value. */\nexport type Operand<T = unknown> = TypedColumnRef<T> | Expression<T> | T\n\ntype Condition = RawBuilder<SqlBool>\n\nfunction isExpression(value: unknown): value is Expression<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { toOperationNode?: unknown }).toOperationNode === 'function'\n )\n}\n\nfunction isColumnRef(value: unknown): value is ColumnRef {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ColumnRef).__tableName === 'string' &&\n typeof (value as ColumnRef).__name === 'string'\n )\n}\n\n/** An operand as SQL: a qualified column reference, the expression itself, or a parameter. */\nfunction toSql(operand: unknown): Expression<unknown> {\n if (isExpression(operand)) return operand\n if (isColumnRef(operand)) return sql.ref(`${operand.__tableName}.${operand.__name}`)\n return sql.val(operand)\n}\n\nfunction binary(op: string) {\n return <L>(left: L, right: Comparable<L>): Condition =>\n sql<SqlBool>`${toSql(left)} ${sql.raw(op)} ${toSql(right)}`\n}\n\nexport const eq = binary('=')\nexport const ne = binary('<>')\nexport const gt = binary('>')\nexport const gte = binary('>=')\nexport const lt = binary('<')\nexport const lte = binary('<=')\n\n/** `left LIKE pattern` — escape user input with `escapeLike()`. */\nexport const like = <L>(left: L, pattern: Operand<string>): Condition =>\n sql<SqlBool>`${toSql(left)} like ${toSql(pattern)}`\nexport const notLike = <L>(left: L, pattern: Operand<string>): Condition =>\n sql<SqlBool>`${toSql(left)} not like ${toSql(pattern)}`\n/** Case-insensitive `LIKE` (Postgres). */\nexport const ilike = <L>(left: L, pattern: Operand<string>): Condition =>\n sql<SqlBool>`${toSql(left)} ilike ${toSql(pattern)}`\n\nexport const isNull = (operand: unknown): Condition => sql<SqlBool>`${toSql(operand)} is null`\nexport const isNotNull = (operand: unknown): Condition =>\n sql<SqlBool>`${toSql(operand)} is not null`\n\n/** `left IN (…)`. An empty list matches nothing, rather than being invalid SQL. */\nexport function inArray<L>(left: L, values: readonly Comparable<L>[]): Condition {\n if (values.length === 0) return sql<SqlBool>`1 = 0`\n return sql<SqlBool>`${toSql(left)} in (${sql.join(values.map(toSql))})`\n}\n\n/** `left NOT IN (…)`. An empty list matches everything. */\nexport function notInArray<L>(left: L, values: readonly Comparable<L>[]): Condition {\n if (values.length === 0) return sql<SqlBool>`1 = 1`\n return sql<SqlBool>`${toSql(left)} not in (${sql.join(values.map(toSql))})`\n}\n\nexport const between = <L>(left: L, low: Comparable<L>, high: Comparable<L>): Condition =>\n sql<SqlBool>`${toSql(left)} between ${toSql(low)} and ${toSql(high)}`\n\n/**\n * All of the conditions. `undefined` entries are skipped, so a filter can be\n * built conditionally: `and(eq(t.a, a), b ? eq(t.b, b) : undefined)`. With\n * none left it matches every row.\n */\nexport function and(...conditions: (Expression<SqlBool> | undefined)[]): Condition {\n return combine(conditions, 'and', sql<SqlBool>`1 = 1`)\n}\n\n/** Any of the conditions; `undefined` entries are skipped. With none left it matches no row. */\nexport function or(...conditions: (Expression<SqlBool> | undefined)[]): Condition {\n return combine(conditions, 'or', sql<SqlBool>`1 = 0`)\n}\n\nfunction combine(\n conditions: (Expression<SqlBool> | undefined)[],\n op: 'and' | 'or',\n empty: Condition,\n): Condition {\n const present = conditions.filter((c): c is Expression<SqlBool> => c !== undefined)\n if (present.length === 0) return empty\n return sql<SqlBool>`(${sql.join(present, sql.raw(` ${op} `))})`\n}\n\nexport const not = (condition: Expression<SqlBool>): Condition => sql<SqlBool>`not (${condition})`\n\n/** `EXISTS (subquery)` — pass a Kysely select; it brings its own parentheses. */\nexport const exists = (subquery: Expression<unknown>): Condition => sql<SqlBool>`exists ${subquery}`\nexport const notExists = (subquery: Expression<unknown>): Condition =>\n sql<SqlBool>`not exists ${subquery}`\n","import type { ColumnBuilder } from './columns/types'\nimport type { ColumnRef, TableDecl } from './table'\n\n/**\n * Generic over the target table so the typegen plugin can pull\n * `target['__name']` without losing the literal string at the type\n * level. Existing callers that only read `kind` / `fields` /\n * `references` see the same surface.\n */\nexport interface RelationOne<\n TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<\n string,\n Record<string, ColumnBuilder>\n >,\n> {\n kind: 'one'\n target: TTarget\n fields: ColumnRef[]\n references: ColumnRef[]\n /**\n * Disambiguates this relation from sibling `one` relations on the\n * same source table that point at the same target. Pair with the\n * matching `relationName` on the inverse `many` side.\n */\n relationName?: string\n}\n\nexport interface RelationMany<\n TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<\n string,\n Record<string, ColumnBuilder>\n >,\n> {\n kind: 'many'\n target: TTarget\n /**\n * A many-to-many through a junction table: `many(tags, { through: postTags })`.\n * The junction's foreign keys to each side decide the join; when it has\n * more than one to a side (a self-referencing `follows`), name them:\n * `{ table: follows, from: [follows.followerId], to: [follows.followeeId] }`.\n */\n through?: ThroughSpec\n /**\n * Pairs with the matching `relationName` on the inverse `one`\n * declaration. Required when the source table has multiple FKs\n * to the same target; resolver throws\n * `RelationalQueryMissingInverseError` otherwise.\n */\n relationName?: string\n}\n\nexport type ThroughSpec =\n | TableDecl<string, Record<string, ColumnBuilder>>\n | { table: TableDecl<string, Record<string, ColumnBuilder>>; from: ColumnRef[]; to: ColumnRef[] }\n\nexport type Relation = RelationOne | RelationMany\n\n/**\n * Generic so the typegen plugin can read the source table name and\n * the per-relation kind/target via `RelationsDecl['__sourceTable']`\n * and `RelationsDecl['__relations']`. The runtime shape is\n * unchanged; the generic parameters narrow the type at call sites.\n */\nexport interface RelationsDecl<\n TSource extends string = string,\n TRelations extends Record<string, Relation> = Record<string, Relation>,\n> {\n __isRelations: true\n __sourceTable: TSource\n __relations: TRelations\n}\n\ninterface Helpers {\n one: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(\n target: T,\n opts: { fields: ColumnRef[]; references: ColumnRef[]; relationName?: string },\n ) => RelationOne<T>\n many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(\n target: T,\n opts?: { relationName?: string; through?: ThroughSpec },\n ) => RelationMany<T>\n}\n\n/**\n * Declare a typed relation set for `source`. The return type\n * preserves `source.__name` and the literal `kind`/`target` of every\n * helper-built entry so `SchemaToRelationsRegister<S>` (re-exported\n * from `@forinda/kickjs-db`) can walk the schema barrel and emit a\n * matching `KickDbRelationsRegister` augmentation at typegen time.\n */\nexport function relations<\n T extends TableDecl<string, Record<string, ColumnBuilder>>,\n R extends Record<string, Relation>,\n>(source: T, builder: (h: Helpers) => R): RelationsDecl<T['__name'], R> {\n const helpers: Helpers = {\n one: (target, opts) => ({\n kind: 'one',\n target,\n fields: opts.fields,\n references: opts.references,\n ...(opts.relationName !== undefined ? { relationName: opts.relationName } : {}),\n }),\n many: (target, opts) => ({\n kind: 'many',\n target,\n ...(opts?.relationName !== undefined ? { relationName: opts.relationName } : {}),\n ...(opts?.through !== undefined ? { through: opts.through } : {}),\n }),\n }\n return {\n __isRelations: true,\n __sourceTable: source.__name,\n __relations: builder(helpers),\n } as RelationsDecl<T['__name'], R>\n}\n","/**\n * LIKE / ILIKE pattern safety helpers.\n *\n * User-supplied search text dropped straight into a `LIKE` pattern lets\n * the user inject wildcards: searching for `100%` matches everything,\n * `a_b` matches `axb`. Worse, a literal `%` from the user combined with a\n * leading wildcard (`%${input}%`) can blow up to a full scan. These\n * helpers escape the LIKE metacharacters so the input is matched\n * literally.\n *\n * Escapes `%`, `_`, and the escape character itself. The default escape\n * char is backslash, which Postgres and MySQL use by default. SQLite has\n * no default escape character — add `ESCAPE '\\'` to the LIKE there, or\n * the escapes are matched as literal backslashes.\n */\n\nexport type LikeMatchMode = 'contains' | 'startsWith' | 'endsWith' | 'exact'\n\n/**\n * Escape LIKE/ILIKE metacharacters in `input` so it matches literally.\n *\n * @example\n * ```ts\n * escapeLike('100%') // '100\\\\%'\n * escapeLike('a_b\\\\c') // 'a\\\\_b\\\\\\\\c'\n * ```\n */\nexport function escapeLike(input: string, escapeChar = '\\\\'): string {\n // The escape char must be exactly one character and not a wildcard\n // itself — `''` would be a no-op, `'%'`/`'_'` would over-escape and\n // corrupt the literal match. This is a safety primitive, so reject\n // bad config loudly rather than emit a silently-wrong pattern.\n if (escapeChar.length !== 1 || escapeChar === '%' || escapeChar === '_') {\n throw new Error(\"escapeLike: escapeChar must be a single character other than '%' or '_'\")\n }\n // Escape the escape char first so we don't double-escape the\n // backslashes we add for % and _.\n const e = escapeChar\n return input\n .replaceAll(e, e + e)\n .replaceAll('%', e + '%')\n .replaceAll('_', e + '_')\n}\n\n/**\n * Build a literal-safe LIKE pattern from user input.\n *\n * @example\n * ```ts\n * likePattern('john%', 'contains') // '%john\\\\%%'\n * likePattern('admin', 'startsWith') // 'admin%'\n * db.selectFrom('users')\n * .where('email', 'like', likePattern(ctx.qs().search, 'contains'))\n * ```\n */\nexport function likePattern(\n input: string,\n mode: LikeMatchMode = 'contains',\n escapeChar = '\\\\',\n): string {\n const safe = escapeLike(input, escapeChar)\n switch (mode) {\n case 'contains':\n return `%${safe}%`\n case 'startsWith':\n return `${safe}%`\n case 'endsWith':\n return `%${safe}`\n case 'exact':\n return safe\n default: {\n // Compile-time exhaustiveness + a runtime guard for JS callers /\n // `as any` that pass an unsupported mode (would otherwise return\n // undefined despite the `: string` signature).\n const _exhaustive: never = mode\n throw new Error(`likePattern: unsupported match mode ${String(_exhaustive)}`)\n }\n }\n}\n","import { sql, type Expression } from 'kysely'\n\n/**\n * Sort direction for a relational `orderBy`, which takes expressions:\n *\n * orderBy: (p, eb) => desc(eb.ref('publishedAt'))\n * orderBy: (p, eb) => [desc(eb.ref('priority')), asc(eb.ref('title'))]\n *\n * Works at the top level and inside `with`, on every dialect.\n */\nexport function desc<T>(expression: Expression<T>): Expression<T> {\n return sql<T>`${expression} desc`\n}\n\n/** Ascending order — the default, spelled out. See {@link desc}. */\nexport function asc<T>(expression: Expression<T>): Expression<T> {\n return sql<T>`${expression} asc`\n}\n"],"mappings":";;;;;;;;;;00BA4BA,SAAgB,mBAAmB,SAAkC,CACnE,IAAM,kBAAoB,IAAI,IACxB,aAAyB,CAAC,EAI1B,MAAQ,SAAS,OAAS,CAAC,EAGjC,IAAK,IAAM,SAAS,OAAO,OAAO,SAAS,MAAM,EAC/C,aAAa,KAAK,YAAY,MAAO,kBAAmB,KAAK,CAAC,EAEhE,IAAM,MAAQ,OAAO,OAAO,SAAS,OAAS,CAAC,CAAC,EAChD,IAAK,IAAM,KAAK,MAAO,aAAa,KAAK,WAAW,EAAG,kBAAmB,KAAK,CAAC,EAEhF,IAAM,QAAU,CAAC,QAAS,GAAG,MAAM,KAAK,iBAAiB,CAAC,CAAC,SAAS,CAAC,EACjE,MAAM,KAAM,GAAM,CAAC,EAAE,YAAY,GAAG,QAAQ,KAAK,MAAM,EAC3D,IAAM,YAAc,MAAM,QAAS,GAAM,EAAE,SAAW,CAAC,CAAC,EACpD,YAAY,KAAM,GAAM,CAAC,EAAE,MAAM,GAAK,CAAC,QAAQ,SAAS,OAAO,GAAG,QAAQ,KAAK,OAAO,EACtF,YAAY,KAAM,GAAM,EAAE,MAAM,GAAK,CAAC,QAAQ,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