arkormx 2.4.5 → 2.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_relationship = require('../relationship-Cku0y1Mt.cjs');
2
+ const require_relationship = require('../relationship-CuPNAoHm.cjs');
3
3
 
4
4
  exports.BelongsToManyRelation = require_relationship.BelongsToManyRelation;
5
5
  exports.BelongsToRelation = require_relationship.BelongsToRelation;
@@ -1,2 +1,2 @@
1
- import { $a as SetBasedEagerLoader, ao as HasManyThroughRelation, co as SingleResultRelation, do as RelationTableLoader, eo as MorphToManyRelation, io as HasOneRelation, lo as BelongsToManyRelation, no as MorphManyRelation, oo as HasManyRelation, ro as HasOneThroughRelation, so as BelongsToRelation, to as MorphOneRelation, uo as Relation } from "../index-A71-nct_.cjs";
1
+ import { ao as HasOneThroughRelation, co as HasManyRelation, do as BelongsToManyRelation, fo as Relation, io as MorphManyRelation, lo as BelongsToRelation, no as MorphToManyRelation, oo as HasOneRelation, po as RelationTableLoader, ro as MorphOneRelation, so as HasManyThroughRelation, to as SetBasedEagerLoader, uo as SingleResultRelation } from "../index-DKqMpR3p.cjs";
2
2
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -1,2 +1,2 @@
1
- import { $a as SetBasedEagerLoader, ao as HasManyThroughRelation, co as SingleResultRelation, do as RelationTableLoader, eo as MorphToManyRelation, io as HasOneRelation, lo as BelongsToManyRelation, no as MorphManyRelation, oo as HasManyRelation, ro as HasOneThroughRelation, so as BelongsToRelation, to as MorphOneRelation, uo as Relation } from "../index-ngpa9-9f.mjs";
1
+ import { ao as HasOneThroughRelation, co as HasManyRelation, do as BelongsToManyRelation, fo as Relation, io as MorphManyRelation, lo as BelongsToRelation, no as MorphToManyRelation, oo as HasOneRelation, po as RelationTableLoader, ro as MorphOneRelation, so as HasManyThroughRelation, to as SetBasedEagerLoader, uo as SingleResultRelation } from "../index-Bn-2R_ax.mjs";
2
2
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -1,3 +1,3 @@
1
- import { An as RelationTableLoader, a as HasOneRelation, c as BelongsToRelation, d as Relation, i as HasOneThroughRelation, kn as SetBasedEagerLoader, l as SingleResultRelation, n as MorphOneRelation, o as HasManyThroughRelation, r as MorphManyRelation, s as HasManyRelation, t as MorphToManyRelation, u as BelongsToManyRelation } from "../relationship-DcvK5Xn-.mjs";
1
+ import { Mn as RelationTableLoader, a as HasOneRelation, c as BelongsToRelation, d as Relation, i as HasOneThroughRelation, jn as SetBasedEagerLoader, l as SingleResultRelation, n as MorphOneRelation, o as HasManyThroughRelation, r as MorphManyRelation, s as HasManyRelation, t as MorphToManyRelation, u as BelongsToManyRelation } from "../relationship-BkNxySap.mjs";
2
2
 
3
3
  export { BelongsToManyRelation, BelongsToRelation, HasManyRelation, HasManyThroughRelation, HasOneRelation, HasOneThroughRelation, MorphManyRelation, MorphOneRelation, MorphToManyRelation, Relation, RelationTableLoader, SetBasedEagerLoader, SingleResultRelation };
@@ -1018,18 +1018,21 @@ var TableBuilder = class {
1018
1018
  this.dropColumnNames = [];
1019
1019
  this.indexes = [];
1020
1020
  this.foreignKeys = [];
1021
+ this.compositeUniqueConstraints = [];
1021
1022
  }
1022
- /**
1023
- * Defines a primary key column in the table.
1024
- *
1025
- * @param columnNameOrOptions
1026
- * @param options
1027
- * @returns
1028
- */
1029
1023
  primary(columnNameOrOptions, options) {
1024
+ if (Array.isArray(columnNameOrOptions)) {
1025
+ const columns = this.normalizeCompositeColumns(columnNameOrOptions, "primary key");
1026
+ if (this.compositePrimaryKey) throw new Error("A composite primary key has already been defined for this table.");
1027
+ this.compositePrimaryKey = {
1028
+ columns,
1029
+ ...typeof options === "string" && options.trim() ? { name: options.trim() } : {}
1030
+ };
1031
+ return this;
1032
+ }
1030
1033
  const config = typeof columnNameOrOptions === "string" ? {
1031
1034
  columnName: columnNameOrOptions,
1032
- ...options ?? {}
1035
+ ...typeof options === "object" ? options : {}
1033
1036
  } : columnNameOrOptions ?? {};
1034
1037
  const column = this.resolveColumn(config.columnName);
1035
1038
  column.primary = true;
@@ -1129,15 +1132,19 @@ var TableBuilder = class {
1129
1132
  float(name, options = {}) {
1130
1133
  return this.column(name, "float", options);
1131
1134
  }
1132
- /**
1133
- * Marks a column as unique in the table.
1134
- *
1135
- * @param name Optional explicit column name.
1136
- * When omitted, applies to the latest defined column.
1137
- * @returns The current TableBuilder instance for chaining.
1138
- */
1139
- unique(name) {
1140
- const column = this.resolveColumn(name);
1135
+ unique(columnsOrName, name) {
1136
+ if (Array.isArray(columnsOrName)) {
1137
+ const columns = this.normalizeCompositeColumns(columnsOrName, "unique constraint");
1138
+ const normalizedName = name?.trim();
1139
+ if (this.compositeUniqueConstraints.find((constraint) => constraint.columns.length === columns.length && constraint.columns.every((column, index) => column === columns[index]))) throw new Error(`A unique constraint for columns [${columns.join(", ")}] has already been defined for this table.`);
1140
+ if (normalizedName && this.compositeUniqueConstraints.some((constraint) => constraint.name === normalizedName)) throw new Error(`A unique constraint named [${normalizedName}] has already been defined for this table.`);
1141
+ this.compositeUniqueConstraints.push({
1142
+ columns,
1143
+ ...normalizedName ? { name: normalizedName } : {}
1144
+ });
1145
+ return this;
1146
+ }
1147
+ const column = this.resolveColumn(columnsOrName);
1141
1148
  column.unique = true;
1142
1149
  return this;
1143
1150
  }
@@ -1379,6 +1386,24 @@ var TableBuilder = class {
1379
1386
  return this.foreignKeys.map((foreignKey) => ({ ...foreignKey }));
1380
1387
  }
1381
1388
  /**
1389
+ * Returns a copy of the table-level composite primary key.
1390
+ */
1391
+ getPrimaryKey() {
1392
+ return this.compositePrimaryKey ? {
1393
+ ...this.compositePrimaryKey,
1394
+ columns: [...this.compositePrimaryKey.columns]
1395
+ } : void 0;
1396
+ }
1397
+ /**
1398
+ * Returns copies of table-level composite unique constraints.
1399
+ */
1400
+ getUniqueConstraints() {
1401
+ return this.compositeUniqueConstraints.map((constraint) => ({
1402
+ ...constraint,
1403
+ columns: [...constraint.columns]
1404
+ }));
1405
+ }
1406
+ /**
1382
1407
  * Defines a column in the table with the given name.
1383
1408
  *
1384
1409
  * @param name The name of the column.
@@ -1420,6 +1445,13 @@ var TableBuilder = class {
1420
1445
  if (!column) throw new Error(`Column [${targetName}] was not found in the table definition.`);
1421
1446
  return column;
1422
1447
  }
1448
+ normalizeCompositeColumns(columns, label) {
1449
+ const normalized = columns.map((column) => column.trim());
1450
+ if (normalized.length < 2) throw new Error(`A composite ${label} must contain at least two columns.`);
1451
+ if (normalized.some((column) => !column)) throw new Error(`Composite ${label} columns must be non-empty strings.`);
1452
+ if (new Set(normalized).size !== normalized.length) throw new Error(`Composite ${label} columns must be unique.`);
1453
+ return normalized;
1454
+ }
1423
1455
  };
1424
1456
 
1425
1457
  //#endregion
@@ -1445,12 +1477,17 @@ var SchemaBuilder = class {
1445
1477
  createTable(table, callback) {
1446
1478
  const builder = new TableBuilder();
1447
1479
  callback(builder);
1480
+ const primaryKey = builder.getPrimaryKey();
1481
+ this.validateCompositePrimaryKey(table, primaryKey, builder.getColumns(), true);
1482
+ this.validateCompositeUniqueConstraints(table, builder.getUniqueConstraints(), builder.getColumns(), true);
1448
1483
  this.operations.push({
1449
1484
  type: "createTable",
1450
1485
  table,
1451
1486
  columns: builder.getColumns(),
1452
1487
  indexes: builder.getIndexes(),
1453
- foreignKeys: builder.getForeignKeys()
1488
+ foreignKeys: builder.getForeignKeys(),
1489
+ primaryKey,
1490
+ uniqueConstraints: builder.getUniqueConstraints()
1454
1491
  });
1455
1492
  return this;
1456
1493
  }
@@ -1464,13 +1501,18 @@ var SchemaBuilder = class {
1464
1501
  alterTable(table, callback) {
1465
1502
  const builder = new TableBuilder();
1466
1503
  callback(builder);
1504
+ const primaryKey = builder.getPrimaryKey();
1505
+ this.validateCompositePrimaryKey(table, primaryKey, builder.getColumns(), false);
1506
+ this.validateCompositeUniqueConstraints(table, builder.getUniqueConstraints(), builder.getColumns(), false);
1467
1507
  this.operations.push({
1468
1508
  type: "alterTable",
1469
1509
  table,
1470
1510
  addColumns: builder.getColumns(),
1471
1511
  dropColumns: builder.getDropColumns(),
1472
1512
  addIndexes: builder.getIndexes(),
1473
- addForeignKeys: builder.getForeignKeys()
1513
+ addForeignKeys: builder.getForeignKeys(),
1514
+ addPrimaryKey: primaryKey,
1515
+ addUniqueConstraints: builder.getUniqueConstraints()
1474
1516
  });
1475
1517
  return this;
1476
1518
  }
@@ -1504,7 +1546,15 @@ var SchemaBuilder = class {
1504
1546
  ...index,
1505
1547
  columns: [...index.columns]
1506
1548
  })),
1507
- foreignKeys: operation.foreignKeys.map((foreignKey) => ({ ...foreignKey }))
1549
+ foreignKeys: operation.foreignKeys.map((foreignKey) => ({ ...foreignKey })),
1550
+ primaryKey: operation.primaryKey ? {
1551
+ ...operation.primaryKey,
1552
+ columns: [...operation.primaryKey.columns]
1553
+ } : void 0,
1554
+ uniqueConstraints: operation.uniqueConstraints?.map((constraint) => ({
1555
+ ...constraint,
1556
+ columns: [...constraint.columns]
1557
+ }))
1508
1558
  };
1509
1559
  if (operation.type === "alterTable") return {
1510
1560
  ...operation,
@@ -1517,11 +1567,37 @@ var SchemaBuilder = class {
1517
1567
  ...index,
1518
1568
  columns: [...index.columns]
1519
1569
  })),
1520
- addForeignKeys: operation.addForeignKeys.map((foreignKey) => ({ ...foreignKey }))
1570
+ addForeignKeys: operation.addForeignKeys.map((foreignKey) => ({ ...foreignKey })),
1571
+ addPrimaryKey: operation.addPrimaryKey ? {
1572
+ ...operation.addPrimaryKey,
1573
+ columns: [...operation.addPrimaryKey.columns]
1574
+ } : void 0,
1575
+ addUniqueConstraints: operation.addUniqueConstraints?.map((constraint) => ({
1576
+ ...constraint,
1577
+ columns: [...constraint.columns]
1578
+ }))
1521
1579
  };
1522
1580
  return { ...operation };
1523
1581
  });
1524
1582
  }
1583
+ validateCompositePrimaryKey(table, primaryKey, columns, requireColumns) {
1584
+ if (!primaryKey) return;
1585
+ if (columns.some((column) => column.primary)) throw new Error(`Table [${table}] cannot combine column primary keys with a composite primary key.`);
1586
+ if (!requireColumns) return;
1587
+ primaryKey.columns.forEach((columnName) => {
1588
+ const column = columns.find((candidate) => candidate.name === columnName);
1589
+ if (!column) throw new Error(`Composite primary key column [${columnName}] was not found on table [${table}].`);
1590
+ if (column.nullable) throw new Error(`Composite primary key column [${columnName}] on table [${table}] cannot be nullable.`);
1591
+ });
1592
+ }
1593
+ validateCompositeUniqueConstraints(table, constraints, columns, requireColumns) {
1594
+ if (!requireColumns) return;
1595
+ constraints.forEach((constraint) => {
1596
+ constraint.columns.forEach((columnName) => {
1597
+ if (!columns.some((column) => column.name === columnName)) throw new Error(`Composite unique constraint column [${columnName}] was not found on table [${table}].`);
1598
+ });
1599
+ });
1600
+ }
1525
1601
  };
1526
1602
 
1527
1603
  //#endregion
@@ -1745,6 +1821,24 @@ const buildIndexLine = (index) => {
1745
1821
  return ` @@index([${index.columns.join(", ")}]${typeof index.name === "string" && index.name.trim().length > 0 ? `, name: "${index.name.replace(/"/g, "\\\"")}"` : ""})`;
1746
1822
  };
1747
1823
  /**
1824
+ * Build a Prisma model-level composite primary key definition.
1825
+ *
1826
+ * @param primaryKey
1827
+ * @returns
1828
+ */
1829
+ const buildPrimaryKeyLine = (primaryKey) => {
1830
+ return ` @@id([${primaryKey.columns.join(", ")}]${typeof primaryKey.name === "string" && primaryKey.name.trim().length > 0 ? `, name: "${primaryKey.name.replace(/"/g, "\\\"")}"` : ""})`;
1831
+ };
1832
+ /**
1833
+ * Build a Prisma model-level composite unique constraint definition.
1834
+ *
1835
+ * @param constraint
1836
+ * @returns
1837
+ */
1838
+ const buildUniqueConstraintLine = (constraint) => {
1839
+ return ` @@unique([${constraint.columns.join(", ")}]${typeof constraint.name === "string" && constraint.name.trim().length > 0 ? `, name: "${constraint.name.replace(/"/g, "\\\"")}"` : ""})`;
1840
+ };
1841
+ /**
1748
1842
  * Derive a relation field name from a foreign key column name by applying
1749
1843
  * common conventions, such as removing "Id" suffixes and converting to camelCase.
1750
1844
  *
@@ -1893,7 +1987,14 @@ const buildModelBlock = (operation) => {
1893
1987
  const mapped = operation.table !== modelName.toLowerCase();
1894
1988
  const fields = operation.columns.map(buildFieldLine);
1895
1989
  const relations = (operation.foreignKeys ?? []).map((foreignKey) => buildRelationLine(modelName, foreignKey, operation.columns));
1896
- const metadata = [...(operation.indexes ?? []).map(buildIndexLine), ...mapped ? [` @@map("${str(operation.table).snake()}")`] : []];
1990
+ const indexes = (operation.indexes ?? []).map(buildIndexLine);
1991
+ const uniqueConstraints = (operation.uniqueConstraints ?? []).map(buildUniqueConstraintLine);
1992
+ const metadata = [
1993
+ ...operation.primaryKey ? [buildPrimaryKeyLine(operation.primaryKey)] : [],
1994
+ ...uniqueConstraints,
1995
+ ...indexes,
1996
+ ...mapped ? [` @@map("${str(operation.table).snake()}")`] : []
1997
+ ];
1897
1998
  return `model ${modelName} {\n${(metadata.length > 0 ? [
1898
1999
  ...fields,
1899
2000
  ...relations,
@@ -1990,6 +2091,18 @@ const applyAlterTableOperation = (schema, operation) => {
1990
2091
  const insertIndex = Math.max(1, bodyLines.length - 1);
1991
2092
  bodyLines.splice(insertIndex, 0, indexLine);
1992
2093
  });
2094
+ if (operation.addPrimaryKey) {
2095
+ const primaryKeyLine = buildPrimaryKeyLine(operation.addPrimaryKey);
2096
+ if (bodyLines.some((line) => line.includes(" @id") || line.trim().startsWith("@@id("))) throw new ArkormException(`Prisma model for table [${operation.table}] already defines a primary key.`);
2097
+ const insertIndex = Math.max(1, bodyLines.length - 1);
2098
+ bodyLines.splice(insertIndex, 0, primaryKeyLine);
2099
+ }
2100
+ for (const constraint of operation.addUniqueConstraints ?? []) {
2101
+ const constraintLine = buildUniqueConstraintLine(constraint);
2102
+ if (bodyLines.some((line) => line.trim() === constraintLine.trim())) continue;
2103
+ const insertIndex = Math.max(1, bodyLines.length - 1);
2104
+ bodyLines.splice(insertIndex, 0, constraintLine);
2105
+ }
1993
2106
  for (const foreignKey of operation.addForeignKeys ?? []) {
1994
2107
  const relationLine = buildRelationLine(model.modelName, foreignKey, operation.addColumns);
1995
2108
  const relationRegex = new RegExp(`^\\s*${escapeRegex(foreignKey.fieldAlias?.trim() || deriveRelationFieldName(foreignKey.column))}\\s+`);
@@ -4866,4 +4979,4 @@ var MorphToManyRelation = class extends Relation {
4866
4979
  };
4867
4980
 
4868
4981
  //#endregion
4869
- export { deletePersistedColumnMappingsState as $, supportsDatabaseCreation as $t, isDelegateLike as A, RelationTableLoader as An, buildModelBlock as At, getRegisteredSeeders as B, findModelBlock as Bt, getRuntimeAdapter as C, resolveMigrationStateFilePath as Cn, applyMigrationToPrismaSchema as Ct, getRuntimePaginationURLDriverFactory as D, RuntimeModuleLoader as Dn, buildIndexLine as Dt, getRuntimePaginationCurrentPageResolver as E, writeAppliedMigrationsStateToStore as En, buildFieldLine as Et, runArkormTransaction as F, deriveRelationAlias as Ft, registerFactories as G, getMigrationPlan as Gt, loadMigrationsFrom as H, formatEnumDefaultValue as Ht, getRegisteredFactories as I, deriveRelationFieldName as It, registerPaths as J, resolveMigrationClassName as Jt, registerMigrations as K, pad as Kt, getRegisteredMigrations as L, deriveSingularFieldName as Lt, isTransactionCapableClient as M, ArkormCollection as Mn, createMigrationTimestamp as Mt, loadArkormConfig as N, ArkormException as Nn, deriveCollectionFieldName as Nt, getRuntimePrismaClient as O, UnsupportedAdapterFeatureException as On, buildInverseRelationLine as Ot, resetArkormRuntimeForTests as P, deriveInverseRelationAlias as Pt, createEmptyPersistedColumnMappingsState as Q, stripPrismaSchemaModelsAndEnums as Qt, getRegisteredModels as R, escapeRegex as Rt, getDefaultStubsPath as S, removeAppliedMigration as Sn, applyMigrationToDatabase as St, getRuntimeDebugHandler as T, writeAppliedMigrationsState as Tn, buildEnumBlock as Tt, loadModelsFrom as U, formatRelationAction as Ut, loadFactoriesFrom as V, formatDefaultValue as Vt, loadSeedersFrom as W, generateMigrationFile as Wt, resetRuntimeRegistryForTests as X, runMigrationWithPrisma as Xt, registerSeeders as Y, resolvePrismaType as Yt, applyOperationsToPersistedColumnMappingsState as Z, runPrismaCommand as Zt, defineConfig as _, isMigrationApplied as _n, applyAlterTableOperation as _t, HasOneRelation as a, EnumBuilder as an, getPersistedTimestampColumns as at, getActiveTransactionAdapter as b, readAppliedMigrationsState as bn, applyMigrationRollbackToDatabase as bt, BelongsToRelation as c, PrimaryKeyGenerationPlanner as cn, resetPersistedColumnMappingsCache as ct, Relation as d, computeMigrationChecksum as dn, syncPersistedColumnMappingsFromState as dt, supportsDatabaseMigrationExecution as en, getPersistedColumnMap as et, LengthAwarePaginator as f, createEmptyAppliedMigrationsState as fn, validatePersistedMetadataFeaturesForMigrations as ft, configureArkormRuntime as g, getLatestAppliedMigrations as gn, PRISMA_MODEL_REGEX as gt, bindAdapterToModels as h, getLastMigrationRun as hn, PRISMA_ENUM_REGEX as ht, HasOneThroughRelation as i, SchemaBuilder as in, getPersistedTableMetadata as it, isQuerySchemaLike as j, RelationResolutionException as jn, buildRelationLine as jt, getUserConfig as k, SetBasedEagerLoader as kn, buildMigrationSource as kt, SingleResultRelation as l, buildMigrationIdentity as ln, resolveColumnMappingsFilePath as lt, URLDriver as m, findAppliedMigration as mn, PRISMA_ENUM_MEMBER_REGEX as mt, MorphOneRelation as n, toMigrationFileSlug as nn, getPersistedEnumTsType as nt, HasManyThroughRelation as o, TableBuilder as on, readPersistedColumnMappingsState as ot, Paginator as p, deleteAppliedMigrationsStateFromStore as pn, writePersistedColumnMappingsState as pt, registerModels as q, resolveEnumName as qt, MorphManyRelation as r, toModelName as rn, getPersistedPrimaryKeyGeneration as rt, HasManyRelation as s, ForeignKeyBuilder as sn, rebuildPersistedColumnMappingsState as st, MorphToManyRelation as t, supportsDatabaseReset as tn, getPersistedEnumMap as tt, BelongsToManyRelation as u, buildMigrationRunId as un, resolvePersistedMetadataFeatures as ut, emitRuntimeDebugEvent as v, markMigrationApplied as vn, applyCreateTableOperation as vt, getRuntimeClient as w, supportsDatabaseMigrationState as wn, applyOperationsToPrismaSchema as wt, getActiveTransactionClient as x, readAppliedMigrationsStateFromStore as xn, applyMigrationRollbackToPrismaSchema as xt, ensureArkormConfigLoading as y, markMigrationRun as yn, applyDropTableOperation as yt, getRegisteredPaths as z, findEnumBlock as zt };
4982
+ export { deletePersistedColumnMappingsState as $, runPrismaCommand as $t, isDelegateLike as A, UnsupportedAdapterFeatureException as An, buildModelBlock as At, getRegisteredSeeders as B, escapeRegex as Bt, getRuntimeAdapter as C, readAppliedMigrationsStateFromStore as Cn, applyMigrationToPrismaSchema as Ct, getRuntimePaginationURLDriverFactory as D, writeAppliedMigrationsState as Dn, buildIndexLine as Dt, getRuntimePaginationCurrentPageResolver as E, supportsDatabaseMigrationState as En, buildFieldLine as Et, runArkormTransaction as F, ArkormException as Fn, deriveCollectionFieldName as Ft, registerFactories as G, formatRelationAction as Gt, loadMigrationsFrom as H, findModelBlock as Ht, getRegisteredFactories as I, deriveInverseRelationAlias as It, registerPaths as J, pad as Jt, registerMigrations as K, generateMigrationFile as Kt, getRegisteredMigrations as L, deriveRelationAlias as Lt, isTransactionCapableClient as M, RelationTableLoader as Mn, buildRelationLine as Mt, loadArkormConfig as N, RelationResolutionException as Nn, buildUniqueConstraintLine as Nt, getRuntimePrismaClient as O, writeAppliedMigrationsStateToStore as On, buildInverseRelationLine as Ot, resetArkormRuntimeForTests as P, ArkormCollection as Pn, createMigrationTimestamp as Pt, createEmptyPersistedColumnMappingsState as Q, runMigrationWithPrisma as Qt, getRegisteredModels as R, deriveRelationFieldName as Rt, getDefaultStubsPath as S, readAppliedMigrationsState as Sn, applyMigrationToDatabase as St, getRuntimeDebugHandler as T, resolveMigrationStateFilePath as Tn, buildEnumBlock as Tt, loadModelsFrom as U, formatDefaultValue as Ut, loadFactoriesFrom as V, findEnumBlock as Vt, loadSeedersFrom as W, formatEnumDefaultValue as Wt, resetRuntimeRegistryForTests as X, resolveMigrationClassName as Xt, registerSeeders as Y, resolveEnumName as Yt, applyOperationsToPersistedColumnMappingsState as Z, resolvePrismaType as Zt, defineConfig as _, getLastMigrationRun as _n, applyAlterTableOperation as _t, HasOneRelation as a, toModelName as an, getPersistedTimestampColumns as at, getActiveTransactionAdapter as b, markMigrationApplied as bn, applyMigrationRollbackToDatabase as bt, BelongsToRelation as c, TableBuilder as cn, resetPersistedColumnMappingsCache as ct, Relation as d, buildMigrationIdentity as dn, syncPersistedColumnMappingsFromState as dt, stripPrismaSchemaModelsAndEnums as en, getPersistedColumnMap as et, LengthAwarePaginator as f, buildMigrationRunId as fn, validatePersistedMetadataFeaturesForMigrations as ft, configureArkormRuntime as g, findAppliedMigration as gn, PRISMA_MODEL_REGEX as gt, bindAdapterToModels as h, deleteAppliedMigrationsStateFromStore as hn, PRISMA_ENUM_REGEX as ht, HasOneThroughRelation as i, toMigrationFileSlug as in, getPersistedTableMetadata as it, isQuerySchemaLike as j, SetBasedEagerLoader as jn, buildPrimaryKeyLine as jt, getUserConfig as k, RuntimeModuleLoader as kn, buildMigrationSource as kt, SingleResultRelation as l, ForeignKeyBuilder as ln, resolveColumnMappingsFilePath as lt, URLDriver as m, createEmptyAppliedMigrationsState as mn, PRISMA_ENUM_MEMBER_REGEX as mt, MorphOneRelation as n, supportsDatabaseMigrationExecution as nn, getPersistedEnumTsType as nt, HasManyThroughRelation as o, SchemaBuilder as on, readPersistedColumnMappingsState as ot, Paginator as p, computeMigrationChecksum as pn, writePersistedColumnMappingsState as pt, registerModels as q, getMigrationPlan as qt, MorphManyRelation as r, supportsDatabaseReset as rn, getPersistedPrimaryKeyGeneration as rt, HasManyRelation as s, EnumBuilder as sn, rebuildPersistedColumnMappingsState as st, MorphToManyRelation as t, supportsDatabaseCreation as tn, getPersistedEnumMap as tt, BelongsToManyRelation as u, PrimaryKeyGenerationPlanner as un, resolvePersistedMetadataFeatures as ut, emitRuntimeDebugEvent as v, getLatestAppliedMigrations as vn, applyCreateTableOperation as vt, getRuntimeClient as w, removeAppliedMigration as wn, applyOperationsToPrismaSchema as wt, getActiveTransactionClient as x, markMigrationRun as xn, applyMigrationRollbackToPrismaSchema as xt, ensureArkormConfigLoading as y, isMigrationApplied as yn, applyDropTableOperation as yt, getRegisteredPaths as z, deriveSingularFieldName as zt };
@@ -1046,18 +1046,21 @@ var TableBuilder = class {
1046
1046
  this.dropColumnNames = [];
1047
1047
  this.indexes = [];
1048
1048
  this.foreignKeys = [];
1049
+ this.compositeUniqueConstraints = [];
1049
1050
  }
1050
- /**
1051
- * Defines a primary key column in the table.
1052
- *
1053
- * @param columnNameOrOptions
1054
- * @param options
1055
- * @returns
1056
- */
1057
1051
  primary(columnNameOrOptions, options) {
1052
+ if (Array.isArray(columnNameOrOptions)) {
1053
+ const columns = this.normalizeCompositeColumns(columnNameOrOptions, "primary key");
1054
+ if (this.compositePrimaryKey) throw new Error("A composite primary key has already been defined for this table.");
1055
+ this.compositePrimaryKey = {
1056
+ columns,
1057
+ ...typeof options === "string" && options.trim() ? { name: options.trim() } : {}
1058
+ };
1059
+ return this;
1060
+ }
1058
1061
  const config = typeof columnNameOrOptions === "string" ? {
1059
1062
  columnName: columnNameOrOptions,
1060
- ...options ?? {}
1063
+ ...typeof options === "object" ? options : {}
1061
1064
  } : columnNameOrOptions ?? {};
1062
1065
  const column = this.resolveColumn(config.columnName);
1063
1066
  column.primary = true;
@@ -1157,15 +1160,19 @@ var TableBuilder = class {
1157
1160
  float(name, options = {}) {
1158
1161
  return this.column(name, "float", options);
1159
1162
  }
1160
- /**
1161
- * Marks a column as unique in the table.
1162
- *
1163
- * @param name Optional explicit column name.
1164
- * When omitted, applies to the latest defined column.
1165
- * @returns The current TableBuilder instance for chaining.
1166
- */
1167
- unique(name) {
1168
- const column = this.resolveColumn(name);
1163
+ unique(columnsOrName, name) {
1164
+ if (Array.isArray(columnsOrName)) {
1165
+ const columns = this.normalizeCompositeColumns(columnsOrName, "unique constraint");
1166
+ const normalizedName = name?.trim();
1167
+ if (this.compositeUniqueConstraints.find((constraint) => constraint.columns.length === columns.length && constraint.columns.every((column, index) => column === columns[index]))) throw new Error(`A unique constraint for columns [${columns.join(", ")}] has already been defined for this table.`);
1168
+ if (normalizedName && this.compositeUniqueConstraints.some((constraint) => constraint.name === normalizedName)) throw new Error(`A unique constraint named [${normalizedName}] has already been defined for this table.`);
1169
+ this.compositeUniqueConstraints.push({
1170
+ columns,
1171
+ ...normalizedName ? { name: normalizedName } : {}
1172
+ });
1173
+ return this;
1174
+ }
1175
+ const column = this.resolveColumn(columnsOrName);
1169
1176
  column.unique = true;
1170
1177
  return this;
1171
1178
  }
@@ -1407,6 +1414,24 @@ var TableBuilder = class {
1407
1414
  return this.foreignKeys.map((foreignKey) => ({ ...foreignKey }));
1408
1415
  }
1409
1416
  /**
1417
+ * Returns a copy of the table-level composite primary key.
1418
+ */
1419
+ getPrimaryKey() {
1420
+ return this.compositePrimaryKey ? {
1421
+ ...this.compositePrimaryKey,
1422
+ columns: [...this.compositePrimaryKey.columns]
1423
+ } : void 0;
1424
+ }
1425
+ /**
1426
+ * Returns copies of table-level composite unique constraints.
1427
+ */
1428
+ getUniqueConstraints() {
1429
+ return this.compositeUniqueConstraints.map((constraint) => ({
1430
+ ...constraint,
1431
+ columns: [...constraint.columns]
1432
+ }));
1433
+ }
1434
+ /**
1410
1435
  * Defines a column in the table with the given name.
1411
1436
  *
1412
1437
  * @param name The name of the column.
@@ -1448,6 +1473,13 @@ var TableBuilder = class {
1448
1473
  if (!column) throw new Error(`Column [${targetName}] was not found in the table definition.`);
1449
1474
  return column;
1450
1475
  }
1476
+ normalizeCompositeColumns(columns, label) {
1477
+ const normalized = columns.map((column) => column.trim());
1478
+ if (normalized.length < 2) throw new Error(`A composite ${label} must contain at least two columns.`);
1479
+ if (normalized.some((column) => !column)) throw new Error(`Composite ${label} columns must be non-empty strings.`);
1480
+ if (new Set(normalized).size !== normalized.length) throw new Error(`Composite ${label} columns must be unique.`);
1481
+ return normalized;
1482
+ }
1451
1483
  };
1452
1484
 
1453
1485
  //#endregion
@@ -1473,12 +1505,17 @@ var SchemaBuilder = class {
1473
1505
  createTable(table, callback) {
1474
1506
  const builder = new TableBuilder();
1475
1507
  callback(builder);
1508
+ const primaryKey = builder.getPrimaryKey();
1509
+ this.validateCompositePrimaryKey(table, primaryKey, builder.getColumns(), true);
1510
+ this.validateCompositeUniqueConstraints(table, builder.getUniqueConstraints(), builder.getColumns(), true);
1476
1511
  this.operations.push({
1477
1512
  type: "createTable",
1478
1513
  table,
1479
1514
  columns: builder.getColumns(),
1480
1515
  indexes: builder.getIndexes(),
1481
- foreignKeys: builder.getForeignKeys()
1516
+ foreignKeys: builder.getForeignKeys(),
1517
+ primaryKey,
1518
+ uniqueConstraints: builder.getUniqueConstraints()
1482
1519
  });
1483
1520
  return this;
1484
1521
  }
@@ -1492,13 +1529,18 @@ var SchemaBuilder = class {
1492
1529
  alterTable(table, callback) {
1493
1530
  const builder = new TableBuilder();
1494
1531
  callback(builder);
1532
+ const primaryKey = builder.getPrimaryKey();
1533
+ this.validateCompositePrimaryKey(table, primaryKey, builder.getColumns(), false);
1534
+ this.validateCompositeUniqueConstraints(table, builder.getUniqueConstraints(), builder.getColumns(), false);
1495
1535
  this.operations.push({
1496
1536
  type: "alterTable",
1497
1537
  table,
1498
1538
  addColumns: builder.getColumns(),
1499
1539
  dropColumns: builder.getDropColumns(),
1500
1540
  addIndexes: builder.getIndexes(),
1501
- addForeignKeys: builder.getForeignKeys()
1541
+ addForeignKeys: builder.getForeignKeys(),
1542
+ addPrimaryKey: primaryKey,
1543
+ addUniqueConstraints: builder.getUniqueConstraints()
1502
1544
  });
1503
1545
  return this;
1504
1546
  }
@@ -1532,7 +1574,15 @@ var SchemaBuilder = class {
1532
1574
  ...index,
1533
1575
  columns: [...index.columns]
1534
1576
  })),
1535
- foreignKeys: operation.foreignKeys.map((foreignKey) => ({ ...foreignKey }))
1577
+ foreignKeys: operation.foreignKeys.map((foreignKey) => ({ ...foreignKey })),
1578
+ primaryKey: operation.primaryKey ? {
1579
+ ...operation.primaryKey,
1580
+ columns: [...operation.primaryKey.columns]
1581
+ } : void 0,
1582
+ uniqueConstraints: operation.uniqueConstraints?.map((constraint) => ({
1583
+ ...constraint,
1584
+ columns: [...constraint.columns]
1585
+ }))
1536
1586
  };
1537
1587
  if (operation.type === "alterTable") return {
1538
1588
  ...operation,
@@ -1545,11 +1595,37 @@ var SchemaBuilder = class {
1545
1595
  ...index,
1546
1596
  columns: [...index.columns]
1547
1597
  })),
1548
- addForeignKeys: operation.addForeignKeys.map((foreignKey) => ({ ...foreignKey }))
1598
+ addForeignKeys: operation.addForeignKeys.map((foreignKey) => ({ ...foreignKey })),
1599
+ addPrimaryKey: operation.addPrimaryKey ? {
1600
+ ...operation.addPrimaryKey,
1601
+ columns: [...operation.addPrimaryKey.columns]
1602
+ } : void 0,
1603
+ addUniqueConstraints: operation.addUniqueConstraints?.map((constraint) => ({
1604
+ ...constraint,
1605
+ columns: [...constraint.columns]
1606
+ }))
1549
1607
  };
1550
1608
  return { ...operation };
1551
1609
  });
1552
1610
  }
1611
+ validateCompositePrimaryKey(table, primaryKey, columns, requireColumns) {
1612
+ if (!primaryKey) return;
1613
+ if (columns.some((column) => column.primary)) throw new Error(`Table [${table}] cannot combine column primary keys with a composite primary key.`);
1614
+ if (!requireColumns) return;
1615
+ primaryKey.columns.forEach((columnName) => {
1616
+ const column = columns.find((candidate) => candidate.name === columnName);
1617
+ if (!column) throw new Error(`Composite primary key column [${columnName}] was not found on table [${table}].`);
1618
+ if (column.nullable) throw new Error(`Composite primary key column [${columnName}] on table [${table}] cannot be nullable.`);
1619
+ });
1620
+ }
1621
+ validateCompositeUniqueConstraints(table, constraints, columns, requireColumns) {
1622
+ if (!requireColumns) return;
1623
+ constraints.forEach((constraint) => {
1624
+ constraint.columns.forEach((columnName) => {
1625
+ if (!columns.some((column) => column.name === columnName)) throw new Error(`Composite unique constraint column [${columnName}] was not found on table [${table}].`);
1626
+ });
1627
+ });
1628
+ }
1553
1629
  };
1554
1630
 
1555
1631
  //#endregion
@@ -1773,6 +1849,24 @@ const buildIndexLine = (index) => {
1773
1849
  return ` @@index([${index.columns.join(", ")}]${typeof index.name === "string" && index.name.trim().length > 0 ? `, name: "${index.name.replace(/"/g, "\\\"")}"` : ""})`;
1774
1850
  };
1775
1851
  /**
1852
+ * Build a Prisma model-level composite primary key definition.
1853
+ *
1854
+ * @param primaryKey
1855
+ * @returns
1856
+ */
1857
+ const buildPrimaryKeyLine = (primaryKey) => {
1858
+ return ` @@id([${primaryKey.columns.join(", ")}]${typeof primaryKey.name === "string" && primaryKey.name.trim().length > 0 ? `, name: "${primaryKey.name.replace(/"/g, "\\\"")}"` : ""})`;
1859
+ };
1860
+ /**
1861
+ * Build a Prisma model-level composite unique constraint definition.
1862
+ *
1863
+ * @param constraint
1864
+ * @returns
1865
+ */
1866
+ const buildUniqueConstraintLine = (constraint) => {
1867
+ return ` @@unique([${constraint.columns.join(", ")}]${typeof constraint.name === "string" && constraint.name.trim().length > 0 ? `, name: "${constraint.name.replace(/"/g, "\\\"")}"` : ""})`;
1868
+ };
1869
+ /**
1776
1870
  * Derive a relation field name from a foreign key column name by applying
1777
1871
  * common conventions, such as removing "Id" suffixes and converting to camelCase.
1778
1872
  *
@@ -1921,7 +2015,14 @@ const buildModelBlock = (operation) => {
1921
2015
  const mapped = operation.table !== modelName.toLowerCase();
1922
2016
  const fields = operation.columns.map(buildFieldLine);
1923
2017
  const relations = (operation.foreignKeys ?? []).map((foreignKey) => buildRelationLine(modelName, foreignKey, operation.columns));
1924
- const metadata = [...(operation.indexes ?? []).map(buildIndexLine), ...mapped ? [` @@map("${(0, _h3ravel_support.str)(operation.table).snake()}")`] : []];
2018
+ const indexes = (operation.indexes ?? []).map(buildIndexLine);
2019
+ const uniqueConstraints = (operation.uniqueConstraints ?? []).map(buildUniqueConstraintLine);
2020
+ const metadata = [
2021
+ ...operation.primaryKey ? [buildPrimaryKeyLine(operation.primaryKey)] : [],
2022
+ ...uniqueConstraints,
2023
+ ...indexes,
2024
+ ...mapped ? [` @@map("${(0, _h3ravel_support.str)(operation.table).snake()}")`] : []
2025
+ ];
1925
2026
  return `model ${modelName} {\n${(metadata.length > 0 ? [
1926
2027
  ...fields,
1927
2028
  ...relations,
@@ -2018,6 +2119,18 @@ const applyAlterTableOperation = (schema, operation) => {
2018
2119
  const insertIndex = Math.max(1, bodyLines.length - 1);
2019
2120
  bodyLines.splice(insertIndex, 0, indexLine);
2020
2121
  });
2122
+ if (operation.addPrimaryKey) {
2123
+ const primaryKeyLine = buildPrimaryKeyLine(operation.addPrimaryKey);
2124
+ if (bodyLines.some((line) => line.includes(" @id") || line.trim().startsWith("@@id("))) throw new ArkormException(`Prisma model for table [${operation.table}] already defines a primary key.`);
2125
+ const insertIndex = Math.max(1, bodyLines.length - 1);
2126
+ bodyLines.splice(insertIndex, 0, primaryKeyLine);
2127
+ }
2128
+ for (const constraint of operation.addUniqueConstraints ?? []) {
2129
+ const constraintLine = buildUniqueConstraintLine(constraint);
2130
+ if (bodyLines.some((line) => line.trim() === constraintLine.trim())) continue;
2131
+ const insertIndex = Math.max(1, bodyLines.length - 1);
2132
+ bodyLines.splice(insertIndex, 0, constraintLine);
2133
+ }
2021
2134
  for (const foreignKey of operation.addForeignKeys ?? []) {
2022
2135
  const relationLine = buildRelationLine(model.modelName, foreignKey, operation.addColumns);
2023
2136
  const relationRegex = new RegExp(`^\\s*${escapeRegex(foreignKey.fieldAlias?.trim() || deriveRelationFieldName(foreignKey.column))}\\s+`);
@@ -5182,12 +5295,24 @@ Object.defineProperty(exports, 'buildModelBlock', {
5182
5295
  return buildModelBlock;
5183
5296
  }
5184
5297
  });
5298
+ Object.defineProperty(exports, 'buildPrimaryKeyLine', {
5299
+ enumerable: true,
5300
+ get: function () {
5301
+ return buildPrimaryKeyLine;
5302
+ }
5303
+ });
5185
5304
  Object.defineProperty(exports, 'buildRelationLine', {
5186
5305
  enumerable: true,
5187
5306
  get: function () {
5188
5307
  return buildRelationLine;
5189
5308
  }
5190
5309
  });
5310
+ Object.defineProperty(exports, 'buildUniqueConstraintLine', {
5311
+ enumerable: true,
5312
+ get: function () {
5313
+ return buildUniqueConstraintLine;
5314
+ }
5315
+ });
5191
5316
  Object.defineProperty(exports, 'computeMigrationChecksum', {
5192
5317
  enumerable: true,
5193
5318
  get: function () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkormx",
3
- "version": "2.4.5",
3
+ "version": "2.4.7",
4
4
  "description": "Modern TypeScript-first ORM for Node.js.",
5
5
  "keywords": [
6
6
  "orm",
@@ -60,7 +60,7 @@
60
60
  "@types/node": "^25.6.2",
61
61
  "@types/pg": "^8.16.0",
62
62
  "@viteplus/versions": "^2.0.6",
63
- "@vitest/coverage-v8": "^4.1.5",
63
+ "@vitest/coverage-v8": "^4.1.8",
64
64
  "barrelize": "^1.7.3",
65
65
  "dotenv": "^17.3.1",
66
66
  "eslint": "^10.3.0",
@@ -73,7 +73,7 @@
73
73
  "unrun": "^0.3.0",
74
74
  "vite-plugin-swc-transform": "^1.1.1",
75
75
  "vitepress": "^2.0.0-alpha.17",
76
- "vitest": "^4.1.5"
76
+ "vitest": "^4.1.8"
77
77
  },
78
78
  "engines": {
79
79
  "node": ">=20.0.0"