@forinda/kickjs-db 7.1.1 → 7.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/dist/cli.d.mts CHANGED
@@ -1,8 +1,7 @@
1
1
 
2
- import { Ut as DriftBehavior, er as Dialect, nt as DbConfig, rt as MigrationAdapterFactory } from "./index-DcuMZ9kb.mjs";
2
+ import { Kt as DriftBehavior, ir as Dialect, nt as DbConfig, rt as MigrationAdapterFactory } from "./index-Ci5DXgUh.mjs";
3
3
  import { CliTypegen, KickCliPlugin } from "@forinda/kickjs-cli-kit";
4
4
  import { Command } from "commander";
5
-
6
5
  //#region src/cli-typegen.d.ts
7
6
  declare const kickDbTypegen: () => CliTypegen;
8
7
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;cA4Ba,aAAA,QAAoB,UAsC/B;;;;;;;;;UClBe,iBAAA;EACf,UAAA;EACA,aAAA;EACA,OAAA,GAAU,OAAA;EACV,gBAAA;EACA,OAAA,GAAU,uBAAA;;;;;;EAMV,UAAA,GAAa,aAAA;AAAA;AAkBf;;;;;;AAAA,iBATgB,kBAAA,CAAmB,GAAA,EAAK,iBAAA,GAAoB,iBAAiB;;AAWzD;AAKpB;;;iBAPgB,iBAAA,IACX,OAAA,GAAU,iBAAA,kBACZ,iBAAiB;;iBAKJ,mBAAA,CAAoB,KAAA,EAAO,iBAAA,eAAgC,QAAQ;;KAuFvE,gBAAA,SAAyB,QAAA,GAAW,OAAA,CAAQ,QAAA;AAvF2B;AAuFnF;;;;;;;AAvFmF,iBAiGnE,kBAAA,CAAmB,MAAA,EAAQ,OAAA,EAAS,SAAA,EAAW,gBAAgB;;;;;AAVf;AAUhE;;;;;;;;cAiNa,WAAA,EAAa,aASxB"}
1
+ {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;cA4Ba,qBAAoB;;;;;;;;;UCoBhB;EACf;EACA;EACA,UAAU;EACV;EACA,UAAU;;;;;;EAMV,aAAa;;;;;;;;iBASC,mBAAmB,KAAK,oBAAoB;;;;;;iBAS5C,qBACX,UAAU,mCACZ;;iBAKa,oBAAoB,OAAO,gCAAgC;;KAuF/D,yBAAyB,WAAW,QAAQ;;;;;;;;;iBAUxC,mBAAmB,QAAQ,SAAS,WAAW;;;;;;;;;;;;;;cAiNlD,aAAa"}
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v7.1.1
2
+ * @forinda/kickjs-db v7.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{$ as migrateStatus,Dt as detectCompositeReferences,M as generate,P as reviewMigration,Q as migrateRollback,X as migrateDown,Z as migrateLatest,et as migrateUp,jt as renderSchemaSource}from"./src-_M69mn2G.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";const DEFAULT_SCHEMA_PATHS=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],kickDbTypegen=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(ctx){let schemaAbs=resolveSchema(ctx.cwd,ctx.config?.db?.schemaPath);if(!schemaAbs)return null;let typesDir=path.resolve(ctx.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${posix(path.relative(typesDir,schemaAbs)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
11
+ import{$ as migrateUp,At as renderSchemaSource,Et as detectCompositeReferences,N as reviewMigration,Q as migrateStatus,X as migrateLatest,Y as migrateDown,Z as migrateRollback,j as generate}from"./src-DibJVBOu.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";const DEFAULT_SCHEMA_PATHS=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],kickDbTypegen=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(ctx){let schemaAbs=resolveSchema(ctx.cwd,ctx.config?.db?.schemaPath);if(!schemaAbs)return null;let typesDir=path.resolve(ctx.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${posix(path.relative(typesDir,schemaAbs)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
12
12
  `)}});function resolveSchema(cwd,configuredPath){if(configuredPath){let abs=path.resolve(cwd,configuredPath);if(existsSync(abs))return abs;let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}for(let candidate of DEFAULT_SCHEMA_PATHS){let abs=path.resolve(cwd,candidate);if(candidate.endsWith(`.ts`)){if(existsSync(abs))return abs}else{let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}}return null}function posix(p){return p.replace(/\\/g,`/`)}function defineKickDbConfig(cfg){return cfg}function mergeKickDbConfig(...configs){return Object.assign({},...configs.filter(Boolean))}function resolveKickDbConfig(block){let db=block??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck}}async function resolveAdapter(config){if(config.adapter){let adapter=await config.adapter();return{adapter,cleanup:async()=>adapter.close()}}if(!config.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory`);let dialect=config.dialect??`postgres`;if(dialect!==`postgres`)throw Error(`kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`);let[{pgAdapter},pg]=await Promise.all([import(`./pg.mjs`),import(`pg`)]),pool=new pg.default.Pool({connectionString:config.connectionString}),adapter=pgAdapter({pool});return{adapter,cleanup:async()=>{await adapter.close(),await pool.end()}}}async function tryResolvePgQueryRunner(config){if(config.adapter||(config.dialect??`postgres`)!==`postgres`||!config.connectionString)return null;let pool=new(await(import(`pg`))).default.Pool({connectionString:config.connectionString});return{runner:pool,cleanup:async()=>void await pool.end()}}function printStatusTable(status){if(status.length===0){console.log(`No migrations.`);return}console.table(status.map(s=>({id:s.id,state:s.state,batch:s.batch??`-`,reviewed:s.reviewed,applied:s.appliedAt??`-`})))}function registerDbCommands(parent,getConfig){parent.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(name,opts)=>{let cwd=process.cwd(),config=await getConfig(),probe=await tryResolvePgQueryRunner(config),detectCompositeRefs=probe?enumName=>detectCompositeReferences(probe.runner,enumName):void 0;try{let result=await generate({name,config,cwd,empty:opts.empty,detectCompositeRefs});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`);return}let plural=result.changeCount===1?``:`s`;console.log(`Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`)}finally{await probe?.cleanup()}});let migrate=parent.command(`migrate`).description(`Migration runner subcommands`);migrate.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`up`).description(`Apply the next single pending migration`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateUp({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed?`Reversed ${r.reversed}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed.length===0?`Nothing to roll back.`:`Rolled back batch ${r.batch}: ${r.reversed.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`status`).description(`Print applied + pending migrations`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{printStatusTable(await migrateStatus({adapter,migrationsDir:config.migrationsDir}))}finally{await cleanup()}}),migrate.command(`review <id>`).description(`Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)`).action(async id=>{let r=await reviewMigration((await getConfig()).migrationsDir,id);console.log(r.alreadyReviewed?`${r.id} was already reviewed.`:`Reviewed ${r.id} — it can now be applied.`)}),parent.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let snapshot=await adapter.introspect();if(opts.json){console.log(JSON.stringify(snapshot,null,2));return}let out=opts.out??config.schemaPath;await writeFile(out,renderSchemaSource(snapshot),`utf8`);let n=Object.keys(snapshot.tables).length;console.log(`Wrote ${out} (${n} table${n===1?``:`s`}).`)}finally{await cleanup()}})}function dbBlockOf(config){return config?.db}const dbCliPlugin=defineCliPlugin({name:`kick/db`,register(program,ctx){registerDbCommands(program.command(`db`).description(`Database commands (kickjs-db)`),()=>resolveKickDbConfig(dbBlockOf(ctx.config)))},typegens:[kickDbTypegen()]});export{dbCliPlugin,defineKickDbConfig,kickDbTypegen,mergeKickDbConfig,registerDbCommands,resolveKickDbConfig};
13
13
  //# sourceMappingURL=cli.mjs.map
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"sourcesContent":["/**\n * `kick/db` typegen — reads the adopter's schema (`src/db/schema.ts` or a\n * `src/db/schema/` barrel) and emits `.kickjs/types/kick__db.d.ts` with\n * three augmentations:\n *\n * 1. global `KickDbSchema = SchemaToTypes<typeof appSchema>` — column\n * shapes computed at type-check time, no runtime cost.\n * 2. `KickDbRegister.db = KickDbClient<KickDbSchema>` — bare\n * `KickDbClient` widens automatically.\n * 3. `KickDbRelationsRegister.db = SchemaToRelationsRegister<typeof\n * appSchema>` — typed `with` keys for `db.query.X.findMany`.\n *\n * Shipped on {@link dbCliPlugin} (`typegens`) so mounting the db plugin\n * brings both the `kick db` commands and this type generation. Typed\n * against the `@forinda/kickjs-cli-kit` `CliTypegen` contract so it needs\n * no kickjs-cli internals — it only reads `ctx.cwd`.\n */\nimport path from 'node:path'\nimport { existsSync } from 'node:fs'\n\nimport type { CliTypegen } from '@forinda/kickjs-cli-kit'\n\nconst DEFAULT_SCHEMA_PATHS = [\n 'src/db/schema.ts',\n 'src/db/schema/index.ts',\n 'src/db/schema',\n] as const\n\nexport const kickDbTypegen = (): CliTypegen => ({\n id: 'kick/db',\n inputs: ['src/db/schema.ts', 'src/db/schema/**/*.ts'],\n async generate(ctx: { cwd: string; config?: { db?: { schemaPath?: string } } }) {\n // Parity with `kick db generate` (cli/config.ts resolveDbConfig):\n // an adopter-configured `db.schemaPath` must drive BOTH the\n // migration engine and this augmentation — previously only the\n // default candidates were probed, so a custom path produced\n // working migrations but a silently untyped client.\n const schemaAbs = resolveSchema(ctx.cwd, ctx.config?.db?.schemaPath)\n if (!schemaAbs) return null\n\n // Strip the `.ts` extension and any trailing `/index` so the import\n // specifier stays stable across single-file vs barrel-folder layouts.\n const typesDir = path.resolve(ctx.cwd, '.kickjs/types')\n const rel = posix(path.relative(typesDir, schemaAbs))\n .replace(/\\.ts$/, '')\n .replace(/\\/index$/, '')\n\n return [\n `import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,\n `import type * as appSchema from '${rel}'`,\n ``,\n `declare global {`,\n ` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,\n `}`,\n ``,\n `declare module '@forinda/kickjs-db' {`,\n ` interface KickDbRegister {`,\n ` db: KickDbClient<KickDbSchema>`,\n ` }`,\n ``,\n ` interface KickDbRelationsRegister {`,\n ` db: SchemaToRelationsRegister<typeof appSchema>`,\n ` }`,\n `}`,\n ].join('\\n')\n },\n})\n\nfunction resolveSchema(cwd: string, configuredPath?: string): string | null {\n // kick.config `db.schemaPath` wins when the file exists; a configured-\n // but-missing path falls through to the candidates rather than\n // emitting an augmentation with a broken import specifier.\n if (configuredPath) {\n const abs = path.resolve(cwd, configuredPath)\n if (existsSync(abs)) return abs\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n for (const candidate of DEFAULT_SCHEMA_PATHS) {\n const abs = path.resolve(cwd, candidate)\n if (candidate.endsWith('.ts')) {\n if (existsSync(abs)) return abs\n } else {\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n }\n return null\n}\n\nfunction posix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n","/**\n * `@forinda/kickjs-db/cli` — the database command tree as a mountable CLI\n * plugin + the building blocks for a standalone `kickjs-db` bin.\n *\n * Two ways to use it:\n * 1. **As a kickjs-cli plugin** — add `dbCliPlugin` to `kick.config.ts`\n * `plugins: []`. The host CLI calls `register(program, ctx)` and the\n * db config is read from `ctx.config.db` (already loaded — no re-parse).\n * 2. **Standalone** — the `kickjs-db` bin builds a commander program,\n * resolves config from `kickjs-db.config.ts` (or a `kick.config.ts`\n * `db` block), and calls {@link registerDbCommands} directly. Lets\n * `npx kickjs-db migrate latest` work without installing kickjs-cli.\n *\n * @module @forinda/kickjs-db/cli\n */\n\nimport { writeFile } from 'node:fs/promises'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\n reviewMigration,\n renderSchemaSource,\n type CompositeQueryRunner,\n type DbConfig,\n type MigrationAdapter,\n} from './index'\nimport type { Dialect } from './snapshot/types'\nimport type { MigrationAdapterFactory } from './cli/config'\nimport type { DriftBehavior } from './migrate/drift'\n\n/**\n * Authoring shape for the db config — every field optional, defaults\n * applied by {@link resolveKickDbConfig}. This is the same shape as the\n * `db` block in `kick.config.ts`, so a config authored with\n * `defineKickDbConfig` drops straight into either place.\n */\nexport interface KickDbConfigInput {\n schemaPath?: string\n migrationsDir?: string\n dialect?: Dialect\n connectionString?: string\n adapter?: MigrationAdapterFactory\n /**\n * How `migrate` reacts to out-of-band schema (drift): `'error'`\n * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,\n * so SQLite/MySQL's lossy introspection doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n}\n\n/**\n * Identity helper for type inference — mirrors vite's `defineConfig`.\n * Use it in a standalone `kickjs-db.config.ts` (`export default\n * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s\n * `db` field. Both resolve through {@link resolveKickDbConfig}.\n */\nexport function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput {\n return cfg\n}\n\n/**\n * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).\n * Lets a standalone `kickjs-db.config.ts` layer over a project's\n * `kick.config.ts` `db` block, or vice versa.\n */\nexport function mergeKickDbConfig(\n ...configs: (KickDbConfigInput | undefined)[]\n): KickDbConfigInput {\n return Object.assign({}, ...configs.filter(Boolean))\n}\n\n/** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */\nexport function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig {\n const db = block ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\n }\n}\n\n/**\n * Resolve a MigrationAdapter from config:\n * 1. config.adapter() — explicit factory wins.\n * 2. config.connectionString — built-in pgAdapter path; dynamically\n * imports `./pg` + `pg` so non-PG workflows don't pull pg.\n */\nasync function resolveAdapter(config: DbConfig): Promise<{\n adapter: MigrationAdapter\n cleanup: () => Promise<void>\n}> {\n if (config.adapter) {\n const adapter = await config.adapter()\n return { adapter, cleanup: async () => adapter.close() }\n }\n if (!config.connectionString) {\n throw new Error(\n 'kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory',\n )\n }\n const dialect = config.dialect ?? 'postgres'\n if (dialect !== 'postgres') {\n throw new Error(\n `kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`,\n )\n }\n // Dynamic import so we don't hard-require pg unless this path runs.\n const [{ pgAdapter }, pg] = await Promise.all([import('./pg'), import('pg')])\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n const adapter = pgAdapter({ pool })\n return {\n adapter,\n cleanup: async () => {\n await adapter.close()\n await pool.end()\n },\n }\n}\n\ninterface PgQueryRunnerProbe {\n runner: CompositeQueryRunner\n cleanup: () => Promise<void>\n}\n\n/**\n * Resolve a pg-protocol query runner for the composite-type check at\n * `generate` time. Only fires for the built-in pgAdapter path\n * (dialect=postgres + connection string, no custom adapter factory).\n */\nasync function tryResolvePgQueryRunner(config: DbConfig): Promise<PgQueryRunnerProbe | null> {\n if (config.adapter) return null\n if ((config.dialect ?? 'postgres') !== 'postgres') return null\n if (!config.connectionString) return null\n\n const pg = await import('pg')\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n return { runner: pool, cleanup: async () => void (await pool.end()) }\n}\n\nfunction printStatusTable(status: Awaited<ReturnType<typeof migrateStatus>>): void {\n if (status.length === 0) {\n console.log('No migrations.')\n return\n }\n console.table(\n status.map((s) => ({\n id: s.id,\n state: s.state,\n batch: s.batch ?? '-',\n reviewed: s.reviewed,\n applied: s.appliedAt ?? '-',\n })),\n )\n}\n\n/** A config source — resolved lazily so each command reads fresh config. */\nexport type DbConfigResolver = () => DbConfig | Promise<DbConfig>\n\n/**\n * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a\n * commander command. `parent` is the command they hang off — the plugin\n * passes a `db` subcommand (so `kick db generate`), the standalone bin\n * passes the root program (so `kickjs-db generate`). `getConfig` supplies\n * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,\n * standalone from `kickjs-db.config.ts`.\n */\nexport function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void {\n parent\n .command('generate <name>')\n .description('Generate a new migration from schema diff')\n .option(\n '-e, --empty',\n 'Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)',\n )\n .action(async (name: string, opts: { empty?: boolean }) => {\n const cwd = process.cwd()\n const config = await getConfig()\n\n const probe = await tryResolvePgQueryRunner(config)\n const detectCompositeRefs = probe\n ? (enumName: string) => detectCompositeReferences(probe.runner, enumName)\n : undefined\n\n try {\n const result = await generate({ name, config, cwd, empty: opts.empty, detectCompositeRefs })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`)\n return\n }\n const plural = result.changeCount === 1 ? '' : 's'\n console.log(\n `Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`,\n )\n } finally {\n await probe?.cleanup()\n }\n })\n\n // ── migrate runner subcommands ─────────────────────────────────────────\n const migrate = parent.command('migrate').description('Migration runner subcommands')\n\n migrate\n .command('latest')\n .description('Apply all pending migrations in a new batch')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied batch ${r.batch}: ${r.applied.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('up')\n .description('Apply the next single pending migration')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied[0]} (batch ${r.batch})`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('down')\n .description('Reverse the most recent applied migration')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(r.reversed ? `Reversed ${r.reversed}.` : 'Nothing to reverse.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\n : `Rolled back batch ${r.batch}: ${r.reversed.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('status')\n .description('Print applied + pending migrations')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n printStatusTable(await migrateStatus({ adapter, migrationsDir: config.migrationsDir }))\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('review <id>')\n .description('Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)')\n .action(async (id: string) => {\n // No adapter/DB needed — review only touches the migration files.\n const config = await getConfig()\n const r = await reviewMigration(config.migrationsDir, id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already reviewed.`\n : `Reviewed ${r.id} — it can now be applied.`,\n )\n })\n\n // ── kick db introspect ─────────────────────────────────────────────────\n parent\n .command('introspect')\n .description('Generate a TypeScript schema file from a live database')\n .option('--out <path>', 'Output file (defaults to db.schemaPath from config)')\n .option('--json', 'Print the raw SchemaSnapshot JSON to stdout instead of writing TS source')\n .action(async (opts: { out?: string; json?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const snapshot = await adapter.introspect()\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2))\n return\n }\n const out = opts.out ?? config.schemaPath\n await writeFile(out, renderSchemaSource(snapshot), 'utf8')\n const n = Object.keys(snapshot.tables).length\n console.log(`Wrote ${out} (${n} table${n === 1 ? '' : 's'}).`)\n } finally {\n await cleanup()\n }\n })\n}\n\n/**\n * Read the `db` block off a host CLI config object. The kit types\n * `ctx.config` as `unknown`; the db block is structurally a\n * {@link KickDbConfigInput}.\n */\nfunction dbBlockOf(config: unknown): KickDbConfigInput | undefined {\n return (config as { db?: KickDbConfigInput } | null)?.db\n}\n\n/**\n * The database CLI plugin. Mount it in `kick.config.ts`:\n *\n * ```ts\n * import { defineConfig } from '@forinda/kickjs-cli'\n * import { dbCliPlugin } from '@forinda/kickjs-db/cli'\n *\n * export default defineConfig({ plugins: [dbCliPlugin] })\n * ```\n *\n * `kick db generate|migrate|introspect` then read config from the\n * `db` block of the same `kick.config.ts`.\n */\nexport const dbCliPlugin: KickCliPlugin = defineCliPlugin({\n name: 'kick/db',\n register(program, ctx) {\n const db = program.command('db').description('Database commands (kickjs-db)')\n registerDbCommands(db, () => resolveKickDbConfig(dbBlockOf(ctx.config)))\n },\n // Mounting the plugin also wires `.kickjs/types/kick__db.d.ts` generation\n // into `kick typegen` — db commands + db types from one opt-in plugin.\n typegens: [kickDbTypegen()],\n})\n"],"mappings":";;;;;;;;;;iXAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,GAAI,UACJ,OAAQ,CAAC,mBAAoB,uBAAuB,EACpD,MAAM,SAAS,IAAiE,CAM9E,IAAM,UAAY,cAAc,IAAI,IAAK,IAAI,QAAQ,IAAI,UAAU,EACnE,GAAI,CAAC,UAAW,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,CAAC,CACzE,EAGA,SAAU,CAAC,cAAc,CAAC,CAC5B,CAAC"}
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"sourcesContent":["/**\n * `kick/db` typegen — reads the adopter's schema (`src/db/schema.ts` or a\n * `src/db/schema/` barrel) and emits `.kickjs/types/kick__db.d.ts` with\n * three augmentations:\n *\n * 1. global `KickDbSchema = SchemaToTypes<typeof appSchema>` — column\n * shapes computed at type-check time, no runtime cost.\n * 2. `KickDbRegister.db = KickDbClient<KickDbSchema>` — bare\n * `KickDbClient` widens automatically.\n * 3. `KickDbRelationsRegister.db = SchemaToRelationsRegister<typeof\n * appSchema>` — typed `with` keys for `db.query.X.findMany`.\n *\n * Shipped on {@link dbCliPlugin} (`typegens`) so mounting the db plugin\n * brings both the `kick db` commands and this type generation. Typed\n * against the `@forinda/kickjs-cli-kit` `CliTypegen` contract so it needs\n * no kickjs-cli internals — it only reads `ctx.cwd`.\n */\nimport path from 'node:path'\nimport { existsSync } from 'node:fs'\n\nimport type { CliTypegen } from '@forinda/kickjs-cli-kit'\n\nconst DEFAULT_SCHEMA_PATHS = [\n 'src/db/schema.ts',\n 'src/db/schema/index.ts',\n 'src/db/schema',\n] as const\n\nexport const kickDbTypegen = (): CliTypegen => ({\n id: 'kick/db',\n inputs: ['src/db/schema.ts', 'src/db/schema/**/*.ts'],\n async generate(ctx: { cwd: string; config?: { db?: { schemaPath?: string } } }) {\n // Parity with `kick db generate` (cli/config.ts resolveDbConfig):\n // an adopter-configured `db.schemaPath` must drive BOTH the\n // migration engine and this augmentation — previously only the\n // default candidates were probed, so a custom path produced\n // working migrations but a silently untyped client.\n const schemaAbs = resolveSchema(ctx.cwd, ctx.config?.db?.schemaPath)\n if (!schemaAbs) return null\n\n // Strip the `.ts` extension and any trailing `/index` so the import\n // specifier stays stable across single-file vs barrel-folder layouts.\n const typesDir = path.resolve(ctx.cwd, '.kickjs/types')\n const rel = posix(path.relative(typesDir, schemaAbs))\n .replace(/\\.ts$/, '')\n .replace(/\\/index$/, '')\n\n return [\n `import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,\n `import type * as appSchema from '${rel}'`,\n ``,\n `declare global {`,\n ` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,\n `}`,\n ``,\n `declare module '@forinda/kickjs-db' {`,\n ` interface KickDbRegister {`,\n ` db: KickDbClient<KickDbSchema>`,\n ` }`,\n ``,\n ` interface KickDbRelationsRegister {`,\n ` db: SchemaToRelationsRegister<typeof appSchema>`,\n ` }`,\n `}`,\n ].join('\\n')\n },\n})\n\nfunction resolveSchema(cwd: string, configuredPath?: string): string | null {\n // kick.config `db.schemaPath` wins when the file exists; a configured-\n // but-missing path falls through to the candidates rather than\n // emitting an augmentation with a broken import specifier.\n if (configuredPath) {\n const abs = path.resolve(cwd, configuredPath)\n if (existsSync(abs)) return abs\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n for (const candidate of DEFAULT_SCHEMA_PATHS) {\n const abs = path.resolve(cwd, candidate)\n if (candidate.endsWith('.ts')) {\n if (existsSync(abs)) return abs\n } else {\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n }\n return null\n}\n\nfunction posix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n","/**\n * `@forinda/kickjs-db/cli` — the database command tree as a mountable CLI\n * plugin + the building blocks for a standalone `kickjs-db` bin.\n *\n * Two ways to use it:\n * 1. **As a kickjs-cli plugin** — add `dbCliPlugin` to `kick.config.ts`\n * `plugins: []`. The host CLI calls `register(program, ctx)` and the\n * db config is read from `ctx.config.db` (already loaded — no re-parse).\n * 2. **Standalone** — the `kickjs-db` bin builds a commander program,\n * resolves config from `kickjs-db.config.ts` (or a `kick.config.ts`\n * `db` block), and calls {@link registerDbCommands} directly. Lets\n * `npx kickjs-db migrate latest` work without installing kickjs-cli.\n *\n * @module @forinda/kickjs-db/cli\n */\n\nimport { writeFile } from 'node:fs/promises'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\n reviewMigration,\n renderSchemaSource,\n type CompositeQueryRunner,\n type DbConfig,\n type MigrationAdapter,\n} from './index'\nimport type { Dialect } from './snapshot/types'\nimport type { MigrationAdapterFactory } from './cli/config'\nimport type { DriftBehavior } from './migrate/drift'\n\n/**\n * Authoring shape for the db config — every field optional, defaults\n * applied by {@link resolveKickDbConfig}. This is the same shape as the\n * `db` block in `kick.config.ts`, so a config authored with\n * `defineKickDbConfig` drops straight into either place.\n */\nexport interface KickDbConfigInput {\n schemaPath?: string\n migrationsDir?: string\n dialect?: Dialect\n connectionString?: string\n adapter?: MigrationAdapterFactory\n /**\n * How `migrate` reacts to out-of-band schema (drift): `'error'`\n * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,\n * so SQLite/MySQL's lossy introspection doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n}\n\n/**\n * Identity helper for type inference — mirrors vite's `defineConfig`.\n * Use it in a standalone `kickjs-db.config.ts` (`export default\n * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s\n * `db` field. Both resolve through {@link resolveKickDbConfig}.\n */\nexport function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput {\n return cfg\n}\n\n/**\n * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).\n * Lets a standalone `kickjs-db.config.ts` layer over a project's\n * `kick.config.ts` `db` block, or vice versa.\n */\nexport function mergeKickDbConfig(\n ...configs: (KickDbConfigInput | undefined)[]\n): KickDbConfigInput {\n return Object.assign({}, ...configs.filter(Boolean))\n}\n\n/** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */\nexport function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig {\n const db = block ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n driftCheck: db.driftCheck,\n }\n}\n\n/**\n * Resolve a MigrationAdapter from config:\n * 1. config.adapter() — explicit factory wins.\n * 2. config.connectionString — built-in pgAdapter path; dynamically\n * imports `./pg` + `pg` so non-PG workflows don't pull pg.\n */\nasync function resolveAdapter(config: DbConfig): Promise<{\n adapter: MigrationAdapter\n cleanup: () => Promise<void>\n}> {\n if (config.adapter) {\n const adapter = await config.adapter()\n return { adapter, cleanup: async () => adapter.close() }\n }\n if (!config.connectionString) {\n throw new Error(\n 'kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory',\n )\n }\n const dialect = config.dialect ?? 'postgres'\n if (dialect !== 'postgres') {\n throw new Error(\n `kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`,\n )\n }\n // Dynamic import so we don't hard-require pg unless this path runs.\n const [{ pgAdapter }, pg] = await Promise.all([import('./pg'), import('pg')])\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n const adapter = pgAdapter({ pool })\n return {\n adapter,\n cleanup: async () => {\n await adapter.close()\n await pool.end()\n },\n }\n}\n\ninterface PgQueryRunnerProbe {\n runner: CompositeQueryRunner\n cleanup: () => Promise<void>\n}\n\n/**\n * Resolve a pg-protocol query runner for the composite-type check at\n * `generate` time. Only fires for the built-in pgAdapter path\n * (dialect=postgres + connection string, no custom adapter factory).\n */\nasync function tryResolvePgQueryRunner(config: DbConfig): Promise<PgQueryRunnerProbe | null> {\n if (config.adapter) return null\n if ((config.dialect ?? 'postgres') !== 'postgres') return null\n if (!config.connectionString) return null\n\n const pg = await import('pg')\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n return { runner: pool, cleanup: async () => void (await pool.end()) }\n}\n\nfunction printStatusTable(status: Awaited<ReturnType<typeof migrateStatus>>): void {\n if (status.length === 0) {\n console.log('No migrations.')\n return\n }\n console.table(\n status.map((s) => ({\n id: s.id,\n state: s.state,\n batch: s.batch ?? '-',\n reviewed: s.reviewed,\n applied: s.appliedAt ?? '-',\n })),\n )\n}\n\n/** A config source — resolved lazily so each command reads fresh config. */\nexport type DbConfigResolver = () => DbConfig | Promise<DbConfig>\n\n/**\n * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a\n * commander command. `parent` is the command they hang off — the plugin\n * passes a `db` subcommand (so `kick db generate`), the standalone bin\n * passes the root program (so `kickjs-db generate`). `getConfig` supplies\n * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,\n * standalone from `kickjs-db.config.ts`.\n */\nexport function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void {\n parent\n .command('generate <name>')\n .description('Generate a new migration from schema diff')\n .option(\n '-e, --empty',\n 'Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)',\n )\n .action(async (name: string, opts: { empty?: boolean }) => {\n const cwd = process.cwd()\n const config = await getConfig()\n\n const probe = await tryResolvePgQueryRunner(config)\n const detectCompositeRefs = probe\n ? (enumName: string) => detectCompositeReferences(probe.runner, enumName)\n : undefined\n\n try {\n const result = await generate({ name, config, cwd, empty: opts.empty, detectCompositeRefs })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`)\n return\n }\n const plural = result.changeCount === 1 ? '' : 's'\n console.log(\n `Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`,\n )\n } finally {\n await probe?.cleanup()\n }\n })\n\n // ── migrate runner subcommands ─────────────────────────────────────────\n const migrate = parent.command('migrate').description('Migration runner subcommands')\n\n migrate\n .command('latest')\n .description('Apply all pending migrations in a new batch')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied batch ${r.batch}: ${r.applied.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('up')\n .description('Apply the next single pending migration')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied[0]} (batch ${r.batch})`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('down')\n .description('Reverse the most recent applied migration')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(r.reversed ? `Reversed ${r.reversed}.` : 'Nothing to reverse.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\n : `Rolled back batch ${r.batch}: ${r.reversed.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('status')\n .description('Print applied + pending migrations')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n printStatusTable(await migrateStatus({ adapter, migrationsDir: config.migrationsDir }))\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('review <id>')\n .description('Mark a migration reviewed (flips meta.json; migrates legacy -- REVIEWED markers)')\n .action(async (id: string) => {\n // No adapter/DB needed — review only touches the migration files.\n const config = await getConfig()\n const r = await reviewMigration(config.migrationsDir, id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already reviewed.`\n : `Reviewed ${r.id} — it can now be applied.`,\n )\n })\n\n // ── kick db introspect ─────────────────────────────────────────────────\n parent\n .command('introspect')\n .description('Generate a TypeScript schema file from a live database')\n .option('--out <path>', 'Output file (defaults to db.schemaPath from config)')\n .option('--json', 'Print the raw SchemaSnapshot JSON to stdout instead of writing TS source')\n .action(async (opts: { out?: string; json?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const snapshot = await adapter.introspect()\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2))\n return\n }\n const out = opts.out ?? config.schemaPath\n await writeFile(out, renderSchemaSource(snapshot), 'utf8')\n const n = Object.keys(snapshot.tables).length\n console.log(`Wrote ${out} (${n} table${n === 1 ? '' : 's'}).`)\n } finally {\n await cleanup()\n }\n })\n}\n\n/**\n * Read the `db` block off a host CLI config object. The kit types\n * `ctx.config` as `unknown`; the db block is structurally a\n * {@link KickDbConfigInput}.\n */\nfunction dbBlockOf(config: unknown): KickDbConfigInput | undefined {\n return (config as { db?: KickDbConfigInput } | null)?.db\n}\n\n/**\n * The database CLI plugin. Mount it in `kick.config.ts`:\n *\n * ```ts\n * import { defineConfig } from '@forinda/kickjs-cli'\n * import { dbCliPlugin } from '@forinda/kickjs-db/cli'\n *\n * export default defineConfig({ plugins: [dbCliPlugin] })\n * ```\n *\n * `kick db generate|migrate|introspect` then read config from the\n * `db` block of the same `kick.config.ts`.\n */\nexport const dbCliPlugin: KickCliPlugin = defineCliPlugin({\n name: 'kick/db',\n register(program, ctx) {\n const db = program.command('db').description('Database commands (kickjs-db)')\n registerDbCommands(db, () => resolveKickDbConfig(dbBlockOf(ctx.config)))\n },\n // Mounting the plugin also wires `.kickjs/types/kick__db.d.ts` generation\n // into `kick typegen` — db commands + db types from one opt-in plugin.\n typegens: [kickDbTypegen()],\n})\n"],"mappings":";;;;;;;;;;gXAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,GAAI,UACJ,OAAQ,CAAC,mBAAoB,uBAAuB,EACpD,MAAM,SAAS,IAAiE,CAM9E,IAAM,UAAY,cAAc,IAAI,IAAK,IAAI,QAAQ,IAAI,UAAU,EACnE,GAAI,CAAC,UAAW,OAAO,KAIvB,IAAM,SAAW,KAAK,QAAQ,IAAI,IAAK,eAAe,EAKtD,MAAO,CACL,mGACA,oCANU,MAAM,KAAK,SAAS,SAAU,SAAS,CAAC,CAAC,CAClD,QAAQ,QAAS,EAAE,CAAC,CACpB,QAAQ,WAAY,EAIiB,EAAE,GACxC,GACA,mBACA,sEACA,IACA,GACA,wCACA,+BACA,qCACA,MACA,GACA,wCACA,sDACA,MACA,GACF,CAAC,CAAC,KAAK;CAAI,CACb,CACF,GAEA,SAAS,cAAc,IAAa,eAAwC,CAI1E,GAAI,eAAgB,CAClB,IAAM,IAAM,KAAK,QAAQ,IAAK,cAAc,EAC5C,GAAI,WAAW,GAAG,EAAG,OAAO,IAC5B,IAAM,IAAM,KAAK,KAAK,IAAK,UAAU,EACrC,GAAI,WAAW,GAAG,EAAG,OAAO,GAC9B,CACA,IAAK,IAAM,aAAa,qBAAsB,CAC5C,IAAM,IAAM,KAAK,QAAQ,IAAK,SAAS,EACvC,GAAI,UAAU,SAAS,KAAK,EACtB,IAAA,WAAW,GAAG,EAAG,OAAO,GAAA,KACvB,CACL,IAAM,IAAM,KAAK,KAAK,IAAK,U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SAAU,KAAM,CAAC,CAAC,EAC7C,MACF,CACA,IAAM,IAAM,KAAK,KAAO,OAAO,WAC/B,MAAM,UAAU,IAAK,mBAAmB,QAAQ,EAAG,MAAM,EACzD,IAAM,EAAI,OAAO,KAAK,SAAS,MAAM,CAAC,CAAC,OACvC,QAAQ,IAAI,SAAS,IAAI,IAAI,EAAE,QAAQ,IAAM,EAAI,GAAK,IAAI,GAAG,CAC/D,QAAU,CACR,MAAM,QAAQ,CAChB,CACF,CAAC,CACL,CAOA,SAAS,UAAU,OAAgD,CACjE,OAAQ,QAA8C,EACxD,CAeA,MAAa,YAA6B,gBAAgB,CACxD,KAAM,UACN,SAAS,QAAS,IAAK,CAErB,mBADW,QAAQ,QAAQ,IAAI,CAAC,CAAC,YAAY,+BACzB,MAAS,oBAAoB,UAAU,IAAI,MAAM,CAAC,CAAC,CACzE,EAGA,SAAU,CAAC,cAAc,CAAC,CAC5B,CAAC"}
@@ -1,6 +1,5 @@
1
1
 
2
- import { a as QueryErrorEvent, o as QueryEvent, s as SlowQueryEvent } from "./types-BZGFAXPN.mjs";
3
-
2
+ import { a as QueryErrorEvent, o as QueryEvent, s as SlowQueryEvent } from "./types-NkfgZHEN.mjs";
4
3
  //#region src/devtools-events.d.ts
5
4
  declare module '@forinda/kickjs-devtools-kit/bus' {
6
5
  interface KickDevtoolsEventRegistry {
@@ -26,5 +25,5 @@ declare module '@forinda/kickjs-devtools-kit/bus' {
26
25
  batch: number | null;
27
26
  };
28
27
  }
29
- } //# sourceMappingURL=devtools-events.d.ts.map
28
+ }
30
29
  //# sourceMappingURL=devtools-events.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"devtools-events.d.mts","names":[],"sources":["../src/devtools-events.ts"],"mappings":";;;;;YAsBY,yBAAA;IAHqE;;;;;IAS7E,UAAA,EAAY,UAAA;MAAe,OAAA;IAAA;IANnB;IAQR,eAAA,EAAiB,cAAA;IAFL;IAIZ,gBAAA,EAAkB,eAAA;IAFlB;;;;;IAQA,sBAAA;MAA0B,OAAA;MAAmB,KAAA;IAAA;EAAA;AAAA"}
1
+ {"version":3,"file":"devtools-events.d.mts","names":[],"sources":["../src/devtools-events.ts"],"mappings":";;;;YAsBY;;;;;;IAMR,YAAY;MAAe;;;IAE3B,iBAAiB;;IAEjB,kBAAkB;;;;;;IAMlB;MAA0B;MAAmB"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v7.1.1
2
+ * @forinda/kickjs-db v7.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,9 +1,8 @@
1
1
 
2
- import { h as RelationMapEntry, n as CreateDbClientOptions, r as KickDbClient } from "./types-BZGFAXPN.mjs";
2
+ import { h as RelationMapEntry, n as CreateDbClientOptions, r as KickDbClient } from "./types-NkfgZHEN.mjs";
3
3
  import { InjectionToken } from "@forinda/kickjs";
4
4
  import { Generated, KyselyPlugin } from "kysely";
5
5
  import { ReadonlyKysely } from "kysely/readonly";
6
-
7
6
  //#region src/snapshot/types.d.ts
8
7
  type Dialect$1 = 'postgres' | 'sqlite' | 'mysql';
9
8
  type FkAction = 'cascade' | 'restrict' | 'set_null' | 'set_default' | 'no_action';
@@ -32,7 +31,18 @@ interface CheckSnapshot {
32
31
  expression: string;
33
32
  }
34
33
  interface TableSnapshot {
34
+ /**
35
+ * Bare table name, unqualified. The schema (when any) lives in
36
+ * {@link TableSnapshot.schema}; the map key on `SchemaSnapshot.tables` is
37
+ * the qualified form (`billing.invoices`).
38
+ */
35
39
  name: string;
40
+ /**
41
+ * Named SQL schema, from `pgSchema('x').table(...)`. Absent for tables in
42
+ * the connection's default search_path, which keeps pre-schema snapshots
43
+ * byte-identical (and their migration hashes valid).
44
+ */
45
+ schema?: string;
36
46
  columns: Record<string, ColumnSnapshot>;
37
47
  indexes: IndexSnapshot[];
38
48
  foreignKeys: ForeignKeySnapshot[];
@@ -78,7 +88,20 @@ interface RelationSnapshot {
78
88
  interface SchemaSnapshot {
79
89
  version: 1;
80
90
  dialect: Dialect$1;
91
+ /**
92
+ * Keyed by QUALIFIED name — `billing.invoices` for a table declared through
93
+ * `pgSchema('billing')`, the bare name otherwise. Qualifying the key is what
94
+ * lets two schemas hold same-named tables without colliding, and it makes
95
+ * every `table: string` field on a diff `Change` already schema-correct:
96
+ * `quoteIdent` splits on `.`, rendering `"billing"."invoices"`.
97
+ */
81
98
  tables: Record<string, TableSnapshot>;
99
+ /**
100
+ * Named schemas the tables in this snapshot live in, sorted. Drives
101
+ * `CREATE SCHEMA IF NOT EXISTS` emission. PG-only; absent when no table
102
+ * declares a schema, so existing snapshots keep their exact shape.
103
+ */
104
+ schemas?: readonly string[];
82
105
  /** ENUM types declared via `pgEnum()`. PG-only; absent on other dialects. */
83
106
  enums?: Record<string, EnumSnapshot>;
84
107
  /**
@@ -113,6 +136,19 @@ declare function extractSnapshot(schema: Record<string, unknown>, dialect: Diale
113
136
  declare function renderSchemaSource(snapshot: SchemaSnapshot): string;
114
137
  //#endregion
115
138
  //#region src/diff/types.d.ts
139
+ /**
140
+ * `CREATE SCHEMA IF NOT EXISTS "x"` — emitted ahead of every table change so
141
+ * a new schema exists before anything is created inside it.
142
+ *
143
+ * There is deliberately no `dropSchema` counterpart. A schema can hold objects
144
+ * this app never declared (another service's tables, extensions, views), so a
145
+ * `DROP SCHEMA` inferred from "no table references it any more" could destroy
146
+ * data the diff never saw. Removing a schema stays a manual operation.
147
+ */
148
+ interface CreateSchema {
149
+ kind: 'createSchema';
150
+ schema: string;
151
+ }
116
152
  interface CreateTable {
117
153
  kind: 'createTable';
118
154
  table: TableSnapshot;
@@ -231,7 +267,7 @@ interface RemoveEnumValue {
231
267
  default: string | null;
232
268
  }[];
233
269
  }
234
- type Change = CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumn | AddIndex | DropIndex | AddForeignKey | DropForeignKey | CreateEnum | DropEnum | AddEnumValue | RemoveEnumValue;
270
+ type Change = CreateSchema | CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumn | AddIndex | DropIndex | AddForeignKey | DropForeignKey | CreateEnum | DropEnum | AddEnumValue | RemoveEnumValue;
235
271
  type ChangeSet = Change[];
236
272
  //#endregion
237
273
  //#region src/diff/engine.d.ts
@@ -772,14 +808,37 @@ declare function unique(name: string): {
772
808
  };
773
809
  //#endregion
774
810
  //#region src/dsl/table.d.ts
775
- interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>> {
811
+ interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>, TSchema extends string | undefined = string | undefined> {
776
812
  __isTable: true;
777
813
  __name: TName;
778
814
  __columns: C;
779
815
  __indexes: IndexDecl[];
816
+ /**
817
+ * Named SQL schema this table lives in, from `pgSchema('x').table(...)`.
818
+ * `undefined` means the connection's default search_path (`public` on PG),
819
+ * which is every table declared through the bare `table()` factory.
820
+ *
821
+ * PostgreSQL only — `assertSchemasSupported()` rejects a declared schema
822
+ * on MySQL/SQLite at snapshot time rather than emitting subtly wrong DDL.
823
+ */
824
+ __schema?: TSchema;
780
825
  }
781
- type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>> = TableDecl<TName, C> & { [K in keyof C]: ColumnRef };
782
- type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: { [K in keyof C]: ColumnRef }) => Record<string, IndexDecl>;
826
+ /**
827
+ * Fully-qualified name used as the snapshot key, the Kysely table key, and
828
+ * the emitted identifier. `quoteIdent` splits on `.`, so `billing.invoices`
829
+ * renders as `"billing"."invoices"` with no further work.
830
+ *
831
+ * Unqualified tables keep their bare name, so every pre-schema snapshot,
832
+ * migration hash, and `KickDbSchema` key is byte-identical to before.
833
+ */
834
+ type QualifiedName<TName extends string, TSchema extends string | undefined> = TSchema extends string ? `${TSchema}.${TName}` : TName;
835
+ /** Runtime counterpart of {@link QualifiedName}. */
836
+ declare function qualifiedTableName(decl: {
837
+ __name: string;
838
+ __schema?: string | undefined;
839
+ }): string;
840
+ type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined = undefined> = TableDecl<TName, C, TSchema> & { [K in keyof C]: ColumnRef; };
841
+ type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: { [K in keyof C]: ColumnRef; }) => Record<string, IndexDecl>;
783
842
  /**
784
843
  * Declare a typed table. The `TName extends string` generic narrows to the
785
844
  * literal table name so `SchemaToTypes<S>` can index by it without losing
@@ -787,6 +846,11 @@ type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: { [K in
787
846
  * not `TableDecl<string, …>`.
788
847
  */
789
848
  declare function table<TName extends string, C extends Record<string, ColumnBuilder>>(name: TName, columns: C, constraints?: ConstraintBuilder<C>): TableRefs<TName, C>;
849
+ /**
850
+ * Shared table constructor. `table()` passes `schema: undefined`;
851
+ * `pgSchema('x').table()` passes the schema name through.
852
+ */
853
+ declare function buildTable<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined>(name: TName, columns: C, constraints: ConstraintBuilder<C> | undefined, schema: TSchema): TableRefs<TName, C, TSchema>;
790
854
  //#endregion
791
855
  //#region src/client/schema-types.d.ts
792
856
  /**
@@ -807,7 +871,25 @@ declare function table<TName extends string, C extends Record<string, ColumnBuil
807
871
  */
808
872
  type IsNullable<C> = C extends NotNullBrand ? false : true;
809
873
  type ColumnTSType<C> = C extends ColumnBuilder<infer T> ? IsNullable<C> extends true ? C extends GeneratedBrand ? Generated<T> | null : T | null : C extends GeneratedBrand ? Generated<T> : T : never;
810
- type SchemaToTypes<S> = { [K in keyof S as S[K] extends TableDecl<string, Record<string, ColumnBuilder>> ? S[K]['__name'] : never]: S[K] extends TableDecl<string, infer C> ? { [Col in keyof C]: ColumnTSType<C[Col]> } : never };
874
+ /**
875
+ * Table key Kysely sees. A table declared via `pgSchema('billing').table(...)`
876
+ * keys as `'billing.invoices'` — Kysely treats a dotted table name as
877
+ * schema-qualified, so `db.selectFrom('billing.invoices')` resolves without a
878
+ * `withSchema()` call. Unqualified tables keep their bare key, so existing
879
+ * `KickDbSchema['users']` lookups are unchanged.
880
+ *
881
+ * Matched on `__isTable` rather than on `TableDecl<...>` assignability: the
882
+ * schema generic makes a qualified table structurally incompatible with the
883
+ * unqualified default, which would silently drop it from the map.
884
+ */
885
+ type TableKey<T> = T extends {
886
+ __name: infer N extends string;
887
+ } ? Extract<T extends {
888
+ __schema?: infer S;
889
+ } ? S : never, string> extends (infer Schema) ? [Schema] extends [never] ? N : Schema extends string ? `${Schema}.${N}` : N : never : never;
890
+ type SchemaToTypes<S> = { [K in keyof S as S[K] extends {
891
+ __isTable: true;
892
+ } ? TableKey<S[K]> : never]: S[K] extends TableDecl<string, infer C, string | undefined> ? { [Col in keyof C]: ColumnTSType<C[Col]>; } : never; };
811
893
  //#endregion
812
894
  //#region src/client/create.d.ts
813
895
  declare function createDbClient<TSchema, DB = SchemaToTypes<TSchema>>(opts: CreateDbClientOptions<TSchema, DB>): KickDbClient<DB>;
@@ -1227,7 +1309,7 @@ type ResolvedRelations = Record<string, Record<string, ResolvedRelation>>;
1227
1309
  type SchemaToRelationsRegister<S> = MergeBySource<{ [K in keyof S]: S[K] extends RelationsDecl<infer Source, infer R> ? Source extends string ? R extends Record<string, Relation> ? {
1228
1310
  source: Source;
1229
1311
  relations: ResolveRelations<R>;
1230
- } : never : never : never }[keyof S]>;
1312
+ } : never : never : never; }[keyof S]>;
1231
1313
  /**
1232
1314
  * Pull `{ kind, target }` for each relation entry. `target` shrinks
1233
1315
  * to the literal table name so the registry stays declarative
@@ -1236,7 +1318,7 @@ type SchemaToRelationsRegister<S> = MergeBySource<{ [K in keyof S]: S[K] extends
1236
1318
  type ResolveRelations<R extends Record<string, Relation>> = { [K in keyof R]: {
1237
1319
  kind: R[K]['kind'];
1238
1320
  target: R[K]['target'] extends TableDecl<infer N, Record<string, ColumnBuilder>> ? N extends string ? N : string : string;
1239
- } };
1321
+ }; };
1240
1322
  /**
1241
1323
  * Fold a union of `{ source, relations }` records into a single
1242
1324
  * object keyed by `source`. TypeScript distributes the conditional
@@ -1247,7 +1329,7 @@ type MergeBySource<U extends {
1247
1329
  relations: Record<string, RelationMapEntry>;
1248
1330
  }> = { [Source in U['source']]: Extract<U, {
1249
1331
  source: Source;
1250
- }>['relations'] };
1332
+ }>['relations']; };
1251
1333
  //#endregion
1252
1334
  //#region src/query/errors.d.ts
1253
1335
  /**
@@ -1407,5 +1489,5 @@ declare function markDialect<T extends object>(dialect: T, tag: DialectTag): T;
1407
1489
  */
1408
1490
  declare function readDialectMark(dialect: object): DialectTag | undefined;
1409
1491
  //#endregion
1410
- export { GenerateOptions as $, ColumnSnapshot as $n, IntrospectPgOptions as $t, bigSerial as A, hasAmbiguousReverse as An, ColumnRef as At, json as B, CreateEnum as Bn, KickDbAdapterConfig as Bt, Relation as C, UnreviewedMigrationError as Cn, SchemaToTypes as Ct, relations as D, detectCompositeReferences as Dn, index as Dt, RelationsDecl as E, CompositeRef as En, IndexDecl as Et, date as F, AddForeignKey as Fn, KICK_NOT_NULL as Ft, smallSerial as G, DropIndex as Gn, checkDrift as Gt, numeric as H, DropColumn as Hn, kickDbAdapter as Ht, decimal as I, AddIndex as In, NotNullBrand as It, time as J, RenameColumn as Jn, introspectMysql as Jt, smallint as K, DropTable as Kn, IntrospectMysqlOptions as Kt, doublePrecision as L, AlterColumn as Ln, DB_CLIENT as Lt, boolean as M, diff as Mn, FkSpec as Mt, bytea as N, AddColumn as Nn, GeneratedBrand as Nt, TimestampBuilder as O, KickDbError as On, unique as Ot, char as P, AddEnumValue as Pn, KICK_GENERATED as Pt, varchar as Q, CheckSnapshot as Qn, introspectPg as Qt, integer as R, Change as Rn, DB_PRIMARY as Rt, customType as S, SchemaDiffSummary as Sn, createDbClient as St, RelationOne as T, CompositeQueryRunner as Tn, table as Tt, real as U, DropEnum as Un, DriftBehavior as Ut, jsonb as V, CreateTable as Vn, MigrationsOnBoot as Vt, serial as W, DropForeignKey as Wn, DriftLogger as Wt, timestamptz as X, renderSchemaSource as Xn, SqliteIntrospectDb as Xt, timestamp as Y, RenameTable as Yn, IntrospectSqliteOptions as Yt, uuid as Z, extractSnapshot as Zn, introspectSqlite as Zt, SchemaToRelationsRegister as _, MigrationDriftError as _n, migrateLatest as _t, markDialect as a, migrationsTableDdl as an, RelationSnapshot as ar, emitMysql as at, CustomColumnBuilder as b, MigrationHashError as bn, migrateUp as bt, escapeLike as c, Journal as cn, emitPg as ct, RelationalQueryAmbiguousRelationNameError as d, computeMigrationHash as dn, AppliedSummary as dt, PgQueryRunner as en, Dialect$1 as er, GenerateResult as et, RelationalQueryCancelledError as f, readJournal as fn, ReversedSummary as ft, RelationalQueryUnknownRelationError as g, parseEnumDropHeader as gn, migrateDown as gt, RelationalQueryNotSupportedError as h, enforceEnumDropGate as hn, StatusEntry as ht, isDialectTag as i, lockTableDdl as in, IndexSnapshot as ir, resolveDbConfig as it, bigint as j, invertChanges as jn, ColumnState as jt, UuidBuilder as k, RemovedValueAsDefaultError as kn, ColumnBuilder as kt, likePattern as l, JournalEntry as ln, ReviewResult as lt, RelationalQueryMissingInverseError as m, EnumDropHeader as mn, RunnerOptions as mt, DialectTag as n, KICK_LOCK_TABLE as nn, FkAction as nr, DbConfig as nt, readDialectMark as o, MigrationAdapter as on, SchemaSnapshot as or, SqliteRebuildRequiredError as ot, RelationalQueryDepthError as p, verifyMigrationHash as pn, RollbackSummary as pt, text as q, RemoveEnumValue as qn, MysqlIntrospectDb as qt, KICK_DIALECT as r, KICK_MIGRATIONS_TABLE as rn, ForeignKeySnapshot as rr, MigrationAdapterFactory as rt, LikeMatchMode as s, MigrationRow as sn, TableSnapshot as sr, emitSqlite as st, ReadonlyKysely as t, MemoryMigrationAdapter as tn, EnumSnapshot as tr, generate as tt, RelationalQueryAliasCollisionError as u, appendJournalEntry as un, reviewMigration as ut, ResolvedRelation as v, MigrationEnumDropError as vn, migrateRollback as vt, RelationMany as w, CompositeEnumReferenceError as wn, TableDecl as wt, CustomTypeOptions as x, MigrationLockError as xn, safeNullComparison as xt, ResolvedRelations as y, MigrationError as yn, migrateStatus as yt, interval as z, ChangeSet as zn, DB_REPLICA as zt };
1411
- //# sourceMappingURL=index-DcuMZ9kb.d.mts.map
1492
+ export { GenerateOptions as $, RenameTable as $n, SqliteIntrospectDb as $t, bigSerial as A, detectCompositeReferences as An, index as At, json as B, AlterColumn as Bn, DB_CLIENT as Bt, Relation as C, MigrationHashError as Cn, SchemaToTypes as Ct, relations as D, CompositeEnumReferenceError as Dn, qualifiedTableName as Dt, RelationsDecl as E, UnreviewedMigrationError as En, buildTable as Et, date as F, diff as Fn, FkSpec as Ft, smallSerial as G, CreateTable as Gn, kickDbAdapter as Gt, numeric as H, ChangeSet as Hn, DB_REPLICA as Ht, decimal as I, AddColumn as In, GeneratedBrand as It, time as J, DropForeignKey as Jn, checkDrift as Jt, smallint as K, DropColumn as Kn, DriftBehavior as Kt, doublePrecision as L, AddEnumValue as Ln, KICK_GENERATED as Lt, boolean as M, RemovedValueAsDefaultError as Mn, ColumnBuilder as Mt, bytea as N, hasAmbiguousReverse as Nn, ColumnRef as Nt, TimestampBuilder as O, CompositeQueryRunner as On, table as Ot, char as P, invertChanges as Pn, ColumnState as Pt, varchar as Q, RenameColumn as Qn, IntrospectSqliteOptions as Qt, integer as R, AddForeignKey as Rn, KICK_NOT_NULL as Rt, customType as S, MigrationError as Sn, createDbClient as St, RelationOne as T, SchemaDiffSummary as Tn, TableDecl as Tt, real as U, CreateEnum as Un, KickDbAdapterConfig as Ut, jsonb as V, Change as Vn, DB_PRIMARY as Vt, serial as W, CreateSchema as Wn, MigrationsOnBoot as Wt, timestamptz as X, DropTable as Xn, MysqlIntrospectDb as Xt, timestamp as Y, DropIndex as Yn, IntrospectMysqlOptions as Yt, uuid as Z, RemoveEnumValue as Zn, introspectMysql as Zt, SchemaToRelationsRegister as _, EnumDropHeader as _n, migrateLatest as _t, markDialect as a, KICK_LOCK_TABLE as an, EnumSnapshot as ar, emitMysql as at, CustomColumnBuilder as b, MigrationDriftError as bn, migrateUp as bt, escapeLike as c, migrationsTableDdl as cn, IndexSnapshot as cr, emitPg as ct, RelationalQueryAmbiguousRelationNameError as d, Journal as dn, TableSnapshot as dr, AppliedSummary as dt, introspectSqlite as en, renderSchemaSource as er, GenerateResult as et, RelationalQueryCancelledError as f, JournalEntry as fn, ReversedSummary as ft, RelationalQueryUnknownRelationError as g, verifyMigrationHash as gn, migrateDown as gt, RelationalQueryNotSupportedError as h, readJournal as hn, StatusEntry as ht, isDialectTag as i, MemoryMigrationAdapter as in, Dialect$1 as ir, resolveDbConfig as it, bigint as j, KickDbError as jn, unique as jt, UuidBuilder as k, CompositeRef as kn, IndexDecl as kt, likePattern as l, MigrationAdapter as ln, RelationSnapshot as lr, ReviewResult as lt, RelationalQueryMissingInverseError as m, computeMigrationHash as mn, RunnerOptions as mt, DialectTag as n, IntrospectPgOptions as nn, CheckSnapshot as nr, DbConfig as nt, readDialectMark as o, KICK_MIGRATIONS_TABLE as on, FkAction as or, SqliteRebuildRequiredError as ot, RelationalQueryDepthError as p, appendJournalEntry as pn, RollbackSummary as pt, text as q, DropEnum as qn, DriftLogger as qt, KICK_DIALECT as r, PgQueryRunner as rn, ColumnSnapshot as rr, MigrationAdapterFactory as rt, LikeMatchMode as s, lockTableDdl as sn, ForeignKeySnapshot as sr, emitSqlite as st, ReadonlyKysely as t, introspectPg as tn, extractSnapshot as tr, generate as tt, RelationalQueryAliasCollisionError as u, MigrationRow as un, SchemaSnapshot as ur, reviewMigration as ut, ResolvedRelation as v, enforceEnumDropGate as vn, migrateRollback as vt, RelationMany as w, MigrationLockError as wn, QualifiedName as wt, CustomTypeOptions as x, MigrationEnumDropError as xn, safeNullComparison as xt, ResolvedRelations as y, parseEnumDropHeader as yn, migrateStatus as yt, interval as z, AddIndex as zn, NotNullBrand as zt };
1493
+ //# sourceMappingURL=index-Ci5DXgUh.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-Ci5DXgUh.d.mts","names":[],"sources":["../src/snapshot/types.ts","../src/snapshot/extract.ts","../src/snapshot/render.ts","../src/diff/types.ts","../src/diff/engine.ts","../src/diff/invert.ts","../src/errors.ts","../src/diff/composite-detect.ts","../src/migrate/errors.ts","../src/migrate/enum-drop-gate.ts","../src/migrate/journal.ts","../src/migrate/adapter.ts","../src/migrate/schema.ts","../src/migrate/memory-adapter.ts","../src/migrate/introspect-types.ts","../src/migrate/introspect-pg.ts","../src/migrate/introspect-sqlite.ts","../src/migrate/introspect-mysql.ts","../src/migrate/drift.ts","../src/adapter.ts","../src/tokens.ts","../src/dsl/columns/types.ts","../src/dsl/constraints.ts","../src/dsl/table.ts","../src/client/schema-types.ts","../src/client/create.ts","../src/client/plugins.ts","../src/migrate/runner.ts","../src/migrate/review.ts","../src/emit/pg.ts","../src/emit/sqlite.ts","../src/emit/mysql.ts","../src/cli/config.ts","../src/cli/generate.ts","../src/dsl/columns/builders.ts","../src/dsl/relations.ts","../src/custom-type.ts","../src/query/relations.ts","../src/query/schema-relations-types.ts","../src/query/errors.ts","../src/query/like.ts","../src/dialect-marker.ts"],"mappings":";;;;;;KAAY;KAEA;UAEK;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA,UAAU;EACV,UAAU;;UAGK;EACf;EACA;;UAGe;;;;;;EAMf;;;;;;EAMA;EACA,SAAS,eAAe;EACxB,SAAS;EACT,aAAa;EACb,QAAQ;;;;;;;UAQO;EACf;;EAEA;;;;;;;;;;;;;;UAee;EACf;;EAEA;;EAEA;;EAEA;;;;;;EAMA;;UAGe;EACf;EACA,SAAS;;;;;;;;EAQT,QAAQ,eAAe;;;;;;EAMvB;;EAEA,QAAQ,eAAe;;;;;;;EAOvB,YAAY,eAAe,eAAe;;;;iBCnD5B,gBAAgB,QAAQ,yBAAyB,SAAS,YAAU;;;;;;;;;;;;;;;;;;;iBCxCpE,mBAAmB,UAAU;;;;;;;;;;;;UCP5B;EACf;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Ae,gBAC5C,WAAW;EACV,MAAM,EAAE;EACR,QAAQ,EAAE,qBAAqB,gBAAgB,GAAG,eAAe,kBAC7D,mBACE;;;;;;;KAWL,cAAc;EAAY;EAAgB,WAAW,eAAe;QACtE,UAAU,cAAc,QAAQ;EAAK,QAAQ;;;;;;;;cCvDnC,4CAA4C;WAC9C;WACA;EACT,YAAY,qBAAqB;;;;;;;cAgBtB,kCAAkC;WACpC;WACA;EACT,YAAY,kBAAkB;;;;;;;;cAiBnB,2CAA2C;WAC7C;WACA;EACT,YAAY,qBAAqB;;;;;;;;;;;;;cAsBtB,sCAAsC;WACxC;EAET,YAAY;;;;;;;cA0BD,yCAAyC;WAC3C;EACT,YAAY;;;;;;;;;;cAkBD,kDAAkD;WACpD;WACA;WACA;;WAEA;EACT,YACE,qBACA,qBACA,sBACA;;;;;;;;;cAwBS,2CAA2C;WAC7C;WACA;WACA;EACT,YAAY,qBAAqB,sBAAsB;;;;;;;;;;;;;;;;;;;;KCrJ7C;;;;;;;;;;iBAWI,WAAW,eAAe;;;;;;;;;;;;iBA4B1B,YACd,eACA,OAAM,eACN;;;;;;;;;;;;;;;;;;;;cCpCW;KAED;;iBAKI,aAAa,iBAAiB,SAAS;;iBAKvC,YAAY,kBAAkB,SAAS,GAAG,KAAK,aAAa;;;;;;;iBAgB5D,gBAAgB,kBAAkB"}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
1
 
2
- import { $ as GenerateOptions, $n as ColumnSnapshot, $t as IntrospectPgOptions, A as bigSerial, An as hasAmbiguousReverse, At as ColumnRef, B as json, Bn as CreateEnum, Bt as KickDbAdapterConfig, C as Relation, Cn as UnreviewedMigrationError, Ct as SchemaToTypes, D as relations, Dn as detectCompositeReferences, Dt as index, E as RelationsDecl, En as CompositeRef, Et as IndexDecl, F as date, Fn as AddForeignKey, Ft as KICK_NOT_NULL, G as smallSerial, Gn as DropIndex, Gt as checkDrift, H as numeric, Hn as DropColumn, Ht as kickDbAdapter, I as decimal, In as AddIndex, It as NotNullBrand, J as time, Jn as RenameColumn, Jt as introspectMysql, K as smallint, Kn as DropTable, Kt as IntrospectMysqlOptions, L as doublePrecision, Ln as AlterColumn, Lt as DB_CLIENT, M as boolean, Mn as diff, Mt as FkSpec, N as bytea, Nn as AddColumn, Nt as GeneratedBrand, O as TimestampBuilder, On as KickDbError, Ot as unique, P as char, Pn as AddEnumValue, Pt as KICK_GENERATED, Q as varchar, Qn as CheckSnapshot, Qt as introspectPg, R as integer, Rn as Change, Rt as DB_PRIMARY, S as customType, Sn as SchemaDiffSummary, St as createDbClient, T as RelationOne, Tn as CompositeQueryRunner, Tt as table, U as real, Un as DropEnum, Ut as DriftBehavior, V as jsonb, Vn as CreateTable, Vt as MigrationsOnBoot, W as serial, Wn as DropForeignKey, Wt as DriftLogger, X as timestamptz, Xn as renderSchemaSource, Xt as SqliteIntrospectDb, Y as timestamp, Yn as RenameTable, Yt as IntrospectSqliteOptions, Z as uuid, Zn as extractSnapshot, Zt as introspectSqlite, _ as SchemaToRelationsRegister, _n as MigrationDriftError, _t as migrateLatest, a as markDialect, an as migrationsTableDdl, ar as RelationSnapshot, at as emitMysql, b as CustomColumnBuilder, bn as MigrationHashError, bt as migrateUp, c as escapeLike, cn as Journal, ct as emitPg, d as RelationalQueryAmbiguousRelationNameError, dn as computeMigrationHash, dt as AppliedSummary, en as PgQueryRunner, er as Dialect, et as GenerateResult, f as RelationalQueryCancelledError, fn as readJournal, ft as ReversedSummary, g as RelationalQueryUnknownRelationError, gn as parseEnumDropHeader, gt as migrateDown, h as RelationalQueryNotSupportedError, hn as enforceEnumDropGate, ht as StatusEntry, i as isDialectTag, in as lockTableDdl, ir as IndexSnapshot, it as resolveDbConfig, j as bigint, jn as invertChanges, jt as ColumnState, k as UuidBuilder, kn as RemovedValueAsDefaultError, kt as ColumnBuilder, l as likePattern, ln as JournalEntry, lt as ReviewResult, m as RelationalQueryMissingInverseError, mn as EnumDropHeader, mt as RunnerOptions, n as DialectTag, nn as KICK_LOCK_TABLE, nr as FkAction, nt as DbConfig, o as readDialectMark, on as MigrationAdapter, or as SchemaSnapshot, ot as SqliteRebuildRequiredError, p as RelationalQueryDepthError, pn as verifyMigrationHash, pt as RollbackSummary, q as text, qn as RemoveEnumValue, qt as MysqlIntrospectDb, r as KICK_DIALECT, rn as KICK_MIGRATIONS_TABLE, rr as ForeignKeySnapshot, s as LikeMatchMode, sn as MigrationRow, sr as TableSnapshot, st as emitSqlite, t as ReadonlyKysely, tn as MemoryMigrationAdapter, tr as EnumSnapshot, tt as generate, u as RelationalQueryAliasCollisionError, un as appendJournalEntry, ut as reviewMigration, v as ResolvedRelation, vn as MigrationEnumDropError, vt as migrateRollback, w as RelationMany, wn as CompositeEnumReferenceError, wt as TableDecl, x as CustomTypeOptions, xn as MigrationLockError, xt as safeNullComparison, y as ResolvedRelations, yn as MigrationError, yt as migrateStatus, z as interval, zn as ChangeSet, zt as DB_REPLICA } from "./index-DcuMZ9kb.mjs";
3
- import { C as ModelExtensions, S as ExtensionDefinition, _ as TableRelations, a as QueryErrorEvent, b as RegisteredDB, c as TransactionEvent, d as FindManyRow, f as KickDbRelationsRegister, g as TableQueryNamespace, h as RelationMapEntry, i as KickDbClientEvents, l as TransactionRollbackEvent, m as RegisteredRelations, n as CreateDbClientOptions, o as QueryEvent, p as QueryNamespace, r as KickDbClient, t as BeforeQueryEvent, u as FindManyOptions, v as WithClause, x as ExtendedClient, y as KickDbRegister } from "./types-BZGFAXPN.mjs";
4
- export { type AddColumn, type AddEnumValue, type AddForeignKey, type AddIndex, type AlterColumn, type AppliedSummary, type BeforeQueryEvent, type Change, type ChangeSet, type CheckSnapshot, ColumnBuilder, type ColumnRef, type ColumnSnapshot, type ColumnState, CompositeEnumReferenceError, type CompositeQueryRunner, type CompositeRef, type CreateDbClientOptions, type CreateEnum, type CreateTable, CustomColumnBuilder, type CustomTypeOptions, DB_CLIENT, DB_PRIMARY, DB_REPLICA, type DbConfig, type Dialect, type DialectTag, type DriftBehavior, type DriftLogger, type DropColumn, type DropEnum, type DropForeignKey, type DropIndex, type DropTable, type EnumDropHeader, type EnumSnapshot, type ExtendedClient, type ExtensionDefinition, type FindManyOptions, type FindManyRow, type FkAction, type FkSpec, type ForeignKeySnapshot, type GenerateOptions, type GenerateResult, type GeneratedBrand, IndexDecl, type IndexSnapshot, type IntrospectMysqlOptions, type IntrospectPgOptions, type IntrospectSqliteOptions, type Journal, type JournalEntry, KICK_DIALECT, KICK_GENERATED, KICK_LOCK_TABLE, KICK_MIGRATIONS_TABLE, KICK_NOT_NULL, type KickDbAdapterConfig, type KickDbClient, type KickDbClientEvents, KickDbError, type KickDbRegister, type KickDbRelationsRegister, type LikeMatchMode, MemoryMigrationAdapter, type MigrationAdapter, MigrationDriftError, MigrationEnumDropError, MigrationError, MigrationHashError, MigrationLockError, type MigrationRow, type MigrationsOnBoot, type ModelExtensions, type MysqlIntrospectDb, type NotNullBrand, type PgQueryRunner, type QueryErrorEvent, type QueryEvent, type QueryNamespace, type ReadonlyKysely, type RegisteredDB, type RegisteredRelations, Relation, RelationMany, type RelationMapEntry, RelationOne, type RelationSnapshot, RelationalQueryAliasCollisionError, RelationalQueryAmbiguousRelationNameError, RelationalQueryCancelledError, RelationalQueryDepthError, RelationalQueryMissingInverseError, RelationalQueryNotSupportedError, RelationalQueryUnknownRelationError, RelationsDecl, type RemoveEnumValue, RemovedValueAsDefaultError, type RenameColumn, type RenameTable, type ResolvedRelation, type ResolvedRelations, type ReversedSummary, type ReviewResult, type RollbackSummary, type RunnerOptions, type SchemaDiffSummary, type SchemaSnapshot, type SchemaToRelationsRegister, type SchemaToTypes, type SqliteIntrospectDb, SqliteRebuildRequiredError, type StatusEntry, TableDecl, type TableQueryNamespace, type TableRelations, type TableSnapshot, TimestampBuilder, type TransactionEvent, type TransactionRollbackEvent, UnreviewedMigrationError, UuidBuilder, type WithClause, appendJournalEntry, bigSerial, bigint, boolean, bytea, char, checkDrift, computeMigrationHash, createDbClient, customType, date, decimal, detectCompositeReferences, diff, doublePrecision, emitMysql, emitPg, emitSqlite, enforceEnumDropGate, escapeLike, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectMysql, introspectPg, introspectSqlite, invertChanges, isDialectTag, json, jsonb, kickDbAdapter, likePattern, lockTableDdl, markDialect, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, parseEnumDropHeader, readDialectMark, readJournal, real, relations, renderSchemaSource, resolveDbConfig, reviewMigration, safeNullComparison, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
2
+ import { $ as GenerateOptions, $n as RenameTable, $t as SqliteIntrospectDb, A as bigSerial, An as detectCompositeReferences, At as index, B as json, Bn as AlterColumn, Bt as DB_CLIENT, C as Relation, Cn as MigrationHashError, Ct as SchemaToTypes, D as relations, Dn as CompositeEnumReferenceError, Dt as qualifiedTableName, E as RelationsDecl, En as UnreviewedMigrationError, Et as buildTable, F as date, Fn as diff, Ft as FkSpec, G as smallSerial, Gn as CreateTable, Gt as kickDbAdapter, H as numeric, Hn as ChangeSet, Ht as DB_REPLICA, I as decimal, In as AddColumn, It as GeneratedBrand, J as time, Jn as DropForeignKey, Jt as checkDrift, K as smallint, Kn as DropColumn, Kt as DriftBehavior, L as doublePrecision, Ln as AddEnumValue, Lt as KICK_GENERATED, M as boolean, Mn as RemovedValueAsDefaultError, Mt as ColumnBuilder, N as bytea, Nn as hasAmbiguousReverse, Nt as ColumnRef, O as TimestampBuilder, On as CompositeQueryRunner, Ot as table, P as char, Pn as invertChanges, Pt as ColumnState, Q as varchar, Qn as RenameColumn, Qt as IntrospectSqliteOptions, R as integer, Rn as AddForeignKey, Rt as KICK_NOT_NULL, S as customType, Sn as MigrationError, St as createDbClient, T as RelationOne, Tn as SchemaDiffSummary, Tt as TableDecl, U as real, Un as CreateEnum, Ut as KickDbAdapterConfig, V as jsonb, Vn as Change, Vt as DB_PRIMARY, W as serial, Wn as CreateSchema, Wt as MigrationsOnBoot, X as timestamptz, Xn as DropTable, Xt as MysqlIntrospectDb, Y as timestamp, Yn as DropIndex, Yt as IntrospectMysqlOptions, Z as uuid, Zn as RemoveEnumValue, Zt as introspectMysql, _ as SchemaToRelationsRegister, _n as EnumDropHeader, _t as migrateLatest, a as markDialect, an as KICK_LOCK_TABLE, ar as EnumSnapshot, at as emitMysql, b as CustomColumnBuilder, bn as MigrationDriftError, bt as migrateUp, c as escapeLike, cn as migrationsTableDdl, cr as IndexSnapshot, ct as emitPg, d as RelationalQueryAmbiguousRelationNameError, dn as Journal, dr as TableSnapshot, dt as AppliedSummary, en as introspectSqlite, er as renderSchemaSource, et as GenerateResult, f as RelationalQueryCancelledError, fn as JournalEntry, ft as ReversedSummary, g as RelationalQueryUnknownRelationError, gn as verifyMigrationHash, gt as migrateDown, h as RelationalQueryNotSupportedError, hn as readJournal, ht as StatusEntry, i as isDialectTag, in as MemoryMigrationAdapter, ir as Dialect, it as resolveDbConfig, j as bigint, jn as KickDbError, jt as unique, k as UuidBuilder, kn as CompositeRef, kt as IndexDecl, l as likePattern, ln as MigrationAdapter, lr as RelationSnapshot, lt as ReviewResult, m as RelationalQueryMissingInverseError, mn as computeMigrationHash, mt as RunnerOptions, n as DialectTag, nn as IntrospectPgOptions, nr as CheckSnapshot, nt as DbConfig, o as readDialectMark, on as KICK_MIGRATIONS_TABLE, or as FkAction, ot as SqliteRebuildRequiredError, p as RelationalQueryDepthError, pn as appendJournalEntry, pt as RollbackSummary, q as text, qn as DropEnum, qt as DriftLogger, r as KICK_DIALECT, rn as PgQueryRunner, rr as ColumnSnapshot, s as LikeMatchMode, sn as lockTableDdl, sr as ForeignKeySnapshot, st as emitSqlite, t as ReadonlyKysely, tn as introspectPg, tr as extractSnapshot, tt as generate, u as RelationalQueryAliasCollisionError, un as MigrationRow, ur as SchemaSnapshot, ut as reviewMigration, v as ResolvedRelation, vn as enforceEnumDropGate, vt as migrateRollback, w as RelationMany, wn as MigrationLockError, wt as QualifiedName, x as CustomTypeOptions, xn as MigrationEnumDropError, xt as safeNullComparison, y as ResolvedRelations, yn as parseEnumDropHeader, yt as migrateStatus, z as interval, zn as AddIndex, zt as NotNullBrand } from "./index-Ci5DXgUh.mjs";
3
+ import { C as ModelExtensions, S as ExtensionDefinition, _ as TableRelations, a as QueryErrorEvent, b as RegisteredDB, c as TransactionEvent, d as FindManyRow, f as KickDbRelationsRegister, g as TableQueryNamespace, h as RelationMapEntry, i as KickDbClientEvents, l as TransactionRollbackEvent, m as RegisteredRelations, n as CreateDbClientOptions, o as QueryEvent, p as QueryNamespace, r as KickDbClient, t as BeforeQueryEvent, u as FindManyOptions, v as WithClause, x as ExtendedClient, y as KickDbRegister } from "./types-NkfgZHEN.mjs";
4
+ export { type AddColumn, type AddEnumValue, type AddForeignKey, type AddIndex, type AlterColumn, type AppliedSummary, type BeforeQueryEvent, type Change, type ChangeSet, type CheckSnapshot, ColumnBuilder, type ColumnRef, type ColumnSnapshot, type ColumnState, CompositeEnumReferenceError, type CompositeQueryRunner, type CompositeRef, type CreateDbClientOptions, type CreateEnum, type CreateSchema, type CreateTable, CustomColumnBuilder, type CustomTypeOptions, DB_CLIENT, DB_PRIMARY, DB_REPLICA, type DbConfig, type Dialect, type DialectTag, type DriftBehavior, type DriftLogger, type DropColumn, type DropEnum, type DropForeignKey, type DropIndex, type DropTable, type EnumDropHeader, type EnumSnapshot, type ExtendedClient, type ExtensionDefinition, type FindManyOptions, type FindManyRow, type FkAction, type FkSpec, type ForeignKeySnapshot, type GenerateOptions, type GenerateResult, type GeneratedBrand, IndexDecl, type IndexSnapshot, type IntrospectMysqlOptions, type IntrospectPgOptions, type IntrospectSqliteOptions, type Journal, type JournalEntry, KICK_DIALECT, KICK_GENERATED, KICK_LOCK_TABLE, KICK_MIGRATIONS_TABLE, KICK_NOT_NULL, type KickDbAdapterConfig, type KickDbClient, type KickDbClientEvents, KickDbError, type KickDbRegister, type KickDbRelationsRegister, type LikeMatchMode, MemoryMigrationAdapter, type MigrationAdapter, MigrationDriftError, MigrationEnumDropError, MigrationError, MigrationHashError, MigrationLockError, type MigrationRow, type MigrationsOnBoot, type ModelExtensions, type MysqlIntrospectDb, type NotNullBrand, type PgQueryRunner, QualifiedName, type QueryErrorEvent, type QueryEvent, type QueryNamespace, type ReadonlyKysely, type RegisteredDB, type RegisteredRelations, Relation, RelationMany, type RelationMapEntry, RelationOne, type RelationSnapshot, RelationalQueryAliasCollisionError, RelationalQueryAmbiguousRelationNameError, RelationalQueryCancelledError, RelationalQueryDepthError, RelationalQueryMissingInverseError, RelationalQueryNotSupportedError, RelationalQueryUnknownRelationError, RelationsDecl, type RemoveEnumValue, RemovedValueAsDefaultError, type RenameColumn, type RenameTable, type ResolvedRelation, type ResolvedRelations, type ReversedSummary, type ReviewResult, type RollbackSummary, type RunnerOptions, type SchemaDiffSummary, type SchemaSnapshot, type SchemaToRelationsRegister, type SchemaToTypes, type SqliteIntrospectDb, SqliteRebuildRequiredError, type StatusEntry, TableDecl, type TableQueryNamespace, type TableRelations, type TableSnapshot, TimestampBuilder, type TransactionEvent, type TransactionRollbackEvent, UnreviewedMigrationError, UuidBuilder, type WithClause, appendJournalEntry, bigSerial, bigint, boolean, buildTable, bytea, char, checkDrift, computeMigrationHash, createDbClient, customType, date, decimal, detectCompositeReferences, diff, doublePrecision, emitMysql, emitPg, emitSqlite, enforceEnumDropGate, escapeLike, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectMysql, introspectPg, introspectSqlite, invertChanges, isDialectTag, json, jsonb, kickDbAdapter, likePattern, lockTableDdl, markDialect, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, parseEnumDropHeader, qualifiedTableName, readDialectMark, readJournal, real, relations, renderSchemaSource, resolveDbConfig, reviewMigration, safeNullComparison, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v7.1.1
2
+ * @forinda/kickjs-db v7.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{$ as migrateStatus,A as uuid,At as diff,B as readDialectMark,Bt as KickDbError,C as serial,Ct as MigrationHashError,D as time,Dt as detectCompositeReferences,E as text,Et as CompositeEnumReferenceError,F as safeNullComparison,Ft as RelationalQueryCancelledError,G as KICK_NOT_NULL,H as customType,I as createDbClient,It as RelationalQueryDepthError,J as DB_REPLICA,K as DB_CLIENT,L as KICK_DIALECT,Lt as RelationalQueryMissingInverseError,M as generate,Mt as extractSnapshot,N as resolveDbConfig,Nt as RelationalQueryAliasCollisionError,O as timestamp,Ot as hasAmbiguousReverse,P as reviewMigration,Pt as RelationalQueryAmbiguousRelationNameError,Q as migrateRollback,R as isDialectTag,Rt as RelationalQueryNotSupportedError,S as real,St as MigrationError,T as smallint,Tt as UnreviewedMigrationError,U as ColumnBuilder,V as CustomColumnBuilder,Vt as RemovedValueAsDefaultError,W as KICK_GENERATED,X as migrateDown,Y as kickDbAdapter,Z as migrateLatest,_ as integer,_t as enforceEnumDropGate,a as unique,at as introspectMysql,b as jsonb,bt as MigrationDriftError,c as UuidBuilder,ct as MemoryMigrationAdapter,d as boolean,dt as lockTableDdl,et as migrateUp,f as bytea,ft as migrationsTableDdl,g as doublePrecision,gt as verifyMigrationHash,h as decimal,ht as readJournal,i as index,it as emitSqlite,j as varchar,jt as renderSchemaSource,k as timestamptz,kt as invertChanges,l as bigSerial,lt as KICK_LOCK_TABLE,m as date,mt as computeMigrationHash,n as likePattern,nt as emitMysql,o as table,ot as introspectSqlite,p as char,pt as appendJournalEntry,q as DB_PRIMARY,r as relations,rt as SqliteRebuildRequiredError,s as TimestampBuilder,st as introspectPg,t as escapeLike,tt as checkDrift,u as bigint,ut as KICK_MIGRATIONS_TABLE,v as interval,vt as parseEnumDropHeader,w as smallSerial,wt as MigrationLockError,x as numeric,xt as MigrationEnumDropError,y as json,yt as emitPg,z as markDialect,zt as RelationalQueryUnknownRelationError}from"./src-_M69mn2G.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_DIALECT,KICK_GENERATED,KICK_LOCK_TABLE,KICK_MIGRATIONS_TABLE,KICK_NOT_NULL,KickDbError,MemoryMigrationAdapter,MigrationDriftError,MigrationEnumDropError,MigrationError,MigrationHashError,MigrationLockError,RelationalQueryAliasCollisionError,RelationalQueryAmbiguousRelationNameError,RelationalQueryCancelledError,RelationalQueryDepthError,RelationalQueryMissingInverseError,RelationalQueryNotSupportedError,RelationalQueryUnknownRelationError,RemovedValueAsDefaultError,SqliteRebuildRequiredError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,detectCompositeReferences,diff,doublePrecision,emitMysql,emitPg,emitSqlite,enforceEnumDropGate,escapeLike,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,isDialectTag,json,jsonb,kickDbAdapter,likePattern,lockTableDdl,markDialect,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,readDialectMark,readJournal,real,relations,renderSchemaSource,resolveDbConfig,reviewMigration,safeNullComparison,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
11
+ import{$ as migrateUp,A as varchar,At as renderSchemaSource,B as CustomColumnBuilder,Bt as RemovedValueAsDefaultError,C as smallSerial,Ct as MigrationLockError,D as timestamp,Dt as hasAmbiguousReverse,E as time,Et as detectCompositeReferences,F as createDbClient,Ft as RelationalQueryDepthError,G as DB_CLIENT,H as ColumnBuilder,Ht as qualifiedTableName,I as KICK_DIALECT,It as RelationalQueryMissingInverseError,J as kickDbAdapter,K as DB_PRIMARY,L as isDialectTag,Lt as RelationalQueryNotSupportedError,M as resolveDbConfig,Mt as RelationalQueryAliasCollisionError,N as reviewMigration,Nt as RelationalQueryAmbiguousRelationNameError,O as timestamptz,Ot as invertChanges,P as safeNullComparison,Pt as RelationalQueryCancelledError,Q as migrateStatus,R as markDialect,Rt as RelationalQueryUnknownRelationError,S as serial,St as MigrationHashError,T as text,Tt as CompositeEnumReferenceError,U as KICK_GENERATED,Ut as table,V as customType,Vt as buildTable,W as KICK_NOT_NULL,X as migrateLatest,Y as migrateDown,Z as migrateRollback,_ as interval,_t as parseEnumDropHeader,a as unique,at as introspectSqlite,b as numeric,bt as MigrationEnumDropError,c as bigSerial,ct as KICK_LOCK_TABLE,d as bytea,dt as migrationsTableDdl,et as checkDrift,f as char,ft as appendJournalEntry,g as integer,gt as enforceEnumDropGate,h as doublePrecision,ht as verifyMigrationHash,i as index,it as introspectMysql,j as generate,jt as extractSnapshot,k as uuid,kt as diff,l as bigint,lt as KICK_MIGRATIONS_TABLE,m as decimal,mt as readJournal,n as likePattern,nt as SqliteRebuildRequiredError,o as TimestampBuilder,ot as introspectPg,p as date,pt as computeMigrationHash,q as DB_REPLICA,r as relations,rt as emitSqlite,s as UuidBuilder,st as MemoryMigrationAdapter,t as escapeLike,tt as emitMysql,u as boolean,ut as lockTableDdl,v as json,vt as emitPg,w as smallint,wt as UnreviewedMigrationError,x as real,xt as MigrationError,y as jsonb,yt as MigrationDriftError,z as readDialectMark,zt as KickDbError}from"./src-DibJVBOu.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_DIALECT,KICK_GENERATED,KICK_LOCK_TABLE,KICK_MIGRATIONS_TABLE,KICK_NOT_NULL,KickDbError,MemoryMigrationAdapter,MigrationDriftError,MigrationEnumDropError,MigrationError,MigrationHashError,MigrationLockError,RelationalQueryAliasCollisionError,RelationalQueryAmbiguousRelationNameError,RelationalQueryCancelledError,RelationalQueryDepthError,RelationalQueryMissingInverseError,RelationalQueryNotSupportedError,RelationalQueryUnknownRelationError,RemovedValueAsDefaultError,SqliteRebuildRequiredError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,buildTable,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,detectCompositeReferences,diff,doublePrecision,emitMysql,emitPg,emitSqlite,enforceEnumDropGate,escapeLike,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,isDialectTag,json,jsonb,kickDbAdapter,likePattern,lockTableDdl,markDialect,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,qualifiedTableName,readDialectMark,readJournal,real,relations,renderSchemaSource,resolveDbConfig,reviewMigration,safeNullComparison,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
package/dist/mysql.d.mts CHANGED
@@ -1,7 +1,6 @@
1
1
 
2
- import { on as MigrationAdapter } from "./index-DcuMZ9kb.mjs";
2
+ import { ln as MigrationAdapter } from "./index-Ci5DXgUh.mjs";
3
3
  import { Dialect } from "kysely";
4
-
5
4
  //#region src/adapters/mysql/adapter.d.ts
6
5
  /**
7
6
  * mysql2-shaped pool that `mysqlAdapter` consumes. Mirrors the
@@ -1 +1 @@
1
- {"version":3,"file":"mysql.d.mts","names":[],"sources":["../src/adapters/mysql/adapter.ts","../src/adapters/mysql/dialect.ts"],"mappings":";;;;;;;;AAwBA;;;;;;;;;;UAAiB,mBAAA;EACf,KAAA,cAAmB,GAAA,UAAa,MAAA,wBAA8B,OAAO,EAAE,CAAA;EACvE,OAAA;AAAA;AAAA,UAGe,aAAA;EACf,KAAA,cAAmB,GAAA,UAAa,MAAA,wBAA8B,OAAA,EAAS,CAAA;EACvE,aAAA,IAAiB,OAAA,CAAQ,mBAAA;AAAA;AAAA,UAGV,mBAAA;EA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1.1
2
+ * @forinda/kickjs-db v7.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Bt as KickDbError,at as introspectMysql,dt as lockTableDdl,ft as migrationsTableDdl,z as markDialect}from"./src-_M69mn2G.mjs";import{MysqlDialect}from"kysely";function parseMysqlVersion(version){let trimmed=version.trim();if(/MariaDB/i.test(trimmed)){let m=/(\d+)\.(\d+)(?:\.\d+)?-MariaDB/i.exec(trimmed);if(m){let major=Number(m[1]),minor=Number(m[2]);if(Number.isFinite(major)&&Number.isFinite(minor))return{flavor:`mariadb`,major,minor}}let fallback=/^(\d+)\.(\d+)/.exec(trimmed);if(!fallback)return null;let major=Number(fallback[1]),minor=Number(fallback[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mariadb`,major,minor}}let m=/^(\d+)\.(\d+)/.exec(trimmed);if(!m)return null;let major=Number(m[1]),minor=Number(m[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mysql`,major,minor}}function parseMysqlMajorVersion(version){return parseMysqlVersion(version)?.major??null}function checkVersionSupport(parsed,raw){return parsed==null?`unparseable version string: ${raw||`<empty>`}`:parsed.flavor===`mariadb`?parsed.major>10?null:parsed.major<10||parsed.minor<5?`MariaDB 10.5+ required (detected: ${raw})`:null:parsed.major<8?`MySQL 8.0+ required (detected: ${raw})`:null}function splitMysqlStatements(sql){let out=[],buf=``,inSingle=!1,inDouble=!1,inBacktick=!1,inLineComment=!1,inBlockComment=!1,isCommentWhitespace=c=>c===` `||c===` `||c===`
11
+ import{R as markDialect,dt as migrationsTableDdl,it as introspectMysql,ut as lockTableDdl,zt as KickDbError}from"./src-DibJVBOu.mjs";import{MysqlDialect}from"kysely";function parseMysqlVersion(version){let trimmed=version.trim();if(/MariaDB/i.test(trimmed)){let m=/(\d+)\.(\d+)(?:\.\d+)?-MariaDB/i.exec(trimmed);if(m){let major=Number(m[1]),minor=Number(m[2]);if(Number.isFinite(major)&&Number.isFinite(minor))return{flavor:`mariadb`,major,minor}}let fallback=/^(\d+)\.(\d+)/.exec(trimmed);if(!fallback)return null;let major=Number(fallback[1]),minor=Number(fallback[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mariadb`,major,minor}}let m=/^(\d+)\.(\d+)/.exec(trimmed);if(!m)return null;let major=Number(m[1]),minor=Number(m[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mysql`,major,minor}}function parseMysqlMajorVersion(version){return parseMysqlVersion(version)?.major??null}function checkVersionSupport(parsed,raw){return parsed==null?`unparseable version string: ${raw||`<empty>`}`:parsed.flavor===`mariadb`?parsed.major>10?null:parsed.major<10||parsed.minor<5?`MariaDB 10.5+ required (detected: ${raw})`:null:parsed.major<8?`MySQL 8.0+ required (detected: ${raw})`:null}function splitMysqlStatements(sql){let out=[],buf=``,inSingle=!1,inDouble=!1,inBacktick=!1,inLineComment=!1,inBlockComment=!1,isCommentWhitespace=c=>c===` `||c===` `||c===`
12
12
  `||c===`\r`||c===`\f`||c===`\v`;for(let i=0;i<sql.length;i++){let ch=sql[i],next=i+1<sql.length?sql[i+1]:``,after=i+2<sql.length?sql[i+2]:``;if(inLineComment){buf+=ch,ch===`
13
13
  `&&(inLineComment=!1);continue}if(inBlockComment){buf+=ch,ch===`*`&&next===`/`&&(buf+=next,i++,inBlockComment=!1);continue}if(inSingle){if(ch===`'`&&next===`'`){buf+=ch,buf+=next,i++;continue}if(buf+=ch,ch===`\\`&&next!==``){buf+=next,i++;continue}ch===`'`&&(inSingle=!1);continue}if(inDouble){if(ch===`"`&&next===`"`){buf+=ch,buf+=next,i++;continue}if(buf+=ch,ch===`\\`&&next!==``){buf+=next,i++;continue}ch===`"`&&(inDouble=!1);continue}if(inBacktick){buf+=ch,ch==="`"&&(inBacktick=!1);continue}if(ch===`-`&&next===`-`&&(after===``||isCommentWhitespace(after))){buf+=ch,inLineComment=!0;continue}if(ch===`/`&&next===`*`){buf+=ch,inBlockComment=!0;continue}if(ch===`'`){buf+=ch,inSingle=!0;continue}if(ch===`"`){buf+=ch,inDouble=!0;continue}if(ch==="`"){buf+=ch,inBacktick=!0;continue}if(ch===`;`){let trimmed=buf.trim();trimmed.length>0&&out.push(trimmed),buf=``;continue}buf+=ch}let tail=buf.trim();return tail.length>0&&out.push(tail),out}function mysqlAdapter(opts){let dialect=`mysql`,{pool}=opts,versionVerified=!1;async function assertVersion(){if(versionVerified)return;let[rows]=await pool.query("SELECT VERSION() AS `version`"),versionString=rows[0]?.version??``,failure=checkVersionSupport(parseMysqlVersion(versionString),versionString);if(failure)throw new KickDbError(`KICK_DB_RELATIONAL_NOT_SUPPORTED`,`${failure}. JSON_ARRAYAGG (required by the relational query layer) shipped in MySQL 8.0 and MariaDB 10.5. Use layer-1/layer-2 queries (selectFrom / selectAll) on older versions.`);versionVerified=!0}async function runStatements(sql){for(let stmt of splitMysqlStatements(sql))await pool.query(stmt)}async function runStatementsOnConn(conn,sql){for(let stmt of splitMysqlStatements(sql))await conn.query(stmt)}return{dialect,async ensureMigrationTables(){await assertVersion(),await runStatements(migrationsTableDdl(dialect)),await runStatements(lockTableDdl(dialect))},async listApplied(){let[rows]=await pool.query(`SELECT id, name, hash, batch, applied_at, direction
14
14
  FROM \`kick_migrations\`