@forinda/kickjs-db 5.3.0 → 5.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/devtools-events.d.mts +1 -1
- package/dist/devtools-events.mjs +1 -1
- package/dist/index.d.mts +37 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +2 -2
- package/dist/{types-CnjiG9ij.mjs → types-Ddl8seq-.mjs} +2 -2
- package/dist/{types-CnjiG9ij.mjs.map → types-Ddl8seq-.mjs.map} +1 -1
- package/dist/{types-7Ko9gPCO.d.mts → types-fdccN5bW.d.mts} +7 -1
- package/dist/types-fdccN5bW.d.mts.map +1 -0
- package/dist/{types-BBdfnVt3.d.mts → types-s-I0Eb5S.d.mts} +7 -3
- package/dist/types-s-I0Eb5S.d.mts.map +1 -0
- package/package.json +7 -2
- package/dist/types-7Ko9gPCO.d.mts.map +0 -1
- package/dist/types-BBdfnVt3.d.mts.map +0 -1
package/dist/devtools-events.mjs
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
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-
|
|
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-
|
|
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-s-I0Eb5S.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-fdccN5bW.mjs";
|
|
4
4
|
import * as _$_forinda_kickjs0 from "@forinda/kickjs";
|
|
5
5
|
import { InjectionToken } from "@forinda/kickjs";
|
|
6
6
|
import { Generated } from "kysely";
|
|
@@ -640,10 +640,24 @@ interface RelationOne<TTarget extends TableDecl<string, Record<string, ColumnBui
|
|
|
640
640
|
target: TTarget;
|
|
641
641
|
fields: ColumnRef[];
|
|
642
642
|
references: ColumnRef[];
|
|
643
|
+
/**
|
|
644
|
+
* Disambiguates this relation from sibling `one` relations on the
|
|
645
|
+
* same source table that point at the same target. Pair with the
|
|
646
|
+
* matching `relationName` on the inverse `many` side. See
|
|
647
|
+
* docs/db/spec-relation-name.md.
|
|
648
|
+
*/
|
|
649
|
+
relationName?: string;
|
|
643
650
|
}
|
|
644
651
|
interface RelationMany<TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<string, Record<string, ColumnBuilder>>> {
|
|
645
652
|
kind: 'many';
|
|
646
653
|
target: TTarget;
|
|
654
|
+
/**
|
|
655
|
+
* Pairs with the matching `relationName` on the inverse `one`
|
|
656
|
+
* declaration. Required when the source table has multiple FKs
|
|
657
|
+
* to the same target; resolver throws
|
|
658
|
+
* `RelationalQueryMissingInverseError` otherwise.
|
|
659
|
+
*/
|
|
660
|
+
relationName?: string;
|
|
647
661
|
}
|
|
648
662
|
type Relation = RelationOne | RelationMany;
|
|
649
663
|
/**
|
|
@@ -661,8 +675,11 @@ interface Helpers {
|
|
|
661
675
|
one: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T, opts: {
|
|
662
676
|
fields: ColumnRef[];
|
|
663
677
|
references: ColumnRef[];
|
|
678
|
+
relationName?: string;
|
|
664
679
|
}) => RelationOne<T>;
|
|
665
|
-
many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T
|
|
680
|
+
many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T, opts?: {
|
|
681
|
+
relationName?: string;
|
|
682
|
+
}) => RelationMany<T>;
|
|
666
683
|
}
|
|
667
684
|
/**
|
|
668
685
|
* Declare a typed relation set for `source`. The return type
|
|
@@ -809,6 +826,22 @@ declare class RelationalQueryNotSupportedError extends KickDbError {
|
|
|
809
826
|
readonly dialect: string;
|
|
810
827
|
constructor(dialect: string);
|
|
811
828
|
}
|
|
829
|
+
/**
|
|
830
|
+
* Thrown at extract time when more than one inverse `one` declared
|
|
831
|
+
* on the **target** table shares the same `relationName` AND points
|
|
832
|
+
* back at the same source — the actual ambiguity case for resolver
|
|
833
|
+
* step 1. Scope is per `(sourceTable, targetTable, relationName)`:
|
|
834
|
+
* the same tag can be reused across unrelated table pairs. Spec:
|
|
835
|
+
* docs/db/spec-relation-name.md §7 R-2.
|
|
836
|
+
*/
|
|
837
|
+
declare class RelationalQueryAmbiguousRelationNameError extends KickDbError {
|
|
838
|
+
readonly sourceTable: string;
|
|
839
|
+
readonly targetTable: string;
|
|
840
|
+
readonly relationName: string;
|
|
841
|
+
/** Relation keys on the target table whose inverse `one` shares the tag. */
|
|
842
|
+
readonly conflicting: readonly string[];
|
|
843
|
+
constructor(sourceTable: string, targetTable: string, relationName: string, conflicting: readonly string[]);
|
|
844
|
+
}
|
|
812
845
|
/**
|
|
813
846
|
* Thrown at extract time when a `many` relation has no inverse
|
|
814
847
|
* `one` declared on the target table. The compiler needs the FK
|
|
@@ -823,5 +856,5 @@ declare class RelationalQueryMissingInverseError extends KickDbError {
|
|
|
823
856
|
constructor(sourceTable: string, relationName: string, targetTable: string);
|
|
824
857
|
}
|
|
825
858
|
//#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 };
|
|
859
|
+
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, RelationalQueryAmbiguousRelationNameError, 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 };
|
|
827
860
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -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/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;E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SACA,YAAA;EAAA,SACA,WAAA;cACG,WAAA,UAAqB,YAAA,UAAsB,WAAA;AAAA"}
|
|
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,EA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AAkB,KAAA;AAAA;;;;;;;cAiBnB,kCAAA,SAA2C,WAAA;EAAA,SAC7C,WAAA;EAAA,SACA,eAAA;cACG,WAAA,UAAqB,eAAA;AAAA;;;;;A5B5CnC;c4B4Da,gCAAA,SAAyC,WAAA;EAAA,SAC3C,OAAA;cACG,OAAA;AAAA;;;;;A5BzDd;;;;c4B2Ea,yCAAA,SAAkD,WAAA;EAAA,SACpD,WAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;E5B3EP;EAAA,S4B6EO,WAAA;cAEP,WAAA,UACA,WAAA,UACA,YAAA,UACA,WAAA;AAAA;;;;;;;;cAwBS,kCAAA,SAA2C,WAAA;EAAA,SAC7C,WAAA;EAAA,SACA,YAAA;EAAA,SACA,WAAA;cACG,WAAA,UAAqB,YAAA,UAAsB,WAAA;AAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v5.
|
|
2
|
+
* @forinda/kickjs-db v5.4.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-
|
|
11
|
+
import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Ddl8seq-.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,ParseJSONResultsPlugin,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{jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from"kysely/helpers/sqlite";import{jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from"kysely/helpers/mysql";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}},RelationalQueryAmbiguousRelationNameError=class extends KickDbError{sourceTable;targetTable;relationName;conflicting;constructor(sourceTable,targetTable,relationName,conflicting){super(`KICK_DB_RELATIONAL_AMBIGUOUS_RELATION_NAME`,`Cannot pair \`${sourceTable}\`'s \`many\` with relationName='${relationName}' — multiple \`one\` relations on \`${targetTable}\` share that tag and point back at \`${sourceTable}\` (${conflicting.map(c=>`\`${targetTable}.${c}\``).join(`, `)}). The pairing tag must be unique per (source, target, name) triple — rename one of the \`one\` relations on \`${targetTable}\` or split the schema.`),this.sourceTable=sourceTable,this.targetTable=targetTable,this.relationName=relationName,this.conflicting=conflicting}},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}\`, and ${targetTable}'s foreign keys to ${sourceTable} are either zero or ambiguous. If the target has multiple FKs to the source, tag both sides with the same \`relationName: 'foo'\` to pair them — see docs/db/spec-relation-name.md. Otherwise 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),...rel.relationName===void 0?{}:{relationName:rel.relationName}};continue}let target=rel.target.__name,targetRelations=declsBySource[target]??{},relNameSpread=rel.relationName===void 0?{}:{relationName:rel.relationName};if(rel.relationName!==void 0){let matchingInverses=findInversesByRelationName(targetRelations,sourceTable,rel.relationName);if(matchingInverses.length>1)throw new RelationalQueryAmbiguousRelationNameError(sourceTable,target,rel.relationName,matchingInverses.map(m=>m.relationKey));if(matchingInverses.length===1){let inverse=matchingInverses[0].relation;out[sourceTable][relationName]={kind:`many`,target,sourceColumns:inverse.references.map(r=>r.__name),targetColumns:inverse.fields.map(f=>f.__name),...relNameSpread};continue}}let untaggedInverse=findUniqueUntaggedInverse(targetRelations,sourceTable);if(untaggedInverse){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:untaggedInverse.references.map(r=>r.__name),targetColumns:untaggedInverse.fields.map(f=>f.__name),...relNameSpread};continue}let fkFallback=resolveByForeignKey(tables[target],sourceTable);if(fkFallback){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:fkFallback.refColumns,targetColumns:fkFallback.columns,...relNameSpread};continue}throw new RelationalQueryMissingInverseError(sourceTable,relationName,target)}}}return out}function findInversesByRelationName(targetRelations,sourceTable,relationName){let matches=[];for(let[key,rel]of Object.entries(targetRelations))rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===relationName&&matches.push({relationKey:key,relation:rel});return matches}function findUniqueUntaggedInverse(targetRelations,sourceTable){let unique=null;for(let rel of Object.values(targetRelations))if(rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===void 0){if(unique)return null;unique=rel}return unique}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(`,
|
|
@@ -101,7 +101,7 @@ import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Cn
|
|
|
101
101
|
WHERE tc.table_schema = $1
|
|
102
102
|
AND tc.table_name = $2
|
|
103
103
|
AND tc.constraint_type = 'FOREIGN KEY'
|
|
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
|
|
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,tables,compile){return new Proxy({},{get(_target,prop){if(typeof prop==`string`)return makeTableNamespace(qb,prop,relations,tables,compile)}})}function makeTableNamespace(qb,table,relations,tables,compile){return{async findMany(options){return await execute(qb,compile(qb,table,options??{},relations,tables,`many`))},async findFirst(options){return(await execute(qb,compile(qb,table,options??{},relations,tables,`first`)))[0]??null},async findUnique(options){return(await execute(qb,compile(qb,table,options,relations,tables,`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.tables,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 makeAlias(name,depth){return`${name}_${depth}`}function runCompile(db,table,options,relations,tables,mode,helpers){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,tables,maxDepth,[outerAlias],helpers)),query=applyWhereOrderLimit(query,outerAlias,options,mode),query.compile()}function applyWithSelects(query,source,sourceAlias,withClause,relations,tables,maxDepth,trace,helpers){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,tables,maxDepth,trace,helpers);rel.kind===`many`?out.push(helpers.jsonArrayFrom(inner).as(key)):out.push(helpers.jsonObjectFrom(inner).as(key))}return out})}function buildInnerSelect(eb,sourceAlias,rel,innerAlias,subOptions,relations,tables,maxDepth,trace,helpers){let targetTable=tables[rel.target],columns=targetTable?Object.keys(targetTable.columns).map(c=>`${innerAlias}.${c}`):null,sub=eb.selectFrom(`${rel.target} as ${innerAlias}`);sub=columns&&columns.length>0?sub.select(columns):sub.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,tables,maxDepth,nextTrace,helpers)),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 PG_HELPERS={jsonArrayFrom,jsonObjectFrom};function compilePg(db,table,options,relations,tables,mode=`many`){return runCompile(db,table,options,relations,tables,mode,PG_HELPERS)}const SQLITE_HELPERS={jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1};function compileSqlite(db,table,options,relations,tables,mode=`many`){return runCompile(db,table,options,relations,tables,mode,SQLITE_HELPERS)}const MYSQL_HELPERS={jsonArrayFrom:jsonArrayFrom$2,jsonObjectFrom:jsonObjectFrom$2};function compileMysql(db,table,options,relations,tables,mode=`many`){return runCompile(db,table,options,relations,tables,mode,MYSQL_HELPERS)}function pickCompiler(dialect){switch(dialect){case`postgres`:return compilePg;case`sqlite`:return compileSqlite;case`mysql`:return compileMysql}}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,dialectTag=detectDialect(opts.dialect),plugins=[];codecPlugin&&plugins.push(codecPlugin),(dialectTag===`sqlite`||dialectTag===`mysql`)&&plugins.push(new ParseJSONResultsPlugin);let kysely=new Kysely({dialect:opts.dialect,plugins:plugins.length>0?plugins: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}),tables=extractSnapshot(opts.schema,dialectTag).tables;return wrap(kysely,{events,dialect:dialectTag,savepointCounter:{value:0},query:{relations:extractRelations(opts.schema,tables)??{},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-Cn
|
|
|
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,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};
|
|
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,...opts.relationName===void 0?{}:{relationName:opts.relationName}}),many:(target,opts)=>({kind:`many`,target,...opts?.relationName===void 0?{}:{relationName:opts.relationName}})})}}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,RelationalQueryAmbiguousRelationNameError,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
|