arkormx 2.12.9 → 2.12.11

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/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as buildPrimaryKeyLine, $n as readAppliedMigrationsState, $t as bindAdapterToModels, A as resetPersistedColumnMappingsCache, An as registerFactories, At as EnumBuilder, B as applyCreateTableOperation, Bn as ForeignKeyBuilder, Bt as col, C as getPersistedEnumMap, Cn as getRegisteredModels, Ct as supportsDatabaseCreation, D as getPersistedTimestampColumns, Dn as loadMigrationsFrom, Dt as toModelName, E as getPersistedTableMetadata, En as loadFactoriesFrom, Et as toMigrationFileSlug, F as writePersistedColumnMappingsState, Fn as resetRuntimeRegistryForTests, Ft as Expression, G as applyMigrationToPrismaSchema, Gn as deleteAppliedMigrationsStateFromStore, Gt as json, H as applyMigrationRollbackToDatabase, Hn as buildMigrationRunId, Ht as expressionBuilder, I as PRISMA_ENUM_MEMBER_REGEX, In as resolveRegisteredModel, It as JsonExpression, J as buildFieldLine, Jn as getLastMigrationRun, Jt as raw, K as applyOperationsToPrismaSchema, Kn as findAppliedMigration, Kt as max, L as PRISMA_ENUM_REGEX, Ln as UnsupportedAdapterFeatureException, Lt as avg, M as resolvePersistedMetadataFeatures, Mn as registerModels, Mt as resolveGeneratedExpression, N as syncPersistedColumnMappingsFromState, Nn as registerPaths, Nt as AggregateExpression, O as readPersistedColumnMappingsState, On as loadModelsFrom, Ot as isMigrationPlanningActive, P as validatePersistedMetadataFeaturesForMigrations, Pn as registerSeeders, Pt as CaseExpression, Q as buildModelBlock, Qn as markMigrationRun, Qt as awaitConfiguredModelsRegistration, R as PRISMA_MODEL_REGEX, Rn as RuntimeModuleLoader, Rt as caseWhen, S as getPersistedColumnMap, Sn as getRegisteredMigrations, St as stripPrismaSchemaModelsAndEnums, T as getPersistedPrimaryKeyGeneration, Tn as getRegisteredSeeders, Tt as supportsDatabaseReset, U as applyMigrationRollbackToPrismaSchema, Un as computeMigrationChecksum, Ut as fn, V as applyDropTableOperation, Vn as buildMigrationIdentity, Vt as count, W as applyMigrationToDatabase, Wn as createEmptyAppliedMigrationsState, Wt as fromExpressionNode, X as buildInverseRelationLine, Xn as isMigrationApplied, Xt as val, Y as buildIndexLine, Yn as getLatestAppliedMigrations, Yt as sum, Z as buildMigrationSource, Zn as markMigrationApplied, Zt as where, _ as SetBasedEagerLoader, _n as isTransactionCapableClient, _t as resolveEnumName, a as MorphManyRelation, an as getActiveTransactionAdapter, ar as writeAppliedMigrationsStateToStore, at as deriveRelationAlias, b as createEmptyPersistedColumnMappingsState, bn as runArkormTransaction, bt as runMigrationWithPrisma, c as HasManyThroughRelation, cn as getRuntimeAdapter, cr as ArkormException, ct as escapeRegex, dn as getRuntimePaginationCurrentPageResolver, dt as formatDefaultValue, en as configureArkormRuntime, er as readAppliedMigrationsStateFromStore, et as buildRelationLine, f as BelongsToManyRelation, fn as getRuntimePaginationURLDriverFactory, ft as formatEnumDefaultValue, g as URLDriver, gn as isQuerySchemaLike, gt as pad, h as Paginator, hn as isDelegateLike, ht as getMigrationPlan, i as MorphOneRelation, in as ensureArkormConfigLoading, ir as writeAppliedMigrationsState, it as deriveInverseRelationAlias, j as resolveColumnMappingsFilePath, jn as registerMigrations, jt as TableBuilder, k as rebuildPersistedColumnMappingsState, kn as loadSeedersFrom, kt as SchemaBuilder, l as HasManyRelation, ln as getRuntimeClient, lt as findEnumBlock, m as LengthAwarePaginator, mn as getUserConfig, mt as generateMigrationFile, n as MorphedByManyRelation, nn as disposeArkormRuntime, nr as resolveMigrationStateFilePath, nt as createMigrationTimestamp, o as HasOneThroughRelation, on as getActiveTransactionClient, or as RelationResolutionException, ot as deriveRelationFieldName, p as Relation, pn as getRuntimePrismaClient, pt as formatRelationAction, q as buildEnumBlock, qn as getLastBatchMigrations, qt as min, r as MorphToManyRelation, rn as emitRuntimeDebugEvent, rr as supportsDatabaseMigrationState, rt as deriveCollectionFieldName, s as HasOneRelation, sn as getDefaultStubsPath, sr as ArkormCollection, st as deriveSingularFieldName, t as MorphToRelation, tn as defineConfig, tr as removeAppliedMigration, tt as buildUniqueConstraintLine, u as BelongsToRelation, un as getRuntimeDebugHandler, ut as findModelBlock, vn as loadArkormConfig, vt as resolveMigrationClassName, w as getPersistedEnumTsType, wn as getRegisteredPaths, wt as supportsDatabaseMigrationExecution, x as deletePersistedColumnMappingsState, xn as getRegisteredFactories, xt as runPrismaCommand, y as applyOperationsToPersistedColumnMappingsState, yn as resetArkormRuntimeForTests, yt as resolvePrismaType, z as applyAlterTableOperation, zn as PrimaryKeyGenerationPlanner, zt as coalesce } from "./relationship-DZ4WJ0Si.mjs";
1
+ import { $ as buildPrimaryKeyLine, $n as readAppliedMigrationsState, $t as bindAdapterToModels, A as resetPersistedColumnMappingsCache, An as registerFactories, At as EnumBuilder, B as applyCreateTableOperation, Bn as ForeignKeyBuilder, Bt as col, C as getPersistedEnumMap, Cn as getRegisteredModels, Ct as supportsDatabaseCreation, D as getPersistedTimestampColumns, Dn as loadMigrationsFrom, Dt as toModelName, E as getPersistedTableMetadata, En as loadFactoriesFrom, Et as toMigrationFileSlug, F as writePersistedColumnMappingsState, Fn as resetRuntimeRegistryForTests, Ft as Expression, G as applyMigrationToPrismaSchema, Gn as deleteAppliedMigrationsStateFromStore, Gt as json, H as applyMigrationRollbackToDatabase, Hn as buildMigrationRunId, Ht as expressionBuilder, I as PRISMA_ENUM_MEMBER_REGEX, In as resolveRegisteredModel, It as JsonExpression, J as buildFieldLine, Jn as getLastMigrationRun, Jt as raw, K as applyOperationsToPrismaSchema, Kn as findAppliedMigration, Kt as max, L as PRISMA_ENUM_REGEX, Ln as UnsupportedAdapterFeatureException, Lt as avg, M as resolvePersistedMetadataFeatures, Mn as registerModels, Mt as resolveGeneratedExpression, N as syncPersistedColumnMappingsFromState, Nn as registerPaths, Nt as AggregateExpression, O as readPersistedColumnMappingsState, On as loadModelsFrom, Ot as isMigrationPlanningActive, P as validatePersistedMetadataFeaturesForMigrations, Pn as registerSeeders, Pt as CaseExpression, Q as buildModelBlock, Qn as markMigrationRun, Qt as awaitConfiguredModelsRegistration, R as PRISMA_MODEL_REGEX, Rn as RuntimeModuleLoader, Rt as caseWhen, S as getPersistedColumnMap, Sn as getRegisteredMigrations, St as stripPrismaSchemaModelsAndEnums, T as getPersistedPrimaryKeyGeneration, Tn as getRegisteredSeeders, Tt as supportsDatabaseReset, U as applyMigrationRollbackToPrismaSchema, Un as computeMigrationChecksum, Ut as fn, V as applyDropTableOperation, Vn as buildMigrationIdentity, Vt as count, W as applyMigrationToDatabase, Wn as createEmptyAppliedMigrationsState, Wt as fromExpressionNode, X as buildInverseRelationLine, Xn as isMigrationApplied, Xt as val, Y as buildIndexLine, Yn as getLatestAppliedMigrations, Yt as sum, Z as buildMigrationSource, Zn as markMigrationApplied, Zt as where, _ as SetBasedEagerLoader, _n as isTransactionCapableClient, _t as resolveEnumName, a as MorphManyRelation, an as getActiveTransactionAdapter, ar as writeAppliedMigrationsStateToStore, at as deriveRelationAlias, b as createEmptyPersistedColumnMappingsState, bn as runArkormTransaction, bt as runMigrationWithPrisma, c as HasManyThroughRelation, cn as getRuntimeAdapter, cr as ArkormException, ct as escapeRegex, dn as getRuntimePaginationCurrentPageResolver, dt as formatDefaultValue, en as configureArkormRuntime, er as readAppliedMigrationsStateFromStore, et as buildRelationLine, f as BelongsToManyRelation, fn as getRuntimePaginationURLDriverFactory, ft as formatEnumDefaultValue, g as URLDriver, gn as isQuerySchemaLike, gt as pad, h as Paginator, hn as isDelegateLike, ht as getMigrationPlan, i as MorphOneRelation, in as ensureArkormConfigLoading, ir as writeAppliedMigrationsState, it as deriveInverseRelationAlias, j as resolveColumnMappingsFilePath, jn as registerMigrations, jt as TableBuilder, k as rebuildPersistedColumnMappingsState, kn as loadSeedersFrom, kt as SchemaBuilder, l as HasManyRelation, ln as getRuntimeClient, lt as findEnumBlock, m as LengthAwarePaginator, mn as getUserConfig, mt as generateMigrationFile, n as MorphedByManyRelation, nn as disposeArkormRuntime, nr as resolveMigrationStateFilePath, nt as createMigrationTimestamp, o as HasOneThroughRelation, on as getActiveTransactionClient, or as RelationResolutionException, ot as deriveRelationFieldName, p as Relation, pn as getRuntimePrismaClient, pt as formatRelationAction, q as buildEnumBlock, qn as getLastBatchMigrations, qt as min, r as MorphToManyRelation, rn as emitRuntimeDebugEvent, rr as supportsDatabaseMigrationState, rt as deriveCollectionFieldName, s as HasOneRelation, sn as getDefaultStubsPath, sr as ArkormCollection, st as deriveSingularFieldName, t as MorphToRelation, tn as defineConfig, tr as removeAppliedMigration, tt as buildUniqueConstraintLine, u as BelongsToRelation, un as getRuntimeDebugHandler, ut as findModelBlock, vn as loadArkormConfig, vt as resolveMigrationClassName, w as getPersistedEnumTsType, wn as getRegisteredPaths, wt as supportsDatabaseMigrationExecution, x as deletePersistedColumnMappingsState, xn as getRegisteredFactories, xt as runPrismaCommand, y as applyOperationsToPersistedColumnMappingsState, yn as resetArkormRuntimeForTests, yt as resolvePrismaType, z as applyAlterTableOperation, zn as PrimaryKeyGenerationPlanner, zt as coalesce } from "./relationship-PB57C4Pt.mjs";
2
2
  import { Pool } from "pg";
3
3
  import { extname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
@@ -35,6 +35,27 @@ var QueryExecutionException = class extends ArkormException {
35
35
  //#endregion
36
36
  //#region src/adapters/KyselyDatabaseAdapter.ts
37
37
  /**
38
+ * Reads back the schema plan recorded against an applied migration.
39
+ *
40
+ * The driver hands `jsonb` back already parsed, but a `json`/`text` column (or
41
+ * an older pg driver) yields a string, so both are accepted. Anything else
42
+ * including rows written before the column existed resolves to `undefined`,
43
+ * which makes the consumer fall back to replaying the migration file.
44
+ *
45
+ * @param value
46
+ * @returns
47
+ */
48
+ const parseRecordedMigrationOperations = (value) => {
49
+ if (Array.isArray(value)) return value;
50
+ if (typeof value !== "string") return void 0;
51
+ try {
52
+ const parsed = JSON.parse(value);
53
+ return Array.isArray(parsed) ? parsed : void 0;
54
+ } catch {
55
+ return;
56
+ }
57
+ };
58
+ /**
38
59
  * Database adapter implementation for Kysely, allowing Arkorm to execute queries using Kysely
39
60
  * as the underlying query builder and executor.
40
61
  *
@@ -534,8 +555,13 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
534
555
  file text not null,
535
556
  class_name text not null,
536
557
  applied_at timestamptz not null,
537
- checksum text null
558
+ checksum text null,
559
+ operations jsonb null
538
560
  )
561
+ `, executor);
562
+ await this.executeRawStatement(`
563
+ alter table ${this.quoteIdentifier(KyselyDatabaseAdapter.migrationStateTable)}
564
+ add column if not exists operations jsonb null
539
565
  `, executor);
540
566
  await this.executeRawStatement(`
541
567
  create table if not exists ${this.quoteIdentifier(KyselyDatabaseAdapter.migrationRunTable)} (
@@ -550,8 +576,8 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
550
576
  await this.executeRawStatement(`delete from ${this.quoteIdentifier(KyselyDatabaseAdapter.migrationRunTable)}`, executor);
551
577
  await this.executeRawStatement(`delete from ${this.quoteIdentifier(KyselyDatabaseAdapter.migrationStateTable)}`, executor);
552
578
  for (const migration of state.migrations) await sql`
553
- insert into ${sql.table(KyselyDatabaseAdapter.migrationStateTable)} (id, file, class_name, applied_at, checksum)
554
- values (${migration.id}, ${migration.file}, ${migration.className}, ${migration.appliedAt}, ${migration.checksum ?? null})
579
+ insert into ${sql.table(KyselyDatabaseAdapter.migrationStateTable)} (id, file, class_name, applied_at, checksum, operations)
580
+ values (${migration.id}, ${migration.file}, ${migration.className}, ${migration.appliedAt}, ${migration.checksum ?? null}, cast(${migration.operations ? JSON.stringify(migration.operations) : null} as jsonb))
555
581
  `.execute(executor);
556
582
  for (const run of state.runs ?? []) await sql`
557
583
  insert into ${sql.table(KyselyDatabaseAdapter.migrationRunTable)} (id, applied_at, migration_ids)
@@ -992,6 +1018,19 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
992
1018
  buildColumnReference(table, column) {
993
1019
  return sql`${sql.table(table)}.${sql.id(column)}`;
994
1020
  }
1021
+ /**
1022
+ * Renders the relation's source table, aliasing it when a self-referential
1023
+ * relation would otherwise put the same name on both sides of a correlated
1024
+ * subquery.
1025
+ *
1026
+ * @param sourceTable
1027
+ * @param table
1028
+ * @returns
1029
+ */
1030
+ buildTableSource(sourceTable, table) {
1031
+ if (sourceTable === table) return sql`${sql.table(table)}`;
1032
+ return sql`${sql.table(sourceTable)} as ${sql.table(table)}`;
1033
+ }
995
1034
  buildRelatedTargetFromRelation(target, relation) {
996
1035
  const metadata = target.model?.getRelationMetadata(relation);
997
1036
  if (!metadata) throw new UnsupportedAdapterFeatureException(`Relation [${relation}] could not be resolved for SQL-backed relation execution.`, {
@@ -999,7 +1038,7 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
999
1038
  model: target.modelName,
1000
1039
  relation
1001
1040
  });
1002
- if (metadata.type !== "hasMany" && metadata.type !== "hasOne" && metadata.type !== "belongsTo" && metadata.type !== "belongsToMany" && metadata.type !== "hasOneThrough" && metadata.type !== "hasManyThrough") throw new UnsupportedAdapterFeatureException(`Relation [${relation}] is not supported for SQL-backed relation execution by the Kysely adapter yet.`, {
1041
+ if (metadata.type !== "hasMany" && metadata.type !== "hasOne" && metadata.type !== "belongsTo" && metadata.type !== "belongsToMany" && metadata.type !== "hasOneThrough" && metadata.type !== "hasManyThrough" && metadata.type !== "morphOne" && metadata.type !== "morphMany") throw new UnsupportedAdapterFeatureException(`Relation [${relation}] is not supported for SQL-backed relation execution by the Kysely adapter yet.`, {
1003
1042
  operation: "adapter.relation.metadata",
1004
1043
  model: target.modelName,
1005
1044
  relation,
@@ -1009,12 +1048,15 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1009
1048
  }
1010
1049
  });
1011
1050
  const relatedMetadata = metadata.relatedModel.getModelMetadata();
1051
+ const sourceTable = this.resolveMappedTable(relatedMetadata.table);
1052
+ const table = sourceTable === this.resolveTable(target) ? `${sourceTable}_arkorm_self` : relatedMetadata.table;
1012
1053
  return {
1013
1054
  metadata,
1055
+ sourceTable,
1014
1056
  relatedTarget: {
1015
1057
  model: metadata.relatedModel,
1016
1058
  modelName: metadata.relatedModel.name,
1017
- table: relatedMetadata.table,
1059
+ table,
1018
1060
  primaryKey: relatedMetadata.primaryKey,
1019
1061
  columns: relatedMetadata.columns,
1020
1062
  softDelete: relatedMetadata.softDelete
@@ -1024,12 +1066,12 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1024
1066
  resolveMappedTable(table) {
1025
1067
  return this.mapping[table] ?? table;
1026
1068
  }
1027
- buildBelongsToManyJoinSource(outerTarget, relatedTarget, metadata) {
1069
+ buildBelongsToManyJoinSource(outerTarget, relatedTarget, metadata, sourceTable) {
1028
1070
  const outerTable = this.resolveTable(outerTarget);
1029
1071
  const relatedTable = this.resolveTable(relatedTarget);
1030
1072
  const pivotTable = this.resolveMappedTable(metadata.throughTable);
1031
1073
  return {
1032
- from: sql`${sql.table(relatedTable)} inner join ${sql.table(pivotTable)} on ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.relatedKey))} = ${this.buildColumnReference(pivotTable, metadata.relatedPivotKey)}`,
1074
+ from: sql`${this.buildTableSource(sourceTable, relatedTable)} inner join ${sql.table(pivotTable)} on ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.relatedKey))} = ${this.buildColumnReference(pivotTable, metadata.relatedPivotKey)}`,
1033
1075
  condition: sql`
1034
1076
  ${this.buildColumnReference(pivotTable, metadata.foreignPivotKey)}
1035
1077
  =
@@ -1037,12 +1079,12 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1037
1079
  `
1038
1080
  };
1039
1081
  }
1040
- buildThroughJoinSource(outerTarget, relatedTarget, metadata) {
1082
+ buildThroughJoinSource(outerTarget, relatedTarget, metadata, sourceTable) {
1041
1083
  const outerTable = this.resolveTable(outerTarget);
1042
1084
  const relatedTable = this.resolveTable(relatedTarget);
1043
1085
  const throughTable = this.resolveMappedTable(metadata.throughTable);
1044
1086
  return {
1045
- from: sql`${sql.table(relatedTable)} inner join ${sql.table(throughTable)} on ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.secondKey))} = ${this.buildColumnReference(throughTable, metadata.secondLocalKey)}`,
1087
+ from: sql`${this.buildTableSource(sourceTable, relatedTable)} inner join ${sql.table(throughTable)} on ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.secondKey))} = ${this.buildColumnReference(throughTable, metadata.secondLocalKey)}`,
1046
1088
  condition: sql`
1047
1089
  ${this.buildColumnReference(throughTable, metadata.firstKey)}
1048
1090
  =
@@ -1050,12 +1092,35 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1050
1092
  `
1051
1093
  };
1052
1094
  }
1095
+ /**
1096
+ * The value a polymorphic child stores in its type column for this parent: the
1097
+ * parent model's class name, matching what the relationship writes on create
1098
+ * and what the set-based eager loader groups parents by.
1099
+ *
1100
+ * @param target
1101
+ * @param relation
1102
+ * @returns
1103
+ */
1104
+ resolveMorphType(target, relation) {
1105
+ const morphType = target.modelName ?? target.model?.name;
1106
+ if (!morphType) throw new UnsupportedAdapterFeatureException(`Relation [${relation}] needs a named parent model to resolve its polymorphic type.`, {
1107
+ operation: "adapter.relation.metadata",
1108
+ model: target.modelName,
1109
+ relation,
1110
+ meta: {
1111
+ feature: "relationFilters",
1112
+ relationType: "morph"
1113
+ }
1114
+ });
1115
+ return morphType;
1116
+ }
1053
1117
  buildRelatedJoinCondition(outerTarget, relation) {
1054
- const { metadata, relatedTarget } = this.buildRelatedTargetFromRelation(outerTarget, relation);
1118
+ const { metadata, relatedTarget, sourceTable } = this.buildRelatedTargetFromRelation(outerTarget, relation);
1055
1119
  const outerTable = this.resolveTable(outerTarget);
1056
1120
  const relatedTable = this.resolveTable(relatedTarget);
1121
+ const relatedFrom = this.buildTableSource(sourceTable, relatedTable);
1057
1122
  if (metadata.type === "belongsToMany") {
1058
- const joinSource = this.buildBelongsToManyJoinSource(outerTarget, relatedTarget, metadata);
1123
+ const joinSource = this.buildBelongsToManyJoinSource(outerTarget, relatedTarget, metadata, sourceTable);
1059
1124
  return {
1060
1125
  relatedTarget,
1061
1126
  from: joinSource.from,
@@ -1063,7 +1128,7 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1063
1128
  };
1064
1129
  }
1065
1130
  if (metadata.type === "hasOneThrough" || metadata.type === "hasManyThrough") {
1066
- const joinSource = this.buildThroughJoinSource(outerTarget, relatedTarget, metadata);
1131
+ const joinSource = this.buildThroughJoinSource(outerTarget, relatedTarget, metadata, sourceTable);
1067
1132
  return {
1068
1133
  relatedTarget,
1069
1134
  from: joinSource.from,
@@ -1072,16 +1137,29 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1072
1137
  }
1073
1138
  if (metadata.type === "hasMany" || metadata.type === "hasOne") return {
1074
1139
  relatedTarget,
1075
- from: sql`${sql.table(relatedTable)}`,
1140
+ from: relatedFrom,
1076
1141
  condition: sql`
1077
1142
  ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.foreignKey))}
1078
1143
  =
1079
1144
  ${this.buildColumnReference(outerTable, this.mapColumn(outerTarget, metadata.localKey))}
1080
1145
  `
1081
1146
  };
1147
+ if (metadata.type === "morphOne" || metadata.type === "morphMany") return {
1148
+ relatedTarget,
1149
+ from: relatedFrom,
1150
+ condition: sql`
1151
+ ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.morphIdColumn))}
1152
+ =
1153
+ ${this.buildColumnReference(outerTable, this.mapColumn(outerTarget, metadata.localKey))}
1154
+ and
1155
+ ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.morphTypeColumn))}
1156
+ =
1157
+ ${this.resolveMorphType(outerTarget, relation)}
1158
+ `
1159
+ };
1082
1160
  return {
1083
1161
  relatedTarget,
1084
- from: sql`${sql.table(relatedTable)}`,
1162
+ from: relatedFrom,
1085
1163
  condition: sql`
1086
1164
  ${this.buildColumnReference(relatedTable, this.mapColumn(relatedTarget, metadata.ownerKey))}
1087
1165
  =
@@ -1751,7 +1829,7 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1751
1829
  async readAppliedMigrationsState() {
1752
1830
  await this.ensureMigrationStateTables();
1753
1831
  const migrationsResult = await sql`
1754
- select id, file, class_name, applied_at, checksum
1832
+ select id, file, class_name, applied_at, checksum, operations
1755
1833
  from ${sql.table(KyselyDatabaseAdapter.migrationStateTable)}
1756
1834
  order by applied_at asc, id asc
1757
1835
  `.execute(this.db);
@@ -1767,7 +1845,8 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
1767
1845
  file: row.file,
1768
1846
  className: row.class_name,
1769
1847
  appliedAt: row.applied_at instanceof Date ? row.applied_at.toISOString() : String(row.applied_at),
1770
- checksum: row.checksum ?? void 0
1848
+ checksum: row.checksum ?? void 0,
1849
+ operations: parseRecordedMigrationOperations(row.operations)
1771
1850
  })),
1772
1851
  runs: runsResult.rows.map((row) => ({
1773
1852
  id: row.id,
@@ -4016,13 +4095,18 @@ var MigrateCommand = class extends Command {
4016
4095
  if (!appliedMigrationState) return true;
4017
4096
  const identity = buildMigrationIdentity(file, migrationClass.name);
4018
4097
  const checksum = computeMigrationChecksum(file);
4019
- const alreadyApplied = isMigrationApplied(appliedMigrationState, identity, checksum);
4020
- if (alreadyApplied) skipped.push([migrationClass, file]);
4021
- else if (findAppliedMigration(appliedMigrationState, identity)) changed.push([migrationClass, file]);
4098
+ const recorded = findAppliedMigration(appliedMigrationState, identity);
4099
+ const alreadyApplied = useDatabaseMigrations ? Boolean(recorded) : isMigrationApplied(appliedMigrationState, identity, checksum);
4100
+ if (alreadyApplied) skipped.push([
4101
+ migrationClass,
4102
+ file,
4103
+ Boolean(recorded?.checksum) && recorded?.checksum !== checksum
4104
+ ]);
4105
+ else if (recorded) changed.push([migrationClass, file]);
4022
4106
  return !alreadyApplied;
4023
4107
  });
4024
- skipped.forEach(([migrationClass, file]) => {
4025
- this.success(this.app.splitLogger("Skipped", `${file} (${migrationClass.name})`));
4108
+ skipped.forEach(([migrationClass, file, drifted]) => {
4109
+ this.success(this.app.splitLogger("Skipped", `${file} (${migrationClass.name})${drifted ? " [changed since applied]" : ""}`));
4026
4110
  });
4027
4111
  changed.forEach(([migrationClass, file]) => {
4028
4112
  this.success(this.app.splitLogger("Changed", `${file} (${migrationClass.name})`));
@@ -4039,7 +4123,9 @@ var MigrateCommand = class extends Command {
4039
4123
  return;
4040
4124
  }
4041
4125
  let columnMappingsState = createEmptyPersistedColumnMappingsState();
4042
- for (const [MigrationClassItem] of pending) {
4126
+ const executedPlans = /* @__PURE__ */ new Map();
4127
+ for (const [MigrationClassItem, file] of pending) {
4128
+ const identity = buildMigrationIdentity(file, MigrationClassItem.name);
4043
4129
  if (useDatabaseMigrations) {
4044
4130
  const planned = await this.runWithDatabaseCreationRetry(adapter, () => getMigrationPlan(MigrationClassItem, "up", { inert: true }));
4045
4131
  if (!planned.ok) return;
@@ -4049,13 +4135,16 @@ var MigrateCommand = class extends Command {
4049
4135
  this.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
4050
4136
  return;
4051
4137
  }
4052
- if (!(await this.runWithDatabaseCreationRetry(adapter, () => applyMigrationToDatabase(adapter, MigrationClassItem))).ok) return;
4138
+ const applied = await this.runWithDatabaseCreationRetry(adapter, () => applyMigrationToDatabase(adapter, MigrationClassItem));
4139
+ if (!applied.ok) return;
4140
+ executedPlans.set(identity, applied.value.operations);
4053
4141
  continue;
4054
4142
  }
4055
- await applyMigrationToPrismaSchema(MigrationClassItem, {
4143
+ const applied = await applyMigrationToPrismaSchema(MigrationClassItem, {
4056
4144
  schemaPath,
4057
4145
  write: true
4058
4146
  });
4147
+ executedPlans.set(identity, applied.operations);
4059
4148
  }
4060
4149
  if (appliedMigrationState) {
4061
4150
  const runAppliedIds = [];
@@ -4066,7 +4155,8 @@ var MigrateCommand = class extends Command {
4066
4155
  file,
4067
4156
  className: migrationClass.name,
4068
4157
  appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
4069
- checksum: computeMigrationChecksum(file)
4158
+ checksum: computeMigrationChecksum(file),
4159
+ operations: executedPlans.get(identity)
4070
4160
  });
4071
4161
  runAppliedIds.push(identity);
4072
4162
  }
@@ -4255,23 +4345,32 @@ var MigrateFreshCommand = class extends Command {
4255
4345
  }
4256
4346
  let appliedState = createEmptyAppliedMigrationsState();
4257
4347
  if (!(await this.runWithDatabaseCreationRetry(adapter, () => writeAppliedMigrationsStateToStore(adapter, stateFilePath, appliedState))).ok) return;
4258
- for (const [MigrationClassItem] of migrations) {
4348
+ const executedPlans = /* @__PURE__ */ new Map();
4349
+ for (const [MigrationClassItem, file] of migrations) {
4350
+ const identity = buildMigrationIdentity(file, MigrationClassItem.name);
4259
4351
  if (useDatabaseMigrations) {
4260
- if (!(await this.runWithDatabaseCreationRetry(adapter, () => applyMigrationToDatabase(adapter, MigrationClassItem))).ok) return;
4352
+ const applied = await this.runWithDatabaseCreationRetry(adapter, () => applyMigrationToDatabase(adapter, MigrationClassItem));
4353
+ if (!applied.ok) return;
4354
+ executedPlans.set(identity, applied.value.operations);
4261
4355
  continue;
4262
4356
  }
4263
- await applyMigrationToPrismaSchema(MigrationClassItem, {
4357
+ const applied = await applyMigrationToPrismaSchema(MigrationClassItem, {
4264
4358
  schemaPath,
4265
4359
  write: true
4266
4360
  });
4361
+ executedPlans.set(identity, applied.operations);
4362
+ }
4363
+ for (const [migrationClass, file] of migrations) {
4364
+ const identity = buildMigrationIdentity(file, migrationClass.name);
4365
+ appliedState = markMigrationApplied(appliedState, {
4366
+ id: identity,
4367
+ file,
4368
+ className: migrationClass.name,
4369
+ appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
4370
+ checksum: computeMigrationChecksum(file),
4371
+ operations: executedPlans.get(identity)
4372
+ });
4267
4373
  }
4268
- for (const [migrationClass, file] of migrations) appliedState = markMigrationApplied(appliedState, {
4269
- id: buildMigrationIdentity(file, migrationClass.name),
4270
- file,
4271
- className: migrationClass.name,
4272
- appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
4273
- checksum: computeMigrationChecksum(file)
4274
- });
4275
4374
  appliedState = markMigrationRun(appliedState, {
4276
4375
  id: buildMigrationRunId(),
4277
4376
  appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -4481,7 +4580,7 @@ var MigrationHistoryCommand = class extends Command {
4481
4580
  {--state-file= : Path to applied migration state file}
4482
4581
  {--reset : Clear tracked migration history file}
4483
4582
  {--delete : Delete tracked migration history file}
4484
- {--json : Print raw JSON output}
4583
+ {--json : Print JSON output (without each migration's recorded schema plan)}
4485
4584
  `;
4486
4585
  this.description = "Inspect or reset tracked migration history";
4487
4586
  }
@@ -4517,7 +4616,11 @@ var MigrationHistoryCommand = class extends Command {
4517
4616
  if (this.option("json")) {
4518
4617
  this.success(JSON.stringify({
4519
4618
  path: usesDatabaseState ? "database" : stateFilePath,
4520
- ...state
4619
+ ...state,
4620
+ migrations: state.migrations.map(({ operations: _operations, ...migration }) => ({
4621
+ ...migration,
4622
+ hasRecordedPlan: Array.isArray(_operations)
4623
+ }))
4521
4624
  }, null, 2));
4522
4625
  return;
4523
4626
  }
@@ -8754,7 +8857,7 @@ var QueryBuilder = class QueryBuilder {
8754
8857
  }
8755
8858
  isSqlRelationFeatureMetadata(metadata) {
8756
8859
  if (!metadata) return false;
8757
- return metadata.type === "hasMany" || metadata.type === "hasOne" || metadata.type === "belongsTo" || metadata.type === "belongsToMany" || metadata.type === "hasOneThrough" || metadata.type === "hasManyThrough";
8860
+ return metadata.type === "hasMany" || metadata.type === "hasOne" || metadata.type === "belongsTo" || metadata.type === "belongsToMany" || metadata.type === "hasOneThrough" || metadata.type === "hasManyThrough" || metadata.type === "morphOne" || metadata.type === "morphMany";
8758
8861
  }
8759
8862
  async filterModelsByRelationConstraints(models, relationCache, baseIds) {
8760
8863
  return (await Promise.all(models.map(async (model) => {
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_relationship = require('../relationship-D7MhPUIX.cjs');
2
+ const require_relationship = require('../relationship-ChCzFqO1.cjs');
3
3
 
4
4
  exports.BelongsToManyRelation = require_relationship.BelongsToManyRelation;
5
5
  exports.BelongsToRelation = require_relationship.BelongsToRelation;
@@ -1,2 +1,2 @@
1
- import { Cs as Relation, Ss as BelongsToManyRelation, _s as HasOneRelation, bs as BelongsToRelation, ds as MorphToRelation, fs as MorphedByManyRelation, gs as HasOneThroughRelation, hs as MorphManyRelation, ms as MorphOneRelation, ps as MorphToManyRelation, us as SetBasedEagerLoader, vs as HasManyThroughRelation, ws as RelationTableLoader, xs as SingleResultRelation, ys as HasManyRelation } from "../index-Lxl6NdHS.cjs";
1
+ import { Cs as Relation, Ss as BelongsToManyRelation, _s as HasOneRelation, bs as BelongsToRelation, ds as MorphToRelation, fs as MorphedByManyRelation, gs as HasOneThroughRelation, hs as MorphManyRelation, ms as MorphOneRelation, ps as MorphToManyRelation, us as SetBasedEagerLoader, vs as HasManyThroughRelation, ws as RelationTableLoader, xs as SingleResultRelation, ys as HasManyRelation } from "../index-DdMKdS88.cjs";
2
2
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, MorphToRelation, MorphedByManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -1,2 +1,2 @@
1
- import { Cs as Relation, Ss as BelongsToManyRelation, _s as HasOneRelation, bs as BelongsToRelation, ds as MorphToRelation, fs as MorphedByManyRelation, gs as HasOneThroughRelation, hs as MorphManyRelation, ms as MorphOneRelation, ps as MorphToManyRelation, us as SetBasedEagerLoader, vs as HasManyThroughRelation, ws as RelationTableLoader, xs as SingleResultRelation, ys as HasManyRelation } from "../index-O3-Mi7hj.mjs";
1
+ import { Cs as Relation, Ss as BelongsToManyRelation, _s as HasOneRelation, bs as BelongsToRelation, ds as MorphToRelation, fs as MorphedByManyRelation, gs as HasOneThroughRelation, hs as MorphManyRelation, ms as MorphOneRelation, ps as MorphToManyRelation, us as SetBasedEagerLoader, vs as HasManyThroughRelation, ws as RelationTableLoader, xs as SingleResultRelation, ys as HasManyRelation } from "../index-Cot4hmHA.mjs";
2
2
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, MorphToRelation, MorphedByManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -1,3 +1,3 @@
1
- import { _ as SetBasedEagerLoader, a as MorphManyRelation, c as HasManyThroughRelation, d as SingleResultRelation, f as BelongsToManyRelation, i as MorphOneRelation, l as HasManyRelation, n as MorphedByManyRelation, o as HasOneThroughRelation, p as Relation, r as MorphToManyRelation, s as HasOneRelation, t as MorphToRelation, u as BelongsToRelation, v as RelationTableLoader } from "../relationship-DZ4WJ0Si.mjs";
1
+ import { _ as SetBasedEagerLoader, a as MorphManyRelation, c as HasManyThroughRelation, d as SingleResultRelation, f as BelongsToManyRelation, i as MorphOneRelation, l as HasManyRelation, n as MorphedByManyRelation, o as HasOneThroughRelation, p as Relation, r as MorphToManyRelation, s as HasOneRelation, t as MorphToRelation, u as BelongsToRelation, v as RelationTableLoader } from "../relationship-PB57C4Pt.mjs";
2
2
 
3
3
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, MorphToRelation, MorphedByManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -123,6 +123,9 @@ const readAppliedMigrationsState = (stateFilePath) => {
123
123
  version: 1,
124
124
  migrations: parsed.migrations.filter((migration) => {
125
125
  return typeof migration?.id === "string" && typeof migration?.file === "string" && typeof migration?.className === "string" && typeof migration?.appliedAt === "string" && (migration?.checksum === void 0 || typeof migration?.checksum === "string");
126
+ }).map((migration) => migration.operations === void 0 || Array.isArray(migration.operations) ? migration : {
127
+ ...migration,
128
+ operations: void 0
126
129
  }),
127
130
  runs: Array.isArray(parsed.runs) ? parsed.runs.filter((run) => {
128
131
  return typeof run?.id === "string" && typeof run?.appliedAt === "string" && Array.isArray(run?.migrationIds) && run.migrationIds.every((item) => typeof item === "string");
@@ -157,6 +160,20 @@ const deleteAppliedMigrationsStateFromStore = async (adapter, stateFilePath) =>
157
160
  writeAppliedMigrationsState(stateFilePath, createEmptyAppliedMigrationsState());
158
161
  return "file";
159
162
  };
163
+ /**
164
+ * Whether `identity` counts as applied in `state`.
165
+ *
166
+ * Passing a `checksum` makes an edited migration file count as *not* applied so
167
+ * it is re-run. That only suits the Prisma/file-backed flow, where re-applying a
168
+ * migration just rewrites the generated schema. Adapter-backed runtimes must
169
+ * omit the checksum and let the state store alone decide, since replaying an
170
+ * already-applied `up()` would run its SQL a second time.
171
+ *
172
+ * @param state
173
+ * @param identity
174
+ * @param checksum
175
+ * @returns
176
+ */
160
177
  const isMigrationApplied = (state, identity, checksum) => {
161
178
  const matched = state.migrations.find((migration) => migration.id === identity);
162
179
  if (!matched) return false;
@@ -3537,6 +3554,30 @@ const applyOperationsToPersistedColumnMappingsState = (state, operations, featur
3537
3554
  tables: nextTables
3538
3555
  };
3539
3556
  };
3557
+ /**
3558
+ * Replays an applied migration's `up()` from the current file to recover its
3559
+ * schema plan.
3560
+ *
3561
+ * Only used for entries recorded before the plan was stored alongside them; the
3562
+ * result reflects the file as it stands now, which is why a recorded plan always
3563
+ * wins over this.
3564
+ *
3565
+ * @param migration
3566
+ * @param availableByIdentity
3567
+ * @returns
3568
+ */
3569
+ const replayAppliedMigrationPlan = async (migration, availableByIdentity) => {
3570
+ const migrationClass = availableByIdentity.get(migration.id);
3571
+ if (!migrationClass) throw new ArkormException(`Unable to rebuild persisted column mappings because migration [${migration.id}] could not be resolved from the current migration files.`, {
3572
+ operation: "migration.columnMappings",
3573
+ meta: {
3574
+ migrationId: migration.id,
3575
+ file: migration.file,
3576
+ className: migration.className
3577
+ }
3578
+ });
3579
+ return await getMigrationPlan(migrationClass, "up", { inert: true });
3580
+ };
3540
3581
  const rebuildPersistedColumnMappingsState = async (state, availableMigrations, features = resolvePersistedMetadataFeatures()) => {
3541
3582
  const availableByIdentity = new Map(availableMigrations.map(([migrationClass, file]) => [buildMigrationIdentity(file, migrationClass.name), migrationClass]));
3542
3583
  let nextState = createEmptyPersistedColumnMappingsState();
@@ -3549,16 +3590,7 @@ const rebuildPersistedColumnMappingsState = async (state, availableMigrations, f
3549
3590
  return left.index - right.index;
3550
3591
  });
3551
3592
  for (const { migration } of orderedMigrations) {
3552
- const migrationClass = availableByIdentity.get(migration.id);
3553
- if (!migrationClass) throw new ArkormException(`Unable to rebuild persisted column mappings because migration [${migration.id}] could not be resolved from the current migration files.`, {
3554
- operation: "migration.columnMappings",
3555
- meta: {
3556
- migrationId: migration.id,
3557
- file: migration.file,
3558
- className: migration.className
3559
- }
3560
- });
3561
- const operations = await getMigrationPlan(migrationClass, "up", { inert: true });
3593
+ const operations = migration.operations ?? await replayAppliedMigrationPlan(migration, availableByIdentity);
3562
3594
  nextState = applyOperationsToPersistedColumnMappingsState(nextState, operations, features);
3563
3595
  }
3564
3596
  return nextState;
@@ -95,6 +95,9 @@ const readAppliedMigrationsState = (stateFilePath) => {
95
95
  version: 1,
96
96
  migrations: parsed.migrations.filter((migration) => {
97
97
  return typeof migration?.id === "string" && typeof migration?.file === "string" && typeof migration?.className === "string" && typeof migration?.appliedAt === "string" && (migration?.checksum === void 0 || typeof migration?.checksum === "string");
98
+ }).map((migration) => migration.operations === void 0 || Array.isArray(migration.operations) ? migration : {
99
+ ...migration,
100
+ operations: void 0
98
101
  }),
99
102
  runs: Array.isArray(parsed.runs) ? parsed.runs.filter((run) => {
100
103
  return typeof run?.id === "string" && typeof run?.appliedAt === "string" && Array.isArray(run?.migrationIds) && run.migrationIds.every((item) => typeof item === "string");
@@ -129,6 +132,20 @@ const deleteAppliedMigrationsStateFromStore = async (adapter, stateFilePath) =>
129
132
  writeAppliedMigrationsState(stateFilePath, createEmptyAppliedMigrationsState());
130
133
  return "file";
131
134
  };
135
+ /**
136
+ * Whether `identity` counts as applied in `state`.
137
+ *
138
+ * Passing a `checksum` makes an edited migration file count as *not* applied so
139
+ * it is re-run. That only suits the Prisma/file-backed flow, where re-applying a
140
+ * migration just rewrites the generated schema. Adapter-backed runtimes must
141
+ * omit the checksum and let the state store alone decide, since replaying an
142
+ * already-applied `up()` would run its SQL a second time.
143
+ *
144
+ * @param state
145
+ * @param identity
146
+ * @param checksum
147
+ * @returns
148
+ */
132
149
  const isMigrationApplied = (state, identity, checksum) => {
133
150
  const matched = state.migrations.find((migration) => migration.id === identity);
134
151
  if (!matched) return false;
@@ -3509,6 +3526,30 @@ const applyOperationsToPersistedColumnMappingsState = (state, operations, featur
3509
3526
  tables: nextTables
3510
3527
  };
3511
3528
  };
3529
+ /**
3530
+ * Replays an applied migration's `up()` from the current file to recover its
3531
+ * schema plan.
3532
+ *
3533
+ * Only used for entries recorded before the plan was stored alongside them; the
3534
+ * result reflects the file as it stands now, which is why a recorded plan always
3535
+ * wins over this.
3536
+ *
3537
+ * @param migration
3538
+ * @param availableByIdentity
3539
+ * @returns
3540
+ */
3541
+ const replayAppliedMigrationPlan = async (migration, availableByIdentity) => {
3542
+ const migrationClass = availableByIdentity.get(migration.id);
3543
+ if (!migrationClass) throw new ArkormException(`Unable to rebuild persisted column mappings because migration [${migration.id}] could not be resolved from the current migration files.`, {
3544
+ operation: "migration.columnMappings",
3545
+ meta: {
3546
+ migrationId: migration.id,
3547
+ file: migration.file,
3548
+ className: migration.className
3549
+ }
3550
+ });
3551
+ return await getMigrationPlan(migrationClass, "up", { inert: true });
3552
+ };
3512
3553
  const rebuildPersistedColumnMappingsState = async (state, availableMigrations, features = resolvePersistedMetadataFeatures()) => {
3513
3554
  const availableByIdentity = new Map(availableMigrations.map(([migrationClass, file]) => [buildMigrationIdentity(file, migrationClass.name), migrationClass]));
3514
3555
  let nextState = createEmptyPersistedColumnMappingsState();
@@ -3521,16 +3562,7 @@ const rebuildPersistedColumnMappingsState = async (state, availableMigrations, f
3521
3562
  return left.index - right.index;
3522
3563
  });
3523
3564
  for (const { migration } of orderedMigrations) {
3524
- const migrationClass = availableByIdentity.get(migration.id);
3525
- if (!migrationClass) throw new ArkormException(`Unable to rebuild persisted column mappings because migration [${migration.id}] could not be resolved from the current migration files.`, {
3526
- operation: "migration.columnMappings",
3527
- meta: {
3528
- migrationId: migration.id,
3529
- file: migration.file,
3530
- className: migration.className
3531
- }
3532
- });
3533
- const operations = await getMigrationPlan(migrationClass, "up", { inert: true });
3565
+ const operations = migration.operations ?? await replayAppliedMigrationPlan(migration, availableByIdentity);
3534
3566
  nextState = applyOperationsToPersistedColumnMappingsState(nextState, operations, features);
3535
3567
  }
3536
3568
  return nextState;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkormx",
3
- "version": "2.12.9",
3
+ "version": "2.12.11",
4
4
  "description": "Modern TypeScript-first ORM for Node.js.",
5
5
  "keywords": [
6
6
  "orm",