@zenstackhq/orm 3.9.7 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  enumerable: true
31
31
  }) : target, mod));
32
32
  //#endregion
33
+ const require_constants = require("./constants-CcJSpq4B.cjs");
33
34
  const require_common_types = require("./common-types.cjs");
34
35
  let _zenstackhq_common_helpers = require("@zenstackhq/common-helpers");
35
36
  let kysely = require("kysely");
@@ -243,6 +244,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
243
244
  isEnum: () => isEnum,
244
245
  isForeignKeyField: () => isForeignKeyField,
245
246
  isInheritedField: () => isInheritedField,
247
+ isPrimitiveTypeDef: () => isPrimitiveTypeDef,
246
248
  isRelationField: () => isRelationField,
247
249
  isScalarField: () => isScalarField,
248
250
  isTypeDef: () => isTypeDef,
@@ -423,6 +425,9 @@ function getEnum(schema, type) {
423
425
  function isTypeDef(schema, type) {
424
426
  return !!schema.typeDefs?.[type];
425
427
  }
428
+ function isPrimitiveTypeDef(schema, type) {
429
+ return !!schema.typeDefs?.[type]?.base;
430
+ }
426
431
  function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
427
432
  const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
428
433
  return keyPairs.map(({ fk, pk }) => {
@@ -578,75 +583,6 @@ function tmpAlias(name) {
578
583
  else return name;
579
584
  }
580
585
  //#endregion
581
- //#region src/client/constants.ts
582
- /**
583
- * The types of fields that are numeric.
584
- */
585
- const NUMERIC_FIELD_TYPES = [
586
- "Int",
587
- "Float",
588
- "BigInt",
589
- "Decimal"
590
- ];
591
- /**
592
- * Prefix for JSON field used to store joined delegate rows.
593
- */
594
- const DELEGATE_JOINED_FIELD_PREFIX = "$delegate$";
595
- /**
596
- * Logical combinators used in filters.
597
- */
598
- const LOGICAL_COMBINATORS = [
599
- "AND",
600
- "OR",
601
- "NOT"
602
- ];
603
- /**
604
- * Aggregation operators.
605
- */
606
- const AggregateOperators = [
607
- "_count",
608
- "_sum",
609
- "_avg",
610
- "_min",
611
- "_max"
612
- ];
613
- /**
614
- * Mapping of filter operators to their corresponding filter kind categories.
615
- */
616
- const FILTER_PROPERTY_TO_KIND = {
617
- equals: "Equality",
618
- not: "Equality",
619
- in: "Equality",
620
- notIn: "Equality",
621
- lt: "Range",
622
- lte: "Range",
623
- gt: "Range",
624
- gte: "Range",
625
- between: "Range",
626
- contains: "Like",
627
- startsWith: "Like",
628
- endsWith: "Like",
629
- mode: "Like",
630
- is: "Relation",
631
- isNot: "Relation",
632
- some: "Relation",
633
- every: "Relation",
634
- none: "Relation",
635
- path: "Json",
636
- string_contains: "Json",
637
- string_starts_with: "Json",
638
- string_ends_with: "Json",
639
- array_contains: "Json",
640
- array_starts_with: "Json",
641
- array_ends_with: "Json",
642
- fuzzy: "Fuzzy",
643
- fts: "FullText",
644
- has: "List",
645
- hasEvery: "List",
646
- hasSome: "List",
647
- isEmpty: "List"
648
- };
649
- //#endregion
650
586
  //#region src/client/contract.ts
651
587
  /**
652
588
  * Transaction isolation levels.
@@ -795,12 +731,12 @@ var BaseCrudDialect = class {
795
731
  const { args: _args, ...rest } = payload;
796
732
  filterPayload = rest;
797
733
  }
798
- const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias, true, computedArgs);
734
+ const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, this.delegateFieldAlias(model, modelAlias, fieldDef), true, computedArgs);
799
735
  if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
800
736
  else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
801
737
  }
802
738
  }
803
- if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb));
739
+ if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb, { modelAlias }));
804
740
  return result;
805
741
  }
806
742
  buildCursorFilter(model, query, cursor, orderBy, negateOrderBy, modelAlias) {
@@ -815,8 +751,8 @@ var BaseCrudDialect = class {
815
751
  const [field, order] = orderByItems[j];
816
752
  const op = j === i ? (negateOrderBy ? order === "asc" ? "desc" : "asc" : order) === "asc" ? ">=" : "<=" : "=";
817
753
  const fieldDef = requireField(this.schema, model, field);
818
- const outerAlias = fieldDef.originModel ?? modelAlias;
819
- const subSelectAlias = fieldDef.originModel ?? subQueryAlias;
754
+ const outerAlias = this.delegateFieldAlias(model, modelAlias, fieldDef);
755
+ const subSelectAlias = this.delegateFieldAlias(model, subQueryAlias, fieldDef);
820
756
  andFilters.push(this.eb(this.eb.ref(`${outerAlias}.${field}`), op, this.buildSelectModel(model, subQueryAlias).select(`${subSelectAlias}.${field}`).where(cursorFilter)));
821
757
  }
822
758
  filters.push(this.eb.and(andFilters));
@@ -825,7 +761,7 @@ var BaseCrudDialect = class {
825
761
  return result;
826
762
  }
827
763
  isLogicalCombinator(key) {
828
- return LOGICAL_COMBINATORS.includes(key);
764
+ return require_constants.LOGICAL_COMBINATORS.includes(key);
829
765
  }
830
766
  buildCompositeFilter(model, modelAlias, key, payload) {
831
767
  const normalizedFilters = (0, _zenstackhq_common_helpers.enumerate)(payload).filter((el) => {
@@ -854,7 +790,7 @@ var BaseCrudDialect = class {
854
790
  else return this.buildToOneRelationFilter(model, modelAlias, field, fieldDef, { is: null });
855
791
  }
856
792
  const joinAlias = tmpAlias(`${modelAlias}$${field}`);
857
- const joinPairs = buildJoinPairs(this.schema, model, fieldDef.originModel ?? modelAlias, field, joinAlias);
793
+ const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
858
794
  const baseJoin = this.buildSelectModel(fieldDef.type, joinAlias).select(this.eb.lit(1).as("_")).where(() => this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), "=", this.eb.ref(right)))));
859
795
  const existsSelect = (extraFilter) => {
860
796
  const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
@@ -948,11 +884,13 @@ var BaseCrudDialect = class {
948
884
  buildPrimitiveFilter(fieldRef, fieldDef, payload) {
949
885
  if (payload === null) return this.eb(fieldRef, "is", null);
950
886
  if (isEnum(this.schema, fieldDef.type)) return this.buildEnumFilter(fieldRef, fieldDef, payload);
951
- if (isTypeDef(this.schema, fieldDef.type)) {
887
+ let type = fieldDef.type;
888
+ if (isTypeDef(this.schema, fieldDef.type)) if (isPrimitiveTypeDef(this.schema, fieldDef.type)) type = this.schema["typeDefs"][fieldDef.type]["base"];
889
+ else {
952
890
  if (payload instanceof require_common_types.DbNullClass || payload instanceof require_common_types.JsonNullClass || payload instanceof require_common_types.AnyNullClass) return this.buildJsonValueFilterClause(fieldRef, payload);
953
891
  return this.buildJsonFilter(fieldRef, payload, fieldDef);
954
892
  }
955
- return (0, ts_pattern.match)(fieldDef.type).with("String", () => this.buildStringFilter(fieldRef, payload, fieldDef)).with(ts_pattern.P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(fieldRef, type, payload)).with("Boolean", () => this.buildBooleanFilter(fieldRef, payload)).with("DateTime", () => this.buildDateTimeFilter(fieldRef, payload)).with("Bytes", () => this.buildBytesFilter(fieldRef, payload)).with("Json", () => this.buildJsonFilter(fieldRef, payload, fieldDef)).with("Unsupported", () => {
893
+ return (0, ts_pattern.match)(type).with("String", () => this.buildStringFilter(fieldRef, payload, fieldDef)).with(ts_pattern.P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(fieldRef, type, payload)).with("Boolean", () => this.buildBooleanFilter(fieldRef, payload)).with("DateTime", () => this.buildDateTimeFilter(fieldRef, payload)).with("Bytes", () => this.buildBytesFilter(fieldRef, payload)).with("Json", () => this.buildJsonFilter(fieldRef, payload, fieldDef)).with("Unsupported", () => {
956
894
  throw createInvalidInputError(`Unsupported field cannot be used in filters`);
957
895
  }).exhaustive();
958
896
  }
@@ -1052,11 +990,12 @@ var BaseCrudDialect = class {
1052
990
  const fieldDef = typeDef.fields[key];
1053
991
  (0, _zenstackhq_common_helpers.invariant)(fieldDef, `Field "${key}" not found in type definition "${typeDefName}"`);
1054
992
  const fieldReceiver = this.buildJsonPathSelection(receiver, `$.${key}`);
1055
- if (isTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
993
+ if (isTypeDef(this.schema, fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
1056
994
  else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
1057
995
  else {
996
+ const effectiveType = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
1058
997
  let _receiver = fieldReceiver;
1059
- if (fieldDef.type === "String" || isEnum(this.schema, fieldDef.type)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
998
+ if (effectiveType === "String" || isEnum(this.schema, effectiveType)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
1060
999
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
1061
1000
  }
1062
1001
  }
@@ -1102,7 +1041,7 @@ var BaseCrudDialect = class {
1102
1041
  (0, _zenstackhq_common_helpers.invariant)(rhs.length === 2, "right hand side must have a length of 2");
1103
1042
  const [start, end] = rhs;
1104
1043
  return this.eb.and([this.eb(lhs, ">=", start), this.eb(lhs, "<=", end)]);
1105
- }).with("not", () => this.eb.not(recurse(value))).with(ts_pattern.P.union(...AggregateOperators), (op) => {
1044
+ }).with("not", () => this.eb.not(recurse(value))).with(ts_pattern.P.union(...require_constants.AggregateOperators), (op) => {
1106
1045
  const innerResult = this.buildStandardFilter(type, value, aggregate(this.eb, lhs, op), getRhs, recurse, throwIfInvalid);
1107
1046
  consumedKeys.push(...innerResult.consumedKeys);
1108
1047
  return this.and(...innerResult.conditions);
@@ -1200,7 +1139,7 @@ var BaseCrudDialect = class {
1200
1139
  let result = query;
1201
1140
  const buildFieldRef = (model, field, modelAlias, computedArgs) => {
1202
1141
  const fieldDef = requireField(this.schema, model, field);
1203
- return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel, true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1142
+ return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, this.delegateJoinAlias(model, modelAlias, fieldDef.originModel), true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1204
1143
  };
1205
1144
  (0, _zenstackhq_common_helpers.enumerate)(orderBy).forEach((orderBy, index) => {
1206
1145
  for (const [field, value] of Object.entries(orderBy)) {
@@ -1249,10 +1188,15 @@ var BaseCrudDialect = class {
1249
1188
  return query;
1250
1189
  }
1251
1190
  const joinAlias = tmpAlias(`${modelAlias}$ob$${index}`);
1252
- const joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
1253
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, joinAlias);
1191
+ let joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
1192
+ const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
1254
1193
  return join.on((eb) => this.and(...joinPairs.map(([left, right]) => eb(this.eb.ref(left), "=", this.eb.ref(right)))));
1255
1194
  });
1195
+ let joinBase = requireModel(this.schema, relationModel).baseModel;
1196
+ while (joinBase) {
1197
+ joined = this.buildDelegateJoin(relationModel, joinAlias, joinBase, joined);
1198
+ joinBase = requireModel(this.schema, joinBase).baseModel;
1199
+ }
1256
1200
  return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
1257
1201
  }
1258
1202
  applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
@@ -1316,14 +1260,15 @@ var BaseCrudDialect = class {
1316
1260
  const descendants = getDelegateDescendantModels(this.schema, model);
1317
1261
  for (const subModel of descendants) {
1318
1262
  result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
1263
+ const subModelAlias = this.delegateJoinAlias(model, modelAlias, subModel.name);
1319
1264
  result = result.select(() => {
1320
1265
  const jsonObject = {};
1321
1266
  for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
1322
1267
  if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
1323
1268
  if (fieldDef.computed && fieldDef.params) continue;
1324
- jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1269
+ jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModelAlias);
1325
1270
  }
1326
- return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1271
+ return this.buildJsonObject(jsonObject).as(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1327
1272
  });
1328
1273
  }
1329
1274
  return result;
@@ -1344,17 +1289,35 @@ var BaseCrudDialect = class {
1344
1289
  buildSelectField(query, model, modelAlias, field, computedArgs) {
1345
1290
  const fieldDef = requireField(this.schema, model, field);
1346
1291
  const fieldModel = fieldDef.originModel ?? model;
1347
- const alias = fieldDef.originModel ?? modelAlias;
1292
+ const alias = this.delegateFieldAlias(model, modelAlias, fieldDef);
1348
1293
  return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
1349
1294
  }
1350
- buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1295
+ buildDelegateJoin(thisModel, thisModelAlias, otherModel, query) {
1351
1296
  const idFields = requireIdFields(this.schema, thisModel);
1352
- query = query.leftJoin(otherModelAlias, (qb) => {
1297
+ const otherModelAlias = this.delegateJoinAlias(thisModel, thisModelAlias, otherModel);
1298
+ const table = otherModelAlias === otherModel ? otherModel : `${otherModel} as ${otherModelAlias}`;
1299
+ query = query.leftJoin(table, (qb) => {
1353
1300
  for (const idField of idFields) qb = qb.onRef(`${thisModelAlias}.${idField}`, "=", `${otherModelAlias}.${idField}`);
1354
1301
  return qb;
1355
1302
  });
1356
1303
  return query;
1357
1304
  }
1305
+ /**
1306
+ * Gets the alias under which a delegate base or sub model is joined to a model selected as `modelAlias`.
1307
+ * A model selected under its own name (a top-level query) has them joined under their own model names.
1308
+ * A model selected under another alias (a relation subquery) has them joined under aliases derived from
1309
+ * it, so they never shadow a table of an enclosing query in the same delegate hierarchy.
1310
+ */
1311
+ delegateJoinAlias(model, modelAlias, joinedModel) {
1312
+ return modelAlias === model ? joinedModel : tmpAlias(`${modelAlias}$${joinedModel}`);
1313
+ }
1314
+ /**
1315
+ * Gets the alias of the table holding a field of a model selected as `modelAlias`: the joined base
1316
+ * table for a field inherited from a delegate base, otherwise the model's own table.
1317
+ */
1318
+ delegateFieldAlias(model, modelAlias, fieldDef) {
1319
+ return fieldDef.originModel ? this.delegateJoinAlias(model, modelAlias, fieldDef.originModel) : modelAlias;
1320
+ }
1358
1321
  buildCountJson(model, eb, parentAlias, payload) {
1359
1322
  const modelDef = requireModel(this.schema, model);
1360
1323
  const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
@@ -1561,7 +1524,7 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1561
1524
  const relationModelDef = requireModel(this.schema, relationModel);
1562
1525
  const objArgs = {};
1563
1526
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1564
- if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1527
+ if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1565
1528
  if (payload === true || !payload.select) {
1566
1529
  const omit = typeof payload === "object" ? payload.omit : void 0;
1567
1530
  Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
@@ -1626,9 +1589,10 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1626
1589
  if (value instanceof require_common_types.JsonNullClass) return this.eb.cast(kysely.sql.lit("null"), "json");
1627
1590
  else if (value instanceof require_common_types.DbNullClass) return null;
1628
1591
  else if (value instanceof require_common_types.AnyNullClass) (0, _zenstackhq_common_helpers.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1629
- if (isTypeDef(this.schema, type)) if (typeof value !== "string") return this.transformInput(value, "Json", forArrayField);
1592
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
1593
+ else if (typeof value !== "string") return this.transformInput(value, "Json", forArrayField);
1630
1594
  else return value;
1631
- else if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1595
+ if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1632
1596
  else throw createNotSupportedError(`MySQL does not support array literals`);
1633
1597
  else switch (type) {
1634
1598
  case "Boolean": return value ? 1 : 0;
@@ -1643,6 +1607,7 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1643
1607
  }
1644
1608
  transformOutput(value, type, array) {
1645
1609
  if (value === null || value === void 0) return value;
1610
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
1646
1611
  switch (type) {
1647
1612
  case "Boolean": return this.transformOutputBoolean(value);
1648
1613
  case "DateTime": return this.transformOutputDate(value);
@@ -1671,7 +1636,12 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1671
1636
  return new Date(!anchored.endsWith("Z") ? anchored + "Z" : anchored);
1672
1637
  }
1673
1638
  transformOutputBytes(value) {
1674
- return Buffer.isBuffer(value) ? Uint8Array.from(value) : value;
1639
+ if (Buffer.isBuffer(value)) return Uint8Array.from(value);
1640
+ if (typeof value === "string") {
1641
+ const match = /^base64:type\d+:(.*)$/s.exec(value);
1642
+ if (match) return Uint8Array.from(Buffer.from(match[1], "base64"));
1643
+ }
1644
+ return value;
1675
1645
  }
1676
1646
  buildExistsExpression(innerQuery) {
1677
1647
  return this.eb.exists(this.eb.selectFrom(innerQuery.as("$exists_sub")).select(this.eb.lit(1).as("_")));
@@ -1883,9 +1853,10 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1883
1853
  if (value instanceof require_common_types.JsonNullClass) return "null";
1884
1854
  else if (value instanceof require_common_types.DbNullClass) return null;
1885
1855
  else if (value instanceof require_common_types.AnyNullClass) (0, _zenstackhq_common_helpers.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1886
- if (isTypeDef(this.schema, type)) if (typeof value !== "string") return JSON.stringify(value);
1856
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
1857
+ else if (typeof value !== "string") return JSON.stringify(value);
1887
1858
  else return value;
1888
- else if (Array.isArray(value)) if (type === "Json" && !forArrayField) return JSON.stringify(value);
1859
+ if (Array.isArray(value)) if (type === "Json" && !forArrayField) return JSON.stringify(value);
1889
1860
  else return value.map((v) => this.transformInput(v, type, false, fieldDef));
1890
1861
  else switch (type) {
1891
1862
  case "DateTime": {
@@ -1903,6 +1874,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1903
1874
  }
1904
1875
  transformOutput(value, type, array) {
1905
1876
  if (value === null || value === void 0) return value;
1877
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
1906
1878
  switch (type) {
1907
1879
  case "DateTime": return this.transformOutputDate(value);
1908
1880
  case "Bytes": return this.transformOutputBytes(value);
@@ -2015,6 +1987,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
2015
1987
  const mapped = PostgresCrudDialect.dbAttributeToSqlTypeMap[attr.name];
2016
1988
  if (mapped) return mapped;
2017
1989
  }
1990
+ if (isPrimitiveTypeDef(this.schema, zmodelType)) zmodelType = this.schema.typeDefs[zmodelType].base;
2018
1991
  if (isEnum(this.schema, zmodelType)) return "text";
2019
1992
  else return this.zmodelToSqlTypeMap[zmodelType] ?? "text";
2020
1993
  }
@@ -2198,7 +2171,9 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2198
2171
  if (value instanceof require_common_types.JsonNullClass) return "null";
2199
2172
  else if (value instanceof require_common_types.DbNullClass) return null;
2200
2173
  else if (value instanceof require_common_types.AnyNullClass) (0, _zenstackhq_common_helpers.invariant)(false, "should not reach here: AnyNull is not a valid input value");
2201
- if (type === "Json" || this.schema.typeDefs && type in this.schema.typeDefs) return JSON.stringify(value);
2174
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema.typeDefs[type].base;
2175
+ else return JSON.stringify(value);
2176
+ if (type === "Json") return JSON.stringify(value);
2202
2177
  if (Array.isArray(value)) return value.map((v) => this.transformInput(v, type, false));
2203
2178
  else switch (type) {
2204
2179
  case "Boolean": return value ? 1 : 0;
@@ -2210,8 +2185,10 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2210
2185
  }
2211
2186
  transformOutput(value, type, array) {
2212
2187
  if (value === null || value === void 0) return value;
2213
- else if (this.schema.typeDefs && type in this.schema.typeDefs) return this.transformOutputJson(value);
2214
- else switch (type) {
2188
+ else if (this.schema.typeDefs && type in this.schema.typeDefs) {
2189
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
2190
+ return this.transformOutputJson(value);
2191
+ } else switch (type) {
2215
2192
  case "Boolean": return this.transformOutputBoolean(value);
2216
2193
  case "DateTime": return this.transformOutputDate(value);
2217
2194
  case "Bytes": return this.transformOutputBytes(value);
@@ -2271,7 +2248,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2271
2248
  tbl = tbl.select(() => {
2272
2249
  const objArgs = [];
2273
2250
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
2274
- if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [kysely.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2251
+ if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [kysely.sql.lit(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2275
2252
  if (payload === true || !payload.select) {
2276
2253
  const omit = typeof payload === "object" ? payload.omit : void 0;
2277
2254
  objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
@@ -2491,7 +2468,7 @@ function coercedDateTimeSchema() {
2491
2468
  var ZodSchemaFactory = class {
2492
2469
  schemaCache = /* @__PURE__ */ new Map();
2493
2470
  schemaRegistry = zod.z.registry();
2494
- allFilterKinds = [...new Set(Object.values(FILTER_PROPERTY_TO_KIND))];
2471
+ allFilterKinds = [...new Set(Object.values(require_constants.FILTER_PROPERTY_TO_KIND))];
2495
2472
  schema;
2496
2473
  options;
2497
2474
  extraValidationsEnabled = true;
@@ -2633,7 +2610,7 @@ var ZodSchemaFactory = class {
2633
2610
  return result;
2634
2611
  }
2635
2612
  makeScalarSchema(type, attributes) {
2636
- if (this.schema.typeDefs && type in this.schema.typeDefs) return this.makeTypeDefSchema(type);
2613
+ if (this.schema.typeDefs && type in this.schema.typeDefs) return this.schema.typeDefs[type].base ? this.makeTypeDefSchema(type, attributes) : this.makeTypeDefSchema(type);
2637
2614
  else if (this.schema.enums && type in this.schema.enums) return this.makeEnumSchema(type);
2638
2615
  else return (0, ts_pattern.match)(type).with("String", () => this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addStringValidation(zod.z.string(), attributes) : zod.z.string()).with("Int", () => this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addNumberValidation(zod.z.number().int(), attributes) : zod.z.number().int()).with("Float", () => this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addNumberValidation(zod.z.number(), attributes) : zod.z.number()).with("Boolean", () => zod.z.boolean()).with("BigInt", () => zod.z.union([this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addNumberValidation(zod.z.number().int(), attributes) : zod.z.number().int(), this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addBigIntValidation(zod.z.bigint(), attributes) : zod.z.bigint()])).with("Decimal", () => {
2639
2616
  return zod.z.union([
@@ -2669,9 +2646,20 @@ var ZodSchemaFactory = class {
2669
2646
  this.registerSchema(_enum, schema);
2670
2647
  return schema;
2671
2648
  }
2672
- makeTypeDefSchema(type) {
2649
+ /**
2650
+ * Attributes to validate each value of a scalar field against. For typedef list fields, the
2651
+ * field's own attributes (e.g. `@length`) validate the list rather than its items.
2652
+ */
2653
+ getItemAttributes(fieldDef) {
2654
+ return fieldDef.array && isTypeDef(this.schema, fieldDef.type) ? void 0 : fieldDef.attributes;
2655
+ }
2656
+ makeTypeDefSchema(type, fieldAttributes) {
2673
2657
  const typeDef = getTypeDef(this.schema, type);
2674
2658
  (0, _zenstackhq_common_helpers.invariant)(typeDef, `Type definition "${type}" not found in schema`);
2659
+ if (typeDef.base) {
2660
+ const schema = this.makeScalarSchema(typeDef.base, [...typeDef.fields["this"]?.attributes ?? [], ...fieldAttributes ?? []]);
2661
+ return this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addCustomValidation(schema, typeDef.attributes) : schema;
2662
+ }
2675
2663
  const schema = (typeDef.strict ? zod.z.strictObject : zod.z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2676
2664
  let fieldSchema = isTypeDef(this.schema, def.type) ? zod.z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
2677
2665
  if (def.array) fieldSchema = fieldSchema.array();
@@ -2716,8 +2704,8 @@ var ZodSchemaFactory = class {
2716
2704
  if (enumDef) {
2717
2705
  if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, withAggregations, allowedFilterKinds);
2718
2706
  } else if (fieldDef.array) fieldSchema = this.makeArrayFilterSchema(fieldDef.type, allowedFilterKinds);
2719
- else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2720
- else fieldSchema = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2707
+ else if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2708
+ else fieldSchema = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2721
2709
  }
2722
2710
  if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2723
2711
  if (fieldSchema) fields[field] = fieldSchema.optional();
@@ -2760,10 +2748,10 @@ var ZodSchemaFactory = class {
2760
2748
  const candidates = [];
2761
2749
  if (!array) {
2762
2750
  const fieldSchemas = {};
2763
- for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
2751
+ for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
2764
2752
  else if (getEnum(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, false, void 0).optional();
2765
2753
  else if (fieldDef.array) fieldSchemas[fieldName] = this.makeArrayFilterSchema(fieldDef.type, void 0).optional();
2766
- else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, false, void 0).optional();
2754
+ else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, false, void 0).optional();
2767
2755
  candidates.push(zod.z.strictObject(fieldSchemas));
2768
2756
  }
2769
2757
  const recursiveSchema = zod.z.lazy(() => this.makeTypedJsonFilterSchema(type, optional, false, allowedFilterKinds)).optional();
@@ -2801,6 +2789,10 @@ var ZodSchemaFactory = class {
2801
2789
  isTypeDefType(type) {
2802
2790
  return this.schema.typeDefs && type in this.schema.typeDefs;
2803
2791
  }
2792
+ getEffectiveFieldType(type) {
2793
+ if (isPrimitiveTypeDef(this.schema, type)) return this.schema.typeDefs[type].base;
2794
+ return type;
2795
+ }
2804
2796
  makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds) {
2805
2797
  const enumDef = getEnum(this.schema, enumName);
2806
2798
  (0, _zenstackhq_common_helpers.invariant)(enumDef, `Enum "${enumName}" not found in schema`);
@@ -3276,7 +3268,7 @@ var ZodSchemaFactory = class {
3276
3268
  checkedVariantFields[field] = fieldSchema;
3277
3269
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3278
3270
  } else {
3279
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3271
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3280
3272
  if (fieldDef.array) {
3281
3273
  fieldSchema = _zenstackhq_zod.ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
3282
3274
  fieldSchema = zod.z.union([fieldSchema, zod.z.strictObject({ set: fieldSchema })]).optional();
@@ -3454,7 +3446,7 @@ var ZodSchemaFactory = class {
3454
3446
  checkedVariantFields[field] = fieldSchema;
3455
3447
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3456
3448
  } else {
3457
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3449
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3458
3450
  if (this.isNumericField(fieldDef)) fieldSchema = zod.z.union([fieldSchema, zod.z.object({
3459
3451
  set: this.nullableIf(zod.z.number().optional(), !!fieldDef.optional).optional(),
3460
3452
  increment: zod.z.number().optional(),
@@ -3588,7 +3580,7 @@ var ZodSchemaFactory = class {
3588
3580
  schema = schema.refine((value) => {
3589
3581
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3590
3582
  if (value.having && typeof value.having === "object") for (const [key, val] of Object.entries(value.having)) {
3591
- if (AggregateOperators.includes(key)) continue;
3583
+ if (require_constants.AggregateOperators.includes(key)) continue;
3592
3584
  if (bys.includes(key)) continue;
3593
3585
  if (!val || typeof val !== "object") return false;
3594
3586
  if (!this.onlyAggregationFields(val)) return false;
@@ -3597,7 +3589,7 @@ var ZodSchemaFactory = class {
3597
3589
  }, "fields in \"having\" must be in \"by\"");
3598
3590
  schema = schema.refine((value) => {
3599
3591
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3600
- for (const orderBy of (0, _zenstackhq_common_helpers.enumerate)(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3592
+ for (const orderBy of (0, _zenstackhq_common_helpers.enumerate)(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !require_constants.AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3601
3593
  return true;
3602
3594
  }, "fields in \"orderBy\" must be in \"by\"");
3603
3595
  this.registerSchema(`${model}GroupByArgs`, schema);
@@ -3605,8 +3597,8 @@ var ZodSchemaFactory = class {
3605
3597
  }
3606
3598
  onlyAggregationFields(val) {
3607
3599
  for (const [key, value] of Object.entries(val)) {
3608
- if (AggregateOperators.includes(key)) continue;
3609
- if (LOGICAL_COMBINATORS.includes(key)) {
3600
+ if (require_constants.AggregateOperators.includes(key)) continue;
3601
+ if (require_constants.LOGICAL_COMBINATORS.includes(key)) {
3610
3602
  if ((0, _zenstackhq_common_helpers.enumerate)(value).every((v) => this.onlyAggregationFields(v))) continue;
3611
3603
  }
3612
3604
  return false;
@@ -3661,10 +3653,10 @@ var ZodSchemaFactory = class {
3661
3653
  result = createSchema.extend(updateSchema.shape);
3662
3654
  } else if (createSchema) result = createSchema;
3663
3655
  else if (updateSchema) result = updateSchema;
3664
- } else if (CoreCreateOperations.includes(operation) && "$create" in plugin.queryArgs && plugin.queryArgs["$create"]) result = plugin.queryArgs["$create"];
3665
- else if (CoreReadOperations.includes(operation) && "$read" in plugin.queryArgs && plugin.queryArgs["$read"]) result = plugin.queryArgs["$read"];
3666
- else if (CoreUpdateOperations.includes(operation) && "$update" in plugin.queryArgs && plugin.queryArgs["$update"]) result = plugin.queryArgs["$update"];
3667
- else if (CoreDeleteOperations.includes(operation) && "$delete" in plugin.queryArgs && plugin.queryArgs["$delete"]) result = plugin.queryArgs["$delete"];
3656
+ } else if (require_constants.CoreCreateOperations.includes(operation) && "$create" in plugin.queryArgs && plugin.queryArgs["$create"]) result = plugin.queryArgs["$create"];
3657
+ else if (require_constants.CoreReadOperations.includes(operation) && "$read" in plugin.queryArgs && plugin.queryArgs["$read"]) result = plugin.queryArgs["$read"];
3658
+ else if (require_constants.CoreUpdateOperations.includes(operation) && "$update" in plugin.queryArgs && plugin.queryArgs["$update"]) result = plugin.queryArgs["$update"];
3659
+ else if (require_constants.CoreDeleteOperations.includes(operation) && "$delete" in plugin.queryArgs && plugin.queryArgs["$delete"]) result = plugin.queryArgs["$delete"];
3668
3660
  else if ("$all" in plugin.queryArgs && plugin.queryArgs["$all"]) result = plugin.queryArgs["$all"];
3669
3661
  (0, _zenstackhq_common_helpers.invariant)(result === void 0 || result instanceof zod.ZodObject, "Plugin extended query args schema must be a Zod object");
3670
3662
  return result;
@@ -3695,7 +3687,7 @@ var ZodSchemaFactory = class {
3695
3687
  return canBeArray ? zod.z.union([schema, zod.z.array(schema)]) : schema;
3696
3688
  }
3697
3689
  isNumericField(fieldDef) {
3698
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3690
+ return require_constants.NUMERIC_FIELD_TYPES.includes(this.getEffectiveFieldType(fieldDef.type)) && !fieldDef.array;
3699
3691
  }
3700
3692
  get providerSupportsCaseSensitivity() {
3701
3693
  return this.schema.provider.type === "postgresql";
@@ -3748,7 +3740,7 @@ var ZodSchemaFactory = class {
3748
3740
  trimFilterOperators(operators, allowedKinds) {
3749
3741
  if (!allowedKinds) return operators;
3750
3742
  return Object.fromEntries(Object.entries(operators).filter(([key, _]) => {
3751
- return !(key in FILTER_PROPERTY_TO_KIND) || allowedKinds.includes(FILTER_PROPERTY_TO_KIND[key]);
3743
+ return !(key in require_constants.FILTER_PROPERTY_TO_KIND) || allowedKinds.includes(require_constants.FILTER_PROPERTY_TO_KIND[key]);
3752
3744
  }));
3753
3745
  }
3754
3746
  createUnionFilterSchema(valueSchema, optional, components, allowedFilterKinds) {
@@ -3815,7 +3807,7 @@ __decorate([
3815
3807
  __decorate([
3816
3808
  cache(),
3817
3809
  __decorateMetadata("design:type", Function),
3818
- __decorateMetadata("design:paramtypes", [String]),
3810
+ __decorateMetadata("design:paramtypes", [String, Array]),
3819
3811
  __decorateMetadata("design:returntype", typeof (_ref2 = typeof zod.ZodType !== "undefined" && zod.ZodType) === "function" ? _ref2 : Object)
3820
3812
  ], ZodSchemaFactory.prototype, "makeTypeDefSchema", null);
3821
3813
  __decorate([
@@ -4320,94 +4312,13 @@ var InputValidator = class {
4320
4312
  //#endregion
4321
4313
  //#region src/client/crud/operations/base.ts
4322
4314
  /**
4323
- * List of core CRUD operations. It excludes the 'orThrow' variants.
4315
+ * Maximum number of rows identified by id in a single statement during cascade delete simulation.
4324
4316
  */
4325
- const CoreCrudOperations = [
4326
- "findMany",
4327
- "findUnique",
4328
- "findFirst",
4329
- "create",
4330
- "createMany",
4331
- "createManyAndReturn",
4332
- "update",
4333
- "updateMany",
4334
- "updateManyAndReturn",
4335
- "upsert",
4336
- "delete",
4337
- "deleteMany",
4338
- "count",
4339
- "aggregate",
4340
- "groupBy",
4341
- "exists"
4342
- ];
4317
+ const DELETE_ID_BATCH_SIZE = 1e3;
4343
4318
  /**
4344
- * List of core read operations. It excludes the 'orThrow' variants.
4319
+ * Same as `DELETE_ID_BATCH_SIZE`, for compound ids, which are matched with one `OR` branch per row.
4345
4320
  */
4346
- const CoreReadOperations = [
4347
- "findMany",
4348
- "findUnique",
4349
- "findFirst",
4350
- "count",
4351
- "aggregate",
4352
- "groupBy",
4353
- "exists"
4354
- ];
4355
- /**
4356
- * List of core write operations.
4357
- */
4358
- const CoreWriteOperations = [
4359
- "create",
4360
- "createMany",
4361
- "createManyAndReturn",
4362
- "update",
4363
- "updateMany",
4364
- "updateManyAndReturn",
4365
- "upsert",
4366
- "delete",
4367
- "deleteMany"
4368
- ];
4369
- /**
4370
- * List of core create operations.
4371
- */
4372
- const CoreCreateOperations = [
4373
- "create",
4374
- "createMany",
4375
- "createManyAndReturn",
4376
- "upsert"
4377
- ];
4378
- /**
4379
- * List of core update operations.
4380
- */
4381
- const CoreUpdateOperations = [
4382
- "update",
4383
- "updateMany",
4384
- "updateManyAndReturn",
4385
- "upsert"
4386
- ];
4387
- /**
4388
- * List of core delete operations.
4389
- */
4390
- const CoreDeleteOperations = ["delete", "deleteMany"];
4391
- /**
4392
- * List of all CRUD operations, including 'orThrow' variants.
4393
- */
4394
- const AllCrudOperations = [
4395
- ...CoreCrudOperations,
4396
- "findUniqueOrThrow",
4397
- "findFirstOrThrow"
4398
- ];
4399
- /**
4400
- * List of all read operations, including 'orThrow' variants.
4401
- */
4402
- const AllReadOperations = [
4403
- ...CoreReadOperations,
4404
- "findUniqueOrThrow",
4405
- "findFirstOrThrow"
4406
- ];
4407
- /**
4408
- * List of all write operations - simply an alias of CoreWriteOperations.
4409
- */
4410
- const AllWriteOperations = CoreWriteOperations;
4321
+ const DELETE_COMPOUND_ID_BATCH_SIZE = 100;
4411
4322
  var BaseOperationHandler = class {
4412
4323
  dialect;
4413
4324
  constructor(client, model, inputValidator) {
@@ -4502,7 +4413,7 @@ var BaseOperationHandler = class {
4502
4413
  result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4503
4414
  } else {
4504
4415
  if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
4505
- if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, fieldDef.originModel, payload);
4416
+ if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, this.dialect.delegateJoinAlias(model, parentAlias, fieldDef.originModel), payload);
4506
4417
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
4507
4418
  }
4508
4419
  }
@@ -4864,16 +4775,9 @@ var BaseOperationHandler = class {
4864
4775
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4865
4776
  const origWhere = combinedWhere;
4866
4777
  const modelDef = this.requireModel(model);
4867
- let finalData = data;
4868
- const autoUpdatedFields = [];
4869
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && finalData[fieldName] === void 0) {
4870
- const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
4871
- if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
4872
- if (finalData === data) finalData = (0, _zenstackhq_common_helpers.clone)(data);
4873
- finalData[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
4874
- autoUpdatedFields.push(fieldName);
4875
- }
4876
- }
4778
+ const filled = this.fillUpdatedAtFields(modelDef, data);
4779
+ let finalData = filled.data;
4780
+ const autoUpdatedFields = filled.autoUpdatedFields;
4877
4781
  let thisEntity;
4878
4782
  const loadThisEntity = async () => {
4879
4783
  if (thisEntity === void 0) {
@@ -5022,7 +4926,8 @@ var BaseOperationHandler = class {
5022
4926
  });
5023
4927
  }
5024
4928
  isNumericField(fieldDef) {
5025
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
4929
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
4930
+ return require_constants.NUMERIC_FIELD_TYPES.includes(type) && !fieldDef.array;
5026
4931
  }
5027
4932
  makeContextComment(_context) {
5028
4933
  return kysely.sql``;
@@ -5035,11 +4940,13 @@ var BaseOperationHandler = class {
5035
4940
  const parentWhere = await this.buildUpdateParentRelationFilter(kysely$19, fromRelation);
5036
4941
  let combinedWhere = where ?? true;
5037
4942
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4943
+ const { data: finalData } = this.fillUpdatedAtFields(modelDef, data);
4944
+ if (modelDef.baseModel && filterModel === void 0) return this.updateManyByIds(kysely$19, model, combinedWhere, finalData, returnData, fieldsToReturn);
5038
4945
  filterModel ??= model;
5039
4946
  let updateFields = {};
5040
- for (const field in data) {
4947
+ for (const field in finalData) {
5041
4948
  if (isRelationField(this.schema, model, field)) continue;
5042
- updateFields[field] = this.processScalarFieldUpdateData(model, field, data);
4949
+ updateFields[field] = this.processScalarFieldUpdateData(model, field, finalData);
5043
4950
  }
5044
4951
  let resultFromBaseModel = void 0;
5045
4952
  if (modelDef.baseModel) {
@@ -5090,7 +4997,51 @@ var BaseOperationHandler = class {
5090
4997
  }
5091
4998
  }
5092
4999
  }
5093
- async processBaseModelUpdateMany(kysely$20, model, where, updateFields, filterModel) {
5000
+ /**
5001
+ * Runs `updateMany` on a delegate sub model by id. Reads the ids of the rows that match
5002
+ * `where`, then updates them in batches with an id filter. Callers run this inside a
5003
+ * transaction (`needsNestedUpdate` is true for every model with a base model).
5004
+ */
5005
+ async updateManyByIds(kysely$20, model, where, data, returnData, fieldsToReturn) {
5006
+ const idFields = requireIdFields(this.schema, model);
5007
+ const rows = await this.read(kysely$20, model, {
5008
+ where,
5009
+ select: Object.fromEntries(idFields.map((f) => [f, true]))
5010
+ });
5011
+ const batchSize = idFields.length === 1 ? 1e3 : 100;
5012
+ let count = 0;
5013
+ const returned = [];
5014
+ for (let i = 0; i < rows.length; i += batchSize) {
5015
+ const batch = rows.slice(i, i + batchSize);
5016
+ const idWhere = idFields.length === 1 ? { [idFields[0]]: { in: batch.map((row) => row[idFields[0]]) } } : { OR: batch.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
5017
+ const result = await this.updateMany(kysely$20, model, idWhere, data, void 0, returnData, model, void 0, fieldsToReturn);
5018
+ if (returnData) returned.push(...result);
5019
+ else count += result.count;
5020
+ }
5021
+ return returnData ? returned : { count };
5022
+ }
5023
+ /**
5024
+ * Sets `@updatedAt` fields to the current time when `data` changes a scalar or foreign key
5025
+ * field that is not in the field's `ignore` list. A value given explicitly in `data` is kept.
5026
+ * Returns the original `data` object when nothing is filled in, otherwise a clone.
5027
+ */
5028
+ fillUpdatedAtFields(modelDef, data) {
5029
+ let result = data;
5030
+ const autoUpdatedFields = [];
5031
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && result[fieldName] === void 0) {
5032
+ const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
5033
+ if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
5034
+ if (result === data) result = (0, _zenstackhq_common_helpers.clone)(data);
5035
+ result[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
5036
+ autoUpdatedFields.push(fieldName);
5037
+ }
5038
+ }
5039
+ return {
5040
+ data: result,
5041
+ autoUpdatedFields
5042
+ };
5043
+ }
5044
+ async processBaseModelUpdateMany(kysely$21, model, where, updateFields, filterModel) {
5094
5045
  const thisUpdateFields = {};
5095
5046
  const remainingFields = {};
5096
5047
  Object.entries(updateFields).forEach(([field, value]) => {
@@ -5098,14 +5049,14 @@ var BaseOperationHandler = class {
5098
5049
  else remainingFields[field] = value;
5099
5050
  });
5100
5051
  return {
5101
- baseResult: await this.updateMany(kysely$20, model, where, thisUpdateFields, void 0, false, filterModel),
5052
+ baseResult: await this.updateMany(kysely$21, model, where, thisUpdateFields, void 0, false, filterModel),
5102
5053
  remainingFields
5103
5054
  };
5104
5055
  }
5105
- buildIdFieldRefs(kysely$21, model) {
5106
- return requireIdFields(this.schema, model).map((f) => kysely$21.dynamic.ref(`${model}.${f}`));
5056
+ buildIdFieldRefs(kysely$22, model) {
5057
+ return requireIdFields(this.schema, model).map((f) => kysely$22.dynamic.ref(`${model}.${f}`));
5107
5058
  }
5108
- async processRelationUpdates(kysely$22, model, field, fieldDef, parentIds, args) {
5059
+ async processRelationUpdates(kysely$23, model, field, fieldDef, parentIds, args) {
5109
5060
  const fieldModel = fieldDef.type;
5110
5061
  const fromRelationContext = {
5111
5062
  model,
@@ -5116,24 +5067,24 @@ var BaseOperationHandler = class {
5116
5067
  for (const [key, value] of Object.entries(args)) switch (key) {
5117
5068
  case "create":
5118
5069
  (0, _zenstackhq_common_helpers.invariant)(!Array.isArray(value) || fieldDef.array, "relation must be an array if create is an array");
5119
- for (const item of (0, _zenstackhq_common_helpers.enumerate)(value)) await this.create(kysely$22, fieldModel, item, fromRelationContext);
5070
+ for (const item of (0, _zenstackhq_common_helpers.enumerate)(value)) await this.create(kysely$23, fieldModel, item, fromRelationContext);
5120
5071
  break;
5121
5072
  case "createMany":
5122
5073
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array for createMany");
5123
- await this.createMany(kysely$22, fieldModel, value, false, fromRelationContext);
5074
+ await this.createMany(kysely$23, fieldModel, value, false, fromRelationContext);
5124
5075
  break;
5125
5076
  case "connect":
5126
- await this.connectRelation(kysely$22, fieldModel, value, fromRelationContext);
5077
+ await this.connectRelation(kysely$23, fieldModel, value, fromRelationContext);
5127
5078
  break;
5128
5079
  case "connectOrCreate":
5129
- await this.connectOrCreateRelation(kysely$22, fieldModel, value, fromRelationContext);
5080
+ await this.connectOrCreateRelation(kysely$23, fieldModel, value, fromRelationContext);
5130
5081
  break;
5131
5082
  case "disconnect":
5132
- await this.disconnectRelation(kysely$22, fieldModel, value, fromRelationContext);
5083
+ await this.disconnectRelation(kysely$23, fieldModel, value, fromRelationContext);
5133
5084
  break;
5134
5085
  case "set":
5135
5086
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array");
5136
- await this.setRelation(kysely$22, fieldModel, value, fromRelationContext);
5087
+ await this.setRelation(kysely$23, fieldModel, value, fromRelationContext);
5137
5088
  break;
5138
5089
  case "update":
5139
5090
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
@@ -5148,76 +5099,76 @@ var BaseOperationHandler = class {
5148
5099
  data = item;
5149
5100
  }
5150
5101
  const throwIfNotFound = !fieldDef.array || !!where;
5151
- await this.update(kysely$22, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5102
+ await this.update(kysely$23, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5152
5103
  }
5153
5104
  break;
5154
5105
  case "upsert":
5155
5106
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5156
5107
  const item = _item;
5157
- if (!await this.update(kysely$22, fieldModel, item.where, item.update, fromRelationContext, true, false)) await this.create(kysely$22, fieldModel, item.create, fromRelationContext);
5108
+ if (!await this.update(kysely$23, fieldModel, item.where, item.update, fromRelationContext, true, false)) await this.create(kysely$23, fieldModel, item.create, fromRelationContext);
5158
5109
  }
5159
5110
  break;
5160
5111
  case "updateMany":
5161
5112
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5162
5113
  const item = _item;
5163
- await this.updateMany(kysely$22, fieldModel, item.where, item.data, item.limit, false, fieldModel, fromRelationContext);
5114
+ await this.updateMany(kysely$23, fieldModel, item.where, item.data, item.limit, false, void 0, fromRelationContext);
5164
5115
  }
5165
5116
  break;
5166
5117
  case "delete":
5167
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, true, true);
5118
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, true, true);
5168
5119
  break;
5169
5120
  case "deleteMany":
5170
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, false, false);
5121
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, false, false);
5171
5122
  break;
5172
5123
  default: throw createInvalidInputError(`Invalid relation update operation: ${key}`);
5173
5124
  }
5174
5125
  return fromRelationContext.parentUpdates;
5175
5126
  }
5176
- async connectRelation(kysely$23, model, data, fromRelation) {
5127
+ async connectRelation(kysely$24, model, data, fromRelation) {
5177
5128
  const _data = this.normalizeRelationManipulationInput(model, data);
5178
5129
  if (_data.length === 0) return;
5179
5130
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5180
5131
  if (m2m) {
5181
- const allIds = await this.getEntitiesIds(kysely$23, model, _data);
5132
+ const allIds = await this.getEntitiesIds(kysely$24, model, _data);
5182
5133
  if (allIds.length !== _data.length) throw createNotFoundError(model);
5183
- await this.handleManyToManyRelation(kysely$23, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5134
+ await this.handleManyToManyRelation(kysely$24, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5184
5135
  } else {
5185
5136
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5186
5137
  if (ownedByModel) {
5187
5138
  (0, _zenstackhq_common_helpers.invariant)(_data.length === 1, "only one entity can be connected");
5188
- const target = await this.readUnique(kysely$23, model, { where: _data[0] });
5139
+ const target = await this.readUnique(kysely$24, model, { where: _data[0] });
5189
5140
  if (!target) throw createNotFoundError(model);
5190
5141
  for (const { fk, pk } of keyPairs) fromRelation.parentUpdates[fk] = target[pk];
5191
5142
  } else {
5192
5143
  if (!this.requireField(fromRelation.model, fromRelation.field).array) {
5193
- const query = kysely$23.updateTable(model).where((eb) => eb.and(keyPairs.map(({ fk, pk }) => eb(eb.ref(fk), "=", fromRelation.ids[pk])))).set(keyPairs.reduce((acc, { fk }) => ({
5144
+ const query = kysely$24.updateTable(model).where((eb) => eb.and(keyPairs.map(({ fk, pk }) => eb(eb.ref(fk), "=", fromRelation.ids[pk])))).set(keyPairs.reduce((acc, { fk }) => ({
5194
5145
  ...acc,
5195
5146
  [fk]: null
5196
5147
  }), {})).modifyEnd(this.makeContextComment({
5197
5148
  model: fromRelation.model,
5198
5149
  operation: "update"
5199
5150
  }));
5200
- await this.executeQuery(kysely$23, query, "disconnect");
5151
+ await this.executeQuery(kysely$24, query, "disconnect");
5201
5152
  }
5202
- const query = kysely$23.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5153
+ const query = kysely$24.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5203
5154
  ...acc,
5204
5155
  [fk]: fromRelation.ids[pk]
5205
5156
  }), {})).modifyEnd(this.makeContextComment({
5206
5157
  model,
5207
5158
  operation: "update"
5208
5159
  }));
5209
- const updateResult = await this.executeQuery(kysely$23, query, "connect");
5160
+ const updateResult = await this.executeQuery(kysely$24, query, "connect");
5210
5161
  if (!updateResult.numAffectedRows || _data.length > updateResult.numAffectedRows) throw createNotFoundError(model);
5211
5162
  }
5212
5163
  }
5213
5164
  }
5214
- async connectOrCreateRelation(kysely$24, model, data, fromRelation) {
5165
+ async connectOrCreateRelation(kysely$25, model, data, fromRelation) {
5215
5166
  const _data = (0, _zenstackhq_common_helpers.enumerate)(data);
5216
5167
  if (_data.length === 0) return;
5217
- for (const { where, create } of _data) if (await this.exists(kysely$24, model, where)) await this.connectRelation(kysely$24, model, [where], fromRelation);
5218
- else await this.create(kysely$24, model, create, fromRelation);
5168
+ for (const { where, create } of _data) if (await this.exists(kysely$25, model, where)) await this.connectRelation(kysely$25, model, [where], fromRelation);
5169
+ else await this.create(kysely$25, model, create, fromRelation);
5219
5170
  }
5220
- async disconnectRelation(kysely$25, model, data, fromRelation) {
5171
+ async disconnectRelation(kysely$26, model, data, fromRelation) {
5221
5172
  let disconnectConditions = [];
5222
5173
  if (typeof data === "boolean") if (data === false) return;
5223
5174
  else disconnectConditions = [true];
@@ -5229,8 +5180,8 @@ var BaseOperationHandler = class {
5229
5180
  if (disconnectConditions.length === 0) return;
5230
5181
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5231
5182
  if (m2m) {
5232
- const allIds = await this.getEntitiesIds(kysely$25, model, disconnectConditions);
5233
- if (allIds.length > 0) await this.handleManyToManyRelation(kysely$25, "disconnect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5183
+ const allIds = await this.getEntitiesIds(kysely$26, model, disconnectConditions);
5184
+ if (allIds.length > 0) await this.handleManyToManyRelation(kysely$26, "disconnect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5234
5185
  } else {
5235
5186
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5236
5187
  const eb = (0, kysely.expressionBuilder)();
@@ -5239,39 +5190,39 @@ var BaseOperationHandler = class {
5239
5190
  const condition = disconnectConditions[0];
5240
5191
  if (condition === true) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5241
5192
  else {
5242
- const fromEntity = await this.readUnique(kysely$25, fromRelation.model, {
5193
+ const fromEntity = await this.readUnique(kysely$26, fromRelation.model, {
5243
5194
  where: fromRelation.ids,
5244
5195
  select: fieldsToSelectObject(keyPairs.map(({ fk }) => fk))
5245
5196
  });
5246
5197
  if (!fromEntity || keyPairs.some(({ fk }) => fromEntity[fk] == null)) return;
5247
5198
  const relationFilter = { AND: [condition, Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]]))] };
5248
- if ((await this.read(kysely$25, model, {
5199
+ if ((await this.read(kysely$26, model, {
5249
5200
  where: relationFilter,
5250
5201
  take: 1,
5251
5202
  select: this.makeIdSelect(model)
5252
5203
  })).length > 0) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5253
5204
  }
5254
5205
  } else {
5255
- const query = kysely$25.updateTable(model).where(eb.and([eb.and(Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]]))), eb.or(disconnectConditions.map((d) => eb.and(d)))])).set(keyPairs.reduce((acc, { fk }) => ({
5206
+ const query = kysely$26.updateTable(model).where(eb.and([eb.and(Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]]))), eb.or(disconnectConditions.map((d) => eb.and(d)))])).set(keyPairs.reduce((acc, { fk }) => ({
5256
5207
  ...acc,
5257
5208
  [fk]: null
5258
5209
  }), {})).modifyEnd(this.makeContextComment({
5259
5210
  model,
5260
5211
  operation: "update"
5261
5212
  }));
5262
- await this.executeQuery(kysely$25, query, "disconnect");
5213
+ await this.executeQuery(kysely$26, query, "disconnect");
5263
5214
  }
5264
5215
  }
5265
5216
  }
5266
- async setRelation(kysely$26, model, data, fromRelation) {
5217
+ async setRelation(kysely$27, model, data, fromRelation) {
5267
5218
  const _data = this.normalizeRelationManipulationInput(model, data);
5268
5219
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5269
5220
  if (m2m) {
5270
- await this.resetManyToManyRelation(kysely$26, fromRelation.model, fromRelation.field, fromRelation.ids);
5221
+ await this.resetManyToManyRelation(kysely$27, fromRelation.model, fromRelation.field, fromRelation.ids);
5271
5222
  if (_data.length > 0) {
5272
- const allIds = await this.getEntitiesIds(kysely$26, model, _data);
5223
+ const allIds = await this.getEntitiesIds(kysely$27, model, _data);
5273
5224
  if (allIds.length !== _data.length) throw createNotFoundError(model);
5274
- await this.handleManyToManyRelation(kysely$26, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5225
+ await this.handleManyToManyRelation(kysely$27, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5275
5226
  }
5276
5227
  } else {
5277
5228
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
@@ -5280,28 +5231,28 @@ var BaseOperationHandler = class {
5280
5231
  ...acc,
5281
5232
  [fk]: fromRelation.ids[pk]
5282
5233
  }), {});
5283
- const query = kysely$26.updateTable(model).where((eb) => eb.and([eb.and(fkConditions), eb.not(eb.or(_data.map((d) => eb.and(d))))])).set(keyPairs.reduce((acc, { fk }) => ({
5234
+ const query = kysely$27.updateTable(model).where((eb) => eb.and([eb.and(fkConditions), eb.not(eb.or(_data.map((d) => eb.and(d))))])).set(keyPairs.reduce((acc, { fk }) => ({
5284
5235
  ...acc,
5285
5236
  [fk]: null
5286
5237
  }), {})).modifyEnd(this.makeContextComment({
5287
5238
  model,
5288
5239
  operation: "update"
5289
5240
  }));
5290
- await this.executeQuery(kysely$26, query, "disconnect");
5241
+ await this.executeQuery(kysely$27, query, "disconnect");
5291
5242
  if (_data.length > 0) {
5292
- const query = kysely$26.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5243
+ const query = kysely$27.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5293
5244
  ...acc,
5294
5245
  [fk]: fromRelation.ids[pk]
5295
5246
  }), {})).modifyEnd(this.makeContextComment({
5296
5247
  model,
5297
5248
  operation: "update"
5298
5249
  }));
5299
- const r = await this.executeQuery(kysely$26, query, "connect");
5250
+ const r = await this.executeQuery(kysely$27, query, "connect");
5300
5251
  if (!r.numAffectedRows || _data.length > r.numAffectedRows) throw createNotFoundError(model);
5301
5252
  }
5302
5253
  }
5303
5254
  }
5304
- async deleteRelation(kysely$27, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5255
+ async deleteRelation(kysely$28, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5305
5256
  let deleteConditions = [];
5306
5257
  let expectedDeleteCount = -1;
5307
5258
  if (typeof data === "boolean") if (data === false) return;
@@ -5323,18 +5274,18 @@ var BaseOperationHandler = class {
5323
5274
  deleteFromModel = model;
5324
5275
  const fieldDef = this.requireField(fromRelation.model, fromRelation.field);
5325
5276
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.relation?.opposite);
5326
- deleteResult = await this.delete(kysely$27, model, { AND: [{ [fieldDef.relation.opposite]: { some: fromRelation.ids } }, { OR: deleteConditions }] });
5277
+ deleteResult = await this.delete(kysely$28, model, { AND: [{ [fieldDef.relation.opposite]: { some: fromRelation.ids } }, { OR: deleteConditions }] });
5327
5278
  } else {
5328
5279
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5329
5280
  if (ownedByModel) {
5330
5281
  deleteFromModel = fromRelation.model;
5331
- const fromEntity = await this.readUnique(kysely$27, fromRelation.model, { where: fromRelation.ids });
5282
+ const fromEntity = await this.readUnique(kysely$28, fromRelation.model, { where: fromRelation.ids });
5332
5283
  if (!fromEntity) throw createNotFoundError(fromRelation.model);
5333
5284
  (0, _zenstackhq_common_helpers.invariant)(this.requireField(fromRelation.model, fromRelation.field).relation?.opposite);
5334
- deleteResult = await this.delete(kysely$27, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]])), { OR: deleteConditions }] });
5285
+ deleteResult = await this.delete(kysely$28, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]])), { OR: deleteConditions }] });
5335
5286
  } else {
5336
5287
  deleteFromModel = model;
5337
- deleteResult = await this.delete(kysely$27, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]])), { OR: deleteConditions }] });
5288
+ deleteResult = await this.delete(kysely$28, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]])), { OR: deleteConditions }] });
5338
5289
  }
5339
5290
  }
5340
5291
  if (throwForNotFound && expectedDeleteCount >= 0 && expectedDeleteCount > (deleteResult.numAffectedRows ?? 0)) throw createNotFoundError(deleteFromModel);
@@ -5342,37 +5293,125 @@ var BaseOperationHandler = class {
5342
5293
  normalizeRelationManipulationInput(model, data) {
5343
5294
  return (0, _zenstackhq_common_helpers.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
5344
5295
  }
5345
- async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn) {
5296
+ async delete(kysely$29, model, where, limit, filterModel, fieldsToReturn, visited) {
5346
5297
  filterModel ??= model;
5298
+ visited ??= /* @__PURE__ */ new Set();
5347
5299
  const modelDef = this.requireModel(model);
5348
5300
  if (modelDef.baseModel) {
5349
5301
  if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5350
- return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel);
5302
+ return this.processBaseModelDelete(kysely$29, modelDef.baseModel, where, limit, filterModel, visited);
5303
+ }
5304
+ const cascadeRelations = this.getDelegateCascadeRelations(model, filterModel);
5305
+ if (cascadeRelations.length === 0) return this.executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn);
5306
+ const discriminator = getDiscriminatorField(this.schema, model);
5307
+ const deletedRows = await this.read(kysely$29, filterModel, {
5308
+ where,
5309
+ select: {
5310
+ ...this.makeIdSelect(filterModel),
5311
+ ...discriminator ? { [discriminator]: true } : {}
5312
+ },
5313
+ ...limit !== void 0 ? { take: limit } : {}
5314
+ });
5315
+ deletedRows.forEach((row) => visited.add(this.makeVisitedKey(model, row)));
5316
+ for (const { fieldDef, discriminatorValue } of cascadeRelations) {
5317
+ const parentRows = discriminatorValue === void 0 ? deletedRows : deletedRows.filter((row) => row[discriminator] === discriminatorValue);
5318
+ for (const batch of this.batchRows(model, parentRows)) {
5319
+ const childModel = fieldDef.type;
5320
+ const pendingRows = (await this.read(kysely$29, childModel, {
5321
+ where: this.makeChildFilter(model, fieldDef, batch),
5322
+ select: this.makeIdSelect(childModel)
5323
+ })).filter((row) => {
5324
+ const key = this.makeVisitedKey(childModel, row);
5325
+ if (visited.has(key)) return false;
5326
+ visited.add(key);
5327
+ return true;
5328
+ });
5329
+ for (const childBatch of this.batchRows(childModel, pendingRows)) await this.delete(kysely$29, childModel, this.makeIdsFilter(childModel, childBatch), void 0, void 0, void 0, visited);
5330
+ }
5351
5331
  }
5332
+ let numAffectedRows = 0n;
5333
+ const rows = [];
5334
+ for (const batch of this.batchRows(model, deletedRows)) {
5335
+ const result = await this.executeDelete(kysely$29, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
5336
+ numAffectedRows += result.numAffectedRows ?? 0n;
5337
+ rows.push(...result.rows);
5338
+ }
5339
+ return {
5340
+ numAffectedRows,
5341
+ rows
5342
+ };
5343
+ }
5344
+ async executeDelete(kysely$30, model, where, limit, filterModel, fieldsToReturn) {
5345
+ const modelDef = this.requireModel(model);
5352
5346
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
5353
5347
  let needIdFilter = false;
5354
5348
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
5355
5349
  if (modelDef.isDelegate || modelDef.baseModel) needIdFilter = true;
5356
- const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely$28, model)), "in", eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely$28, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()) : () => this.dialect.buildFilter(model, model, where);
5357
- await this.processDelegateRelationDelete(kysely$28, modelDef, where, limit);
5358
- const query = kysely$28.deleteFrom(model).where(deleteFilter).$if(this.dialect.supportsReturning, (qb) => qb.returning(fieldsToReturn)).$if(limit !== void 0 && this.dialect.supportsDeleteWithLimit, (qb) => qb.limit(limit)).modifyEnd(this.makeContextComment({
5350
+ const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely$30, model)), "in", eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely$30, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()) : () => this.dialect.buildFilter(model, model, where);
5351
+ const query = kysely$30.deleteFrom(model).where(deleteFilter).$if(this.dialect.supportsReturning, (qb) => qb.returning(fieldsToReturn)).$if(limit !== void 0 && this.dialect.supportsDeleteWithLimit, (qb) => qb.limit(limit)).modifyEnd(this.makeContextComment({
5359
5352
  model,
5360
5353
  operation: "delete"
5361
5354
  }));
5362
- return this.executeQuery(kysely$28, query, "delete");
5355
+ return this.executeQuery(kysely$30, query, "delete");
5363
5356
  }
5364
- async processDelegateRelationDelete(kysely$29, modelDef, where, limit) {
5365
- for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation && fieldDef.relation.opposite) {
5357
+ /**
5358
+ * Gets the relations whose deletion must be simulated when deleting from the given model: relations
5359
+ * pointing to a model that extends a delegate model, with cascade delete on the opposite side. For a
5360
+ * delegate model, this includes relations declared on its sub models, because deleting a base row
5361
+ * cascades to the sub model rows in the database. `discriminatorValue` is set for a sub model relation:
5362
+ * it is the base model's discriminator value of the rows the relation can belong to.
5363
+ */
5364
+ getDelegateCascadeRelations(model, filterModel = model) {
5365
+ const modelDef = this.requireModel(model);
5366
+ const filterDiscriminatorValue = filterModel === model ? void 0 : this.getDiscriminatorValueBelow(model, filterModel);
5367
+ const candidates = Object.values(modelDef.fields).map((fieldDef) => ({
5368
+ fieldDef,
5369
+ discriminatorValue: void 0
5370
+ }));
5371
+ if (modelDef.isDelegate) for (const subModel of getDelegateDescendantModels(this.schema, model)) {
5372
+ const discriminatorValue = this.getDiscriminatorValueBelow(model, subModel.name);
5373
+ if (filterDiscriminatorValue !== void 0 && discriminatorValue !== filterDiscriminatorValue) continue;
5374
+ for (const fieldDef of Object.values(subModel.fields)) if (!fieldDef.originModel) candidates.push({
5375
+ fieldDef,
5376
+ discriminatorValue
5377
+ });
5378
+ }
5379
+ return candidates.filter(({ fieldDef }) => {
5380
+ if (!fieldDef.relation?.opposite) return false;
5366
5381
  const oppositeModelDef = this.requireModel(fieldDef.type);
5367
5382
  const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5368
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") {
5369
- if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5370
- await this.delete(kysely$29, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0);
5371
- }
5372
- }
5383
+ return !!oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade";
5384
+ });
5385
+ }
5386
+ getDiscriminatorValueBelow(model, subModel) {
5387
+ let ancestor = this.requireModel(subModel);
5388
+ while (ancestor.baseModel !== model) ancestor = this.requireModel(ancestor.baseModel);
5389
+ return getDelegateDiscriminatorValue(this.schema, ancestor.name);
5390
+ }
5391
+ makeVisitedKey(model, row) {
5392
+ let root = model;
5393
+ for (let base = this.requireModel(root).baseModel; base; base = this.requireModel(root).baseModel) root = base;
5394
+ return JSON.stringify([root, ...this.requireModel(model).idFields.map((f) => row[f])]);
5395
+ }
5396
+ makeChildFilter(model, fieldDef, parentRows) {
5397
+ const opposite = fieldDef.relation.opposite;
5398
+ const { fields, references } = this.requireField(fieldDef.type, opposite).relation ?? {};
5399
+ const idFields = this.requireModel(model).idFields;
5400
+ if (!fields || !references || !references.every((f) => idFields.includes(f))) return { [opposite]: this.makeIdsFilter(model, parentRows) };
5401
+ if (fields.length === 1) return { [fields[0]]: { in: parentRows.map((row) => row[references[0]]) } };
5402
+ return { OR: parentRows.map((row) => Object.fromEntries(fields.map((f, i) => [f, row[references[i]]]))) };
5403
+ }
5404
+ makeIdsFilter(model, rows) {
5405
+ const idFields = this.requireModel(model).idFields;
5406
+ if (idFields.length === 1) return { [idFields[0]]: { in: rows.map((row) => row[idFields[0]]) } };
5407
+ return { OR: rows.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
5408
+ }
5409
+ *batchRows(model, rows) {
5410
+ const size = this.requireModel(model).idFields.length === 1 ? DELETE_ID_BATCH_SIZE : DELETE_COMPOUND_ID_BATCH_SIZE;
5411
+ for (let i = 0; i < rows.length; i += size) yield rows.slice(i, i + size);
5373
5412
  }
5374
- async processBaseModelDelete(kysely$30, model, where, limit, filterModel) {
5375
- return this.delete(kysely$30, model, where, limit, filterModel);
5413
+ async processBaseModelDelete(kysely$31, model, where, limit, filterModel, visited) {
5414
+ return this.delete(kysely$31, model, where, limit, filterModel, void 0, visited);
5376
5415
  }
5377
5416
  makeIdSelect(model) {
5378
5417
  return this.requireModel(model).idFields.reduce((acc, f) => {
@@ -5407,14 +5446,14 @@ var BaseOperationHandler = class {
5407
5446
  if (condition) return this.safeTransaction(callback, isolationLevel);
5408
5447
  else return callback(this.kysely);
5409
5448
  }
5410
- getEntityIds(kysely$31, model, uniqueFilter) {
5411
- return this.readUnique(kysely$31, model, {
5449
+ getEntityIds(kysely$32, model, uniqueFilter) {
5450
+ return this.readUnique(kysely$32, model, {
5412
5451
  where: uniqueFilter,
5413
5452
  select: this.makeIdSelect(model)
5414
5453
  });
5415
5454
  }
5416
- getEntitiesIds(kysely$32, model, uniqueFilters) {
5417
- return this.read(kysely$32, model, {
5455
+ getEntitiesIds(kysely$33, model, uniqueFilters) {
5456
+ return this.read(kysely$33, model, {
5418
5457
  where: { OR: uniqueFilters },
5419
5458
  select: this.makeIdSelect(model)
5420
5459
  });
@@ -5434,14 +5473,14 @@ var BaseOperationHandler = class {
5434
5473
  else if (value && (0, _zenstackhq_common_helpers.isPlainObject)(value)) this.doNormalizeArgs(value);
5435
5474
  }
5436
5475
  }
5437
- executeQuery(kysely$33, query, _operation) {
5438
- return kysely$33.executeQuery(query.compile());
5476
+ executeQuery(kysely$34, query, _operation) {
5477
+ return kysely$34.executeQuery(query.compile());
5439
5478
  }
5440
- async executeQueryTakeFirst(kysely$34, query, _operation) {
5441
- return (await kysely$34.executeQuery(query.compile())).rows[0];
5479
+ async executeQueryTakeFirst(kysely$35, query, _operation) {
5480
+ return (await kysely$35.executeQuery(query.compile())).rows[0];
5442
5481
  }
5443
- async executeQueryTakeFirstOrThrow(kysely$35, query, _operation) {
5444
- const result = await kysely$35.executeQuery(query.compile());
5482
+ async executeQueryTakeFirstOrThrow(kysely$36, query, _operation) {
5483
+ const result = await kysely$36.executeQuery(query.compile());
5445
5484
  if (result.rows.length === 0) throw new ORMError(ORMErrorReason.NOT_FOUND, "No rows found");
5446
5485
  return result.rows[0];
5447
5486
  }
@@ -5548,7 +5587,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5548
5587
  if (typeof value === "string") {
5549
5588
  const fieldDef = getField(this.schema, this.model, field);
5550
5589
  if (fieldDef) {
5551
- const type = fieldDef.type;
5590
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5552
5591
  if (op === "_avg") val = parseFloat(val);
5553
5592
  else if (op === "_sum" || op === "_min" || op === "_max") val = (0, ts_pattern.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
5554
5593
  }
@@ -5675,14 +5714,8 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
5675
5714
  });
5676
5715
  }
5677
5716
  needsNestedDelete() {
5678
- const modelDef = this.requireModel(this.model);
5679
- if (modelDef.baseModel) return true;
5680
- for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation?.opposite) {
5681
- const oppositeModelDef = this.requireModel(fieldDef.type);
5682
- const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5683
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") return true;
5684
- }
5685
- return false;
5717
+ if (this.requireModel(this.model).baseModel) return true;
5718
+ return this.getDelegateCascadeRelations(this.model).length > 0;
5686
5719
  }
5687
5720
  };
5688
5721
  //#endregion
@@ -5777,7 +5810,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5777
5810
  if (typeof value === "string") {
5778
5811
  const fieldDef = getField(this.schema, this.model, field);
5779
5812
  if (fieldDef) {
5780
- const type = fieldDef.type;
5813
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5781
5814
  if (op === "_avg") val = parseFloat(val);
5782
5815
  else if (op === "_sum" || op === "_min" || op === "_max") val = (0, ts_pattern.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
5783
5816
  }
@@ -6197,7 +6230,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6197
6230
  return kysely.ColumnNode.create(mappedName);
6198
6231
  }
6199
6232
  transformBinaryOperation(node, queryId) {
6200
- if (kysely.ReferenceNode.is(node.leftOperand) && kysely.ColumnNode.is(node.leftOperand.column) && (kysely.ValueNode.is(node.rightOperand) || kysely.PrimitiveValueListNode.is(node.rightOperand))) {
6233
+ if (kysely.ReferenceNode.is(node.leftOperand) && kysely.ColumnNode.is(node.leftOperand.column) && (kysely.ValueNode.is(node.rightOperand) || kysely.PrimitiveValueListNode.is(node.rightOperand) || kysely.ValueListNode.is(node.rightOperand))) {
6201
6234
  const columnNode = node.leftOperand.column;
6202
6235
  const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
6203
6236
  if (resolvedScope?.model) {
@@ -6205,6 +6238,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6205
6238
  let resultValue = valueNode;
6206
6239
  if (kysely.ValueNode.is(valueNode)) resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
6207
6240
  else if (kysely.PrimitiveValueListNode.is(valueNode)) resultValue = kysely.PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
6241
+ else if (kysely.ValueListNode.is(valueNode)) resultValue = kysely.ValueListNode.create(valueNode.values.map((v) => kysely.ValueNode.is(v) ? this.processEnumMappingForValue(resolvedScope.model, columnNode, v) : v));
6208
6242
  return super.transformBinaryOperation({
6209
6243
  ...node,
6210
6244
  rightOperand: resultValue
@@ -6605,7 +6639,11 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6605
6639
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6606
6640
  }
6607
6641
  get hasEntityMutationPluginsWithAfterMutationHooks() {
6608
- return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
6642
+ return (this.client.$options.plugins ?? []).some((plugin) => {
6643
+ if (!plugin.onEntityMutation) return false;
6644
+ if (plugin.onEntityMutation["$all"]?.afterEntityMutation) return true;
6645
+ return Object.keys(this.client.$schema.models).some((model) => plugin.onEntityMutation?.[model]?.afterEntityMutation);
6646
+ });
6609
6647
  }
6610
6648
  get hasOnKyselyHooks() {
6611
6649
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onKyselyQuery);
@@ -6710,8 +6748,17 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6710
6748
  const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
6711
6749
  if (this.options.plugins) for (const plugin of this.options.plugins) {
6712
6750
  const onEntityMutation = plugin.onEntityMutation;
6713
- if (!onEntityMutation?.beforeEntityMutation) continue;
6714
- await onEntityMutation.beforeEntityMutation({
6751
+ if (!onEntityMutation) continue;
6752
+ if (onEntityMutation["$all"]?.beforeEntityMutation) await onEntityMutation["$all"].beforeEntityMutation({
6753
+ model: mutationInfo.model,
6754
+ action: mutationInfo.action,
6755
+ queryNode,
6756
+ loadBeforeMutationEntities,
6757
+ client,
6758
+ queryId
6759
+ });
6760
+ const modelHooks = onEntityMutation[mutationInfo.model];
6761
+ if (modelHooks?.beforeEntityMutation) await modelHooks.beforeEntityMutation({
6715
6762
  model: mutationInfo.model,
6716
6763
  action: mutationInfo.action,
6717
6764
  queryNode,
@@ -6726,10 +6773,16 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6726
6773
  const hooks = [];
6727
6774
  for (const plugin of this.options.plugins ?? []) {
6728
6775
  const onEntityMutation = plugin.onEntityMutation;
6729
- if (!onEntityMutation?.afterEntityMutation) continue;
6730
- if (filterFor === "inTx" && !onEntityMutation.runAfterMutationWithinTransaction) continue;
6731
- if (filterFor === "outTx" && onEntityMutation.runAfterMutationWithinTransaction) continue;
6732
- hooks.push(onEntityMutation.afterEntityMutation.bind(plugin));
6776
+ if (!onEntityMutation) continue;
6777
+ if (onEntityMutation["$all"]?.afterEntityMutation) {
6778
+ const runInTx = onEntityMutation["$all"].runAfterMutationWithinTransaction ?? false;
6779
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(onEntityMutation["$all"].afterEntityMutation.bind(plugin));
6780
+ }
6781
+ const modelHooks = onEntityMutation[mutationInfo.model];
6782
+ if (modelHooks?.afterEntityMutation) {
6783
+ const runInTx = modelHooks.runAfterMutationWithinTransaction ?? false;
6784
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(modelHooks.afterEntityMutation.bind(plugin));
6785
+ }
6733
6786
  }
6734
6787
  if (hooks.length === 0) return;
6735
6788
  for (const hook of hooks) await hook({
@@ -6744,7 +6797,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6744
6797
  }
6745
6798
  async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
6746
6799
  if (mutationInfo.action === "delete") return;
6747
- if (this.dialect.supportsReturning) return queryResult.rows;
6800
+ if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
6748
6801
  else {
6749
6802
  const mutatedIds = kysely.InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
6750
6803
  if (mutatedIds) {
@@ -7204,8 +7257,12 @@ var SchemaDbPusher = class {
7204
7257
  return kysely.sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
7205
7258
  } else return "text";
7206
7259
  if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") return "serial";
7207
- if (this.isCustomType(fieldDef.type)) return this.jsonType;
7208
- const type = fieldDef.type;
7260
+ let type = fieldDef.type;
7261
+ if (this.isCustomType(type)) {
7262
+ const typeDef = Object.values(this.schema.typeDefs).find((def) => def.name === type);
7263
+ if (typeDef.base) type = typeDef.base;
7264
+ else return this.jsonType;
7265
+ }
7209
7266
  const result = (0, ts_pattern.match)(type).with("String", () => this.stringType).with("Boolean", () => this.booleanType).with("Int", () => this.intType).with("Float", () => this.floatType).with("BigInt", () => this.bigIntType).with("Decimal", () => this.decimalType).with("DateTime", () => this.dateTimeType).with("Bytes", () => this.bytesType).with("Json", () => this.jsonType).otherwise(() => {
7210
7267
  throw new Error(`Unsupported field type: ${type}`);
7211
7268
  });
@@ -7341,7 +7398,7 @@ var ResultProcessor = class {
7341
7398
  else if (key.startsWith("$delegate$")) {
7342
7399
  if (value) {
7343
7400
  const subRow = this.dialect.transformOutput(value, "Json", false);
7344
- const subModel = key.slice(10);
7401
+ const subModel = key.slice(require_constants.DELEGATE_JOINED_FIELD_PREFIX.length);
7345
7402
  const idValues = getIdValues(this.schema, subModel, subRow);
7346
7403
  if (Object.values(idValues).some((v) => v === null || v === void 0)) {
7347
7404
  delete data[key];
@@ -7397,6 +7454,7 @@ var ResultProcessor = class {
7397
7454
  };
7398
7455
  //#endregion
7399
7456
  //#region src/client/client-impl.ts
7457
+ const warnedPlugins = /* @__PURE__ */ new WeakSet();
7400
7458
  /**
7401
7459
  * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7402
7460
  */
@@ -7427,6 +7485,7 @@ var ClientImpl = class ClientImpl {
7427
7485
  ...functions_exports,
7428
7486
  ...this.$options.functions
7429
7487
  };
7488
+ if (this.$options.plugins) this.$options.plugins = this.normalizePlugins(this.$options.plugins);
7430
7489
  this.validateOptions(baseClient, options);
7431
7490
  if (baseClient) {
7432
7491
  this.kyselyProps = {
@@ -7460,6 +7519,63 @@ var ClientImpl = class ClientImpl {
7460
7519
  this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this, { enabled: this.$options.validateInput !== false });
7461
7520
  return createClientProxy(this);
7462
7521
  }
7522
+ /**
7523
+ * Normalizes plugin definitions for backward compatibility and validates
7524
+ * `onEntityMutation` keys. Legacy plugins that define hooks directly under
7525
+ * `onEntityMutation` (instead of under `$all`) are converted to the new shape
7526
+ * with a one-time warning.
7527
+ */
7528
+ normalizePlugins(plugins) {
7529
+ let changed = false;
7530
+ const result = plugins.map((plugin) => {
7531
+ const normalized = this.normalizeEntityMutationHooks(plugin);
7532
+ if (normalized !== plugin) changed = true;
7533
+ return normalized;
7534
+ });
7535
+ return changed ? result : plugins;
7536
+ }
7537
+ normalizeEntityMutationHooks(plugin) {
7538
+ const hooks = plugin.onEntityMutation;
7539
+ if (!hooks || typeof hooks !== "object") return plugin;
7540
+ const legacyKeys = [
7541
+ "beforeEntityMutation",
7542
+ "afterEntityMutation",
7543
+ "runAfterMutationWithinTransaction"
7544
+ ];
7545
+ const presentLegacyKeys = legacyKeys.filter((key) => key in hooks);
7546
+ const unknownKeys = Object.keys(hooks).filter((key) => key !== "$all" && !legacyKeys.includes(key) && !(key in this.$schema.models));
7547
+ const warnOnce = (message) => {
7548
+ if (!warnedPlugins.has(hooks)) console.warn(message);
7549
+ };
7550
+ if (unknownKeys.length > 0) warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks for unknown keys: ${unknownKeys.map((k) => `"${k}"`).join(", ")}. Valid keys are "$all" and model names. These hooks will never be invoked.`);
7551
+ if (presentLegacyKeys.length === 0) {
7552
+ warnedPlugins.add(hooks);
7553
+ return plugin;
7554
+ }
7555
+ warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks in a deprecated shape. Hooks that apply to all models should be nested under "$all": { onEntityMutation: { $all: { beforeEntityMutation, afterEntityMutation, runAfterMutationWithinTransaction } } }. The legacy shape is still supported but will be removed in a future release.`);
7556
+ warnedPlugins.add(hooks);
7557
+ const legacy = {};
7558
+ const rest = {};
7559
+ for (const [key, value] of Object.entries(hooks)) if (legacyKeys.includes(key)) legacy[key] = value;
7560
+ else rest[key] = value;
7561
+ for (const key of ["beforeEntityMutation", "afterEntityMutation"]) if (typeof legacy[key] === "function") legacy[key] = legacy[key].bind(plugin);
7562
+ const normalizedHooks = {
7563
+ ...rest,
7564
+ $all: {
7565
+ ...legacy,
7566
+ ...rest["$all"]
7567
+ }
7568
+ };
7569
+ warnedPlugins.add(normalizedHooks);
7570
+ const copy = Object.create(Object.getPrototypeOf(plugin), Object.getOwnPropertyDescriptors(plugin));
7571
+ Object.defineProperty(copy, "onEntityMutation", {
7572
+ value: normalizedHooks,
7573
+ enumerable: true,
7574
+ configurable: true,
7575
+ writable: true
7576
+ });
7577
+ return copy;
7578
+ }
7463
7579
  validateOptions(baseClient, options) {
7464
7580
  if (!baseClient && !options.skipValidationForComputedFields) this.validateComputedFieldsConfig(options);
7465
7581
  if (options.diagnostics) {
@@ -8399,20 +8515,20 @@ var MatchingExpressionVisitor = class extends ExpressionVisitor {
8399
8515
  }
8400
8516
  };
8401
8517
  //#endregion
8402
- exports.AllCrudOperations = AllCrudOperations;
8403
- exports.AllReadOperations = AllReadOperations;
8404
- exports.AllWriteOperations = AllWriteOperations;
8518
+ exports.AllCrudOperations = require_constants.AllCrudOperations;
8519
+ exports.AllReadOperations = require_constants.AllReadOperations;
8520
+ exports.AllWriteOperations = require_constants.AllWriteOperations;
8405
8521
  exports.AnyNull = require_common_types.AnyNull;
8406
8522
  exports.AnyNullClass = require_common_types.AnyNullClass;
8407
8523
  exports.BaseCrudDialect = BaseCrudDialect;
8408
8524
  exports.CRUD = CRUD;
8409
8525
  exports.CRUD_EXT = CRUD_EXT;
8410
- exports.CoreCreateOperations = CoreCreateOperations;
8411
- exports.CoreCrudOperations = CoreCrudOperations;
8412
- exports.CoreDeleteOperations = CoreDeleteOperations;
8413
- exports.CoreReadOperations = CoreReadOperations;
8414
- exports.CoreUpdateOperations = CoreUpdateOperations;
8415
- exports.CoreWriteOperations = CoreWriteOperations;
8526
+ exports.CoreCreateOperations = require_constants.CoreCreateOperations;
8527
+ exports.CoreCrudOperations = require_constants.CoreCrudOperations;
8528
+ exports.CoreDeleteOperations = require_constants.CoreDeleteOperations;
8529
+ exports.CoreReadOperations = require_constants.CoreReadOperations;
8530
+ exports.CoreUpdateOperations = require_constants.CoreUpdateOperations;
8531
+ exports.CoreWriteOperations = require_constants.CoreWriteOperations;
8416
8532
  exports.DbNull = require_common_types.DbNull;
8417
8533
  exports.DbNullClass = require_common_types.DbNullClass;
8418
8534
  exports.ExtQueryArgsMarker = ExtQueryArgsMarker;