@forinda/kickjs-db 5.2.2 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as QueryErrorEvent, s as SlowQueryEvent } from "./types-DlFKeljT.mjs";
2
+ import { a as QueryErrorEvent, s as SlowQueryEvent } from "./types-BBdfnVt3.mjs";
3
3
 
4
4
  //#region src/devtools-events.d.ts
5
5
  declare module '@forinda/kickjs-devtools-kit/bus' {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v5.2.2
2
+ * @forinda/kickjs-db v5.3.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { a as QueryErrorEvent, c as TransactionEvent, d as RegisteredDB, f as ExtendedClient, i as KickDbClientEvents, l as TransactionRollbackEvent, m as ModelExtensions, n as CreateDbClientOptions, o as QueryEvent, p as ExtensionDefinition, r as KickDbClient, t as BeforeQueryEvent, u as KickDbRegister } from "./types-DlFKeljT.mjs";
3
- import { _ as TableSnapshot, a as GeneratedBrand, c as NotNullBrand, d as Dialect, f as EnumSnapshot, g as SchemaSnapshot, h as IndexSnapshot, i as FkSpec, l as CheckSnapshot, m as ForeignKeySnapshot, n as ColumnRef, o as KICK_GENERATED, p as FkAction, r as ColumnState, s as KICK_NOT_NULL, t as ColumnBuilder, u as ColumnSnapshot } from "./types-Dc9RQGSf.mjs";
2
+ 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-BBdfnVt3.mjs";
3
+ import { _ as SchemaSnapshot, a as GeneratedBrand, c as NotNullBrand, d as Dialect, f as EnumSnapshot, g as RelationSnapshot, h as IndexSnapshot, i as FkSpec, l as CheckSnapshot, m as ForeignKeySnapshot, n as ColumnRef, o as KICK_GENERATED, p as FkAction, r as ColumnState, s as KICK_NOT_NULL, t as ColumnBuilder, u as ColumnSnapshot, v as TableSnapshot } from "./types-7Ko9gPCO.mjs";
4
4
  import * as _$_forinda_kickjs0 from "@forinda/kickjs";
5
5
  import { InjectionToken } from "@forinda/kickjs";
6
6
  import { Generated } from "kysely";
@@ -109,16 +109,14 @@ interface AddEnumValue {
109
109
  before?: string;
110
110
  }
111
111
  /**
112
- * Advisory-only change kind raised when an enum keeps the same name
113
- * but loses one or more values across the diff. PostgreSQL has no
114
- * `ALTER TYPE … DROP VALUE` — round-tripping requires dropping every
115
- * column that uses the type, dropping the type, recreating with the
116
- * new value list, then recreating the columns and restoring data.
112
+ * Change raised when an enum keeps the same name but loses one or
113
+ * more values across the diff. PostgreSQL has no `ALTER TYPE … DROP
114
+ * VALUE`, so the emitter renders a rename-recreate dance behind a
115
+ * `-- KICK ENUM REMOVE` header. The runner refuses to apply such a
116
+ * migration without `confirmEnumDrop: true` on `RunnerOptions` (or
117
+ * `--confirm-enum-drop` from the CLI).
117
118
  *
118
- * The diff engine records the removed values; the emitter renders a
119
- * multi-line SQL comment with explicit guidance instead of a no-op
120
- * silently swallowed by the migration runner. Operators choosing to
121
- * proceed write the multi-step migration by hand.
119
+ * Spec: docs/db/spec-enum-value-removal.md.
122
120
  */
123
121
  interface RemoveEnumValue {
124
122
  kind: 'removeEnumValue';
@@ -126,6 +124,21 @@ interface RemoveEnumValue {
126
124
  enum: string;
127
125
  /** Values present in the previous snapshot but not in the next. */
128
126
  removed: readonly string[];
127
+ /**
128
+ * Full value list AFTER the removal. Carried on the change so the
129
+ * emitter can render `CREATE TYPE … AS ENUM (…)` without needing
130
+ * the next-snapshot reference.
131
+ */
132
+ values: readonly string[];
133
+ /**
134
+ * Columns in the next snapshot whose declared type is this enum.
135
+ * Each gets one `ALTER TABLE … ALTER COLUMN … TYPE foo USING
136
+ * column::text::foo` clause inside the rename-recreate block.
137
+ */
138
+ affectedColumns: readonly {
139
+ table: string;
140
+ column: string;
141
+ }[];
129
142
  }
130
143
  type Change = CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumn | AddIndex | DropIndex | AddForeignKey | DropForeignKey | CreateEnum | DropEnum | AddEnumValue | RemoveEnumValue;
131
144
  type ChangeSet = Change[];
@@ -182,6 +195,52 @@ declare class UnreviewedMigrationError extends MigrationError {
182
195
  readonly id: string;
183
196
  constructor(id: string);
184
197
  }
198
+ /**
199
+ * Thrown by the runner when a migration carries the `-- KICK ENUM
200
+ * REMOVE` header and the operator hasn't passed `confirmEnumDrop:
201
+ * true` (CLI: `--confirm-enum-drop`). Spec:
202
+ * docs/db/spec-enum-value-removal.md §4.
203
+ */
204
+ declare class MigrationEnumDropError extends MigrationError {
205
+ readonly id: string;
206
+ readonly enums: readonly string[];
207
+ readonly removed: readonly string[];
208
+ readonly columns: readonly string[];
209
+ constructor(id: string, enums: readonly string[], removed: readonly string[], columns: readonly string[]);
210
+ }
211
+ //#endregion
212
+ //#region src/migrate/enum-drop-gate.d.ts
213
+ /**
214
+ * Runner gate for the `-- KICK ENUM REMOVE` header.
215
+ *
216
+ * Pure parser + decision function — no I/O, no adapter, no DB. The
217
+ * runner reads up.sql, hands it to `parseEnumDropHeader`, and
218
+ * passes the result to `enforceEnumDropGate` which throws
219
+ * `MigrationEnumDropError` when the header is present and
220
+ * `confirmEnumDrop` is falsy.
221
+ *
222
+ * Spec: docs/db/spec-enum-value-removal.md §4.
223
+ */
224
+ /**
225
+ * Parsed payload from the header block. Empty arrays for keys not
226
+ * present (resilient to operators editing the migration by hand).
227
+ */
228
+ interface EnumDropHeader {
229
+ enums: string[];
230
+ removed: string[];
231
+ columns: string[];
232
+ }
233
+ /**
234
+ * Scan the first 64 lines of an up.sql for one or more enum-drop
235
+ * header blocks. Returns null when no header is present.
236
+ */
237
+ declare function parseEnumDropHeader(sql: string): EnumDropHeader | null;
238
+ /**
239
+ * Throws `MigrationEnumDropError` when the migration has an
240
+ * enum-drop header and `confirmEnumDrop` is not set. Returns
241
+ * silently otherwise.
242
+ */
243
+ declare function enforceEnumDropGate(id: string, sql: string, confirmEnumDrop: boolean): EnumDropHeader | null;
185
244
  //#endregion
186
245
  //#region src/migrate/journal.d.ts
187
246
  interface JournalEntry {
@@ -433,6 +492,12 @@ interface RunnerOptions {
433
492
  driftCheck?: DriftBehavior;
434
493
  /** Logger surface for drift warnings. Defaults to console. */
435
494
  log?: DriftLogger;
495
+ /**
496
+ * Allow migrations carrying the `-- KICK ENUM REMOVE` header to
497
+ * apply. Default `false`. CLI exposes via `--confirm-enum-drop`.
498
+ * Spec: docs/db/spec-enum-value-removal.md.
499
+ */
500
+ confirmEnumDrop?: boolean;
436
501
  }
437
502
  interface AppliedSummary {
438
503
  applied: string[];
@@ -564,30 +629,49 @@ declare function jsonb<T = unknown>(): ColumnBuilder<T>;
564
629
  declare function bytea(): ColumnBuilder<Uint8Array>;
565
630
  //#endregion
566
631
  //#region src/dsl/relations.d.ts
567
- interface RelationOne {
632
+ /**
633
+ * Generic over the target table so the typegen plugin can pull
634
+ * `target['__name']` without losing the literal string at the type
635
+ * level. Existing callers that only read `kind` / `fields` /
636
+ * `references` see the same surface.
637
+ */
638
+ interface RelationOne<TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<string, Record<string, ColumnBuilder>>> {
568
639
  kind: 'one';
569
- target: TableDecl<string, Record<string, ColumnBuilder>>;
640
+ target: TTarget;
570
641
  fields: ColumnRef[];
571
642
  references: ColumnRef[];
572
643
  }
573
- interface RelationMany {
644
+ interface RelationMany<TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<string, Record<string, ColumnBuilder>>> {
574
645
  kind: 'many';
575
- target: TableDecl<string, Record<string, ColumnBuilder>>;
646
+ target: TTarget;
576
647
  }
577
648
  type Relation = RelationOne | RelationMany;
578
- interface RelationsDecl {
649
+ /**
650
+ * Generic so the typegen plugin can read the source table name and
651
+ * the per-relation kind/target via `RelationsDecl['__sourceTable']`
652
+ * and `RelationsDecl['__relations']`. The runtime shape is
653
+ * unchanged; the generic parameters narrow the type at call sites.
654
+ */
655
+ interface RelationsDecl<TSource extends string = string, TRelations extends Record<string, Relation> = Record<string, Relation>> {
579
656
  __isRelations: true;
580
- __sourceTable: string;
581
- __relations: Record<string, Relation>;
657
+ __sourceTable: TSource;
658
+ __relations: TRelations;
582
659
  }
583
660
  interface Helpers {
584
- one: (target: TableDecl<string, Record<string, ColumnBuilder>>, opts: {
661
+ one: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T, opts: {
585
662
  fields: ColumnRef[];
586
663
  references: ColumnRef[];
587
- }) => RelationOne;
588
- many: (target: TableDecl<string, Record<string, ColumnBuilder>>) => RelationMany;
664
+ }) => RelationOne<T>;
665
+ many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T) => RelationMany<T>;
589
666
  }
590
- declare function relations<T extends TableDecl<string, Record<string, ColumnBuilder>>>(source: T, builder: (h: Helpers) => Record<string, Relation>): RelationsDecl;
667
+ /**
668
+ * Declare a typed relation set for `source`. The return type
669
+ * preserves `source.__name` and the literal `kind`/`target` of every
670
+ * helper-built entry so `SchemaToRelationsRegister<S>` (re-exported
671
+ * from `@forinda/kickjs-db`) can walk the schema barrel and emit a
672
+ * matching `KickDbRelationsRegister` augmentation at typegen time.
673
+ */
674
+ declare function relations<T extends TableDecl<string, Record<string, ColumnBuilder>>, R extends Record<string, Relation>>(source: T, builder: (h: Helpers) => R): RelationsDecl<T['__name'], R>;
591
675
  //#endregion
592
676
  //#region src/custom-type.d.ts
593
677
  interface CustomTypeOptions<TJs, TDriver = unknown> {
@@ -640,5 +724,104 @@ declare class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {
640
724
  */
641
725
  declare function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs>;
642
726
  //#endregion
643
- export { AddColumn, AddEnumValue, AddForeignKey, AddIndex, AlterColumn, type AppliedSummary, type BeforeQueryEvent, Change, ChangeSet, type CheckSnapshot, ColumnBuilder, type ColumnRef, type ColumnSnapshot, ColumnState, type CreateDbClientOptions, CreateEnum, CreateTable, CustomColumnBuilder, type CustomTypeOptions, DB_CLIENT, DB_PRIMARY, DB_REPLICA, type DbConfig, type Dialect, type DriftBehavior, type DriftLogger, DropColumn, DropEnum, DropForeignKey, DropIndex, DropTable, type ExtendedClient, type ExtensionDefinition, type FkAction, FkSpec, type ForeignKeySnapshot, type GenerateOptions, type GenerateResult, GeneratedBrand, IndexDecl, type IndexSnapshot, type IntrospectPgOptions, type Journal, type JournalEntry, KICK_GENERATED, KICK_LOCK_TABLE, KICK_MIGRATIONS_TABLE, KICK_NOT_NULL, type KickDbAdapterConfig, type KickDbClient, type KickDbClientEvents, KickDbError, type KickDbRegister, MemoryMigrationAdapter, type MigrationAdapter, MigrationDriftError, MigrationError, MigrationHashError, MigrationLockError, type MigrationRow, type MigrationsOnBoot, type ModelExtensions, NotNullBrand, type PgQueryRunner, type QueryErrorEvent, type QueryEvent, type RegisteredDB, Relation, RelationMany, RelationOne, RelationsDecl, RemoveEnumValue, RenameColumn, RenameTable, type ReversedSummary, type RollbackSummary, type RunnerOptions, type SchemaDiffSummary, type SchemaSnapshot, type SchemaToTypes, type StatusEntry, TableDecl, type TableSnapshot, TimestampBuilder, type TransactionEvent, type TransactionRollbackEvent, UnreviewedMigrationError, UuidBuilder, appendJournalEntry, bigSerial, bigint, boolean, bytea, char, checkDrift, computeMigrationHash, createDbClient, customType, date, decimal, diff, doublePrecision, emitPg, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectPg, invertChanges, json, jsonb, kickDbAdapter, lockTableDdl, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, readJournal, real, relations, renderSchemaSource, resolveDbConfig, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
727
+ //#region src/query/relations.d.ts
728
+ type ResolvedRelation = RelationSnapshot;
729
+ /**
730
+ * Sidecar map: source table → relation name → resolved entry. Lives
731
+ * on `SchemaSnapshot.relations` and is populated by
732
+ * `extractRelations()` (`query/extract-relations.ts`).
733
+ */
734
+ type ResolvedRelations = Record<string, Record<string, ResolvedRelation>>;
735
+ //#endregion
736
+ //#region src/query/schema-relations-types.d.ts
737
+ /**
738
+ * Distribute over `S` (the schema record), keeping only the entries
739
+ * that are `RelationsDecl<...>`. Each entry contributes one row to
740
+ * the output object — keyed by the source table's `__name` and
741
+ * carrying the per-relation `{ kind, target }` map.
742
+ *
743
+ * `Record<string, Record<string, RelationMapEntry>>` is the
744
+ * structural shape consumed by `KickDbRelationsRegister`; this type
745
+ * narrows it to the literal table names present in the schema.
746
+ */
747
+ type SchemaToRelationsRegister<S> = MergeBySource<{ [K in keyof S]: S[K] extends RelationsDecl<infer Source, infer R> ? Source extends string ? R extends Record<string, Relation> ? {
748
+ source: Source;
749
+ relations: ResolveRelations<R>;
750
+ } : never : never : never }[keyof S]>;
751
+ /**
752
+ * Pull `{ kind, target }` for each relation entry. `target` shrinks
753
+ * to the literal table name so the registry stays declarative
754
+ * (matches the `RelationMapEntry` shape — see `query/types.ts`).
755
+ */
756
+ type ResolveRelations<R extends Record<string, Relation>> = { [K in keyof R]: {
757
+ kind: R[K]['kind'];
758
+ target: R[K]['target'] extends TableDecl<infer N, Record<string, ColumnBuilder>> ? N extends string ? N : string : string;
759
+ } };
760
+ /**
761
+ * Fold a union of `{ source, relations }` records into a single
762
+ * object keyed by `source`. TypeScript distributes the conditional
763
+ * across the union and the mapped type collects every member.
764
+ */
765
+ type MergeBySource<U extends {
766
+ source: string;
767
+ relations: Record<string, RelationMapEntry>;
768
+ }> = { [Source in U['source']]: Extract<U, {
769
+ source: Source;
770
+ }>['relations'] };
771
+ //#endregion
772
+ //#region src/query/errors.d.ts
773
+ /**
774
+ * Thrown at compile time when a `with` key references a relation
775
+ * that the source table doesn't declare.
776
+ */
777
+ declare class RelationalQueryUnknownRelationError extends KickDbError {
778
+ readonly sourceTable: string;
779
+ readonly relationKey: string;
780
+ constructor(sourceTable: string, relationKey: string);
781
+ }
782
+ /**
783
+ * Thrown at compile time when a `with` clause nests deeper than
784
+ * `maxDepth` (spec §7 R-3, default 5). Catches infinite specs on
785
+ * self-referencing tables before any SQL is built.
786
+ */
787
+ declare class RelationalQueryDepthError extends KickDbError {
788
+ readonly maxDepth: number;
789
+ readonly trace: readonly string[];
790
+ constructor(maxDepth: number, trace: readonly string[]);
791
+ }
792
+ /**
793
+ * Thrown at compile time when a relation name collides with a
794
+ * literal column on the same table (spec §7 R-5). Forces the schema
795
+ * author to rename one of them so the LATERAL alias stays
796
+ * unambiguous.
797
+ */
798
+ declare class RelationalQueryAliasCollisionError extends KickDbError {
799
+ readonly sourceTable: string;
800
+ readonly conflictingName: string;
801
+ constructor(sourceTable: string, conflictingName: string);
802
+ }
803
+ /**
804
+ * Thrown by SQLite + MySQL compiler stubs in v1. The interface ships
805
+ * with PG only; the other dialects fill in during M4 without an API
806
+ * change at the call site.
807
+ */
808
+ declare class RelationalQueryNotSupportedError extends KickDbError {
809
+ readonly dialect: string;
810
+ constructor(dialect: string);
811
+ }
812
+ /**
813
+ * Thrown at extract time when a `many` relation has no inverse
814
+ * `one` declared on the target table. The compiler needs the FK
815
+ * column pair to build the join predicate; without an inverse we
816
+ * have no way to discover it. Adopters fix by declaring the inverse
817
+ * `one` on the target side (drizzle-style symmetric declarations).
818
+ */
819
+ declare class RelationalQueryMissingInverseError extends KickDbError {
820
+ readonly sourceTable: string;
821
+ readonly relationName: string;
822
+ readonly targetTable: string;
823
+ constructor(sourceTable: string, relationName: string, targetTable: string);
824
+ }
825
+ //#endregion
826
+ export { AddColumn, AddEnumValue, AddForeignKey, AddIndex, AlterColumn, type AppliedSummary, type BeforeQueryEvent, Change, ChangeSet, type CheckSnapshot, ColumnBuilder, type ColumnRef, type ColumnSnapshot, ColumnState, type CreateDbClientOptions, CreateEnum, CreateTable, CustomColumnBuilder, type CustomTypeOptions, DB_CLIENT, DB_PRIMARY, DB_REPLICA, type DbConfig, type Dialect, type DriftBehavior, type DriftLogger, DropColumn, DropEnum, DropForeignKey, DropIndex, DropTable, type EnumDropHeader, type ExtendedClient, type ExtensionDefinition, type FindManyOptions, type FindManyRow, type FkAction, FkSpec, type ForeignKeySnapshot, type GenerateOptions, type GenerateResult, GeneratedBrand, IndexDecl, type IndexSnapshot, type IntrospectPgOptions, 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, NotNullBrand, type PgQueryRunner, type QueryErrorEvent, type QueryEvent, type QueryNamespace, type RegisteredDB, type RegisteredRelations, Relation, RelationMany, type RelationMapEntry, RelationOne, type RelationSnapshot, RelationalQueryAliasCollisionError, RelationalQueryDepthError, RelationalQueryMissingInverseError, RelationalQueryNotSupportedError, RelationalQueryUnknownRelationError, RelationsDecl, RemoveEnumValue, RenameColumn, RenameTable, type ResolvedRelation, type ResolvedRelations, type ReversedSummary, type RollbackSummary, type RunnerOptions, type SchemaDiffSummary, type SchemaSnapshot, type SchemaToRelationsRegister, type SchemaToTypes, 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, diff, doublePrecision, emitPg, enforceEnumDropGate, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectPg, invertChanges, json, jsonb, kickDbAdapter, lockTableDdl, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, parseEnumDropHeader, readJournal, real, relations, renderSchemaSource, resolveDbConfig, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
644
827
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/snapshot/extract.ts","../src/snapshot/render.ts","../src/diff/types.ts","../src/diff/engine.ts","../src/diff/invert.ts","../src/errors.ts","../src/migrate/errors.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/drift.ts","../src/adapter.ts","../src/tokens.ts","../src/dsl/constraints.ts","../src/dsl/table.ts","../src/client/schema-types.ts","../src/client/create.ts","../src/migrate/runner.ts","../src/emit/pg.ts","../src/cli/config.ts","../src/cli/generate.ts","../src/dsl/columns/builders.ts","../src/dsl/relations.ts","../src/custom-type.ts"],"mappings":";;;;;;;;;iBAuCgB,eAAA,CAAgB,MAAA,EAAQ,MAAA,mBAAyB,OAAA,EAAS,OAAA,GAAU,cAAA;;;;;;;;;;AAApF;;;;;;;;;iBCfgB,kBAAA,CAAmB,QAAA,EAAU,cAAA;;;UChB5B,WAAA;EACf,IAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,SAAA;EACf,IAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,WAAA;EACf,IAAA;EACA,IAAA;EACA,EAAA;AAAA;AAAA,UAGe,SAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA,EAAQ,cAAA;AAAA;AAAA,UAGO,UAAA;EACf,IAAA;EACA,KAA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EACf,aAAA;EACA,aAAA;EACA,WAAA,EAAa,MAAA,SAAe,QAAA;AAAA;AAAA,UAGpB,OAAA;EACR,GAAA,GACE,MAAA,EAAQ,SAAA,SAAkB,MAAA,SAAe,aAAA,IACzC,IAAA;IAAQ,MAAA,EAAQ,SAAA;IAAa,UAAA,EAAY,SAAA;EAAA,MACtC,WAAA;EACL,IAAA,GAAO,MAAA,EAAQ,SAAA,SAAkB,MAAA,SAAe,aAAA,OAAoB,YAAA;AAAA;AAAA,iBAGtD,SAAA,WAAoB,SAAA,SAAkB,MAAA,SAAe,aAAA,GAAA,CACnE,MAAA,EAAQ,CAAA,EACR,OAAA,GAAU,CAAA,EAAG,OAAA,KAAY,MAAA,SAAe,QAAA,IACvC,aAAA;;;UCRc,iBAAA;;;;;;;EAOf,QAAA;E1BM6B;E0BJ7B,QAAA,IAAY,KAAA,EAAO,GAAA,KAAQ,OAAA;E1BIW;E0BFtC,UAAA,IAAc,MAAA,EAAQ,OAAA,KAAY,GAAA;AAAA;;;;;;;;;;cAYvB,mBAAA,cAAiC,aAAA,CAAc,GAAA;;WAEjD,QAAA,IAAY,KAAA,EAAO,GAAA;EzB3Bd;EAAA,SyB6BL,UAAA,IAAc,MAAA,cAAoB,GAAA;cAE/B,IAAA,EAAM,iBAAA,CAAkB,GAAA;AAAA;;;;;AxB/CtC;;;;;;;;;AAKA;;;;;;iBwBoEgB,UAAA,KAAA,CAAgB,IAAA,EAAM,iBAAA,CAAkB,GAAA,UAAa,mBAAA,CAAoB,GAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/snapshot/extract.ts","../src/snapshot/render.ts","../src/diff/types.ts","../src/diff/engine.ts","../src/diff/invert.ts","../src/errors.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/drift.ts","../src/adapter.ts","../src/tokens.ts","../src/dsl/constraints.ts","../src/dsl/table.ts","../src/client/schema-types.ts","../src/client/create.ts","../src/migrate/runner.ts","../src/emit/pg.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":";;;;;;;;;iBAwCgB,eAAA,CAAgB,MAAA,EAAQ,MAAA,mBAAyB,OAAA,EAAS,OAAA,GAAU,cAAA;;;;;;;;;;AAApF;;;;;;;;;iBChBgB,kBAAA,CAAmB,QAAA,EAAU,cAAA;;;UChB5B,WAAA;EACf,IAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,SAAA;EACf,IAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,WAAA;EACf,IAAA;EACA,IAAA;EACA,EAAA;AAAA;AAAA,UAGe,SAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA,EAAQ,cAAA;AAAA;AAAA,UAGO,UAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA,EAAQ,cAAA;AAAA;AAAA,UAGO,YAAA;EACf,IAAA;EACA,KAAA;EACA,IAAA;EACA,EAAA;AAAA;AAAA,UAGe,WAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA;EACA,MAAA,EAAQ,cAAA;EACR,KAAA,EAAO,cAAA;AAAA;AAAA,UAGQ,QAAA;EACf,IAAA;EACA,KAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,SAAA;EACf,IAAA;EACA,KAAA;EACA,KAAA,EAAO,aAAA;AAAA;AAAA,UAGQ,aAAA;EACf,IAAA;EACA,KAAA;EACA,EAAA,EAAI,kBAAA;AAAA;AAAA,UAGW,cAAA;EACf,IAAA;EACA,KAAA;EACA,EAAA,EAAI,kBAAA;AAAA;AAAA,UAGW,UAAA;EACf,IAAA;EACA,IAAA,EAAM,YAAA;AAAA;AAAA,UAGS,QAA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yright (c) Felix Orinda
5
5
  *
@@ -8,13 +8,17 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Cxh6cDtw.mjs";import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{createToken,defineAdapter}from"@forinda/kickjs";import{ColumnNode,ColumnUpdateNode,InsertQueryNode,Kysely,PrimitiveValueListNode,ReferenceNode,SelectAllNode,SelectQueryNode,SelectionNode,TableNode,UpdateQueryNode,ValueListNode,ValueNode,ValuesNode,sql}from"kysely";import{EventEmitter}from"node:events";import{pathToFileURL}from"node:url";function isTable(v){return!!(v&&typeof v==`object`&&v.__isTable===!0)}function isPgEnum(v){if(typeof v!=`function`)return!1;let f=v;return typeof f.enumName==`string`&&Array.isArray(f.values)}function extractSnapshot(schema,dialect){let tables={},enums={};for(let value of Object.values(schema))isTable(value)?tables[value.__name]=extractTable(value):isPgEnum(value)&&(enums[value.enumName]={name:value.enumName,values:[...value.values]});return dialect===`postgres`&&Object.keys(enums).length>0?{version:1,dialect,tables,enums}:{version:1,dialect,tables}}function extractTable(t){let columns={},indexes=[...t.__indexes],foreignKeys=[];for(let[colKey,builder]of Object.entries(t.__columns)){columns[colKey]=builder.toJSON(colKey);let state=builder.__state();if(state.unique&&indexes.push({name:`${t.__name}_${colKey}_unique`,columns:[colKey],unique:!0}),state.references){let ref=state.references.thunk();foreignKeys.push({name:`${t.__name}_${colKey}_fk`,columns:[colKey],refTable:ref.__tableName,refColumns:[ref.__name],onDelete:state.references.onDelete,onUpdate:state.references.onUpdate})}}return{name:t.__name,columns,indexes,foreignKeys,checks:[]}}function renderSchemaSource(snapshot){let usedColumnHelpers=new Set,tableSources=[];for(let table of Object.values(snapshot.tables))tableSources.push(renderTable(table,usedColumnHelpers));let helpers=[`table`,...Array.from(usedColumnHelpers).toSorted()];return Object.values(snapshot.tables).some(t=>t.indexes.some(i=>!isAutoUniqueName(t.name,i)))&&helpers.push(`index`),Object.values(snapshot.tables).some(t=>t.indexes.some(i=>i.unique&&!isAutoUniqueName(t.name,i)))&&!helpers.includes(`unique`)&&helpers.push(`unique`),[`import { ${helpers.join(`, `)} } from '@forinda/kickjs-db'`,``,...tableSources].join(`
11
+ import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-CnjiG9ij.mjs";import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{createToken,defineAdapter}from"@forinda/kickjs";import{ColumnNode,ColumnUpdateNode,InsertQueryNode,Kysely,PrimitiveValueListNode,ReferenceNode,SelectAllNode,SelectQueryNode,SelectionNode,TableNode,UpdateQueryNode,ValueListNode,ValueNode,ValuesNode,sql}from"kysely";import{EventEmitter}from"node:events";import{jsonArrayFrom,jsonObjectFrom}from"kysely/helpers/postgres";import{pathToFileURL}from"node:url";var KickDbError=class extends Error{code;constructor(code,message){super(message),this.name=this.constructor.name,this.code=code}},RelationalQueryUnknownRelationError=class extends KickDbError{sourceTable;relationKey;constructor(sourceTable,relationKey){super(`KICK_DB_RELATIONAL_UNKNOWN_RELATION`,`Unknown relation \`${sourceTable}.${relationKey}\` — declare it via \`relations()\` before referencing it inside \`db.query.${sourceTable}.findMany({ with })\`.`),this.sourceTable=sourceTable,this.relationKey=relationKey}},RelationalQueryDepthError=class extends KickDbError{maxDepth;trace;constructor(maxDepth,trace){super(`KICK_DB_RELATIONAL_DEPTH_EXCEEDED`,`Relational query exceeds maxDepth=${maxDepth}. Path: ${trace.join(` → `)}. Override with \`{ maxDepth: N }\` on the call site if intentional.`),this.maxDepth=maxDepth,this.trace=trace}},RelationalQueryAliasCollisionError=class extends KickDbError{sourceTable;conflictingName;constructor(sourceTable,conflictingName){super(`KICK_DB_RELATIONAL_ALIAS_COLLISION`,`Relation \`${sourceTable}.${conflictingName}\` collides with a column of the same name. Rename the relation or the column to disambiguate.`),this.sourceTable=sourceTable,this.conflictingName=conflictingName}},RelationalQueryNotSupportedError=class extends KickDbError{dialect;constructor(dialect){super(`KICK_DB_RELATIONAL_NOT_SUPPORTED`,`Relational query compiler for dialect \`${dialect}\` lands in M4. Use layer 1 / 2 (\`db.selectFrom(...)\`) with manual joins for now.`),this.dialect=dialect}},RelationalQueryMissingInverseError=class extends KickDbError{sourceTable;relationName;targetTable;constructor(sourceTable,relationName,targetTable){super(`KICK_DB_RELATIONAL_MISSING_INVERSE`,`Cannot resolve \`many\` relation \`${sourceTable}.${relationName}\` — no inverse \`one\` relation declared on \`${targetTable}\` pointing back to \`${sourceTable}\`. Add e.g. \`relations(${targetTable}, h => ({ ${sourceTable}: h.one(${sourceTable}, { fields: [${targetTable}.${sourceTable}Id], references: [${sourceTable}.id] }) }))\` so the compiler knows which columns join the two tables.`),this.sourceTable=sourceTable,this.relationName=relationName,this.targetTable=targetTable}};function isRelations(v){return!!(v&&typeof v==`object`&&v.__isRelations===!0)}function extractRelations(schema,tables){let declsBySource={};for(let value of Object.values(schema))isRelations(value)&&(declsBySource[value.__sourceTable]={...declsBySource[value.__sourceTable],...value.__relations});if(Object.keys(declsBySource).length===0)return;let out={};for(let[sourceTable,relations]of Object.entries(declsBySource)){let tableSnapshot=tables[sourceTable];if(tableSnapshot){out[sourceTable]={};for(let[relationName,rel]of Object.entries(relations)){if(relationName in tableSnapshot.columns)throw new RelationalQueryAliasCollisionError(sourceTable,relationName);if(rel.kind===`one`){out[sourceTable][relationName]={kind:`one`,target:rel.target.__name,sourceColumns:rel.fields.map(f=>f.__name),targetColumns:rel.references.map(r=>r.__name)};continue}let target=rel.target.__name,inverse=findInverseOne(declsBySource[target]??{},sourceTable);if(inverse){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:inverse.references.map(r=>r.__name),targetColumns:inverse.fields.map(f=>f.__name)};continue}let fkFallback=resolveByForeignKey(tables[target],sourceTable);if(fkFallback){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:fkFallback.refColumns,targetColumns:fkFallback.columns};continue}throw new RelationalQueryMissingInverseError(sourceTable,relationName,target)}}}return out}function findInverseOne(targetRelations,sourceTable){for(let rel of Object.values(targetRelations))if(rel.kind===`one`&&rel.target.__name===sourceTable)return rel;return null}function resolveByForeignKey(targetTable,sourceTable){if(!targetTable)return null;let matches=targetTable.foreignKeys.filter(fk=>fk.refTable===sourceTable);if(matches.length!==1)return null;let fk=matches[0];return{columns:fk.columns,refColumns:fk.refColumns}}function isTable(v){return!!(v&&typeof v==`object`&&v.__isTable===!0)}function isPgEnum(v){if(typeof v!=`function`)return!1;let f=v;return typeof f.enumName==`string`&&Array.isArray(f.values)}function extractSnapshot(schema,dialect){let tables={},enums={};for(let value of Object.values(schema))isTable(value)?tables[value.__name]=extractTable(value):isPgEnum(value)&&(enums[value.enumName]={name:value.enumName,values:[...value.values]});let relations=extractRelations(schema,tables),snapshot={version:1,dialect,tables};return dialect===`postgres`&&Object.keys(enums).length>0&&(snapshot.enums=enums),relations&&(snapshot.relations=relations),snapshot}function extractTable(t){let columns={},indexes=[...t.__indexes],foreignKeys=[];for(let[colKey,builder]of Object.entries(t.__columns)){columns[colKey]=builder.toJSON(colKey);let state=builder.__state();if(state.unique&&indexes.push({name:`${t.__name}_${colKey}_unique`,columns:[colKey],unique:!0}),state.references){let ref=state.references.thunk();foreignKeys.push({name:`${t.__name}_${colKey}_fk`,columns:[colKey],refTable:ref.__tableName,refColumns:[ref.__name],onDelete:state.references.onDelete,onUpdate:state.references.onUpdate})}}return{name:t.__name,columns,indexes,foreignKeys,checks:[]}}function renderSchemaSource(snapshot){let usedColumnHelpers=new Set,tableSources=[];for(let table of Object.values(snapshot.tables))tableSources.push(renderTable(table,usedColumnHelpers));let helpers=[`table`,...Array.from(usedColumnHelpers).toSorted()];return Object.values(snapshot.tables).some(t=>t.indexes.some(i=>!isAutoUniqueName(t.name,i)))&&helpers.push(`index`),Object.values(snapshot.tables).some(t=>t.indexes.some(i=>i.unique&&!isAutoUniqueName(t.name,i)))&&!helpers.includes(`unique`)&&helpers.push(`unique`),[`import { ${helpers.join(`, `)} } from '@forinda/kickjs-db'`,``,...tableSources].join(`
12
12
  `).trimEnd()+`
13
13
  `}function renderTable(table,helpers){let ident=jsIdent(table.name),columns=[];for(let col of Object.values(table.columns)){let fk=table.foreignKeys.find(f=>f.columns.length===1&&f.columns[0]===col.name&&f.name===`${table.name}_${col.name}_fk`),inlineUnique=table.indexes.find(i=>i.unique&&i.columns.length===1&&i.columns[0]===col.name&&isAutoUniqueName(table.name,i))!==void 0;columns.push(` ${jsKey(col.name)}: ${renderColumn(col,helpers,fk,inlineUnique)},`)}let explicitIndexes=table.indexes.filter(i=>!isAutoUniqueName(table.name,i)),explicitFks=table.foreignKeys.filter(f=>f.name!==`${table.name}_${f.columns[0]}_fk`||f.columns.length!==1),hasThirdArg=explicitIndexes.length>0,tableArgs=[`'${table.name}'`,`{\n${columns.join(`
14
14
  `)}\n}`];if(hasThirdArg){let callbacks=explicitIndexes.map(i=>` ${jsKey(i.name)}: ${renderIndexCall(i)}`).join(`,
15
15
  `);tableArgs.push(`(t) => ({\n${callbacks},\n })`)}let src=`export const ${ident} = table(${tableArgs.join(`, `)})`;if(explicitFks.length>0){src+=`
16
16
  // TODO: kick db introspect — composite or custom-named foreign keys not auto-rendered:
17
- `;for(let f of explicitFks)src+=`// ${f.name}: (${f.columns.join(`, `)}) → ${f.refTable}(${f.refColumns.join(`, `)})\n`}return src}function renderColumn(col,helpers,fk,inlineUnique){let{helperName,args}=pickColumnHelper(col);helpers.add(helperName);let chain=`${helperName}(${args})`;if(col.primaryKey&&(chain+=`.primaryKey()`),!col.primaryKey&&!col.nullable&&(chain+=`.notNull()`),col.default!==null&&(chain+=`.default(${JSON.stringify(col.default)})`),inlineUnique&&(chain+=`.unique()`),fk){let ref=`${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`,onDelete=fk.onDelete===`no_action`?``:`, { onDelete: '${fk.onDelete}' }`;chain+=`.references(() => ${ref}${onDelete})`}return chain}function pickColumnHelper(col){let t=col.type;return t===`serial`?{helperName:`serial`,args:``}:t===`bigserial`?{helperName:`bigSerial`,args:``}:t===`smallserial`?{helperName:`serial`,args:``}:t===`integer`?{helperName:`integer`,args:``}:t===`bigint`?{helperName:`bigint`,args:``}:t===`smallint`?{helperName:`smallint`,args:``}:t===`real`?{helperName:`real`,args:``}:t===`double precision`?{helperName:`doublePrecision`,args:``}:/^numeric(\(.+\))?$/.test(t)?{helperName:`numeric`,args:extractParens(t)}:/^varchar(\(\d+\))?$/.test(t)?{helperName:`varchar`,args:extractParens(t)}:/^char(\(\d+\))?$/.test(t)?{helperName:`char`,args:extractParens(t)}:t===`text`?{helperName:`text`,args:``}:t===`boolean`?{helperName:`boolean`,args:``}:t===`timestamp`?{helperName:`timestamp`,args:``}:t===`timestamptz`?{helperName:`timestamptz`,args:``}:t===`date`?{helperName:`date`,args:``}:t===`time`?{helperName:`time`,args:``}:t===`interval`?{helperName:`interval`,args:``}:t===`uuid`?{helperName:`uuid`,args:``}:t===`jsonb`?{helperName:`jsonb`,args:``}:t===`json`?{helperName:`json`,args:``}:t===`bytea`?{helperName:`bytea`,args:``}:{helperName:`text`,args:`/* TODO: ${t} */`}}function extractParens(t){let m=t.match(/\(([^)]+)\)/);return m?m[1]:``}function renderIndexCall(idx){let helper=idx.unique?`unique`:`index`,cols=idx.columns.map(c=>`t.${jsIdent(c)}`).join(`, `);return`${helper}('${idx.name}').on(${cols})`}function isAutoUniqueName(tableName,idx){return idx.unique&&idx.columns.length===1&&idx.name===`${tableName}_${idx.columns[0]}_unique`}function jsIdent(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:`_${raw.replace(/[^\w$]/g,`_`)}`}function jsKey(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:JSON.stringify(raw)}function diff(prev,next){let changes=[],prevTables=new Set(Object.keys(prev.tables)),nextTables=new Set(Object.keys(next.tables));diffEnumsCreatePhase(prev,next,changes);for(let name of prevTables)nextTables.has(name)||changes.push({kind:`dropTable`,table:prev.tables[name]});let newTableNames=[...nextTables].filter(n=>!prevTables.has(n));for(let name of newTableNames)changes.push({kind:`createTable`,table:next.tables[name]});for(let name of newTableNames)for(let i of next.tables[name].indexes)changes.push({kind:`addIndex`,table:name,index:i});for(let name of newTableNames)for(let f of next.tables[name].foreignKeys)changes.push({kind:`addForeignKey`,table:name,fk:f});for(let name of nextTables)prevTables.has(name)&&diffTable(prev.tables[name],next.tables[name],changes);return diffEnumsDropPhase(prev,next,changes),changes}function diffEnumsCreatePhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(nextEnums))prevEnums[name]||changes.push({kind:`createEnum`,enum:e});for(let[name,e]of Object.entries(nextEnums)){let prior=prevEnums[name];if(!prior)continue;let priorValues=new Set(prior.values),nextValues=new Set(e.values),nextValueList=e.values;for(let i=0;i<nextValueList.length;i++){let value=nextValueList[i];if(priorValues.has(value))continue;let before=nextValueList[i+1],beforeIsExisting=before!=null&&priorValues.has(before);changes.push({kind:`addEnumValue`,enum:name,value,...beforeIsExisting?{before}:{}})}let removed=prior.values.filter(v=>!nextValues.has(v));removed.length>0&&changes.push({kind:`removeEnumValue`,enum:name,removed})}}function diffEnumsDropPhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(prevEnums))nextEnums[name]||changes.push({kind:`dropEnum`,enum:e})}function diffTable(prev,next,changes){let prevCols=new Map(Object.entries(prev.columns)),nextCols=new Map(Object.entries(next.columns)),drops=[],adds=[];for(let c of prevCols.keys())nextCols.has(c)||drops.push(c);for(let c of nextCols.keys())prevCols.has(c)||adds.push(c);drops.length===1&&adds.length===1&&columnAttrsEqual(prevCols.get(drops[0]),nextCols.get(adds[0]))&&(changes.push({kind:`renameColumn`,table:next.name,from:drops[0],to:adds[0]}),drops.length=0,adds.length=0);for(let c of drops)changes.push({kind:`dropColumn`,table:next.name,column:prevCols.get(c)});for(let c of adds)changes.push({kind:`addColumn`,table:next.name,column:nextCols.get(c)});for(let c of nextCols.keys()){if(!prevCols.has(c))continue;let before=prevCols.get(c),after=nextCols.get(c);columnsEqual(before,after)||changes.push({kind:`alterColumn`,table:next.name,column:c,before,after})}diffByName(prev.indexes,next.indexes,i=>changes.push({kind:`dropIndex`,table:next.name,index:i}),i=>changes.push({kind:`addIndex`,table:next.name,index:i})),diffByName(prev.foreignKeys,next.foreignKeys,f=>changes.push({kind:`dropForeignKey`,table:next.name,fk:f}),f=>changes.push({kind:`addForeignKey`,table:next.name,fk:f}))}function diffByName(prev,next,onDrop,onAdd){let prevByName=new Map(prev.map(p=>[p.name,p])),nextByName=new Map(next.map(n=>[n.name,n]));for(let[n,p]of prevByName)nextByName.has(n)||onDrop(p);for(let[n,x]of nextByName)prevByName.has(n)||onAdd(x)}function columnsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function columnAttrsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function invertChanges(forward){let reversed=[];for(let change of forward)reversed.push(invert(change));return reversed.toReversed()}function invert(change){switch(change.kind){case`createTable`:return{kind:`dropTable`,table:change.table};case`dropTable`:return{kind:`createTable`,table:change.table};case`renameTable`:return{kind:`renameTable`,from:change.to,to:change.from};case`addColumn`:return{kind:`dropColumn`,table:change.table,column:change.column};case`dropColumn`:return{kind:`addColumn`,table:change.table,column:change.column};case`renameColumn`:return{kind:`renameColumn`,table:change.table,from:change.to,to:change.from};case`alterColumn`:return{kind:`alterColumn`,table:change.table,column:change.column,before:change.after,after:change.before};case`addIndex`:return{kind:`dropIndex`,table:change.table,index:change.index};case`dropIndex`:return{kind:`addIndex`,table:change.table,index:change.index};case`addForeignKey`:return{kind:`dropForeignKey`,table:change.table,fk:change.fk};case`dropForeignKey`:return{kind:`addForeignKey`,table:change.table,fk:change.fk};case`createEnum`:return{kind:`dropEnum`,enum:change.enum};case`dropEnum`:return{kind:`createEnum`,enum:change.enum};case`addEnumValue`:return change;case`removeEnumValue`:return change}}const AMBIGUOUS_REVERSE_KINDS=new Set([`dropTable`,`dropColumn`,`alterColumn`,`addEnumValue`,`removeEnumValue`]);function hasAmbiguousReverse(forward){return forward.some(c=>AMBIGUOUS_REVERSE_KINDS.has(c.kind))}var KickDbError=class extends Error{code;constructor(code,message){super(message),this.name=this.constructor.name,this.code=code}},MigrationError=class extends KickDbError{},MigrationLockError=class extends MigrationError{constructor(message){super(`migration_lock_held`,message)}},MigrationDriftError=class extends MigrationError{diff;constructor(message,diff){super(`migration_drift`,message),this.diff=diff}},MigrationHashError=class extends MigrationError{id;expected;actual;constructor(id,expected,actual){super(`migration_hash_mismatch`,`Hash mismatch for migration ${id}`),this.id=id,this.expected=expected,this.actual=actual}},UnreviewedMigrationError=class extends MigrationError{id;constructor(id){super(`migration_unreviewed`,`Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`),this.id=id}};const FILE=`_journal.json`;async function readJournal(migrationsDir,dialect){let file=path.join(migrationsDir,FILE);if(!existsSync(file))return{version:1,dialect,entries:[]};let raw=JSON.parse(await readFile(file,`utf8`));if(raw.version!==1)throw Error(`_journal.json version ${raw.version} unsupported (expected 1)`);return raw}async function appendJournalEntry(migrationsDir,dialect,entry){let j=await readJournal(migrationsDir,dialect);j.entries.push(entry),await writeFile(path.join(migrationsDir,FILE),JSON.stringify(j,null,2)+`
17
+ `;for(let f of explicitFks)src+=`// ${f.name}: (${f.columns.join(`, `)}) → ${f.refTable}(${f.refColumns.join(`, `)})\n`}return src}function renderColumn(col,helpers,fk,inlineUnique){let{helperName,args}=pickColumnHelper(col);helpers.add(helperName);let chain=`${helperName}(${args})`;if(col.primaryKey&&(chain+=`.primaryKey()`),!col.primaryKey&&!col.nullable&&(chain+=`.notNull()`),col.default!==null&&(chain+=`.default(${JSON.stringify(col.default)})`),inlineUnique&&(chain+=`.unique()`),fk){let ref=`${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`,onDelete=fk.onDelete===`no_action`?``:`, { onDelete: '${fk.onDelete}' }`;chain+=`.references(() => ${ref}${onDelete})`}return chain}function pickColumnHelper(col){let t=col.type;return t===`serial`?{helperName:`serial`,args:``}:t===`bigserial`?{helperName:`bigSerial`,args:``}:t===`smallserial`?{helperName:`serial`,args:``}:t===`integer`?{helperName:`integer`,args:``}:t===`bigint`?{helperName:`bigint`,args:``}:t===`smallint`?{helperName:`smallint`,args:``}:t===`real`?{helperName:`real`,args:``}:t===`double precision`?{helperName:`doublePrecision`,args:``}:/^numeric(\(.+\))?$/.test(t)?{helperName:`numeric`,args:extractParens(t)}:/^varchar(\(\d+\))?$/.test(t)?{helperName:`varchar`,args:extractParens(t)}:/^char(\(\d+\))?$/.test(t)?{helperName:`char`,args:extractParens(t)}:t===`text`?{helperName:`text`,args:``}:t===`boolean`?{helperName:`boolean`,args:``}:t===`timestamp`?{helperName:`timestamp`,args:``}:t===`timestamptz`?{helperName:`timestamptz`,args:``}:t===`date`?{helperName:`date`,args:``}:t===`time`?{helperName:`time`,args:``}:t===`interval`?{helperName:`interval`,args:``}:t===`uuid`?{helperName:`uuid`,args:``}:t===`jsonb`?{helperName:`jsonb`,args:``}:t===`json`?{helperName:`json`,args:``}:t===`bytea`?{helperName:`bytea`,args:``}:{helperName:`text`,args:`/* TODO: ${t} */`}}function extractParens(t){let m=t.match(/\(([^)]+)\)/);return m?m[1]:``}function renderIndexCall(idx){let helper=idx.unique?`unique`:`index`,cols=idx.columns.map(c=>`t.${jsIdent(c)}`).join(`, `);return`${helper}('${idx.name}').on(${cols})`}function isAutoUniqueName(tableName,idx){return idx.unique&&idx.columns.length===1&&idx.name===`${tableName}_${idx.columns[0]}_unique`}function jsIdent(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:`_${raw.replace(/[^\w$]/g,`_`)}`}function jsKey(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:JSON.stringify(raw)}function diff(prev,next){let changes=[],prevTables=new Set(Object.keys(prev.tables)),nextTables=new Set(Object.keys(next.tables));diffEnumsCreatePhase(prev,next,changes);for(let name of prevTables)nextTables.has(name)||changes.push({kind:`dropTable`,table:prev.tables[name]});let newTableNames=[...nextTables].filter(n=>!prevTables.has(n));for(let name of newTableNames)changes.push({kind:`createTable`,table:next.tables[name]});for(let name of newTableNames)for(let i of next.tables[name].indexes)changes.push({kind:`addIndex`,table:name,index:i});for(let name of newTableNames)for(let f of next.tables[name].foreignKeys)changes.push({kind:`addForeignKey`,table:name,fk:f});for(let name of nextTables)prevTables.has(name)&&diffTable(prev.tables[name],next.tables[name],changes);return diffEnumsDropPhase(prev,next,changes),changes}function diffEnumsCreatePhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(nextEnums))prevEnums[name]||changes.push({kind:`createEnum`,enum:e});for(let[name,e]of Object.entries(nextEnums)){let prior=prevEnums[name];if(!prior)continue;let priorValues=new Set(prior.values),nextValues=new Set(e.values),nextValueList=e.values;for(let i=0;i<nextValueList.length;i++){let value=nextValueList[i];if(priorValues.has(value))continue;let before=nextValueList[i+1],beforeIsExisting=before!=null&&priorValues.has(before);changes.push({kind:`addEnumValue`,enum:name,value,...beforeIsExisting?{before}:{}})}let removed=prior.values.filter(v=>!nextValues.has(v));removed.length>0&&changes.push({kind:`removeEnumValue`,enum:name,removed,values:nextValueList,affectedColumns:collectColumnsByEnumType(next,name)})}}function collectColumnsByEnumType(snapshot,enumName){let out=[];for(let[tableName,table]of Object.entries(snapshot.tables))for(let[columnName,column]of Object.entries(table.columns))column.type===enumName&&out.push({table:tableName,column:columnName});return out}function diffEnumsDropPhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(prevEnums))nextEnums[name]||changes.push({kind:`dropEnum`,enum:e})}function diffTable(prev,next,changes){let prevCols=new Map(Object.entries(prev.columns)),nextCols=new Map(Object.entries(next.columns)),drops=[],adds=[];for(let c of prevCols.keys())nextCols.has(c)||drops.push(c);for(let c of nextCols.keys())prevCols.has(c)||adds.push(c);drops.length===1&&adds.length===1&&columnAttrsEqual(prevCols.get(drops[0]),nextCols.get(adds[0]))&&(changes.push({kind:`renameColumn`,table:next.name,from:drops[0],to:adds[0]}),drops.length=0,adds.length=0);for(let c of drops)changes.push({kind:`dropColumn`,table:next.name,column:prevCols.get(c)});for(let c of adds)changes.push({kind:`addColumn`,table:next.name,column:nextCols.get(c)});for(let c of nextCols.keys()){if(!prevCols.has(c))continue;let before=prevCols.get(c),after=nextCols.get(c);columnsEqual(before,after)||changes.push({kind:`alterColumn`,table:next.name,column:c,before,after})}diffByName(prev.indexes,next.indexes,i=>changes.push({kind:`dropIndex`,table:next.name,index:i}),i=>changes.push({kind:`addIndex`,table:next.name,index:i})),diffByName(prev.foreignKeys,next.foreignKeys,f=>changes.push({kind:`dropForeignKey`,table:next.name,fk:f}),f=>changes.push({kind:`addForeignKey`,table:next.name,fk:f}))}function diffByName(prev,next,onDrop,onAdd){let prevByName=new Map(prev.map(p=>[p.name,p])),nextByName=new Map(next.map(n=>[n.name,n]));for(let[n,p]of prevByName)nextByName.has(n)||onDrop(p);for(let[n,x]of nextByName)prevByName.has(n)||onAdd(x)}function columnsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function columnAttrsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function invertChanges(forward){let reversed=[];for(let change of forward)reversed.push(invert(change));return reversed.toReversed()}function invert(change){switch(change.kind){case`createTable`:return{kind:`dropTable`,table:change.table};case`dropTable`:return{kind:`createTable`,table:change.table};case`renameTable`:return{kind:`renameTable`,from:change.to,to:change.from};case`addColumn`:return{kind:`dropColumn`,table:change.table,column:change.column};case`dropColumn`:return{kind:`addColumn`,table:change.table,column:change.column};case`renameColumn`:return{kind:`renameColumn`,table:change.table,from:change.to,to:change.from};case`alterColumn`:return{kind:`alterColumn`,table:change.table,column:change.column,before:change.after,after:change.before};case`addIndex`:return{kind:`dropIndex`,table:change.table,index:change.index};case`dropIndex`:return{kind:`addIndex`,table:change.table,index:change.index};case`addForeignKey`:return{kind:`dropForeignKey`,table:change.table,fk:change.fk};case`dropForeignKey`:return{kind:`addForeignKey`,table:change.table,fk:change.fk};case`createEnum`:return{kind:`dropEnum`,enum:change.enum};case`dropEnum`:return{kind:`createEnum`,enum:change.enum};case`addEnumValue`:return change;case`removeEnumValue`:return change}}const AMBIGUOUS_REVERSE_KINDS=new Set([`dropTable`,`dropColumn`,`alterColumn`,`addEnumValue`,`removeEnumValue`]);function hasAmbiguousReverse(forward){return forward.some(c=>AMBIGUOUS_REVERSE_KINDS.has(c.kind))}var MigrationError=class extends KickDbError{},MigrationLockError=class extends MigrationError{constructor(message){super(`migration_lock_held`,message)}},MigrationDriftError=class extends MigrationError{diff;constructor(message,diff){super(`migration_drift`,message),this.diff=diff}},MigrationHashError=class extends MigrationError{id;expected;actual;constructor(id,expected,actual){super(`migration_hash_mismatch`,`Hash mismatch for migration ${id}`),this.id=id,this.expected=expected,this.actual=actual}},UnreviewedMigrationError=class extends MigrationError{id;constructor(id){super(`migration_unreviewed`,`Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`),this.id=id}},MigrationEnumDropError=class extends MigrationError{id;enums;removed;columns;constructor(id,enums,removed,columns){let enumList=enums.join(`, `),valueList=removed.join(`, `);super(`migration_enum_drop_unconfirmed`,`Migration ${id} drops value(s) ${valueList} from PostgreSQL enum(s) ${enumList}. Re-run with \`--confirm-enum-drop\` (CLI) or \`confirmEnumDrop: true\` (RunnerOptions) after reviewing the column-USING clauses in up.sql.`),this.id=id,this.enums=enums,this.removed=removed,this.columns=columns}};function quoteIdent(name){return name.split(`.`).map(part=>`"`+part.replace(/"/g,`""`)+`"`).join(`.`)}function quoteLiteral(value){return`'`+value.replace(/'/g,`''`)+`'`}function emitPg(changes){return changes.map(emitChange).join(`
18
+ `)}function emitChange(change){switch(change.kind){case`createTable`:return emitCreateTable(change.table);case`dropTable`:return`DROP TABLE ${quoteIdent(change.table.name)};`;case`renameTable`:return`ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`;case`addColumn`:return emitAddColumn(change.table,change.column);case`dropColumn`:return`ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`;case`renameColumn`:return`ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`;case`alterColumn`:return emitAlterColumn(change.table,change.before,change.after);case`addIndex`:return emitAddIndex(change.table,change.index);case`dropIndex`:return`DROP INDEX ${quoteIdent(change.index.name)};`;case`addForeignKey`:return emitAddFk(change.table,change.fk);case`dropForeignKey`:return`ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`;case`createEnum`:{let values=change.enum.values.map(v=>quoteLiteral(v)).join(`, `);return`CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`}case`dropEnum`:return`DROP TYPE ${quoteIdent(change.enum.name)};`;case`addEnumValue`:{let before=change.before?` BEFORE ${quoteLiteral(change.before)}`:``;return`ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`}case`removeEnumValue`:return emitRemoveEnumValueRecreate(change)}}function emitRemoveEnumValueRecreate(change){let safeName=sanitizeForLineComment(quoteIdent(change.enum)),removedList=change.removed.map(v=>sanitizeForLineComment(quoteLiteral(v))).join(`, `),columnsList=change.affectedColumns.map(c=>sanitizeForLineComment(`${c.table}.${c.column}`)).join(`, `),oldTypeName=quoteIdent(`${change.enum}__old`),typeName=quoteIdent(change.enum),valuesList=change.values.map(v=>quoteLiteral(v)).join(`, `),header=[`-- KICK ENUM REMOVE`,`-- enum: ${safeName}`,`-- removed: ${removedList}`,`-- columns: ${columnsList||`(none)`}`,`--`,`-- This migration drops values from a PostgreSQL ENUM type. The`,`-- runner refuses to apply it without the --confirm-enum-drop flag`,"-- (or `confirmEnumDrop: true` in RunnerOptions). Inspect the",`-- column USING clauses below to confirm rows holding a removed`,`-- value will fail loudly rather than silently coerce.`],body=[`ALTER TYPE ${typeName} RENAME TO ${oldTypeName};`,`CREATE TYPE ${typeName} AS ENUM (${valuesList});`];for(let col of change.affectedColumns)body.push(`ALTER TABLE ${quoteIdent(col.table)}`,` ALTER COLUMN ${quoteIdent(col.column)} TYPE ${typeName}`,` USING ${quoteIdent(col.column)}::text::${typeName};`);return body.push(`DROP TYPE ${oldTypeName};`),[...header,...body].join(`
19
+ `)}function sanitizeForLineComment(value){let out=``,prevWasLineBreak=!1;for(let i=0;i<value.length;i++){let code=value.charCodeAt(i);if(code===10||code===13||code===8232||code===8233){prevWasLineBreak||(out+=` `),prevWasLineBreak=!0;continue}if(prevWasLineBreak=!1,code>=0&&code<=8||code===11||code===12||code>=14&&code<=31||code===127){out+=`\\x${code.toString(16).padStart(2,`0`)}`;continue}out+=value[i]}return out}function emitAddColumn(table,c){return`ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`}function emitAlterColumn(table,before,after){let stmts=[],t=quoteIdent(table),c=quoteIdent(after.name),typeChanged=before.type!==after.type,nullChanged=before.nullable!==after.nullable,defaultChanged=before.default!==after.default,losingNotNull=!before.nullable&&after.nullable;typeChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`);let emitDefault=()=>{defaultChanged&&stmts.push(after.default===null?`ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;`:`ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`)},emitNullable=()=>{nullChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable?`DROP NOT NULL`:`SET NOT NULL`};`)};return losingNotNull?(emitDefault(),emitNullable()):(emitNullable(),emitDefault()),stmts.join(`
20
+ `)}function emitAddIndex(table,i){let cols=i.columns.map(quoteIdent).join(`, `);return`CREATE${i.unique?` UNIQUE`:``} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`}const FK_ACTIONS={cascade:`CASCADE`,restrict:`RESTRICT`,set_null:`SET NULL`,set_default:`SET DEFAULT`,no_action:`NO ACTION`};function emitAddFk(table,fk){let cols=fk.columns.map(quoteIdent).join(`, `),refCols=fk.refColumns.map(quoteIdent).join(`, `);return`ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`}function emitCreateTable(t){let cols=Object.values(t.columns).map(emitColumnDecl),pk=Object.values(t.columns).filter(c=>c.primaryKey).map(c=>quoteIdent(c.name)),lines=[...cols];return pk.length>0&&lines.push(`PRIMARY KEY (${pk.join(`, `)})`),`CREATE TABLE ${quoteIdent(t.name)} (\n ${lines.join(`,
21
+ `)}\n);`}function emitColumnDecl(c){let s=`${quoteIdent(c.name)} ${c.type}`;return c.nullable||(s+=` NOT NULL`),c.default!==null&&(s+=` DEFAULT ${formatDefault(c.default)}`),s}function formatDefault(value){return/^[A-Z_]+$/.test(value)||/^[a-z_][a-z0-9_]*\s*\([^)]*\)$/i.test(value)||/^-?\d+(\.\d+)?$/.test(value)||value===`true`||value===`false`?value:quoteLiteral(value)}function parseEnumDropHeader(sql){if(!sql.includes(`-- KICK ENUM REMOVE`))return null;let lines=sql.split(/\r?\n/,64),enums=[],removed=[],columns=[];for(let i=0;i<lines.length;i++)if((lines[i]?.trim()??``)===`-- KICK ENUM REMOVE`)for(let j=i+1;j<lines.length;j++){let next=lines[j]?.trim()??``;if(!next.startsWith(`--`))break;let m=/^--\s*([a-z]+):\s*(.+)$/i.exec(next);if(!m)continue;let key=m[1].toLowerCase(),raw=m[2].trim();key===`enum`?enums.push(raw):key===`removed`?removed.push(...splitListing(raw)):key===`columns`&&columns.push(...splitListing(raw))}return enums.length===0&&removed.length===0&&columns.length===0?{enums:[],removed:[],columns:[]}:{enums,removed,columns}}function enforceEnumDropGate(id,sql,confirmEnumDrop){let header=parseEnumDropHeader(sql);if(!header)return null;if(!confirmEnumDrop)throw new MigrationEnumDropError(id,header.enums,header.removed,header.columns);return header}function splitListing(raw){return raw===`(none)`||raw===``?[]:raw.split(`,`).map(s=>s.trim().replace(/^['"`]|['"`]$/g,``)).filter(s=>s.length>0)}const FILE=`_journal.json`;async function readJournal(migrationsDir,dialect){let file=path.join(migrationsDir,FILE);if(!existsSync(file))return{version:1,dialect,entries:[]};let raw=JSON.parse(await readFile(file,`utf8`));if(raw.version!==1)throw Error(`_journal.json version ${raw.version} unsupported (expected 1)`);return raw}async function appendJournalEntry(migrationsDir,dialect,entry){let j=await readJournal(migrationsDir,dialect);j.entries.push(entry),await writeFile(path.join(migrationsDir,FILE),JSON.stringify(j,null,2)+`
18
22
  `,`utf8`)}async function computeMigrationHash(migrationDir){let up=await readFile(path.join(migrationDir,`up.sql`),`utf8`),down=await readFile(path.join(migrationDir,`down.sql`),`utf8`),snap=await readFile(path.join(migrationDir,`snapshot.json`),`utf8`);return`sha256:${createHash(`sha256`).update(up).update(`|`).update(down).update(`|`).update(snap).digest(`hex`)}`}async function verifyMigrationHash(migrationDir,expected){return await computeMigrationHash(migrationDir)===expected}const KICK_MIGRATIONS_TABLE=`kick_migrations`,KICK_LOCK_TABLE=`kick_migrations_lock`;function migrationsTableDdl(dialect){switch(dialect){case`postgres`:return`CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
19
23
  "id" varchar(128) PRIMARY KEY,
20
24
  "name" text NOT NULL,
@@ -97,11 +101,7 @@ import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Cx
97
101
  WHERE tc.table_schema = $1
98
102
  AND tc.table_name = $2
99
103
  AND tc.constraint_type = 'FOREIGN KEY'
100
- ORDER BY tc.constraint_name, kcu.ordinal_position`,[schema,table]),byName=new Map;for(let r of rows.rows){let fk=byName.get(r.constraint_name);fk||(fk={name:r.constraint_name,columns:[],refTable:r.ref_table,refColumns:[],onDelete:mapFkAction(r.delete_rule),onUpdate:mapFkAction(r.update_rule)},byName.set(r.constraint_name,fk)),fk.columns.push(r.column_name),fk.refColumns.push(r.ref_column)}return[...byName.values()].toSorted((a,b)=>a.name.localeCompare(b.name))}function mapFkAction(raw){switch(raw.toUpperCase()){case`CASCADE`:return`cascade`;case`RESTRICT`:return`restrict`;case`SET NULL`:return`set_null`;case`SET DEFAULT`:return`set_default`;default:return`no_action`}}async function checkDrift(liveSnapshot,expectedSnapshot,behavior,log=console){if(behavior===`ignore`)return;let changes=diff(expectedSnapshot,liveSnapshot);if(changes.length===0)return;let summary=summarize(changes),message=`Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`;if(behavior===`warn`){log.warn(message);return}throw new MigrationDriftError(message,summary)}function summarize(changes){let added=[],removed=[],changed=[];for(let c of changes)switch(c.kind){case`createTable`:added.push(c.table.name);break;case`dropTable`:removed.push(c.table.name);break;case`addColumn`:added.push(`${c.table}.${c.column.name}`);break;case`dropColumn`:removed.push(`${c.table}.${c.column.name}`);break;case`alterColumn`:changed.push(`${c.table}.${c.column}`);break;case`renameColumn`:changed.push(`${c.table}.${c.from}→${c.to}`);break;case`renameTable`:changed.push(`${c.from}→${c.to}`);break;case`addIndex`:added.push(`${c.table}#${c.index.name}`);break;case`dropIndex`:removed.push(`${c.table}#${c.index.name}`);break;case`addForeignKey`:added.push(`${c.table}!${c.fk.name}`);break;case`dropForeignKey`:removed.push(`${c.table}!${c.fk.name}`);break}return{added,removed,changed}}async function withLock(opts,fn){let owner=opts.owner??`${process.pid}@${new Date().toISOString()}`;if(!await opts.adapter.acquireLock(owner))throw new MigrationLockError(`Another process holds the migration lock`);try{return await fn()}finally{await opts.adapter.releaseLock()}}async function verifyPending(pending,migrationsDir,requireReviewed){for(let entry of pending){let dir=path.join(migrationsDir,entry.id),actualHash=await computeMigrationHash(dir);if(actualHash!==entry.hash)throw new MigrationHashError(entry.id,entry.hash,actualHash);if(requireReviewed&&JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).reviewed!==!0)throw new UnreviewedMigrationError(entry.id)}}async function applyEntry(entry,batch,opts){let dir=path.join(opts.migrationsDir,entry.id),upSql=await readFile(path.join(dir,`up.sql`),`utf8`);JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).transaction===!1?await opts.adapter.applySqlNoTx(upSql):await opts.adapter.applySqlInTx(upSql),await opts.adapter.recordApplied({id:entry.id,name:entry.tag,hash:entry.hash,batch,direction:`up`})}async function runForward(opts,pending){if(pending.length===0)return{applied:[],batch:null};let requireReviewed=opts.requireReviewed??process.env.NODE_ENV!==`development`;await verifyPending(pending,opts.migrationsDir,requireReviewed);let applied=await opts.adapter.listApplied(),nextBatch=(applied.length===0?0:Math.max(...applied.map(r=>r.batch)))+1,ids=[];for(let entry of pending)await applyEntry(entry,nextBatch,opts),ids.push(entry.id);return{applied:ids,batch:nextBatch}}async function listPending(opts){let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),appliedIds=new Set(applied.map(r=>r.id));return journal.entries.filter(e=>!appliedIds.has(e.id)).map(e=>({id:e.id,tag:e.tag,hash:e.hash}))}async function maybeCheckDrift(opts){let behavior=opts.driftCheck??`error`;if(behavior===`ignore`)return;let applied=await opts.adapter.listApplied();if(applied.length===0)return;let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1],expected;try{expected=JSON.parse(await readFile(path.join(opts.migrationsDir,last.id,`snapshot.json`),`utf8`))}catch{return}await checkDrift(await opts.adapter.introspect(),expected,behavior,opts.log)}async function migrateLatest(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,await listPending(opts))))}async function migrateUp(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,(await listPending(opts)).slice(0,1))))}async function applyReverse(id,opts){let dir=path.join(opts.migrationsDir,id),downSql=await readFile(path.join(dir,`down.sql`),`utf8`),meta=JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`));if((opts.requireReviewed??process.env.NODE_ENV!==`development`)&&meta.reviewed!==!0)throw new UnreviewedMigrationError(id);meta.transaction===!1?await opts.adapter.applySqlNoTx(downSql):await opts.adapter.applySqlInTx(downSql),await opts.adapter.removeApplied(id)}async function migrateDown(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:null};let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1];return await applyReverse(last.id,opts),{reversed:last.id}})}async function migrateStatus(opts){await opts.adapter.ensureMigrationTables();let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),byId=new Map(applied.map(r=>[r.id,r])),entries=[];for(let e of journal.entries){let row=byId.get(e.id),reviewed=!1;try{reviewed=JSON.parse(await readFile(path.join(opts.migrationsDir,e.id,`meta.json`),`utf8`)).reviewed===!0}catch{}entries.push({id:e.id,tag:e.tag,hash:e.hash,state:row?`applied`:`pending`,batch:row?.batch??null,appliedAt:row?.appliedAt??null,reviewed})}return entries}async function migrateRollback(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:[],batch:null};let lastBatch=Math.max(...applied.map(r=>r.batch)),targets=applied.filter(r=>r.batch===lastBatch).toSorted((a,b)=>a.appliedAt.localeCompare(b.appliedAt)).toReversed(),reversed=[];for(let row of targets)await applyReverse(row.id,opts),reversed.push(row.id);return{reversed,batch:lastBatch}})}const kickDbAdapter=defineAdapter({name:`kickjs-db`,build:config=>({async beforeStart({container}){let policy=config.migrationsOnBoot??`fail-if-pending`,pending=(await migrateStatus({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir})).filter(s=>s.state===`pending`);if(pending.length>0){if(policy===`fail-if-pending`)throw Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);if(policy===`apply`){let result=await migrateLatest({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir,requireReviewed:config.requireReviewed,driftCheck:config.driftCheck});config.bus&&config.bus.emit(`db:migration-applied`,{applied:result.applied,batch:result.batch})}}config.token&&container.registerFactory(config.token,()=>config.migrationAdapter)},async shutdown(){await config.migrationAdapter.close()}})}),DB_PRIMARY=createToken(`kick/db/primary`),DB_REPLICA=createToken(`kick/db/replica`),DB_CLIENT=DB_PRIMARY;var KickDbEventEmitter=class{emitter=new EventEmitter;on(event,listener){this.emitter.on(event,listener)}off(event,listener){this.emitter.off(event,listener)}emit(event,payload){this.emitter.emit(event,payload)}},CustomColumnBuilder=class extends ColumnBuilder{toDriver;fromDriver;constructor(opts){super(opts.dataType()),this.toDriver=opts.toDriver,this.fromDriver=opts.fromDriver}};function customType(opts){return()=>new CustomColumnBuilder(opts)}var CodecPlugin=class{constructor(encoders,decoders){this.encoders=encoders,this.decoders=decoders}transformQuery(args){if(this.encoders.size===0)return args.node;let node=args.node;return InsertQueryNode.is(node)?this.transformInsert(node):UpdateQueryNode.is(node)?this.transformUpdate(node):node}async transformResult(args){if(this.decoders.size===0)return args.result;let rows=args.result.rows.map(row=>this.decodeRow(row));return{...args.result,rows}}transformInsert(node){let cols=node.columns,values=node.values;if(!cols||!values)return node;let positional=this.positionalEncoders(cols);if(!positional)return node;if(ValuesNode.is(values)){let items=values.values.map(item=>this.encodeValuesItem(item,positional));return items.some((item,i)=>item!==values.values[i])?InsertQueryNode.cloneWith(node,{values:ValuesNode.create(items)}):node}return node}transformUpdate(node){let updates=node.updates;if(!updates||updates.length===0)return node;let changed=!1,next=updates.map(u=>{let col=u.column;if(!ColumnNode.is(col))return u;let encoder=this.encoders.get(col.column.name);if(!encoder)return u;let encoded=this.encodeValueNode(u.value,encoder);return encoded===u.value?u:(changed=!0,ColumnUpdateNode.create(col,encoded))});return changed?{...node,updates:next}:node}positionalEncoders(cols){let out=Array.from({length:cols.length}),any=!1;for(let i=0;i<cols.length;i++){let enc=this.encoders.get(cols[i].column.name)??null;out[i]=enc,enc&&(any=!0)}return any?out:null}encodeValuesItem(item,positional){if(ValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodeValueNode(v,enc):v});return next.some((v,i)=>v!==item.values[i])?ValueListNode.create(next):item}if(PrimitiveValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodePrimitive(v,enc):v});return next.some((v,i)=>v!==item.values[i])?PrimitiveValueListNode.create(next):item}return item}encodeValueNode(node,encoder){if(!ValueNode.is(node))return node;let value=node.value;if(value==null)return node;let encoded=encoder(value);return encoded===value?node:ValueNode.create(encoded)}encodePrimitive(value,encoder){return value==null?value:encoder(value)}decodeRow(row){let mutated=!1,out={};for(let key of Object.keys(row)){let value=row[key],decoder=this.decoders.get(key);decoder&&value!=null?(out[key]=decoder(value),mutated=!0):out[key]=value}return mutated?out:row}};function buildDecoderMap(schema){return collectCodecs(schema,`fromDriver`)}function buildEncoderMap(schema){return collectCodecs(schema,`toDriver`)}function collectCodecs(schema,key){let out=new Map;if(!schema||typeof schema!=`object`)return out;for(let value of Object.values(schema))if(isTableDecl(value)){for(let[colName,col]of Object.entries(value.__columns))if(col instanceof CustomColumnBuilder){let fn=col[key];fn&&out.set(colName,fn)}}return out}function isTableDecl(value){return typeof value==`object`&&!!value&&value.__isTable===!0}var ResultExtensionPlugin=class{byTable;pending=new Map;constructor(extensions){this.byTable=new Map;for(let[tableName,bag]of Object.entries(extensions)){if(!bag)continue;let entries=Object.entries(bag);entries.length!==0&&this.byTable.set(tableName,Object.fromEntries(entries))}}transformQuery(args){let{node,queryId}=args;if(!SelectQueryNode.is(node))return node;let tableName=singleTableTarget(node);if(!tableName)return node;let bag=this.byTable.get(tableName);return bag?(this.pending.set(queryId,tableName),injectNeeds(node,bag)):node}async transformResult(args){let tableName=this.pending.get(args.queryId);if(!tableName)return args.result;this.pending.delete(args.queryId);let bag=this.byTable.get(tableName);if(!bag)return args.result;let computeds=Object.entries(bag);if(computeds.length===0)return args.result;let rows=args.result.rows.map(row=>{if(row==null)return row;let base=row,next={...base};for(let[key,ext]of computeds)try{next[key]=ext.compute(base)}catch{next[key]=void 0}return next});return{...args.result,rows}}};function singleTableTarget(node){let from=node.from;if(!from||from.froms.length!==1)return null;let target=unwrapAlias(from.froms[0]);return TableNode.is(target)?target.table.identifier.name:null}function unwrapAlias(node){return node.kind===`AliasNode`?node.node:node}function injectNeeds(node,bag){let selections=node.selections??[];if(selections.some(isSelectAll))return node;let have=new Set;for(let sel of selections){let inner=sel.selection;ReferenceNode.is(inner)&&ColumnNode.is(inner.column)?have.add(inner.column.column.name):ColumnNode.is(inner)&&have.add(inner.column.name)}let allNeeded=new Set;for(let ext of Object.values(bag))for(let col of Object.keys(ext.needs))allNeeded.add(col);let missing=[...allNeeded].filter(c=>!have.has(c));if(missing.length===0)return node;let additions=missing.map(col=>SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))));return SelectQueryNode.cloneWithSelections(node,additions)}function isSelectAll(node){let inner=node.selection;return!!(SelectAllNode.is(inner)||ReferenceNode.is(inner)&&SelectAllNode.is(inner.column))}function applyExtensions(client,ctx,ext){let baseClient=client;if(hasResultExtensions(ext.result)){let plugin=new ResultExtensionPlugin(ext.result);baseClient=wrap(client.qb.withPlugin(plugin),ctx)}let proxy,modelBag={},model=ext.model??{};for(let tableName of Object.keys(model)){let methods=model[tableName];if(!methods)continue;let bound={};for(let[methodName,fn]of Object.entries(methods))bound[methodName]=(...args)=>fn.call(proxy,...args);modelBag[tableName]=bound}return proxy=new Proxy(baseClient,{get(target,prop){return typeof prop==`string`&&Object.prototype.hasOwnProperty.call(modelBag,prop)?modelBag[prop]:target[prop]}}),proxy}function hasResultExtensions(result){if(!result||typeof result!=`object`)return!1;for(let bag of Object.values(result))if(bag&&typeof bag==`object`&&Object.keys(bag).length>0)return!0;return!1}function wrap(qb,ctx){let client={qb,dialect:ctx.dialect,selectFrom:qb.selectFrom.bind(qb),insertInto:qb.insertInto.bind(qb),updateTable:qb.updateTable.bind(qb),deleteFrom:qb.deleteFrom.bind(qb),on(event,listener){return ctx.events?.on(event,listener),client},off(event,listener){return ctx.events?.off(event,listener),client},transaction:((a,b)=>{let txOpts=typeof a==`function`?{}:a,fn=typeof a==`function`?a:b;return(async()=>{ctx.events?.emit(`transactionStart`,{isolation:txOpts.isolation});try{let result=await qb.transaction().execute(async tx=>{if(txOpts.isolation){let level=txOpts.isolation.toUpperCase();await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx)}return await fn(wrap(tx,ctx))});return ctx.events?.emit(`transactionCommit`,{isolation:txOpts.isolation}),result}catch(err){throw ctx.events?.emit(`transactionRollback`,{isolation:txOpts.isolation,error:err}),err}})()}),$extends(ext){return applyExtensions(client,ctx,ext)},async savepoint(fn){let name=`sp_${++ctx.savepointCounter.value}`;await sql.raw(`SAVEPOINT ${name}`).execute(qb);try{let result=await fn(wrap(qb,ctx));return await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb),result}catch(err){throw await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb),err}},async destroy(){await qb.destroy()}};return client}function createDbClient(opts){let events=opts.events||opts.slowQueryThresholdMs!=null||opts.bus!=null?new KickDbEventEmitter:null,slowThreshold=opts.slowQueryThresholdMs??null,bus=opts.bus??null;events&&bus&&(events.on(`slowQuery`,payload=>{bus.emit(`db:slow-query`,payload)}),events.on(`queryError`,payload=>{bus.emit(`db:query-error`,payload)}));let decoders=buildDecoderMap(opts.schema),encoders=buildEncoderMap(opts.schema),codecPlugin=decoders.size>0||encoders.size>0?new CodecPlugin(encoders,decoders):null;return wrap(new Kysely({dialect:opts.dialect,plugins:codecPlugin?[codecPlugin]:void 0,log:events?event=>{if(event.level===`query`){let durationMs=event.queryDurationMillis,payload={sql:event.query.sql,parameters:event.query.parameters,durationMs};events.emit(`query`,payload),slowThreshold!=null&&durationMs>=slowThreshold&&events.emit(`slowQuery`,{...payload,thresholdMs:slowThreshold})}else event.level===`error`&&events.emit(`queryError`,{sql:event.query.sql,parameters:event.query.parameters,error:event.error})}:void 0}),{events,dialect:detectDialect(opts.dialect),savepointCounter:{value:0}})}function detectDialect(dialect){let name=dialect.constructor?.name??``;return name.includes(`Postgres`)?`postgres`:name.includes(`Mysql`)||name.includes(`MySql`)?`mysql`:`sqlite`}function quoteIdent(name){return name.split(`.`).map(part=>`"`+part.replace(/"/g,`""`)+`"`).join(`.`)}function quoteLiteral(value){return`'`+value.replace(/'/g,`''`)+`'`}function emitPg(changes){return changes.map(emitChange).join(`
101
- `)}function emitChange(change){switch(change.kind){case`createTable`:return emitCreateTable(change.table);case`dropTable`:return`DROP TABLE ${quoteIdent(change.table.name)};`;case`renameTable`:return`ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`;case`addColumn`:return emitAddColumn(change.table,change.column);case`dropColumn`:return`ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`;case`renameColumn`:return`ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`;case`alterColumn`:return emitAlterColumn(change.table,change.before,change.after);case`addIndex`:return emitAddIndex(change.table,change.index);case`dropIndex`:return`DROP INDEX ${quoteIdent(change.index.name)};`;case`addForeignKey`:return emitAddFk(change.table,change.fk);case`dropForeignKey`:return`ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`;case`createEnum`:{let values=change.enum.values.map(v=>quoteLiteral(v)).join(`, `);return`CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`}case`dropEnum`:return`DROP TYPE ${quoteIdent(change.enum.name)};`;case`addEnumValue`:{let before=change.before?` BEFORE ${quoteLiteral(change.before)}`:``;return`ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`}case`removeEnumValue`:return emitRemoveEnumValueAdvisory(change.enum,change.removed)}}function emitRemoveEnumValueAdvisory(name,removed){let safeName=sanitizeForLineComment(quoteIdent(name));return[`-- WARNING: enum ${safeName} dropped value(s): ${removed.map(v=>sanitizeForLineComment(quoteLiteral(v))).join(`, `)}.`,`-- PostgreSQL has no ALTER TYPE ... DROP VALUE. To round-trip this`,`-- removal you must:`,`-- 1. Drop or migrate every column whose type is ${safeName} (or any`,`-- composite that references it).`,`-- 2. DROP TYPE ${safeName};`,`-- 3. CREATE TYPE ${safeName} AS ENUM (...) with the new value list.`,`-- 4. Recreate the columns + restore data, mapping any rows that held`,`-- one of the dropped value(s) to a still-valid replacement first.`,`-- This migration emits no SQL for this change — write the steps above`,`-- by hand if the removal is intentional, or restore the value(s) in`,`-- the schema definition to silence this warning.`].join(`
102
- `)}function sanitizeForLineComment(value){let out=``,prevWasLineBreak=!1;for(let i=0;i<value.length;i++){let code=value.charCodeAt(i);if(code===10||code===13||code===8232||code===8233){prevWasLineBreak||(out+=` `),prevWasLineBreak=!0;continue}if(prevWasLineBreak=!1,code>=0&&code<=8||code===11||code===12||code>=14&&code<=31||code===127){out+=`\\x${code.toString(16).padStart(2,`0`)}`;continue}out+=value[i]}return out}function emitAddColumn(table,c){return`ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`}function emitAlterColumn(table,before,after){let stmts=[],t=quoteIdent(table),c=quoteIdent(after.name),typeChanged=before.type!==after.type,nullChanged=before.nullable!==after.nullable,defaultChanged=before.default!==after.default,losingNotNull=!before.nullable&&after.nullable;typeChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`);let emitDefault=()=>{defaultChanged&&stmts.push(after.default===null?`ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;`:`ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`)},emitNullable=()=>{nullChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable?`DROP NOT NULL`:`SET NOT NULL`};`)};return losingNotNull?(emitDefault(),emitNullable()):(emitNullable(),emitDefault()),stmts.join(`
103
- `)}function emitAddIndex(table,i){let cols=i.columns.map(quoteIdent).join(`, `);return`CREATE${i.unique?` UNIQUE`:``} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`}const FK_ACTIONS={cascade:`CASCADE`,restrict:`RESTRICT`,set_null:`SET NULL`,set_default:`SET DEFAULT`,no_action:`NO ACTION`};function emitAddFk(table,fk){let cols=fk.columns.map(quoteIdent).join(`, `),refCols=fk.refColumns.map(quoteIdent).join(`, `);return`ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`}function emitCreateTable(t){let cols=Object.values(t.columns).map(emitColumnDecl),pk=Object.values(t.columns).filter(c=>c.primaryKey).map(c=>quoteIdent(c.name)),lines=[...cols];return pk.length>0&&lines.push(`PRIMARY KEY (${pk.join(`, `)})`),`CREATE TABLE ${quoteIdent(t.name)} (\n ${lines.join(`,
104
- `)}\n);`}function emitColumnDecl(c){let s=`${quoteIdent(c.name)} ${c.type}`;return c.nullable||(s+=` NOT NULL`),c.default!==null&&(s+=` DEFAULT ${formatDefault(c.default)}`),s}function formatDefault(value){return/^[A-Z_]+$/.test(value)||/^[a-z_][a-z0-9_]*\s*\([^)]*\)$/i.test(value)||/^-?\d+(\.\d+)?$/.test(value)||value===`true`||value===`false`?value:quoteLiteral(value)}async function resolveDbConfig(opts){let mod=await import(pathToFileURL(path.resolve(opts.configPath)).href),db=(mod.default??mod)?.db??{};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}}async function generate(opts){let migrationsAbs=path.resolve(opts.cwd,opts.config.migrationsDir),{snapshot:prev,id:previousId}=await readLatestSnapshotEntry(migrationsAbs);if(opts.empty)return await writeMigration({opts,migrationsAbs,previousId,target:prev,upBody:``,downBody:``,changeCount:0,draft:!1,empty:!0});let target=extractSnapshot(await import(pathToFileURL(path.resolve(opts.cwd,opts.config.schemaPath)).href),opts.config.dialect),changes=diff(prev,target);return changes.length===0?{status:`no-changes`,changeCount:0}:await writeMigration({opts,migrationsAbs,previousId,target,upBody:emitPg(changes),downBody:emitPg(invertChanges(changes)),changeCount:changes.length,draft:hasAmbiguousReverse(changes),empty:!1})}async function writeMigration(p){let id=formatId(p.opts.now?.()??new Date,p.opts.name),dir=path.join(p.migrationsAbs,id);await mkdir(dir,{recursive:!0});let upSql=`-- REVIEWED: false
104
+ ORDER BY tc.constraint_name, kcu.ordinal_position`,[schema,table]),byName=new Map;for(let r of rows.rows){let fk=byName.get(r.constraint_name);fk||(fk={name:r.constraint_name,columns:[],refTable:r.ref_table,refColumns:[],onDelete:mapFkAction(r.delete_rule),onUpdate:mapFkAction(r.update_rule)},byName.set(r.constraint_name,fk)),fk.columns.push(r.column_name),fk.refColumns.push(r.ref_column)}return[...byName.values()].toSorted((a,b)=>a.name.localeCompare(b.name))}function mapFkAction(raw){switch(raw.toUpperCase()){case`CASCADE`:return`cascade`;case`RESTRICT`:return`restrict`;case`SET NULL`:return`set_null`;case`SET DEFAULT`:return`set_default`;default:return`no_action`}}async function checkDrift(liveSnapshot,expectedSnapshot,behavior,log=console){if(behavior===`ignore`)return;let changes=diff(expectedSnapshot,liveSnapshot);if(changes.length===0)return;let summary=summarize(changes),message=`Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`;if(behavior===`warn`){log.warn(message);return}throw new MigrationDriftError(message,summary)}function summarize(changes){let added=[],removed=[],changed=[];for(let c of changes)switch(c.kind){case`createTable`:added.push(c.table.name);break;case`dropTable`:removed.push(c.table.name);break;case`addColumn`:added.push(`${c.table}.${c.column.name}`);break;case`dropColumn`:removed.push(`${c.table}.${c.column.name}`);break;case`alterColumn`:changed.push(`${c.table}.${c.column}`);break;case`renameColumn`:changed.push(`${c.table}.${c.from}→${c.to}`);break;case`renameTable`:changed.push(`${c.from}→${c.to}`);break;case`addIndex`:added.push(`${c.table}#${c.index.name}`);break;case`dropIndex`:removed.push(`${c.table}#${c.index.name}`);break;case`addForeignKey`:added.push(`${c.table}!${c.fk.name}`);break;case`dropForeignKey`:removed.push(`${c.table}!${c.fk.name}`);break}return{added,removed,changed}}async function withLock(opts,fn){let owner=opts.owner??`${process.pid}@${new Date().toISOString()}`;if(!await opts.adapter.acquireLock(owner))throw new MigrationLockError(`Another process holds the migration lock`);try{return await fn()}finally{await opts.adapter.releaseLock()}}async function verifyPending(pending,migrationsDir,requireReviewed){for(let entry of pending){let dir=path.join(migrationsDir,entry.id),actualHash=await computeMigrationHash(dir);if(actualHash!==entry.hash)throw new MigrationHashError(entry.id,entry.hash,actualHash);if(requireReviewed&&JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).reviewed!==!0)throw new UnreviewedMigrationError(entry.id)}}async function applyEntry(entry,batch,opts){let dir=path.join(opts.migrationsDir,entry.id),upSql=await readFile(path.join(dir,`up.sql`),`utf8`),useTx=JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).transaction!==!1;enforceEnumDropGate(entry.id,upSql,opts.confirmEnumDrop??!1),useTx?await opts.adapter.applySqlInTx(upSql):await opts.adapter.applySqlNoTx(upSql),await opts.adapter.recordApplied({id:entry.id,name:entry.tag,hash:entry.hash,batch,direction:`up`})}async function runForward(opts,pending){if(pending.length===0)return{applied:[],batch:null};let requireReviewed=opts.requireReviewed??process.env.NODE_ENV!==`development`;await verifyPending(pending,opts.migrationsDir,requireReviewed);let applied=await opts.adapter.listApplied(),nextBatch=(applied.length===0?0:Math.max(...applied.map(r=>r.batch)))+1,ids=[];for(let entry of pending)await applyEntry(entry,nextBatch,opts),ids.push(entry.id);return{applied:ids,batch:nextBatch}}async function listPending(opts){let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),appliedIds=new Set(applied.map(r=>r.id));return journal.entries.filter(e=>!appliedIds.has(e.id)).map(e=>({id:e.id,tag:e.tag,hash:e.hash}))}async function maybeCheckDrift(opts){let behavior=opts.driftCheck??`error`;if(behavior===`ignore`)return;let applied=await opts.adapter.listApplied();if(applied.length===0)return;let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1],expected;try{expected=JSON.parse(await readFile(path.join(opts.migrationsDir,last.id,`snapshot.json`),`utf8`))}catch{return}await checkDrift(await opts.adapter.introspect(),expected,behavior,opts.log)}async function migrateLatest(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,await listPending(opts))))}async function migrateUp(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,(await listPending(opts)).slice(0,1))))}async function applyReverse(id,opts){let dir=path.join(opts.migrationsDir,id),downSql=await readFile(path.join(dir,`down.sql`),`utf8`),meta=JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`));if((opts.requireReviewed??process.env.NODE_ENV!==`development`)&&meta.reviewed!==!0)throw new UnreviewedMigrationError(id);meta.transaction===!1?await opts.adapter.applySqlNoTx(downSql):await opts.adapter.applySqlInTx(downSql),await opts.adapter.removeApplied(id)}async function migrateDown(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:null};let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1];return await applyReverse(last.id,opts),{reversed:last.id}})}async function migrateStatus(opts){await opts.adapter.ensureMigrationTables();let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),byId=new Map(applied.map(r=>[r.id,r])),entries=[];for(let e of journal.entries){let row=byId.get(e.id),reviewed=!1;try{reviewed=JSON.parse(await readFile(path.join(opts.migrationsDir,e.id,`meta.json`),`utf8`)).reviewed===!0}catch{}entries.push({id:e.id,tag:e.tag,hash:e.hash,state:row?`applied`:`pending`,batch:row?.batch??null,appliedAt:row?.appliedAt??null,reviewed})}return entries}async function migrateRollback(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:[],batch:null};let lastBatch=Math.max(...applied.map(r=>r.batch)),targets=applied.filter(r=>r.batch===lastBatch).toSorted((a,b)=>a.appliedAt.localeCompare(b.appliedAt)).toReversed(),reversed=[];for(let row of targets)await applyReverse(row.id,opts),reversed.push(row.id);return{reversed,batch:lastBatch}})}const kickDbAdapter=defineAdapter({name:`kickjs-db`,build:config=>({async beforeStart({container}){let policy=config.migrationsOnBoot??`fail-if-pending`,pending=(await migrateStatus({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir})).filter(s=>s.state===`pending`);if(pending.length>0){if(policy===`fail-if-pending`)throw Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);if(policy===`apply`){let result=await migrateLatest({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir,requireReviewed:config.requireReviewed,driftCheck:config.driftCheck});config.bus&&config.bus.emit(`db:migration-applied`,{applied:result.applied,batch:result.batch})}}config.token&&container.registerFactory(config.token,()=>config.migrationAdapter)},async shutdown(){await config.migrationAdapter.close()}})}),DB_PRIMARY=createToken(`kick/db/primary`),DB_REPLICA=createToken(`kick/db/replica`),DB_CLIENT=DB_PRIMARY;var KickDbEventEmitter=class{emitter=new EventEmitter;on(event,listener){this.emitter.on(event,listener)}off(event,listener){this.emitter.off(event,listener)}emit(event,payload){this.emitter.emit(event,payload)}},CustomColumnBuilder=class extends ColumnBuilder{toDriver;fromDriver;constructor(opts){super(opts.dataType()),this.toDriver=opts.toDriver,this.fromDriver=opts.fromDriver}};function customType(opts){return()=>new CustomColumnBuilder(opts)}var CodecPlugin=class{constructor(encoders,decoders){this.encoders=encoders,this.decoders=decoders}transformQuery(args){if(this.encoders.size===0)return args.node;let node=args.node;return InsertQueryNode.is(node)?this.transformInsert(node):UpdateQueryNode.is(node)?this.transformUpdate(node):node}async transformResult(args){if(this.decoders.size===0)return args.result;let rows=args.result.rows.map(row=>this.decodeRow(row));return{...args.result,rows}}transformInsert(node){let cols=node.columns,values=node.values;if(!cols||!values)return node;let positional=this.positionalEncoders(cols);if(!positional)return node;if(ValuesNode.is(values)){let items=values.values.map(item=>this.encodeValuesItem(item,positional));return items.some((item,i)=>item!==values.values[i])?InsertQueryNode.cloneWith(node,{values:ValuesNode.create(items)}):node}return node}transformUpdate(node){let updates=node.updates;if(!updates||updates.length===0)return node;let changed=!1,next=updates.map(u=>{let col=u.column;if(!ColumnNode.is(col))return u;let encoder=this.encoders.get(col.column.name);if(!encoder)return u;let encoded=this.encodeValueNode(u.value,encoder);return encoded===u.value?u:(changed=!0,ColumnUpdateNode.create(col,encoded))});return changed?{...node,updates:next}:node}positionalEncoders(cols){let out=Array.from({length:cols.length}),any=!1;for(let i=0;i<cols.length;i++){let enc=this.encoders.get(cols[i].column.name)??null;out[i]=enc,enc&&(any=!0)}return any?out:null}encodeValuesItem(item,positional){if(ValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodeValueNode(v,enc):v});return next.some((v,i)=>v!==item.values[i])?ValueListNode.create(next):item}if(PrimitiveValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodePrimitive(v,enc):v});return next.some((v,i)=>v!==item.values[i])?PrimitiveValueListNode.create(next):item}return item}encodeValueNode(node,encoder){if(!ValueNode.is(node))return node;let value=node.value;if(value==null)return node;let encoded=encoder(value);return encoded===value?node:ValueNode.create(encoded)}encodePrimitive(value,encoder){return value==null?value:encoder(value)}decodeRow(row){let mutated=!1,out={};for(let key of Object.keys(row)){let value=row[key],decoder=this.decoders.get(key);decoder&&value!=null?(out[key]=decoder(value),mutated=!0):out[key]=value}return mutated?out:row}};function buildDecoderMap(schema){return collectCodecs(schema,`fromDriver`)}function buildEncoderMap(schema){return collectCodecs(schema,`toDriver`)}function collectCodecs(schema,key){let out=new Map;if(!schema||typeof schema!=`object`)return out;for(let value of Object.values(schema))if(isTableDecl(value)){for(let[colName,col]of Object.entries(value.__columns))if(col instanceof CustomColumnBuilder){let fn=col[key];fn&&out.set(colName,fn)}}return out}function isTableDecl(value){return typeof value==`object`&&!!value&&value.__isTable===!0}var ResultExtensionPlugin=class{byTable;pending=new Map;constructor(extensions){this.byTable=new Map;for(let[tableName,bag]of Object.entries(extensions)){if(!bag)continue;let entries=Object.entries(bag);entries.length!==0&&this.byTable.set(tableName,Object.fromEntries(entries))}}transformQuery(args){let{node,queryId}=args;if(!SelectQueryNode.is(node))return node;let tableName=singleTableTarget(node);if(!tableName)return node;let bag=this.byTable.get(tableName);return bag?(this.pending.set(queryId,tableName),injectNeeds(node,bag)):node}async transformResult(args){let tableName=this.pending.get(args.queryId);if(!tableName)return args.result;this.pending.delete(args.queryId);let bag=this.byTable.get(tableName);if(!bag)return args.result;let computeds=Object.entries(bag);if(computeds.length===0)return args.result;let rows=args.result.rows.map(row=>{if(row==null)return row;let base=row,next={...base};for(let[key,ext]of computeds)try{next[key]=ext.compute(base)}catch{next[key]=void 0}return next});return{...args.result,rows}}};function singleTableTarget(node){let from=node.from;if(!from||from.froms.length!==1)return null;let target=unwrapAlias(from.froms[0]);return TableNode.is(target)?target.table.identifier.name:null}function unwrapAlias(node){return node.kind===`AliasNode`?node.node:node}function injectNeeds(node,bag){let selections=node.selections??[];if(selections.some(isSelectAll))return node;let have=new Set;for(let sel of selections){let inner=sel.selection;ReferenceNode.is(inner)&&ColumnNode.is(inner.column)?have.add(inner.column.column.name):ColumnNode.is(inner)&&have.add(inner.column.name)}let allNeeded=new Set;for(let ext of Object.values(bag))for(let col of Object.keys(ext.needs))allNeeded.add(col);let missing=[...allNeeded].filter(c=>!have.has(c));if(missing.length===0)return node;let additions=missing.map(col=>SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))));return SelectQueryNode.cloneWithSelections(node,additions)}function isSelectAll(node){let inner=node.selection;return!!(SelectAllNode.is(inner)||ReferenceNode.is(inner)&&SelectAllNode.is(inner.column))}function applyExtensions(client,ctx,ext){let baseClient=client;if(hasResultExtensions(ext.result)){let plugin=new ResultExtensionPlugin(ext.result);baseClient=wrap(client.qb.withPlugin(plugin),ctx)}let proxy,modelBag={},model=ext.model??{};for(let tableName of Object.keys(model)){let methods=model[tableName];if(!methods)continue;let bound={};for(let[methodName,fn]of Object.entries(methods))bound[methodName]=(...args)=>fn.call(proxy,...args);modelBag[tableName]=bound}return proxy=new Proxy(baseClient,{get(target,prop){return typeof prop==`string`&&Object.prototype.hasOwnProperty.call(modelBag,prop)?modelBag[prop]:target[prop]}}),proxy}function hasResultExtensions(result){if(!result||typeof result!=`object`)return!1;for(let bag of Object.values(result))if(bag&&typeof bag==`object`&&Object.keys(bag).length>0)return!0;return!1}function buildQueryNamespace(qb,relations,compile){return new Proxy({},{get(_target,prop){if(typeof prop==`string`)return makeTableNamespace(qb,prop,relations,compile)}})}function makeTableNamespace(qb,table,relations,compile){return{async findMany(options){return await execute(qb,compile(qb,table,options??{},relations,`many`))},async findFirst(options){return(await execute(qb,compile(qb,table,options??{},relations,`first`)))[0]??null},async findUnique(options){return(await execute(qb,compile(qb,table,options,relations,`unique`)))[0]??null}}}async function execute(qb,compiled){return(await qb.executeQuery(compiled)).rows}function wrap(qb,ctx){let client={qb,dialect:ctx.dialect,query:buildQueryNamespace(qb,ctx.query.relations,ctx.query.compile),selectFrom:qb.selectFrom.bind(qb),insertInto:qb.insertInto.bind(qb),updateTable:qb.updateTable.bind(qb),deleteFrom:qb.deleteFrom.bind(qb),on(event,listener){return ctx.events?.on(event,listener),client},off(event,listener){return ctx.events?.off(event,listener),client},transaction:((a,b)=>{let txOpts=typeof a==`function`?{}:a,fn=typeof a==`function`?a:b;return(async()=>{ctx.events?.emit(`transactionStart`,{isolation:txOpts.isolation});try{let result=await qb.transaction().execute(async tx=>{if(txOpts.isolation){let level=txOpts.isolation.toUpperCase();await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx)}return await fn(wrap(tx,ctx))});return ctx.events?.emit(`transactionCommit`,{isolation:txOpts.isolation}),result}catch(err){throw ctx.events?.emit(`transactionRollback`,{isolation:txOpts.isolation,error:err}),err}})()}),$extends(ext){return applyExtensions(client,ctx,ext)},async savepoint(fn){let name=`sp_${++ctx.savepointCounter.value}`;await sql.raw(`SAVEPOINT ${name}`).execute(qb);try{let result=await fn(wrap(qb,ctx));return await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb),result}catch(err){throw await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb),err}},async destroy(){await qb.destroy()}};return client}function makeTableRefProxy(eb,alias){return new Proxy({},{get(_target,prop){if(typeof prop==`string`)return eb.ref(`${alias}.${prop}`)}})}function compilePg(db,table,options,relations,mode=`many`){let maxDepth=options.maxDepth??5,outerAlias=makeAlias(table,0),query=db.selectFrom(`${table} as ${outerAlias}`).selectAll();return options.with&&(query=applyWithSelects(query,table,outerAlias,options.with,relations,maxDepth,[outerAlias])),query=applyWhereOrderLimit(query,outerAlias,options,mode),query.compile()}function makeAlias(name,depth){return`${name}_${depth}`}function applyWithSelects(query,source,sourceAlias,withClause,relations,maxDepth,trace){if(trace.length>maxDepth)throw new RelationalQueryDepthError(maxDepth,trace);return query.select(eb=>{let out=[];for(let[key,value]of Object.entries(withClause)){let rel=relations[source]?.[key];if(!rel)throw new RelationalQueryUnknownRelationError(source,key);let subOptions=value===!0?{}:value,inner=buildInnerSelect(eb,sourceAlias,rel,makeAlias(rel.target,trace.length),subOptions,relations,maxDepth,trace);rel.kind===`many`?out.push(jsonArrayFrom(inner).as(key)):out.push(jsonObjectFrom(inner).as(key))}return out})}function buildInnerSelect(eb,sourceAlias,rel,innerAlias,subOptions,relations,maxDepth,trace){let sub=eb.selectFrom(`${rel.target} as ${innerAlias}`).selectAll();for(let i=0;i<rel.sourceColumns.length;i++)sub=sub.whereRef(`${innerAlias}.${rel.targetColumns[i]}`,`=`,`${sourceAlias}.${rel.sourceColumns[i]}`);let nextTrace=[...trace,innerAlias];return subOptions.with&&(sub=applyWithSelects(sub,rel.target,innerAlias,subOptions.with,relations,maxDepth,nextTrace)),sub=applyWhereOrderLimit(sub,innerAlias,subOptions,`many`),rel.kind===`one`&&(sub=sub.limit(1)),sub}function applyWhereOrderLimit(query,alias,options,mode){let q=query;return options.where&&(q=q.where(eb=>options.where(makeTableRefProxy(eb,alias),eb))),options.orderBy&&(q=q.orderBy(eb=>options.orderBy(makeTableRefProxy(eb,alias),eb))),typeof options.limit==`number`?q=q.limit(options.limit):(mode===`first`||mode===`unique`)&&(q=q.limit(1)),typeof options.offset==`number`&&(q=q.offset(options.offset)),q}const compileNotSupported=dialect=>()=>{throw new RelationalQueryNotSupportedError(dialect)};function pickCompiler(dialect){return dialect===`postgres`?compilePg:compileNotSupported(dialect)}function createDbClient(opts){let events=opts.events||opts.slowQueryThresholdMs!=null||opts.bus!=null?new KickDbEventEmitter:null,slowThreshold=opts.slowQueryThresholdMs??null,bus=opts.bus??null;events&&bus&&(events.on(`slowQuery`,payload=>{bus.emit(`db:slow-query`,payload)}),events.on(`queryError`,payload=>{bus.emit(`db:query-error`,payload)}));let decoders=buildDecoderMap(opts.schema),encoders=buildEncoderMap(opts.schema),codecPlugin=decoders.size>0||encoders.size>0?new CodecPlugin(encoders,decoders):null,kysely=new Kysely({dialect:opts.dialect,plugins:codecPlugin?[codecPlugin]:void 0,log:events?event=>{if(event.level===`query`){let durationMs=event.queryDurationMillis,payload={sql:event.query.sql,parameters:event.query.parameters,durationMs};events.emit(`query`,payload),slowThreshold!=null&&durationMs>=slowThreshold&&events.emit(`slowQuery`,{...payload,thresholdMs:slowThreshold})}else event.level===`error`&&events.emit(`queryError`,{sql:event.query.sql,parameters:event.query.parameters,error:event.error})}:void 0}),dialectTag=detectDialect(opts.dialect),tables=extractSnapshot(opts.schema,dialectTag).tables;return wrap(kysely,{events,dialect:dialectTag,savepointCounter:{value:0},query:{relations:extractRelations(opts.schema,tables)??{},compile:pickCompiler(dialectTag)}})}function detectDialect(dialect){let tag=`${dialect.constructor?.name??``} ${dialect.createAdapter().constructor?.name??``}`;return/Postgres/i.test(tag)?`postgres`:/Mysql/i.test(tag)?`mysql`:`sqlite`}async function resolveDbConfig(opts){let mod=await import(pathToFileURL(path.resolve(opts.configPath)).href),db=(mod.default??mod)?.db??{};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}}async function generate(opts){let migrationsAbs=path.resolve(opts.cwd,opts.config.migrationsDir),{snapshot:prev,id:previousId}=await readLatestSnapshotEntry(migrationsAbs);if(opts.empty)return await writeMigration({opts,migrationsAbs,previousId,target:prev,upBody:``,downBody:``,changeCount:0,draft:!1,empty:!0});let target=extractSnapshot(await import(pathToFileURL(path.resolve(opts.cwd,opts.config.schemaPath)).href),opts.config.dialect),changes=diff(prev,target);return changes.length===0?{status:`no-changes`,changeCount:0}:await writeMigration({opts,migrationsAbs,previousId,target,upBody:emitPg(changes),downBody:emitPg(invertChanges(changes)),changeCount:changes.length,draft:hasAmbiguousReverse(changes),empty:!1})}async function writeMigration(p){let id=formatId(p.opts.now?.()??new Date,p.opts.name),dir=path.join(p.migrationsAbs,id);await mkdir(dir,{recursive:!0});let upSql=`-- REVIEWED: false
105
105
  `+(p.empty?`-- Empty migration — author SQL below (data migration, seed, etc).
106
106
  `:``)+p.upBody+(p.upBody?`
107
107
  `:``);await writeFile(path.join(dir,`up.sql`),upSql,`utf8`);let downDraft=p.draft?`-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.
@@ -110,5 +110,5 @@ import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Cx
110
110
  `+downDraft+downHint+p.downBody+(p.downBody?`
111
111
  `:``);await writeFile(path.join(dir,`down.sql`),downSql,`utf8`),await writeFile(path.join(dir,`snapshot.json`),JSON.stringify(p.target,null,2)+`
112
112
  `,`utf8`),await writeFile(path.join(dir,`meta.json`),JSON.stringify({id,name:p.opts.name,createdAt:(p.opts.now?.()??new Date).toISOString(),reviewed:!1,dialect:p.opts.config.dialect,previousId:p.previousId,downIsDraft:p.draft,empty:p.empty},null,2)+`
113
- `,`utf8`);let hash=await computeMigrationHash(dir);return await appendJournalEntry(p.migrationsAbs,p.opts.config.dialect,{id,tag:p.opts.name,hash,createdAt:(p.opts.now?.()??new Date).toISOString()}),{status:`created`,migrationDir:dir,changeCount:p.changeCount,empty:p.empty}}async function readLatestSnapshotEntry(migrationsDir){let empty={version:1,dialect:`postgres`,tables:{}};if(!existsSync(migrationsDir))return{snapshot:empty,id:null};let dirs=(await readdir(migrationsDir)).filter(e=>/^\d{8}_\d{6}_/.test(e)).toSorted();if(dirs.length===0)return{snapshot:empty,id:null};let latest=dirs[dirs.length-1],file=path.join(migrationsDir,latest,`snapshot.json`);return{snapshot:JSON.parse(await readFile(file,`utf8`)),id:latest}}function formatId(date,name){let pad=n=>n.toString().padStart(2,`0`);return`${date.getUTCFullYear().toString()+pad(date.getUTCMonth()+1)+pad(date.getUTCDate())+`_`+pad(date.getUTCHours())+pad(date.getUTCMinutes())+pad(date.getUTCSeconds())}_${name.replace(/[^a-z0-9]+/gi,`_`).toLowerCase()}`}function brandGenerated(col){return col}function brandNotNull(col){return col}function formatNumeric(base,precision,scale){return precision===void 0?base:scale===void 0?`${base}(${precision})`:`${base}(${precision}, ${scale})`}function serial(){return brandNotNull(brandGenerated(new ColumnBuilder(`serial`,{nullable:!1})))}function bigSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`bigserial`,{nullable:!1})))}function smallSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`smallserial`,{nullable:!1})))}function integer(){return new ColumnBuilder(`integer`)}function bigint(){return new ColumnBuilder(`bigint`)}function smallint(){return new ColumnBuilder(`smallint`)}function decimal(precision,scale){return new ColumnBuilder(formatNumeric(`decimal`,precision,scale))}function numeric(precision,scale){return new ColumnBuilder(formatNumeric(`numeric`,precision,scale))}function real(){return new ColumnBuilder(`real`)}function doublePrecision(){return new ColumnBuilder(`double precision`)}function varchar(length=255){return new ColumnBuilder(`varchar(${length})`)}function char(length=1){return new ColumnBuilder(`char(${length})`)}function text(){return new ColumnBuilder(`text`)}function boolean(){return new ColumnBuilder(`boolean`)}var TimestampBuilder=class extends ColumnBuilder{constructor(typeName=`timestamp`){super(typeName)}defaultNow(){return this.state.default=`CURRENT_TIMESTAMP`,brandGenerated(this)}};function timestamp(){return new TimestampBuilder(`timestamp`)}function timestamptz(){return new TimestampBuilder(`timestamptz`)}function date(){return new ColumnBuilder(`date`)}function time(){return new ColumnBuilder(`time`)}function interval(){return new ColumnBuilder(`interval`)}var UuidBuilder=class extends ColumnBuilder{constructor(){super(`uuid`)}defaultRandom(){return this.state.default=`gen_random_uuid()`,brandGenerated(this)}};function uuid(){return new UuidBuilder}function json(){return new ColumnBuilder(`json`)}function jsonb(){return new ColumnBuilder(`jsonb`)}function bytea(){return new ColumnBuilder(`bytea`)}function table(name,columns,constraints){let decl={__isTable:!0,__name:name,__columns:columns,__indexes:[]},refs={};for(let[key,builder]of Object.entries(columns))refs[key]={__tableName:name,__name:key,__builder:builder,__state:()=>builder.__state()};if(constraints){let declared=constraints(refs);decl.__indexes=Object.values(declared)}return Object.assign(decl,refs)}function index(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!1}}}}function unique(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!0}}}}function relations(source,builder){return{__isRelations:!0,__sourceTable:source.__name,__relations:builder({one:(target,opts)=>({kind:`one`,target,fields:opts.fields,references:opts.references}),many:target=>({kind:`many`,target})})}}export{ColumnBuilder,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_GENERATED,KICK_LOCK_TABLE,KICK_MIGRATIONS_TABLE,KICK_NOT_NULL,KickDbError,MemoryMigrationAdapter,MigrationDriftError,MigrationError,MigrationHashError,MigrationLockError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,diff,doublePrecision,emitPg,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectPg,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,readJournal,real,relations,renderSchemaSource,resolveDbConfig,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
113
+ `,`utf8`);let hash=await computeMigrationHash(dir);return await appendJournalEntry(p.migrationsAbs,p.opts.config.dialect,{id,tag:p.opts.name,hash,createdAt:(p.opts.now?.()??new Date).toISOString()}),{status:`created`,migrationDir:dir,changeCount:p.changeCount,empty:p.empty}}async function readLatestSnapshotEntry(migrationsDir){let empty={version:1,dialect:`postgres`,tables:{}};if(!existsSync(migrationsDir))return{snapshot:empty,id:null};let dirs=(await readdir(migrationsDir)).filter(e=>/^\d{8}_\d{6}_/.test(e)).toSorted();if(dirs.length===0)return{snapshot:empty,id:null};let latest=dirs[dirs.length-1],file=path.join(migrationsDir,latest,`snapshot.json`);return{snapshot:JSON.parse(await readFile(file,`utf8`)),id:latest}}function formatId(date,name){let pad=n=>n.toString().padStart(2,`0`);return`${date.getUTCFullYear().toString()+pad(date.getUTCMonth()+1)+pad(date.getUTCDate())+`_`+pad(date.getUTCHours())+pad(date.getUTCMinutes())+pad(date.getUTCSeconds())}_${name.replace(/[^a-z0-9]+/gi,`_`).toLowerCase()}`}function brandGenerated(col){return col}function brandNotNull(col){return col}function formatNumeric(base,precision,scale){return precision===void 0?base:scale===void 0?`${base}(${precision})`:`${base}(${precision}, ${scale})`}function serial(){return brandNotNull(brandGenerated(new ColumnBuilder(`serial`,{nullable:!1})))}function bigSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`bigserial`,{nullable:!1})))}function smallSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`smallserial`,{nullable:!1})))}function integer(){return new ColumnBuilder(`integer`)}function bigint(){return new ColumnBuilder(`bigint`)}function smallint(){return new ColumnBuilder(`smallint`)}function decimal(precision,scale){return new ColumnBuilder(formatNumeric(`decimal`,precision,scale))}function numeric(precision,scale){return new ColumnBuilder(formatNumeric(`numeric`,precision,scale))}function real(){return new ColumnBuilder(`real`)}function doublePrecision(){return new ColumnBuilder(`double precision`)}function varchar(length=255){return new ColumnBuilder(`varchar(${length})`)}function char(length=1){return new ColumnBuilder(`char(${length})`)}function text(){return new ColumnBuilder(`text`)}function boolean(){return new ColumnBuilder(`boolean`)}var TimestampBuilder=class extends ColumnBuilder{constructor(typeName=`timestamp`){super(typeName)}defaultNow(){return this.state.default=`CURRENT_TIMESTAMP`,brandGenerated(this)}};function timestamp(){return new TimestampBuilder(`timestamp`)}function timestamptz(){return new TimestampBuilder(`timestamptz`)}function date(){return new ColumnBuilder(`date`)}function time(){return new ColumnBuilder(`time`)}function interval(){return new ColumnBuilder(`interval`)}var UuidBuilder=class extends ColumnBuilder{constructor(){super(`uuid`)}defaultRandom(){return this.state.default=`gen_random_uuid()`,brandGenerated(this)}};function uuid(){return new UuidBuilder}function json(){return new ColumnBuilder(`json`)}function jsonb(){return new ColumnBuilder(`jsonb`)}function bytea(){return new ColumnBuilder(`bytea`)}function table(name,columns,constraints){let decl={__isTable:!0,__name:name,__columns:columns,__indexes:[]},refs={};for(let[key,builder]of Object.entries(columns))refs[key]={__tableName:name,__name:key,__builder:builder,__state:()=>builder.__state()};if(constraints){let declared=constraints(refs);decl.__indexes=Object.values(declared)}return Object.assign(decl,refs)}function index(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!1}}}}function unique(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!0}}}}function relations(source,builder){return{__isRelations:!0,__sourceTable:source.__name,__relations:builder({one:(target,opts)=>({kind:`one`,target,fields:opts.fields,references:opts.references}),many:target=>({kind:`many`,target})})}}export{ColumnBuilder,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,RelationalQueryDepthError,RelationalQueryMissingInverseError,RelationalQueryNotSupportedError,RelationalQueryUnknownRelationError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,diff,doublePrecision,emitPg,enforceEnumDropGate,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectPg,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,readJournal,real,relations,renderSchemaSource,resolveDbConfig,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
114
114
  //# sourceMappingURL=index.mjs.map