@forinda/kickjs-db 6.1.1 → 6.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,5 +1,5 @@
1
1
 
2
- import { Ft as DriftBehavior, J as DbConfig, Kn as Dialect, Y as MigrationAdapterFactory } from "./index-B1r7mcA1.mjs";
2
+ import { Ft as DriftBehavior, J as DbConfig, Kn as Dialect, Y as MigrationAdapterFactory } from "./index-BqFtk5dd.mjs";
3
3
  import { CliTypegen, KickCliPlugin } from "@forinda/kickjs-cli-kit";
4
4
  import { Command } from "commander";
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;cA4Ba,aAAA,QAAoB,UAiC/B;;;;;;;;;UCbe,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,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"}
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.1.1
2
+ * @forinda/kickjs-db v6.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{A as generate,G as migrateLatest,J as migrateUp,K as migrateRollback,M as reviewMigration,Tt as renderSchemaSource,W as migrateDown,q as migrateStatus,xt as detectCompositeReferences}from"./src-Dpz7lQYB.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);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
- `)}});function resolveSchema(cwd){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 + the -- 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};
11
+ import{A as generate,G as migrateLatest,J as migrateUp,K as migrateRollback,M as reviewMigration,Tt as renderSchemaSource,W as migrateDown,q as migrateStatus,xt as detectCompositeReferences}from"./src-CO7SOsHZ.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
+ `)}});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 }) {\n const schemaAbs = resolveSchema(ctx.cwd)\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): string | null {\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 + the -- 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,IAAsB,CACnC,IAAM,UAAY,cAAc,IAAI,GAAG,EACvC,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,IAA4B,CACjD,IAAK,IAAM,aAAa,qBAAsB,CAC5C,IAAM,IAAM,KAAK,QAAQ,IAAK,SAAS,EACvC,GAAI,UAAU,SAAS,KA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AAW,MAAM,QAAQ,WAAW,EAC1C,GAAI,KAAK,KAAM,CACb,QAAQ,IAAI,KAAK,UAAU,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
+ {"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,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+ * @forinda/kickjs-db v6.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -519,10 +519,18 @@ interface IntrospectPgOptions {
519
519
  declare function introspectPg(client: PgQueryRunner, opts?: IntrospectPgOptions): Promise<SchemaSnapshot>;
520
520
  //#endregion
521
521
  //#region src/migrate/introspect-sqlite.d.ts
522
- /** Minimal better-sqlite3 surface introspection needs (sync `.all()`). */
522
+ /**
523
+ * Minimal better-sqlite3 surface introspection needs (sync `.all()`).
524
+ *
525
+ * `all` is deliberately NOT method-generic: better-sqlite3 v12's own
526
+ * `Statement.all(...params): Result[]` is non-generic, so a generic
527
+ * method here would make a real `Database` instance structurally
528
+ * incompatible (callers had to cast). Row typing happens inside this
529
+ * module via per-call assertions instead.
530
+ */
523
531
  interface SqliteIntrospectDb {
524
532
  prepare(sql: string): {
525
- all<R = unknown>(...params: unknown[]): R[];
533
+ all(...params: unknown[]): unknown[];
526
534
  };
527
535
  }
528
536
  interface IntrospectSqliteOptions {
@@ -699,6 +707,16 @@ declare const KICK_NOT_NULL: unique symbol;
699
707
  type NotNullBrand = {
700
708
  readonly [KICK_NOT_NULL]?: true;
701
709
  };
710
+ /**
711
+ * Re-attach the nullability / generated brands after a transform that
712
+ * must return a *new* builder type (e.g. `.array()` widening `T` to
713
+ * `T[]`). Without this, `integer().notNull().array()` silently dropped
714
+ * `NotNullBrand` and the row type regressed to `number[] | null`.
715
+ *
716
+ * Uses the same `extends` checks as `SchemaToTypes` (client/schema-types.ts)
717
+ * so detection stays consistent in both directions.
718
+ */
719
+ type PreserveBrands<Self, Out> = Out & (Self extends NotNullBrand ? NotNullBrand : unknown) & (Self extends GeneratedBrand ? GeneratedBrand : unknown);
702
720
  /**
703
721
  * Phantom-typed column builder. The `T` generic carries the column's TS
704
722
  * value type (number / string / Date / etc.); nullability is tracked via
@@ -715,7 +733,7 @@ declare class ColumnBuilder<T = unknown> {
715
733
  notNull(): this & NotNullBrand;
716
734
  primaryKey(): this & NotNullBrand;
717
735
  unique(): this;
718
- array(): ColumnBuilder<T[]>;
736
+ array(): PreserveBrands<this, ColumnBuilder<T[]>>;
719
737
  references(target: () => ColumnRef, opts?: {
720
738
  onDelete?: FkAction;
721
739
  onUpdate?: FkAction;
@@ -886,15 +904,15 @@ interface ReviewResult {
886
904
  alreadyReviewed: boolean;
887
905
  }
888
906
  /**
889
- * Mark a migration as reviewed: flip `meta.json.reviewed` to `true`,
890
- * swap the `-- REVIEWED: false` markers in `up.sql` / `down.sql` to
891
- * `true`, and recompute the migration's journal hash (the marker swap
892
- * changes the file bytes, so the stored hash must follow or the runner's
893
- * integrity check would fail).
907
+ * Mark a migration as reviewed: flip `meta.json.reviewed` to `true` —
908
+ * the ONLY review state the runner checks. The SQL files carry an
909
+ * immutable provenance banner (`-- Generated by @forinda/kickjs-db vX`),
910
+ * so reviewing never touches them and the journal hash stays valid.
894
911
  *
895
- * This is the single source of truth for "reviewing" — adopters should
896
- * never hand-edit `meta.json`, because that leaves the `-- REVIEWED`
897
- * markers and the journal hash out of sync.
912
+ * Legacy migrations (generated before the banner) still carry mutable
913
+ * `-- REVIEWED: false` markers inside the hashed files; for those we
914
+ * keep the old behaviour — swap the markers and recompute the journal
915
+ * hash so all three stay in sync.
898
916
  */
899
917
  declare function reviewMigration(migrationsDir: string, id: string): Promise<ReviewResult>;
900
918
  //#endregion
@@ -994,7 +1012,7 @@ interface GenerateOptions {
994
1012
  now?: () => Date;
995
1013
  /**
996
1014
  * When true, skip the schema diff and emit an empty migration shell
997
- * (up.sql / down.sql with just the REVIEWED header, snapshot.json copying
1015
+ * (up.sql / down.sql with just the generated-by banner, snapshot.json copying
998
1016
  * the prior schema state). Used for data migrations, seed inserts, or any
999
1017
  * change the diff engine can't author. Matches knex's `migrate:make`.
1000
1018
  */
@@ -1317,4 +1335,4 @@ declare class RelationalQueryMissingInverseError extends KickDbError {
1317
1335
  }
1318
1336
  //#endregion
1319
1337
  export { emitSqlite as $, TableSnapshot as $n, MigrationRow as $t, integer as A, Change as An, DB_PRIMARY as At, time as B, RenameColumn as Bn, introspectMysql as Bt, bigint as C, invertChanges as Cn, ColumnState as Ct, date as D, AddForeignKey as Dn, KICK_NOT_NULL as Dt, char as E, AddEnumValue as En, KICK_GENERATED as Et, real as F, DropEnum as Fn, DriftBehavior as Ft, GenerateOptions as G, ColumnSnapshot as Gn, IntrospectPgOptions as Gt, timestamptz as H, renderSchemaSource as Hn, SqliteIntrospectDb as Ht, serial as I, DropForeignKey as In, DriftLogger as It, DbConfig as J, FkAction as Jn, KICK_LOCK_TABLE as Jt, GenerateResult as K, Dialect$1 as Kn, PgQueryRunner as Kt, smallSerial as L, DropIndex as Ln, checkDrift as Lt, json as M, CreateEnum as Mn, KickDbAdapterConfig as Mt, jsonb as N, CreateTable as Nn, MigrationsOnBoot as Nt, decimal as O, AddIndex as On, NotNullBrand as Ot, numeric as P, DropColumn as Pn, kickDbAdapter as Pt, SqliteRebuildRequiredError as Q, SchemaSnapshot as Qn, MigrationAdapter as Qt, smallint as R, DropTable as Rn, IntrospectMysqlOptions as Rt, bigSerial as S, hasAmbiguousReverse as Sn, ColumnRef as St, bytea as T, AddColumn as Tn, GeneratedBrand as Tt, uuid as U, extractSnapshot as Un, introspectSqlite as Ut, timestamp as V, RenameTable as Vn, IntrospectSqliteOptions as Vt, varchar as W, CheckSnapshot as Wn, introspectPg as Wt, resolveDbConfig as X, IndexSnapshot as Xn, lockTableDdl as Xt, MigrationAdapterFactory as Y, ForeignKeySnapshot as Yn, KICK_MIGRATIONS_TABLE as Yt, emitMysql as Z, RelationSnapshot as Zn, migrationsTableDdl as Zt, RelationOne as _, CompositeQueryRunner as _n, table as _t, RelationalQueryDepthError as a, verifyMigrationHash as an, RollbackSummary as at, TimestampBuilder as b, KickDbError as bn, unique as bt, RelationalQueryUnknownRelationError as c, parseEnumDropHeader as cn, migrateDown as ct, ResolvedRelations as d, MigrationError as dn, migrateStatus as dt, Journal as en, emitPg as et, CustomColumnBuilder as f, MigrationHashError as fn, migrateUp as ft, RelationMany as g, CompositeEnumReferenceError as gn, TableDecl as gt, Relation as h, UnreviewedMigrationError as hn, SchemaToTypes as ht, RelationalQueryCancelledError as i, readJournal as in, ReversedSummary as it, interval as j, ChangeSet as jn, DB_REPLICA as jt, doublePrecision as k, AlterColumn as kn, DB_CLIENT as kt, SchemaToRelationsRegister as l, MigrationDriftError as ln, migrateLatest as lt, customType as m, SchemaDiffSummary as mn, createDbClient as mt, RelationalQueryAliasCollisionError as n, appendJournalEntry as nn, reviewMigration as nt, RelationalQueryMissingInverseError as o, EnumDropHeader as on, RunnerOptions as ot, CustomTypeOptions as p, MigrationLockError as pn, safeNullComparison as pt, generate as q, EnumSnapshot as qn, MemoryMigrationAdapter as qt, RelationalQueryAmbiguousRelationNameError as r, computeMigrationHash as rn, AppliedSummary as rt, RelationalQueryNotSupportedError as s, enforceEnumDropGate as sn, StatusEntry as st, ReadonlyKysely as t, JournalEntry as tn, ReviewResult as tt, ResolvedRelation as u, MigrationEnumDropError as un, migrateRollback as ut, RelationsDecl as v, CompositeRef as vn, IndexDecl as vt, boolean as w, diff as wn, FkSpec as wt, UuidBuilder as x, RemovedValueAsDefaultError as xn, ColumnBuilder as xt, relations as y, detectCompositeReferences as yn, index as yt, text as z, RemoveEnumValue as zn, MysqlIntrospectDb as zt };
1320
- //# sourceMappingURL=index-B1r7mcA1.d.mts.map
1338
+ //# sourceMappingURL=index-BqFtk5dd.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-BqFtk5dd.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"],"mappings":";;;;;;;KAAY,SAAA;AAAA,KAEA,QAAA;AAAA,UAEK,cAAA;EACf,IAAA;EACA,IAAA;EACA,QAAA;EACA,OAAA;EACA,UAAA;AAAA;AAAA,UAGe,aAAA;EACf,IAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,UAGe,kBAAA;EACf,IAAA;EACA,OAAA;EACA,QAAA;EACA,UAAA;EACA,QAAA,EAAU,QAAA;EACV,QAAA,EAAU,QAAQ;AAAA;AAAA,UAGH,aAAA;EACf,IAAA;EACA,UAAU;AAAA;AAAA,UAGK,aAAA;EACf,IAAA;EACA,OAAA,EAAS,MAAA,SAAe,cAAA;EACxB,OAAA,EAAS,aAAA;EACT,WAAA,EAAa,kBAAA;EACb,MAAA,EAAQ,aAAA;AAAA;;;AAtBF;AAGR;;UA2BiB,YAAA;EACf,IAAA;EA3BA;EA6BA,MAAM;AAAA;;;;;;;AAxBY;AAGpB;;;;AAEY;UAkCK,gBAAA;EACf,IAAA;;EAEA,MAAA;EAhCS;EAkCT,aAAA;EAhCa;EAkCb,aAAA;EAjCqB;;;;;EAuCrB,YAAA;AAAA;AAAA,UAGe,cAAA;EACf,OAAA;EACA,OAAA,EAAS,SAAA;EACT,MAAA,EAAQ,MAAA,SAAe,aAAA;EA7Cf;EA+CR,KAAA,GAAQ,MAAA,SAAe,YAAA;EA/CF;AAQvB;;;;AAGQ;EA2CN,SAAA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CAAA,kBACE,CAAA;AAAA;;;;AtC7BE;AAGZ;KsCqCK,aAAA;EAA0B,MAAA;EAAgB,SAAA,EAAW,MAAA,SAAe,gBAAA;AAAA,kBAC5D,CAAA,aAAc,OAAA,CAAQ,CAAA;EAAK,MAAA,EAAQ,MAAA;AAAA;;;;AtCtE7B;AAEnB;;cuCaa,mCAAA,SAA4C,WAAW;EAAA,SACzD,WAAA;EAAA,SACA,WAAA;EACT,WAAA,CAAY,WAAA,UAAqB,WAAA;AAAA;;;;;;cAgBtB,yBAAA,SAAkC,WAAW;EAAA,SAC/C,QAAA;EAAA,SACA,KAAA;EACT,WAAA,CAAY,QAAA,UAAkB,KAAA;AAAA;;;;;;;cAiBnB,kCAAA,SAA2C,WAAW;EAAA,SACxD,WAAA;EAAA,SACA,eAAA;EACT,WAAA,CAAY,WAAA,UAAqB,eAAA;AAAA;;;;;;;;;;;AvCjCf;cuCuDP,6BAAA,SAAsC,WAAW;EAAA,SACnD,KAAA;EAET,WAAA,CAAY,KAAA;AAAA;AvCrDF;AAGZ;;;;AAHY,cuC+EC,gCAAA,SAAyC,WAAW;EAAA,SACtD,OAAA;EACT,WAAA,CAAY,OAAA;AAAA;;;;;;;;;cAkBD,yCAAA,SAAkD,WAAW;EAAA,SAC/D,WAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;EvC9FY;EAAA,SuCgGZ,WAAA;EACT,WAAA,CACE,WAAA,UACA,WAAA,UACA,YAAA,UACA,WAAA;AAAA;;;AvC1FI;AAeR;;;;cuCmGa,kCAAA,SAA2C,WAAW;EAAA,SACxD,WAAA;EAAA,SACA,YAAA;EAAA,SACA,WAAA;EACT,WAAA,CAAY,WAAA,UAAqB,YAAA,UAAsB,WAAA;AAAA"}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
1
 
2
- import { $ as emitSqlite, $n as TableSnapshot, $t as MigrationRow, A as integer, An as Change, At as DB_PRIMARY, B as time, Bn as RenameColumn, Bt as introspectMysql, C as bigint, Cn as invertChanges, Ct as ColumnState, D as date, Dn as AddForeignKey, Dt as KICK_NOT_NULL, E as char, En as AddEnumValue, Et as KICK_GENERATED, F as real, Fn as DropEnum, Ft as DriftBehavior, G as GenerateOptions, Gn as ColumnSnapshot, Gt as IntrospectPgOptions, H as timestamptz, Hn as renderSchemaSource, Ht as SqliteIntrospectDb, I as serial, In as DropForeignKey, It as DriftLogger, J as DbConfig, Jn as FkAction, Jt as KICK_LOCK_TABLE, K as GenerateResult, Kn as Dialect, Kt as PgQueryRunner, L as smallSerial, Ln as DropIndex, Lt as checkDrift, M as json, Mn as CreateEnum, Mt as KickDbAdapterConfig, N as jsonb, Nn as CreateTable, Nt as MigrationsOnBoot, O as decimal, On as AddIndex, Ot as NotNullBrand, P as numeric, Pn as DropColumn, Pt as kickDbAdapter, Q as SqliteRebuildRequiredError, Qn as SchemaSnapshot, Qt as MigrationAdapter, R as smallint, Rn as DropTable, Rt as IntrospectMysqlOptions, S as bigSerial, Sn as hasAmbiguousReverse, St as ColumnRef, T as bytea, Tn as AddColumn, Tt as GeneratedBrand, U as uuid, Un as extractSnapshot, Ut as introspectSqlite, V as timestamp, Vn as RenameTable, Vt as IntrospectSqliteOptions, W as varchar, Wn as CheckSnapshot, Wt as introspectPg, X as resolveDbConfig, Xn as IndexSnapshot, Xt as lockTableDdl, Yn as ForeignKeySnapshot, Yt as KICK_MIGRATIONS_TABLE, Z as emitMysql, Zn as RelationSnapshot, Zt as migrationsTableDdl, _ as RelationOne, _n as CompositeQueryRunner, _t as table, a as RelationalQueryDepthError, an as verifyMigrationHash, at as RollbackSummary, b as TimestampBuilder, bn as KickDbError, bt as unique, c as RelationalQueryUnknownRelationError, cn as parseEnumDropHeader, ct as migrateDown, d as ResolvedRelations, dn as MigrationError, dt as migrateStatus, en as Journal, et as emitPg, f as CustomColumnBuilder, fn as MigrationHashError, ft as migrateUp, g as RelationMany, gn as CompositeEnumReferenceError, gt as TableDecl, h as Relation, hn as UnreviewedMigrationError, ht as SchemaToTypes, i as RelationalQueryCancelledError, in as readJournal, it as ReversedSummary, j as interval, jn as ChangeSet, jt as DB_REPLICA, k as doublePrecision, kn as AlterColumn, kt as DB_CLIENT, l as SchemaToRelationsRegister, ln as MigrationDriftError, lt as migrateLatest, m as customType, mn as SchemaDiffSummary, mt as createDbClient, n as RelationalQueryAliasCollisionError, nn as appendJournalEntry, nt as reviewMigration, o as RelationalQueryMissingInverseError, on as EnumDropHeader, ot as RunnerOptions, p as CustomTypeOptions, pn as MigrationLockError, pt as safeNullComparison, q as generate, qn as EnumSnapshot, qt as MemoryMigrationAdapter, r as RelationalQueryAmbiguousRelationNameError, rn as computeMigrationHash, rt as AppliedSummary, s as RelationalQueryNotSupportedError, sn as enforceEnumDropGate, st as StatusEntry, t as ReadonlyKysely, tn as JournalEntry, tt as ReviewResult, u as ResolvedRelation, un as MigrationEnumDropError, ut as migrateRollback, v as RelationsDecl, vn as CompositeRef, vt as IndexDecl, w as boolean, wn as diff, wt as FkSpec, x as UuidBuilder, xn as RemovedValueAsDefaultError, xt as ColumnBuilder, y as relations, yn as detectCompositeReferences, yt as index, z as text, zn as RemoveEnumValue, zt as MysqlIntrospectDb } from "./index-B1r7mcA1.mjs";
2
+ import { $ as emitSqlite, $n as TableSnapshot, $t as MigrationRow, A as integer, An as Change, At as DB_PRIMARY, B as time, Bn as RenameColumn, Bt as introspectMysql, C as bigint, Cn as invertChanges, Ct as ColumnState, D as date, Dn as AddForeignKey, Dt as KICK_NOT_NULL, E as char, En as AddEnumValue, Et as KICK_GENERATED, F as real, Fn as DropEnum, Ft as DriftBehavior, G as GenerateOptions, Gn as ColumnSnapshot, Gt as IntrospectPgOptions, H as timestamptz, Hn as renderSchemaSource, Ht as SqliteIntrospectDb, I as serial, In as DropForeignKey, It as DriftLogger, J as DbConfig, Jn as FkAction, Jt as KICK_LOCK_TABLE, K as GenerateResult, Kn as Dialect, Kt as PgQueryRunner, L as smallSerial, Ln as DropIndex, Lt as checkDrift, M as json, Mn as CreateEnum, Mt as KickDbAdapterConfig, N as jsonb, Nn as CreateTable, Nt as MigrationsOnBoot, O as decimal, On as AddIndex, Ot as NotNullBrand, P as numeric, Pn as DropColumn, Pt as kickDbAdapter, Q as SqliteRebuildRequiredError, Qn as SchemaSnapshot, Qt as MigrationAdapter, R as smallint, Rn as DropTable, Rt as IntrospectMysqlOptions, S as bigSerial, Sn as hasAmbiguousReverse, St as ColumnRef, T as bytea, Tn as AddColumn, Tt as GeneratedBrand, U as uuid, Un as extractSnapshot, Ut as introspectSqlite, V as timestamp, Vn as RenameTable, Vt as IntrospectSqliteOptions, W as varchar, Wn as CheckSnapshot, Wt as introspectPg, X as resolveDbConfig, Xn as IndexSnapshot, Xt as lockTableDdl, Yn as ForeignKeySnapshot, Yt as KICK_MIGRATIONS_TABLE, Z as emitMysql, Zn as RelationSnapshot, Zt as migrationsTableDdl, _ as RelationOne, _n as CompositeQueryRunner, _t as table, a as RelationalQueryDepthError, an as verifyMigrationHash, at as RollbackSummary, b as TimestampBuilder, bn as KickDbError, bt as unique, c as RelationalQueryUnknownRelationError, cn as parseEnumDropHeader, ct as migrateDown, d as ResolvedRelations, dn as MigrationError, dt as migrateStatus, en as Journal, et as emitPg, f as CustomColumnBuilder, fn as MigrationHashError, ft as migrateUp, g as RelationMany, gn as CompositeEnumReferenceError, gt as TableDecl, h as Relation, hn as UnreviewedMigrationError, ht as SchemaToTypes, i as RelationalQueryCancelledError, in as readJournal, it as ReversedSummary, j as interval, jn as ChangeSet, jt as DB_REPLICA, k as doublePrecision, kn as AlterColumn, kt as DB_CLIENT, l as SchemaToRelationsRegister, ln as MigrationDriftError, lt as migrateLatest, m as customType, mn as SchemaDiffSummary, mt as createDbClient, n as RelationalQueryAliasCollisionError, nn as appendJournalEntry, nt as reviewMigration, o as RelationalQueryMissingInverseError, on as EnumDropHeader, ot as RunnerOptions, p as CustomTypeOptions, pn as MigrationLockError, pt as safeNullComparison, q as generate, qn as EnumSnapshot, qt as MemoryMigrationAdapter, r as RelationalQueryAmbiguousRelationNameError, rn as computeMigrationHash, rt as AppliedSummary, s as RelationalQueryNotSupportedError, sn as enforceEnumDropGate, st as StatusEntry, t as ReadonlyKysely, tn as JournalEntry, tt as ReviewResult, u as ResolvedRelation, un as MigrationEnumDropError, ut as migrateRollback, v as RelationsDecl, vn as CompositeRef, vt as IndexDecl, w as boolean, wn as diff, wt as FkSpec, x as UuidBuilder, xn as RemovedValueAsDefaultError, xt as ColumnBuilder, y as relations, yn as detectCompositeReferences, yt as index, z as text, zn as RemoveEnumValue, zt as MysqlIntrospectDb } from "./index-BqFtk5dd.mjs";
3
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
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 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_GENERATED, KICK_LOCK_TABLE, KICK_MIGRATIONS_TABLE, KICK_NOT_NULL, type KickDbAdapterConfig, type KickDbClient, type KickDbClientEvents, KickDbError, type KickDbRegister, type KickDbRelationsRegister, 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, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectMysql, introspectPg, introspectSqlite, invertChanges, json, jsonb, kickDbAdapter, lockTableDdl, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, parseEnumDropHeader, 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 v6.1.1
2
+ * @forinda/kickjs-db v6.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 introspectMysql,A as generate,At as RelationalQueryDepthError,B as DB_CLIENT,C as smallint,Ct as invertChanges,D as timestamptz,Dt as RelationalQueryAliasCollisionError,E as timestamp,Et as extractSnapshot,F as CustomColumnBuilder,Ft as RemovedValueAsDefaultError,G as migrateLatest,H as DB_REPLICA,I as customType,J as migrateUp,K as migrateRollback,L as ColumnBuilder,M as reviewMigration,Mt as RelationalQueryNotSupportedError,N as safeNullComparison,Nt as RelationalQueryUnknownRelationError,O as uuid,Ot as RelationalQueryAmbiguousRelationNameError,P as createDbClient,Pt as KickDbError,Q as emitSqlite,R as KICK_GENERATED,S as smallSerial,St as hasAmbiguousReverse,T as time,Tt as renderSchemaSource,U as kickDbAdapter,V as DB_PRIMARY,W as migrateDown,X as emitMysql,Y as checkDrift,Z as SqliteRebuildRequiredError,_ as json,_t as MigrationHashError,a as TimestampBuilder,at as lockTableDdl,b as real,bt as CompositeEnumReferenceError,c as bigint,ct as computeMigrationHash,d as char,dt as enforceEnumDropGate,et as introspectSqlite,f as date,ft as parseEnumDropHeader,g as interval,gt as MigrationError,h as integer,ht as MigrationEnumDropError,i as table,it as KICK_MIGRATIONS_TABLE,j as resolveDbConfig,jt as RelationalQueryMissingInverseError,k as varchar,kt as RelationalQueryCancelledError,l as boolean,lt as readJournal,m as doublePrecision,mt as MigrationDriftError,n as index,nt as MemoryMigrationAdapter,o as UuidBuilder,ot as migrationsTableDdl,p as decimal,pt as emitPg,q as migrateStatus,r as unique,rt as KICK_LOCK_TABLE,s as bigSerial,st as appendJournalEntry,t as relations,tt as introspectPg,u as bytea,ut as verifyMigrationHash,v as jsonb,vt as MigrationLockError,w as text,wt as diff,x as serial,xt as detectCompositeReferences,y as numeric,yt as UnreviewedMigrationError,z as KICK_NOT_NULL}from"./src-Dpz7lQYB.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,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,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,readJournal,real,relations,renderSchemaSource,resolveDbConfig,reviewMigration,safeNullComparison,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
11
+ import{$ as introspectMysql,A as generate,At as RelationalQueryDepthError,B as DB_CLIENT,C as smallint,Ct as invertChanges,D as timestamptz,Dt as RelationalQueryAliasCollisionError,E as timestamp,Et as extractSnapshot,F as CustomColumnBuilder,Ft as RemovedValueAsDefaultError,G as migrateLatest,H as DB_REPLICA,I as customType,J as migrateUp,K as migrateRollback,L as ColumnBuilder,M as reviewMigration,Mt as RelationalQueryNotSupportedError,N as safeNullComparison,Nt as RelationalQueryUnknownRelationError,O as uuid,Ot as RelationalQueryAmbiguousRelationNameError,P as createDbClient,Pt as KickDbError,Q as emitSqlite,R as KICK_GENERATED,S as smallSerial,St as hasAmbiguousReverse,T as time,Tt as renderSchemaSource,U as kickDbAdapter,V as DB_PRIMARY,W as migrateDown,X as emitMysql,Y as checkDrift,Z as SqliteRebuildRequiredError,_ as json,_t as MigrationHashError,a as TimestampBuilder,at as lockTableDdl,b as real,bt as CompositeEnumReferenceError,c as bigint,ct as computeMigrationHash,d as char,dt as enforceEnumDropGate,et as introspectSqlite,f as date,ft as parseEnumDropHeader,g as interval,gt as MigrationError,h as integer,ht as MigrationEnumDropError,i as table,it as KICK_MIGRATIONS_TABLE,j as resolveDbConfig,jt as RelationalQueryMissingInverseError,k as varchar,kt as RelationalQueryCancelledError,l as boolean,lt as readJournal,m as doublePrecision,mt as MigrationDriftError,n as index,nt as MemoryMigrationAdapter,o as UuidBuilder,ot as migrationsTableDdl,p as decimal,pt as emitPg,q as migrateStatus,r as unique,rt as KICK_LOCK_TABLE,s as bigSerial,st as appendJournalEntry,t as relations,tt as introspectPg,u as bytea,ut as verifyMigrationHash,v as jsonb,vt as MigrationLockError,w as text,wt as diff,x as serial,xt as detectCompositeReferences,y as numeric,yt as UnreviewedMigrationError,z as KICK_NOT_NULL}from"./src-CO7SOsHZ.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,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,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,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,5 +1,5 @@
1
1
 
2
- import { Qt as MigrationAdapter } from "./index-B1r7mcA1.mjs";
2
+ import { Qt as MigrationAdapter } from "./index-BqFtk5dd.mjs";
3
3
  import { Dialect } from "kysely";
4
4
 
5
5
  //#region src/adapters/mysql/adapter.d.ts
package/dist/mysql.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.1.1
2
+ * @forinda/kickjs-db v6.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{$ as introspectMysql,Pt as KickDbError,at as lockTableDdl,ot as migrationsTableDdl}from"./src-Dpz7lQYB.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{$ as introspectMysql,Pt as KickDbError,at as lockTableDdl,ot as migrationsTableDdl}from"./src-CO7SOsHZ.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\`
package/dist/pg.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { Qt as MigrationAdapter, xt as ColumnBuilder } from "./index-B1r7mcA1.mjs";
2
+ import { Qt as MigrationAdapter, xt as ColumnBuilder } from "./index-BqFtk5dd.mjs";
3
3
  import { Dialect } from "kysely";
4
4
 
5
5
  //#region src/dsl/columns/pg.d.ts
package/dist/pg.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.1.1
2
+ * @forinda/kickjs-db v6.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{L as ColumnBuilder,at as lockTableDdl,ot as migrationsTableDdl,tt as introspectPg}from"./src-Dpz7lQYB.mjs";import{PostgresDialect}from"kysely";var PgEnumColumnBuilder=class extends ColumnBuilder{enumName;values;constructor(enumName,values){super(enumName),this.enumName=enumName,this.values=values}};function pgEnum(name,...values){return Object.assign(()=>new PgEnumColumnBuilder(name,values),{enumName:name,values})}function tsvector(){return new ColumnBuilder(`tsvector`)}function vector(dim){return new ColumnBuilder(dim===void 0?`vector`:`vector(${dim})`)}function citext(){return new ColumnBuilder(`citext`)}function money(){return new ColumnBuilder(`money`)}function inet(){return new ColumnBuilder(`inet`)}function cidr(){return new ColumnBuilder(`cidr`)}function xml(){return new ColumnBuilder(`xml`)}const SAFE_SCHEMA_NAME=/^[a-z_][a-z0-9_]*$/i;function pgAdapter(opts){let dialect=`postgres`,{pool}=opts,schema=opts.schema??`public`;if(!SAFE_SCHEMA_NAME.test(schema))throw Error(`Invalid PG schema name: ${schema}`);return{dialect,async ensureMigrationTables(){await pool.query(migrationsTableDdl(dialect)),await pool.query(lockTableDdl(dialect))},async listApplied(){return(await pool.query(`SELECT id, name, hash, batch, applied_at, direction
11
+ import{L as ColumnBuilder,at as lockTableDdl,ot as migrationsTableDdl,tt as introspectPg}from"./src-CO7SOsHZ.mjs";import{PostgresDialect}from"kysely";var PgEnumColumnBuilder=class extends ColumnBuilder{enumName;values;constructor(enumName,values){super(enumName),this.enumName=enumName,this.values=values}};function pgEnum(name,...values){return Object.assign(()=>new PgEnumColumnBuilder(name,values),{enumName:name,values})}function tsvector(){return new ColumnBuilder(`tsvector`)}function vector(dim){return new ColumnBuilder(dim===void 0?`vector`:`vector(${dim})`)}function citext(){return new ColumnBuilder(`citext`)}function money(){return new ColumnBuilder(`money`)}function inet(){return new ColumnBuilder(`inet`)}function cidr(){return new ColumnBuilder(`cidr`)}function xml(){return new ColumnBuilder(`xml`)}const SAFE_SCHEMA_NAME=/^[a-z_][a-z0-9_]*$/i;function pgAdapter(opts){let dialect=`postgres`,{pool}=opts,schema=opts.schema??`public`;if(!SAFE_SCHEMA_NAME.test(schema))throw Error(`Invalid PG schema name: ${schema}`);return{dialect,async ensureMigrationTables(){await pool.query(migrationsTableDdl(dialect)),await pool.query(lockTableDdl(dialect))},async listApplied(){return(await pool.query(`SELECT id, name, hash, batch, applied_at, direction
12
12
  FROM kick_migrations
13
13
  ORDER BY applied_at ASC, id ASC`)).rows.map(row=>({id:row.id,name:row.name,hash:row.hash,batch:Number(row.batch),appliedAt:row.applied_at instanceof Date?row.applied_at.toISOString():String(row.applied_at),direction:row.direction}))},async recordApplied(row){await pool.query(`INSERT INTO kick_migrations (id, name, hash, batch, direction)
14
14
  VALUES ($1, $2, $3, $4, $5)`,[row.id,row.name,row.hash,row.batch,row.direction])},async removeApplied(id){await pool.query(`DELETE FROM kick_migrations WHERE id = $1`,[id])},async acquireLock(owner){return(await pool.query(`UPDATE kick_migrations_lock
package/dist/sqlite.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { Qt as MigrationAdapter } from "./index-B1r7mcA1.mjs";
2
+ import { Qt as MigrationAdapter } from "./index-BqFtk5dd.mjs";
3
3
  import { Dialect } from "kysely";
4
4
 
5
5
  //#region src/adapters/sqlite/adapter.d.ts
@@ -12,13 +12,20 @@ import { Dialect } from "kysely";
12
12
  * to match the `MigrationAdapter` contract. No I/O actually awaits;
13
13
  * the wrapping is for shape compatibility.
14
14
  */
15
+ /**
16
+ * `all` / `get` are deliberately NOT method-generic: better-sqlite3
17
+ * v12's own `Statement` methods are non-generic, so generic signatures
18
+ * here would make a real `Database` instance structurally incompatible
19
+ * (callers had to cast — same fix as `SqliteIntrospectDb`). Row typing
20
+ * happens at the call sites via assertions instead.
21
+ */
15
22
  interface SqliteStatement {
16
23
  run(...params: readonly unknown[]): {
17
24
  changes: number;
18
25
  lastInsertRowid: number | bigint;
19
26
  };
20
- all<R = unknown>(...params: readonly unknown[]): R[];
21
- get<R = unknown>(...params: readonly unknown[]): R | undefined;
27
+ all(...params: readonly unknown[]): unknown[];
28
+ get(...params: readonly unknown[]): unknown;
22
29
  }
23
30
  interface SqliteDatabaseLike {
24
31
  prepare(sql: string): SqliteStatement;
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite.d.mts","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"mappings":";;;;;;;;AAmBA;;;;;;UAAiB,eAAA;EACf,GAAA,IAAO,MAAA;IAA+B,OAAA;IAAiB,eAAA;EAAA;EACvD,GAAA,iBAAoB,MAAA,uBAA6B,CAAA;EACjD,GAAA,iBAAoB,MAAA,uBAA6B,CAAC;AAAA;AAAA,UAGnC,kBAAA;EACf,OAAA,CAAQ,GAAA,WAAc,eAAe;EACrC,IAAA,CAAK,GAAA;EACL,KAAA;AAAA;AAAA,UAGe,oBAAA;;;;;;;EAOf,QAAA,EAAU,kBAAkB;AAAA;;AAVvB;AAGP;;;;AAO8B;AAgB9B;;;;;;iBAAgB,aAAA,CAAc,IAAA,EAAM,oBAAA,GAAuB,gBAAgB;;;UC7C1D,oBAAA;;ADUjB;;;;;ECHE,QAAA,EAAU,kBAAkB;AAAA;;;;;;;;;;;ADMsB;AAGpD;;;;;;;;iBCagB,aAAA,CAAc,IAAA,EAAM,oBAAA,GAAuB,OAAa"}
1
+ {"version":3,"file":"sqlite.d.mts","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"mappings":";;;;;;;;AA0BA;;;;;;;;;;;;;UAAiB,eAAA;EACf,GAAA,IAAO,MAAA;IAA+B,OAAA;IAAiB,eAAA;EAAA;EACvD,GAAA,IAAO,MAAA;EACP,GAAA,IAAO,MAAA;AAAA;AAAA,UAGQ,kBAAA;EACf,OAAA,CAAQ,GAAA,WAAc,eAAe;EACrC,IAAA,CAAK,GAAA;EACL,KAAA;AAAA;AAAA,UAGe,oBAAA;EAAoB;;;AAOP;AAgB9B;;EAhBE,QAAA,EAAU,kBAAkB;AAAA;;;;;AAgB6C;;;;ACpD3E;;;;AAO8B;iBD6Cd,aAAA,CAAc,IAAA,EAAM,oBAAA,GAAuB,gBAAgB;;;UCpD1D,oBAAA;;ADiBjB;;;;;ECVE,QAAA,EAAU,kBAAkB;AAAA;;;;;;;ADaf;AAGf;;;;;;;;;;;AAGO;iBCGS,aAAA,CAAc,IAAA,EAAM,oBAAA,GAAuB,OAAa"}
package/dist/sqlite.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.1.1
2
+ * @forinda/kickjs-db v6.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{at as lockTableDdl,et as introspectSqlite,ot as migrationsTableDdl}from"./src-Dpz7lQYB.mjs";import{SqliteDialect}from"kysely";function sqliteAdapter(opts){let dialect=`sqlite`,{database}=opts,runBatch=sql=>database.exec(sql);return{dialect,async ensureMigrationTables(){runBatch(migrationsTableDdl(dialect)),runBatch(lockTableDdl(dialect))},async listApplied(){return database.prepare(`SELECT id, name, hash, batch, applied_at, direction
11
+ import{at as lockTableDdl,et as introspectSqlite,ot as migrationsTableDdl}from"./src-CO7SOsHZ.mjs";import{SqliteDialect}from"kysely";function sqliteAdapter(opts){let dialect=`sqlite`,{database}=opts,runBatch=sql=>database.exec(sql);return{dialect,async ensureMigrationTables(){runBatch(migrationsTableDdl(dialect)),runBatch(lockTableDdl(dialect))},async listApplied(){return database.prepare(`SELECT id, name, hash, batch, applied_at, direction
12
12
  FROM kick_migrations
13
13
  ORDER BY applied_at ASC, id ASC`).all().map(row=>({id:row.id,name:row.name,hash:row.hash,batch:Number(row.batch),appliedAt:row.applied_at,direction:row.direction}))},async recordApplied(row){database.prepare(`INSERT INTO kick_migrations (id, name, hash, batch, direction)
14
14
  VALUES (?, ?, ?, ?, ?)`).run(row.id,row.name,row.hash,row.batch,row.direction)},async removeApplied(id){database.prepare(`DELETE FROM kick_migrations WHERE id = ?`).run(id)},async acquireLock(owner){return database.prepare(`UPDATE kick_migrations_lock
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite.mjs","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"sourcesContent":["import {\n lockTableDdl,\n migrationsTableDdl,\n type Dialect,\n type MigrationAdapter,\n type MigrationRow,\n type SchemaSnapshot,\n} from '../../index'\nimport { introspectSqlite } from '../../migrate/introspect-sqlite'\n\n/**\n * better-sqlite3-shaped database handle that `sqliteAdapter` consumes.\n * Mirrors the methods we actually use; both `new Database(...)` from\n * `better-sqlite3` and bun's `bun:sqlite` Database match structurally.\n *\n * better-sqlite3's API is synchronous — we wrap everything in `async`\n * to match the `MigrationAdapter` contract. No I/O actually awaits;\n * the wrapping is for shape compatibility.\n */\nexport interface SqliteStatement {\n run(...params: readonly unknown[]): { changes: number; lastInsertRowid: number | bigint }\n all<R = unknown>(...params: readonly unknown[]): R[]\n get<R = unknown>(...params: readonly unknown[]): R | undefined\n}\n\nexport interface SqliteDatabaseLike {\n prepare(sql: string): SqliteStatement\n exec(sql: string): unknown\n close(): unknown\n}\n\nexport interface SqliteAdapterOptions {\n /**\n * better-sqlite3 (or compatible) Database handle. Caller-owned —\n * the adapter's `close()` does NOT close the database because\n * adopters typically share a single handle across the migration\n * adapter and the KickDbClient.\n */\n database: SqliteDatabaseLike\n}\n\n/**\n * MigrationAdapter implementation backed by better-sqlite3.\n *\n * Lock semantics: single-row UPDATE WHERE locked_at IS NULL on\n * `kick_migrations_lock`. Only the row created by `ensureMigrationTables()`\n * exists, so the UPDATE either flips `locked_at` and returns\n * `changes=1` (we won) or matches zero rows (someone else holds it).\n *\n * Introspection: `introspect()` walks `sqlite_master` + `PRAGMA` via\n * {@link introspectSqlite}. Types come back as SQLite affinities (lossy\n * vs the code-first DSL), so it powers `kick db introspect` rather than\n * byte-exact drift detection.\n */\nexport function sqliteAdapter(opts: SqliteAdapterOptions): MigrationAdapter {\n const dialect: Dialect = 'sqlite'\n const { database } = opts\n\n // Multi-statement DDL runs through better-sqlite3's exec() (it\n // handles `;`-separated batches natively).\n const runBatch = (sql: string) => database.exec(sql)\n\n return {\n dialect,\n\n async ensureMigrationTables() {\n runBatch(migrationsTableDdl(dialect))\n runBatch(lockTableDdl(dialect))\n },\n\n async listApplied(): Promise<MigrationRow[]> {\n const rows = database\n .prepare(\n `SELECT id, name, hash, batch, applied_at, direction\n FROM kick_migrations\n ORDER BY applied_at ASC, id ASC`,\n )\n .all<{\n id: string\n name: string\n hash: string\n batch: number\n applied_at: string\n direction: 'up' | 'down'\n }>()\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n hash: row.hash,\n batch: Number(row.batch),\n appliedAt: row.applied_at,\n direction: row.direction,\n }))\n },\n\n async recordApplied(row) {\n database\n .prepare(\n `INSERT INTO kick_migrations (id, name, hash, batch, direction)\n VALUES (?, ?, ?, ?, ?)`,\n )\n .run(row.id, row.name, row.hash, row.batch, row.direction)\n },\n\n async removeApplied(id: string) {\n database.prepare(`DELETE FROM kick_migrations WHERE id = ?`).run(id)\n },\n\n async acquireLock(owner: string): Promise<boolean> {\n const r = database\n .prepare(\n `UPDATE kick_migrations_lock\n SET locked_at = datetime('now'), locked_by = ?\n WHERE id = 1 AND locked_at IS NULL`,\n )\n .run(owner)\n return r.changes === 1\n },\n\n async releaseLock() {\n database\n .prepare(\n `UPDATE kick_migrations_lock\n SET locked_at = NULL, locked_by = NULL\n WHERE id = 1`,\n )\n .run()\n },\n\n async applySqlInTx(sql: string) {\n // BEGIN / COMMIT around a multi-statement batch gives us\n // atomicity. SQLite rolls back to pre-BEGIN on any error\n // inside the block.\n runBatch('BEGIN')\n try {\n runBatch(sql)\n runBatch('COMMIT')\n } catch (err) {\n try {\n runBatch('ROLLBACK')\n } catch {\n // Swallow rollback errors; we're already throwing the original.\n }\n throw err\n }\n },\n\n async applySqlNoTx(sql: string) {\n runBatch(sql)\n },\n\n async introspect(): Promise<SchemaSnapshot> {\n // Reverse-engineer the live schema via sqlite_master + PRAGMA walks.\n // Types come back as SQLite affinities (a code-first `uuid()` reads as\n // `text`), so this powers `kick db introspect`; byte-exact drift\n // against a code-first snapshot needs a dialect-normalised compare.\n return introspectSqlite(database)\n },\n\n async close() {\n // Caller owns the database handle. The adapter doesn't close\n // it — adopters typically share the same handle with the\n // KickDbClient.\n },\n }\n}\n","// sqliteDialect — thin factory over Kysely's SqliteDialect so adopters\n// never have to reach for `import { SqliteDialect } from 'kysely'`.\n// Mirrors the `@forinda/kickjs-db/pg` template; the kysely subpackage\n// is a pinned internal dep of the framework.\n\nimport { SqliteDialect, type Dialect as KyselyDialect } from 'kysely'\n\nimport type { SqliteDatabaseLike } from './adapter'\n\nexport interface SqliteDialectOptions {\n /**\n * better-sqlite3-compatible database handle. Both `new Database(...)`\n * from `better-sqlite3` and bun's `bun:sqlite` `Database` match\n * structurally (Bun is best-effort — same `.prepare()` shape, no\n * version assertion).\n */\n database: SqliteDatabaseLike\n}\n\n/**\n * Construct the dialect that `createDbClient({ dialect })` consumes.\n *\n * @example\n * ```ts\n * import { createDbClient } from '@forinda/kickjs-db'\n * import { sqliteDialect, sqliteAdapter } from '@forinda/kickjs-db/sqlite'\n * import Database from 'better-sqlite3'\n *\n * const database = new Database(':memory:')\n *\n * export const db = createDbClient({\n * schema,\n * dialect: sqliteDialect({ database }),\n * })\n *\n * export const migrationAdapter = sqliteAdapter({ database })\n * ```\n */\nexport function sqliteDialect(opts: SqliteDialectOptions): KyselyDialect {\n return new SqliteDialect({ database: opts.database as never })\n}\n"],"mappings":";;;;;;;;;;qIAsDA,SAAgB,cAAc,KAA8C,CAC1E,IAAM,QAAmB,SACnB,CAAE,UAAa,KAIf,SAAY,KAAgB,SAAS,KAAK,GAAG,EAEnD,MAAO,CACL,QAEA,MAAM,uBAAwB,CAC5B,SAAS,mBAAmB,OAAO,CAAC,EACpC,SAAS,aAAa,OAAO,CAAC,CAChC,EAEA,MAAM,aAAuC,CAe3C,OAda,SACV,QACC;;2CAGF,CAAC,CACA,IAQO,CAAC,CAAC,IAAK,MAAS,CACxB,GAAI,IAAI,GACR,KAAM,IAAI,KACV,KAAM,IAAI,KACV,MAAO,OAAO,IAAI,KAAK,EACvB,UAAW,IAAI,WACf,UAAW,IAAI,SACjB,EAAE,CACJ,EAEA,MAAM,cAAc,IAAK,CACvB,SACG,QACC;kCAEF,CAAC,CACA,IAAI,IAAI,GAAI,IAAI,KAAM,IAAI,KAAM,IAAI,MAAO,IAAI,SAAS,CAC7D,EAEA,MAAM,cAAc,GAAY,CAC9B,SAAS,QAAQ,0CAA0C,CAAC,CAAC,IAAI,EAAE,CACrE,EAEA,MAAM,YAAY,MAAiC,CAQjD,OAPU,SACP,QACC;;8CAGF,CAAC,CACA,IAAI,KACA,CAAC,CAAC,UAAY,CACvB,EAEA,MAAM,aAAc,CAClB,SACG,QACC;;wBAGF,CAAC,CACA,IAAI,CACT,EAEA,MAAM,aAAa,IAAa,CAI9B,SAAS,OAAO,EAChB,GAAI,CACF,SAAS,GAAG,EACZ,SAAS,QAAQ,CACnB,OAAS,IAAK,CACZ,GAAI,CACF,SAAS,UAAU,CACrB,MAAQ,CAER,CACA,MAAM,GACR,CACF,EAEA,MAAM,aAAa,IAAa,CAC9B,SAAS,GAAG,CACd,EAEA,MAAM,YAAsC,CAK1C,OAAO,iBAAiB,QAAQ,CAClC,EAEA,MAAM,OAAQ,CAId,CACF,CACF,CC/HA,SAAgB,cAAc,KAA2C,CACvE,OAAO,IAAI,cAAc,CAAE,SAAU,KAAK,QAAkB,CAAC,CAC/D"}
1
+ {"version":3,"file":"sqlite.mjs","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"sourcesContent":["import {\n lockTableDdl,\n migrationsTableDdl,\n type Dialect,\n type MigrationAdapter,\n type MigrationRow,\n type SchemaSnapshot,\n} from '../../index'\nimport { introspectSqlite } from '../../migrate/introspect-sqlite'\n\n/**\n * better-sqlite3-shaped database handle that `sqliteAdapter` consumes.\n * Mirrors the methods we actually use; both `new Database(...)` from\n * `better-sqlite3` and bun's `bun:sqlite` Database match structurally.\n *\n * better-sqlite3's API is synchronous — we wrap everything in `async`\n * to match the `MigrationAdapter` contract. No I/O actually awaits;\n * the wrapping is for shape compatibility.\n */\n/**\n * `all` / `get` are deliberately NOT method-generic: better-sqlite3\n * v12's own `Statement` methods are non-generic, so generic signatures\n * here would make a real `Database` instance structurally incompatible\n * (callers had to cast — same fix as `SqliteIntrospectDb`). Row typing\n * happens at the call sites via assertions instead.\n */\nexport interface SqliteStatement {\n run(...params: readonly unknown[]): { changes: number; lastInsertRowid: number | bigint }\n all(...params: readonly unknown[]): unknown[]\n get(...params: readonly unknown[]): unknown\n}\n\nexport interface SqliteDatabaseLike {\n prepare(sql: string): SqliteStatement\n exec(sql: string): unknown\n close(): unknown\n}\n\nexport interface SqliteAdapterOptions {\n /**\n * better-sqlite3 (or compatible) Database handle. Caller-owned —\n * the adapter's `close()` does NOT close the database because\n * adopters typically share a single handle across the migration\n * adapter and the KickDbClient.\n */\n database: SqliteDatabaseLike\n}\n\n/**\n * MigrationAdapter implementation backed by better-sqlite3.\n *\n * Lock semantics: single-row UPDATE WHERE locked_at IS NULL on\n * `kick_migrations_lock`. Only the row created by `ensureMigrationTables()`\n * exists, so the UPDATE either flips `locked_at` and returns\n * `changes=1` (we won) or matches zero rows (someone else holds it).\n *\n * Introspection: `introspect()` walks `sqlite_master` + `PRAGMA` via\n * {@link introspectSqlite}. Types come back as SQLite affinities (lossy\n * vs the code-first DSL), so it powers `kick db introspect` rather than\n * byte-exact drift detection.\n */\nexport function sqliteAdapter(opts: SqliteAdapterOptions): MigrationAdapter {\n const dialect: Dialect = 'sqlite'\n const { database } = opts\n\n // Multi-statement DDL runs through better-sqlite3's exec() (it\n // handles `;`-separated batches natively).\n const runBatch = (sql: string) => database.exec(sql)\n\n return {\n dialect,\n\n async ensureMigrationTables() {\n runBatch(migrationsTableDdl(dialect))\n runBatch(lockTableDdl(dialect))\n },\n\n async listApplied(): Promise<MigrationRow[]> {\n const rows = database\n .prepare(\n `SELECT id, name, hash, batch, applied_at, direction\n FROM kick_migrations\n ORDER BY applied_at ASC, id ASC`,\n )\n .all() as {\n id: string\n name: string\n hash: string\n batch: number\n applied_at: string\n direction: 'up' | 'down'\n }[]\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n hash: row.hash,\n batch: Number(row.batch),\n appliedAt: row.applied_at,\n direction: row.direction,\n }))\n },\n\n async recordApplied(row) {\n database\n .prepare(\n `INSERT INTO kick_migrations (id, name, hash, batch, direction)\n VALUES (?, ?, ?, ?, ?)`,\n )\n .run(row.id, row.name, row.hash, row.batch, row.direction)\n },\n\n async removeApplied(id: string) {\n database.prepare(`DELETE FROM kick_migrations WHERE id = ?`).run(id)\n },\n\n async acquireLock(owner: string): Promise<boolean> {\n const r = database\n .prepare(\n `UPDATE kick_migrations_lock\n SET locked_at = datetime('now'), locked_by = ?\n WHERE id = 1 AND locked_at IS NULL`,\n )\n .run(owner)\n return r.changes === 1\n },\n\n async releaseLock() {\n database\n .prepare(\n `UPDATE kick_migrations_lock\n SET locked_at = NULL, locked_by = NULL\n WHERE id = 1`,\n )\n .run()\n },\n\n async applySqlInTx(sql: string) {\n // BEGIN / COMMIT around a multi-statement batch gives us\n // atomicity. SQLite rolls back to pre-BEGIN on any error\n // inside the block.\n runBatch('BEGIN')\n try {\n runBatch(sql)\n runBatch('COMMIT')\n } catch (err) {\n try {\n runBatch('ROLLBACK')\n } catch {\n // Swallow rollback errors; we're already throwing the original.\n }\n throw err\n }\n },\n\n async applySqlNoTx(sql: string) {\n runBatch(sql)\n },\n\n async introspect(): Promise<SchemaSnapshot> {\n // Reverse-engineer the live schema via sqlite_master + PRAGMA walks.\n // Types come back as SQLite affinities (a code-first `uuid()` reads as\n // `text`), so this powers `kick db introspect`; byte-exact drift\n // against a code-first snapshot needs a dialect-normalised compare.\n return introspectSqlite(database)\n },\n\n async close() {\n // Caller owns the database handle. The adapter doesn't close\n // it — adopters typically share the same handle with the\n // KickDbClient.\n },\n }\n}\n","// sqliteDialect — thin factory over Kysely's SqliteDialect so adopters\n// never have to reach for `import { SqliteDialect } from 'kysely'`.\n// Mirrors the `@forinda/kickjs-db/pg` template; the kysely subpackage\n// is a pinned internal dep of the framework.\n\nimport { SqliteDialect, type Dialect as KyselyDialect } from 'kysely'\n\nimport type { SqliteDatabaseLike } from './adapter'\n\nexport interface SqliteDialectOptions {\n /**\n * better-sqlite3-compatible database handle. Both `new Database(...)`\n * from `better-sqlite3` and bun's `bun:sqlite` `Database` match\n * structurally (Bun is best-effort — same `.prepare()` shape, no\n * version assertion).\n */\n database: SqliteDatabaseLike\n}\n\n/**\n * Construct the dialect that `createDbClient({ dialect })` consumes.\n *\n * @example\n * ```ts\n * import { createDbClient } from '@forinda/kickjs-db'\n * import { sqliteDialect, sqliteAdapter } from '@forinda/kickjs-db/sqlite'\n * import Database from 'better-sqlite3'\n *\n * const database = new Database(':memory:')\n *\n * export const db = createDbClient({\n * schema,\n * dialect: sqliteDialect({ database }),\n * })\n *\n * export const migrationAdapter = sqliteAdapter({ database })\n * ```\n */\nexport function sqliteDialect(opts: SqliteDialectOptions): KyselyDialect {\n return new SqliteDialect({ database: opts.database as never })\n}\n"],"mappings":";;;;;;;;;;qIA6DA,SAAgB,cAAc,KAA8C,CAC1E,IAAM,QAAmB,SACnB,CAAE,UAAa,KAIf,SAAY,KAAgB,SAAS,KAAK,GAAG,EAEnD,MAAO,CACL,QAEA,MAAM,uBAAwB,CAC5B,SAAS,mBAAmB,OAAO,CAAC,EACpC,SAAS,aAAa,OAAO,CAAC,CAChC,EAEA,MAAM,aAAuC,CAe3C,OAda,SACV,QACC;;2CAGF,CAAC,CACA,IAQO,CAAC,CAAC,IAAK,MAAS,CACxB,GAAI,IAAI,GACR,KAAM,IAAI,KACV,KAAM,IAAI,KACV,MAAO,OAAO,IAAI,KAAK,EACvB,UAAW,IAAI,WACf,UAAW,IAAI,SACjB,EAAE,CACJ,EAEA,MAAM,cAAc,IAAK,CACvB,SACG,QACC;kCAEF,CAAC,CACA,IAAI,IAAI,GAAI,IAAI,KAAM,IAAI,KAAM,IAAI,MAAO,IAAI,SAAS,CAC7D,EAEA,MAAM,cAAc,GAAY,CAC9B,SAAS,QAAQ,0CAA0C,CAAC,CAAC,IAAI,EAAE,CACrE,EAEA,MAAM,YAAY,MAAiC,CAQjD,OAPU,SACP,QACC;;8CAGF,CAAC,CACA,IAAI,KACA,CAAC,CAAC,UAAY,CACvB,EAEA,MAAM,aAAc,CAClB,SACG,QACC;;wBAGF,CAAC,CACA,IAAI,CACT,EAEA,MAAM,aAAa,IAAa,CAI9B,SAAS,OAAO,EAChB,GAAI,CACF,SAAS,GAAG,EACZ,SAAS,QAAQ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