@zenstackhq/orm 3.9.8 → 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
@@ -244,6 +244,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
244
244
  isEnum: () => isEnum,
245
245
  isForeignKeyField: () => isForeignKeyField,
246
246
  isInheritedField: () => isInheritedField,
247
+ isPrimitiveTypeDef: () => isPrimitiveTypeDef,
247
248
  isRelationField: () => isRelationField,
248
249
  isScalarField: () => isScalarField,
249
250
  isTypeDef: () => isTypeDef,
@@ -424,6 +425,9 @@ function getEnum(schema, type) {
424
425
  function isTypeDef(schema, type) {
425
426
  return !!schema.typeDefs?.[type];
426
427
  }
428
+ function isPrimitiveTypeDef(schema, type) {
429
+ return !!schema.typeDefs?.[type]?.base;
430
+ }
427
431
  function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
428
432
  const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
429
433
  return keyPairs.map(({ fk, pk }) => {
@@ -727,12 +731,12 @@ var BaseCrudDialect = class {
727
731
  const { args: _args, ...rest } = payload;
728
732
  filterPayload = rest;
729
733
  }
730
- 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);
731
735
  if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
732
736
  else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
733
737
  }
734
738
  }
735
- 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 }));
736
740
  return result;
737
741
  }
738
742
  buildCursorFilter(model, query, cursor, orderBy, negateOrderBy, modelAlias) {
@@ -747,8 +751,8 @@ var BaseCrudDialect = class {
747
751
  const [field, order] = orderByItems[j];
748
752
  const op = j === i ? (negateOrderBy ? order === "asc" ? "desc" : "asc" : order) === "asc" ? ">=" : "<=" : "=";
749
753
  const fieldDef = requireField(this.schema, model, field);
750
- const outerAlias = fieldDef.originModel ?? modelAlias;
751
- const subSelectAlias = fieldDef.originModel ?? subQueryAlias;
754
+ const outerAlias = this.delegateFieldAlias(model, modelAlias, fieldDef);
755
+ const subSelectAlias = this.delegateFieldAlias(model, subQueryAlias, fieldDef);
752
756
  andFilters.push(this.eb(this.eb.ref(`${outerAlias}.${field}`), op, this.buildSelectModel(model, subQueryAlias).select(`${subSelectAlias}.${field}`).where(cursorFilter)));
753
757
  }
754
758
  filters.push(this.eb.and(andFilters));
@@ -786,7 +790,7 @@ var BaseCrudDialect = class {
786
790
  else return this.buildToOneRelationFilter(model, modelAlias, field, fieldDef, { is: null });
787
791
  }
788
792
  const joinAlias = tmpAlias(`${modelAlias}$${field}`);
789
- 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);
790
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)))));
791
795
  const existsSelect = (extraFilter) => {
792
796
  const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
@@ -880,11 +884,13 @@ var BaseCrudDialect = class {
880
884
  buildPrimitiveFilter(fieldRef, fieldDef, payload) {
881
885
  if (payload === null) return this.eb(fieldRef, "is", null);
882
886
  if (isEnum(this.schema, fieldDef.type)) return this.buildEnumFilter(fieldRef, fieldDef, payload);
883
- 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 {
884
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);
885
891
  return this.buildJsonFilter(fieldRef, payload, fieldDef);
886
892
  }
887
- 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", () => {
888
894
  throw createInvalidInputError(`Unsupported field cannot be used in filters`);
889
895
  }).exhaustive();
890
896
  }
@@ -984,11 +990,12 @@ var BaseCrudDialect = class {
984
990
  const fieldDef = typeDef.fields[key];
985
991
  (0, _zenstackhq_common_helpers.invariant)(fieldDef, `Field "${key}" not found in type definition "${typeDefName}"`);
986
992
  const fieldReceiver = this.buildJsonPathSelection(receiver, `$.${key}`);
987
- 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));
988
994
  else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
989
995
  else {
996
+ const effectiveType = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
990
997
  let _receiver = fieldReceiver;
991
- 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));
992
999
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
993
1000
  }
994
1001
  }
@@ -1132,7 +1139,7 @@ var BaseCrudDialect = class {
1132
1139
  let result = query;
1133
1140
  const buildFieldRef = (model, field, modelAlias, computedArgs) => {
1134
1141
  const fieldDef = requireField(this.schema, model, field);
1135
- 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);
1136
1143
  };
1137
1144
  (0, _zenstackhq_common_helpers.enumerate)(orderBy).forEach((orderBy, index) => {
1138
1145
  for (const [field, value] of Object.entries(orderBy)) {
@@ -1181,10 +1188,15 @@ var BaseCrudDialect = class {
1181
1188
  return query;
1182
1189
  }
1183
1190
  const joinAlias = tmpAlias(`${modelAlias}$ob$${index}`);
1184
- const joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
1185
- 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);
1186
1193
  return join.on((eb) => this.and(...joinPairs.map(([left, right]) => eb(this.eb.ref(left), "=", this.eb.ref(right)))));
1187
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
+ }
1188
1200
  return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
1189
1201
  }
1190
1202
  applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
@@ -1248,12 +1260,13 @@ var BaseCrudDialect = class {
1248
1260
  const descendants = getDelegateDescendantModels(this.schema, model);
1249
1261
  for (const subModel of descendants) {
1250
1262
  result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
1263
+ const subModelAlias = this.delegateJoinAlias(model, modelAlias, subModel.name);
1251
1264
  result = result.select(() => {
1252
1265
  const jsonObject = {};
1253
1266
  for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
1254
1267
  if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
1255
1268
  if (fieldDef.computed && fieldDef.params) continue;
1256
- jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1269
+ jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModelAlias);
1257
1270
  }
1258
1271
  return this.buildJsonObject(jsonObject).as(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1259
1272
  });
@@ -1276,17 +1289,35 @@ var BaseCrudDialect = class {
1276
1289
  buildSelectField(query, model, modelAlias, field, computedArgs) {
1277
1290
  const fieldDef = requireField(this.schema, model, field);
1278
1291
  const fieldModel = fieldDef.originModel ?? model;
1279
- const alias = fieldDef.originModel ?? modelAlias;
1292
+ const alias = this.delegateFieldAlias(model, modelAlias, fieldDef);
1280
1293
  return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
1281
1294
  }
1282
- buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1295
+ buildDelegateJoin(thisModel, thisModelAlias, otherModel, query) {
1283
1296
  const idFields = requireIdFields(this.schema, thisModel);
1284
- 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) => {
1285
1300
  for (const idField of idFields) qb = qb.onRef(`${thisModelAlias}.${idField}`, "=", `${otherModelAlias}.${idField}`);
1286
1301
  return qb;
1287
1302
  });
1288
1303
  return query;
1289
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
+ }
1290
1321
  buildCountJson(model, eb, parentAlias, payload) {
1291
1322
  const modelDef = requireModel(this.schema, model);
1292
1323
  const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
@@ -1558,9 +1589,10 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1558
1589
  if (value instanceof require_common_types.JsonNullClass) return this.eb.cast(kysely.sql.lit("null"), "json");
1559
1590
  else if (value instanceof require_common_types.DbNullClass) return null;
1560
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");
1561
- 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);
1562
1594
  else return value;
1563
- else if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1595
+ if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1564
1596
  else throw createNotSupportedError(`MySQL does not support array literals`);
1565
1597
  else switch (type) {
1566
1598
  case "Boolean": return value ? 1 : 0;
@@ -1575,6 +1607,7 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1575
1607
  }
1576
1608
  transformOutput(value, type, array) {
1577
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);
1578
1611
  switch (type) {
1579
1612
  case "Boolean": return this.transformOutputBoolean(value);
1580
1613
  case "DateTime": return this.transformOutputDate(value);
@@ -1603,7 +1636,12 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1603
1636
  return new Date(!anchored.endsWith("Z") ? anchored + "Z" : anchored);
1604
1637
  }
1605
1638
  transformOutputBytes(value) {
1606
- 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;
1607
1645
  }
1608
1646
  buildExistsExpression(innerQuery) {
1609
1647
  return this.eb.exists(this.eb.selectFrom(innerQuery.as("$exists_sub")).select(this.eb.lit(1).as("_")));
@@ -1815,9 +1853,10 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1815
1853
  if (value instanceof require_common_types.JsonNullClass) return "null";
1816
1854
  else if (value instanceof require_common_types.DbNullClass) return null;
1817
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");
1818
- 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);
1819
1858
  else return value;
1820
- 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);
1821
1860
  else return value.map((v) => this.transformInput(v, type, false, fieldDef));
1822
1861
  else switch (type) {
1823
1862
  case "DateTime": {
@@ -1835,6 +1874,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1835
1874
  }
1836
1875
  transformOutput(value, type, array) {
1837
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);
1838
1878
  switch (type) {
1839
1879
  case "DateTime": return this.transformOutputDate(value);
1840
1880
  case "Bytes": return this.transformOutputBytes(value);
@@ -1947,6 +1987,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1947
1987
  const mapped = PostgresCrudDialect.dbAttributeToSqlTypeMap[attr.name];
1948
1988
  if (mapped) return mapped;
1949
1989
  }
1990
+ if (isPrimitiveTypeDef(this.schema, zmodelType)) zmodelType = this.schema.typeDefs[zmodelType].base;
1950
1991
  if (isEnum(this.schema, zmodelType)) return "text";
1951
1992
  else return this.zmodelToSqlTypeMap[zmodelType] ?? "text";
1952
1993
  }
@@ -2130,7 +2171,9 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2130
2171
  if (value instanceof require_common_types.JsonNullClass) return "null";
2131
2172
  else if (value instanceof require_common_types.DbNullClass) return null;
2132
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");
2133
- 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);
2134
2177
  if (Array.isArray(value)) return value.map((v) => this.transformInput(v, type, false));
2135
2178
  else switch (type) {
2136
2179
  case "Boolean": return value ? 1 : 0;
@@ -2142,8 +2185,10 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2142
2185
  }
2143
2186
  transformOutput(value, type, array) {
2144
2187
  if (value === null || value === void 0) return value;
2145
- else if (this.schema.typeDefs && type in this.schema.typeDefs) return this.transformOutputJson(value);
2146
- 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) {
2147
2192
  case "Boolean": return this.transformOutputBoolean(value);
2148
2193
  case "DateTime": return this.transformOutputDate(value);
2149
2194
  case "Bytes": return this.transformOutputBytes(value);
@@ -2565,7 +2610,7 @@ var ZodSchemaFactory = class {
2565
2610
  return result;
2566
2611
  }
2567
2612
  makeScalarSchema(type, attributes) {
2568
- 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);
2569
2614
  else if (this.schema.enums && type in this.schema.enums) return this.makeEnumSchema(type);
2570
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", () => {
2571
2616
  return zod.z.union([
@@ -2601,9 +2646,20 @@ var ZodSchemaFactory = class {
2601
2646
  this.registerSchema(_enum, schema);
2602
2647
  return schema;
2603
2648
  }
2604
- 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) {
2605
2657
  const typeDef = getTypeDef(this.schema, type);
2606
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
+ }
2607
2663
  const schema = (typeDef.strict ? zod.z.strictObject : zod.z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2608
2664
  let fieldSchema = isTypeDef(this.schema, def.type) ? zod.z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
2609
2665
  if (def.array) fieldSchema = fieldSchema.array();
@@ -2648,8 +2704,8 @@ var ZodSchemaFactory = class {
2648
2704
  if (enumDef) {
2649
2705
  if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, withAggregations, allowedFilterKinds);
2650
2706
  } else if (fieldDef.array) fieldSchema = this.makeArrayFilterSchema(fieldDef.type, allowedFilterKinds);
2651
- else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2652
- 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);
2653
2709
  }
2654
2710
  if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2655
2711
  if (fieldSchema) fields[field] = fieldSchema.optional();
@@ -2692,10 +2748,10 @@ var ZodSchemaFactory = class {
2692
2748
  const candidates = [];
2693
2749
  if (!array) {
2694
2750
  const fieldSchemas = {};
2695
- 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();
2696
2752
  else if (getEnum(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, false, void 0).optional();
2697
2753
  else if (fieldDef.array) fieldSchemas[fieldName] = this.makeArrayFilterSchema(fieldDef.type, void 0).optional();
2698
- 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();
2699
2755
  candidates.push(zod.z.strictObject(fieldSchemas));
2700
2756
  }
2701
2757
  const recursiveSchema = zod.z.lazy(() => this.makeTypedJsonFilterSchema(type, optional, false, allowedFilterKinds)).optional();
@@ -2733,6 +2789,10 @@ var ZodSchemaFactory = class {
2733
2789
  isTypeDefType(type) {
2734
2790
  return this.schema.typeDefs && type in this.schema.typeDefs;
2735
2791
  }
2792
+ getEffectiveFieldType(type) {
2793
+ if (isPrimitiveTypeDef(this.schema, type)) return this.schema.typeDefs[type].base;
2794
+ return type;
2795
+ }
2736
2796
  makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds) {
2737
2797
  const enumDef = getEnum(this.schema, enumName);
2738
2798
  (0, _zenstackhq_common_helpers.invariant)(enumDef, `Enum "${enumName}" not found in schema`);
@@ -3208,7 +3268,7 @@ var ZodSchemaFactory = class {
3208
3268
  checkedVariantFields[field] = fieldSchema;
3209
3269
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3210
3270
  } else {
3211
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3271
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3212
3272
  if (fieldDef.array) {
3213
3273
  fieldSchema = _zenstackhq_zod.ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
3214
3274
  fieldSchema = zod.z.union([fieldSchema, zod.z.strictObject({ set: fieldSchema })]).optional();
@@ -3386,7 +3446,7 @@ var ZodSchemaFactory = class {
3386
3446
  checkedVariantFields[field] = fieldSchema;
3387
3447
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3388
3448
  } else {
3389
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3449
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3390
3450
  if (this.isNumericField(fieldDef)) fieldSchema = zod.z.union([fieldSchema, zod.z.object({
3391
3451
  set: this.nullableIf(zod.z.number().optional(), !!fieldDef.optional).optional(),
3392
3452
  increment: zod.z.number().optional(),
@@ -3627,7 +3687,7 @@ var ZodSchemaFactory = class {
3627
3687
  return canBeArray ? zod.z.union([schema, zod.z.array(schema)]) : schema;
3628
3688
  }
3629
3689
  isNumericField(fieldDef) {
3630
- return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3690
+ return require_constants.NUMERIC_FIELD_TYPES.includes(this.getEffectiveFieldType(fieldDef.type)) && !fieldDef.array;
3631
3691
  }
3632
3692
  get providerSupportsCaseSensitivity() {
3633
3693
  return this.schema.provider.type === "postgresql";
@@ -3747,7 +3807,7 @@ __decorate([
3747
3807
  __decorate([
3748
3808
  cache(),
3749
3809
  __decorateMetadata("design:type", Function),
3750
- __decorateMetadata("design:paramtypes", [String]),
3810
+ __decorateMetadata("design:paramtypes", [String, Array]),
3751
3811
  __decorateMetadata("design:returntype", typeof (_ref2 = typeof zod.ZodType !== "undefined" && zod.ZodType) === "function" ? _ref2 : Object)
3752
3812
  ], ZodSchemaFactory.prototype, "makeTypeDefSchema", null);
3753
3813
  __decorate([
@@ -4353,7 +4413,7 @@ var BaseOperationHandler = class {
4353
4413
  result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4354
4414
  } else {
4355
4415
  if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
4356
- 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);
4357
4417
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
4358
4418
  }
4359
4419
  }
@@ -4715,16 +4775,9 @@ var BaseOperationHandler = class {
4715
4775
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4716
4776
  const origWhere = combinedWhere;
4717
4777
  const modelDef = this.requireModel(model);
4718
- let finalData = data;
4719
- const autoUpdatedFields = [];
4720
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && finalData[fieldName] === void 0) {
4721
- const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
4722
- if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
4723
- if (finalData === data) finalData = (0, _zenstackhq_common_helpers.clone)(data);
4724
- finalData[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
4725
- autoUpdatedFields.push(fieldName);
4726
- }
4727
- }
4778
+ const filled = this.fillUpdatedAtFields(modelDef, data);
4779
+ let finalData = filled.data;
4780
+ const autoUpdatedFields = filled.autoUpdatedFields;
4728
4781
  let thisEntity;
4729
4782
  const loadThisEntity = async () => {
4730
4783
  if (thisEntity === void 0) {
@@ -4873,7 +4926,8 @@ var BaseOperationHandler = class {
4873
4926
  });
4874
4927
  }
4875
4928
  isNumericField(fieldDef) {
4876
- return require_constants.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;
4877
4931
  }
4878
4932
  makeContextComment(_context) {
4879
4933
  return kysely.sql``;
@@ -4886,11 +4940,13 @@ var BaseOperationHandler = class {
4886
4940
  const parentWhere = await this.buildUpdateParentRelationFilter(kysely$19, fromRelation);
4887
4941
  let combinedWhere = where ?? true;
4888
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);
4889
4945
  filterModel ??= model;
4890
4946
  let updateFields = {};
4891
- for (const field in data) {
4947
+ for (const field in finalData) {
4892
4948
  if (isRelationField(this.schema, model, field)) continue;
4893
- updateFields[field] = this.processScalarFieldUpdateData(model, field, data);
4949
+ updateFields[field] = this.processScalarFieldUpdateData(model, field, finalData);
4894
4950
  }
4895
4951
  let resultFromBaseModel = void 0;
4896
4952
  if (modelDef.baseModel) {
@@ -4941,7 +4997,51 @@ var BaseOperationHandler = class {
4941
4997
  }
4942
4998
  }
4943
4999
  }
4944
- 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) {
4945
5045
  const thisUpdateFields = {};
4946
5046
  const remainingFields = {};
4947
5047
  Object.entries(updateFields).forEach(([field, value]) => {
@@ -4949,14 +5049,14 @@ var BaseOperationHandler = class {
4949
5049
  else remainingFields[field] = value;
4950
5050
  });
4951
5051
  return {
4952
- 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),
4953
5053
  remainingFields
4954
5054
  };
4955
5055
  }
4956
- buildIdFieldRefs(kysely$21, model) {
4957
- 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}`));
4958
5058
  }
4959
- async processRelationUpdates(kysely$22, model, field, fieldDef, parentIds, args) {
5059
+ async processRelationUpdates(kysely$23, model, field, fieldDef, parentIds, args) {
4960
5060
  const fieldModel = fieldDef.type;
4961
5061
  const fromRelationContext = {
4962
5062
  model,
@@ -4967,24 +5067,24 @@ var BaseOperationHandler = class {
4967
5067
  for (const [key, value] of Object.entries(args)) switch (key) {
4968
5068
  case "create":
4969
5069
  (0, _zenstackhq_common_helpers.invariant)(!Array.isArray(value) || fieldDef.array, "relation must be an array if create is an array");
4970
- 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);
4971
5071
  break;
4972
5072
  case "createMany":
4973
5073
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array for createMany");
4974
- await this.createMany(kysely$22, fieldModel, value, false, fromRelationContext);
5074
+ await this.createMany(kysely$23, fieldModel, value, false, fromRelationContext);
4975
5075
  break;
4976
5076
  case "connect":
4977
- await this.connectRelation(kysely$22, fieldModel, value, fromRelationContext);
5077
+ await this.connectRelation(kysely$23, fieldModel, value, fromRelationContext);
4978
5078
  break;
4979
5079
  case "connectOrCreate":
4980
- await this.connectOrCreateRelation(kysely$22, fieldModel, value, fromRelationContext);
5080
+ await this.connectOrCreateRelation(kysely$23, fieldModel, value, fromRelationContext);
4981
5081
  break;
4982
5082
  case "disconnect":
4983
- await this.disconnectRelation(kysely$22, fieldModel, value, fromRelationContext);
5083
+ await this.disconnectRelation(kysely$23, fieldModel, value, fromRelationContext);
4984
5084
  break;
4985
5085
  case "set":
4986
5086
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array");
4987
- await this.setRelation(kysely$22, fieldModel, value, fromRelationContext);
5087
+ await this.setRelation(kysely$23, fieldModel, value, fromRelationContext);
4988
5088
  break;
4989
5089
  case "update":
4990
5090
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
@@ -4999,76 +5099,76 @@ var BaseOperationHandler = class {
4999
5099
  data = item;
5000
5100
  }
5001
5101
  const throwIfNotFound = !fieldDef.array || !!where;
5002
- await this.update(kysely$22, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5102
+ await this.update(kysely$23, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5003
5103
  }
5004
5104
  break;
5005
5105
  case "upsert":
5006
5106
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5007
5107
  const item = _item;
5008
- 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);
5009
5109
  }
5010
5110
  break;
5011
5111
  case "updateMany":
5012
5112
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5013
5113
  const item = _item;
5014
- 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);
5015
5115
  }
5016
5116
  break;
5017
5117
  case "delete":
5018
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, true, true);
5118
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, true, true);
5019
5119
  break;
5020
5120
  case "deleteMany":
5021
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, false, false);
5121
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, false, false);
5022
5122
  break;
5023
5123
  default: throw createInvalidInputError(`Invalid relation update operation: ${key}`);
5024
5124
  }
5025
5125
  return fromRelationContext.parentUpdates;
5026
5126
  }
5027
- async connectRelation(kysely$23, model, data, fromRelation) {
5127
+ async connectRelation(kysely$24, model, data, fromRelation) {
5028
5128
  const _data = this.normalizeRelationManipulationInput(model, data);
5029
5129
  if (_data.length === 0) return;
5030
5130
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5031
5131
  if (m2m) {
5032
- const allIds = await this.getEntitiesIds(kysely$23, model, _data);
5132
+ const allIds = await this.getEntitiesIds(kysely$24, model, _data);
5033
5133
  if (allIds.length !== _data.length) throw createNotFoundError(model);
5034
- 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);
5035
5135
  } else {
5036
5136
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5037
5137
  if (ownedByModel) {
5038
5138
  (0, _zenstackhq_common_helpers.invariant)(_data.length === 1, "only one entity can be connected");
5039
- const target = await this.readUnique(kysely$23, model, { where: _data[0] });
5139
+ const target = await this.readUnique(kysely$24, model, { where: _data[0] });
5040
5140
  if (!target) throw createNotFoundError(model);
5041
5141
  for (const { fk, pk } of keyPairs) fromRelation.parentUpdates[fk] = target[pk];
5042
5142
  } else {
5043
5143
  if (!this.requireField(fromRelation.model, fromRelation.field).array) {
5044
- 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 }) => ({
5045
5145
  ...acc,
5046
5146
  [fk]: null
5047
5147
  }), {})).modifyEnd(this.makeContextComment({
5048
5148
  model: fromRelation.model,
5049
5149
  operation: "update"
5050
5150
  }));
5051
- await this.executeQuery(kysely$23, query, "disconnect");
5151
+ await this.executeQuery(kysely$24, query, "disconnect");
5052
5152
  }
5053
- 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 }) => ({
5054
5154
  ...acc,
5055
5155
  [fk]: fromRelation.ids[pk]
5056
5156
  }), {})).modifyEnd(this.makeContextComment({
5057
5157
  model,
5058
5158
  operation: "update"
5059
5159
  }));
5060
- const updateResult = await this.executeQuery(kysely$23, query, "connect");
5160
+ const updateResult = await this.executeQuery(kysely$24, query, "connect");
5061
5161
  if (!updateResult.numAffectedRows || _data.length > updateResult.numAffectedRows) throw createNotFoundError(model);
5062
5162
  }
5063
5163
  }
5064
5164
  }
5065
- async connectOrCreateRelation(kysely$24, model, data, fromRelation) {
5165
+ async connectOrCreateRelation(kysely$25, model, data, fromRelation) {
5066
5166
  const _data = (0, _zenstackhq_common_helpers.enumerate)(data);
5067
5167
  if (_data.length === 0) return;
5068
- for (const { where, create } of _data) if (await this.exists(kysely$24, model, where)) await this.connectRelation(kysely$24, model, [where], fromRelation);
5069
- 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);
5070
5170
  }
5071
- async disconnectRelation(kysely$25, model, data, fromRelation) {
5171
+ async disconnectRelation(kysely$26, model, data, fromRelation) {
5072
5172
  let disconnectConditions = [];
5073
5173
  if (typeof data === "boolean") if (data === false) return;
5074
5174
  else disconnectConditions = [true];
@@ -5080,8 +5180,8 @@ var BaseOperationHandler = class {
5080
5180
  if (disconnectConditions.length === 0) return;
5081
5181
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5082
5182
  if (m2m) {
5083
- const allIds = await this.getEntitiesIds(kysely$25, model, disconnectConditions);
5084
- 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);
5085
5185
  } else {
5086
5186
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5087
5187
  const eb = (0, kysely.expressionBuilder)();
@@ -5090,39 +5190,39 @@ var BaseOperationHandler = class {
5090
5190
  const condition = disconnectConditions[0];
5091
5191
  if (condition === true) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5092
5192
  else {
5093
- const fromEntity = await this.readUnique(kysely$25, fromRelation.model, {
5193
+ const fromEntity = await this.readUnique(kysely$26, fromRelation.model, {
5094
5194
  where: fromRelation.ids,
5095
5195
  select: fieldsToSelectObject(keyPairs.map(({ fk }) => fk))
5096
5196
  });
5097
5197
  if (!fromEntity || keyPairs.some(({ fk }) => fromEntity[fk] == null)) return;
5098
5198
  const relationFilter = { AND: [condition, Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]]))] };
5099
- if ((await this.read(kysely$25, model, {
5199
+ if ((await this.read(kysely$26, model, {
5100
5200
  where: relationFilter,
5101
5201
  take: 1,
5102
5202
  select: this.makeIdSelect(model)
5103
5203
  })).length > 0) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5104
5204
  }
5105
5205
  } else {
5106
- 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 }) => ({
5107
5207
  ...acc,
5108
5208
  [fk]: null
5109
5209
  }), {})).modifyEnd(this.makeContextComment({
5110
5210
  model,
5111
5211
  operation: "update"
5112
5212
  }));
5113
- await this.executeQuery(kysely$25, query, "disconnect");
5213
+ await this.executeQuery(kysely$26, query, "disconnect");
5114
5214
  }
5115
5215
  }
5116
5216
  }
5117
- async setRelation(kysely$26, model, data, fromRelation) {
5217
+ async setRelation(kysely$27, model, data, fromRelation) {
5118
5218
  const _data = this.normalizeRelationManipulationInput(model, data);
5119
5219
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5120
5220
  if (m2m) {
5121
- await this.resetManyToManyRelation(kysely$26, fromRelation.model, fromRelation.field, fromRelation.ids);
5221
+ await this.resetManyToManyRelation(kysely$27, fromRelation.model, fromRelation.field, fromRelation.ids);
5122
5222
  if (_data.length > 0) {
5123
- const allIds = await this.getEntitiesIds(kysely$26, model, _data);
5223
+ const allIds = await this.getEntitiesIds(kysely$27, model, _data);
5124
5224
  if (allIds.length !== _data.length) throw createNotFoundError(model);
5125
- 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);
5126
5226
  }
5127
5227
  } else {
5128
5228
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
@@ -5131,28 +5231,28 @@ var BaseOperationHandler = class {
5131
5231
  ...acc,
5132
5232
  [fk]: fromRelation.ids[pk]
5133
5233
  }), {});
5134
- 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 }) => ({
5135
5235
  ...acc,
5136
5236
  [fk]: null
5137
5237
  }), {})).modifyEnd(this.makeContextComment({
5138
5238
  model,
5139
5239
  operation: "update"
5140
5240
  }));
5141
- await this.executeQuery(kysely$26, query, "disconnect");
5241
+ await this.executeQuery(kysely$27, query, "disconnect");
5142
5242
  if (_data.length > 0) {
5143
- 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 }) => ({
5144
5244
  ...acc,
5145
5245
  [fk]: fromRelation.ids[pk]
5146
5246
  }), {})).modifyEnd(this.makeContextComment({
5147
5247
  model,
5148
5248
  operation: "update"
5149
5249
  }));
5150
- const r = await this.executeQuery(kysely$26, query, "connect");
5250
+ const r = await this.executeQuery(kysely$27, query, "connect");
5151
5251
  if (!r.numAffectedRows || _data.length > r.numAffectedRows) throw createNotFoundError(model);
5152
5252
  }
5153
5253
  }
5154
5254
  }
5155
- async deleteRelation(kysely$27, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5255
+ async deleteRelation(kysely$28, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5156
5256
  let deleteConditions = [];
5157
5257
  let expectedDeleteCount = -1;
5158
5258
  if (typeof data === "boolean") if (data === false) return;
@@ -5174,18 +5274,18 @@ var BaseOperationHandler = class {
5174
5274
  deleteFromModel = model;
5175
5275
  const fieldDef = this.requireField(fromRelation.model, fromRelation.field);
5176
5276
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.relation?.opposite);
5177
- 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 }] });
5178
5278
  } else {
5179
5279
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5180
5280
  if (ownedByModel) {
5181
5281
  deleteFromModel = fromRelation.model;
5182
- 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 });
5183
5283
  if (!fromEntity) throw createNotFoundError(fromRelation.model);
5184
5284
  (0, _zenstackhq_common_helpers.invariant)(this.requireField(fromRelation.model, fromRelation.field).relation?.opposite);
5185
- 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 }] });
5186
5286
  } else {
5187
5287
  deleteFromModel = model;
5188
- 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 }] });
5189
5289
  }
5190
5290
  }
5191
5291
  if (throwForNotFound && expectedDeleteCount >= 0 && expectedDeleteCount > (deleteResult.numAffectedRows ?? 0)) throw createNotFoundError(deleteFromModel);
@@ -5193,27 +5293,22 @@ var BaseOperationHandler = class {
5193
5293
  normalizeRelationManipulationInput(model, data) {
5194
5294
  return (0, _zenstackhq_common_helpers.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
5195
5295
  }
5196
- async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn, visited) {
5296
+ async delete(kysely$29, model, where, limit, filterModel, fieldsToReturn, visited) {
5197
5297
  filterModel ??= model;
5198
5298
  visited ??= /* @__PURE__ */ new Set();
5199
5299
  const modelDef = this.requireModel(model);
5200
5300
  if (modelDef.baseModel) {
5201
5301
  if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5202
- return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel, visited);
5302
+ return this.processBaseModelDelete(kysely$29, modelDef.baseModel, where, limit, filterModel, visited);
5203
5303
  }
5204
5304
  const cascadeRelations = this.getDelegateCascadeRelations(model, filterModel);
5205
- if (cascadeRelations.length === 0) return this.executeDelete(kysely$28, model, where, limit, filterModel, fieldsToReturn);
5206
- if (!modelDef.isDelegate) {
5207
- if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5208
- for (const { fieldDef } of cascadeRelations) await this.delete(kysely$28, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0, void 0, void 0, visited);
5209
- return this.executeDelete(kysely$28, model, where, limit, filterModel, fieldsToReturn);
5210
- }
5305
+ if (cascadeRelations.length === 0) return this.executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn);
5211
5306
  const discriminator = getDiscriminatorField(this.schema, model);
5212
- const deletedRows = await this.read(kysely$28, filterModel, {
5307
+ const deletedRows = await this.read(kysely$29, filterModel, {
5213
5308
  where,
5214
5309
  select: {
5215
5310
  ...this.makeIdSelect(filterModel),
5216
- [discriminator]: true
5311
+ ...discriminator ? { [discriminator]: true } : {}
5217
5312
  },
5218
5313
  ...limit !== void 0 ? { take: limit } : {}
5219
5314
  });
@@ -5222,7 +5317,7 @@ var BaseOperationHandler = class {
5222
5317
  const parentRows = discriminatorValue === void 0 ? deletedRows : deletedRows.filter((row) => row[discriminator] === discriminatorValue);
5223
5318
  for (const batch of this.batchRows(model, parentRows)) {
5224
5319
  const childModel = fieldDef.type;
5225
- const pendingRows = (await this.read(kysely$28, childModel, {
5320
+ const pendingRows = (await this.read(kysely$29, childModel, {
5226
5321
  where: this.makeChildFilter(model, fieldDef, batch),
5227
5322
  select: this.makeIdSelect(childModel)
5228
5323
  })).filter((row) => {
@@ -5231,13 +5326,13 @@ var BaseOperationHandler = class {
5231
5326
  visited.add(key);
5232
5327
  return true;
5233
5328
  });
5234
- for (const childBatch of this.batchRows(childModel, pendingRows)) await this.delete(kysely$28, childModel, this.makeIdsFilter(childModel, childBatch), void 0, void 0, void 0, visited);
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);
5235
5330
  }
5236
5331
  }
5237
5332
  let numAffectedRows = 0n;
5238
5333
  const rows = [];
5239
5334
  for (const batch of this.batchRows(model, deletedRows)) {
5240
- const result = await this.executeDelete(kysely$28, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
5335
+ const result = await this.executeDelete(kysely$29, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
5241
5336
  numAffectedRows += result.numAffectedRows ?? 0n;
5242
5337
  rows.push(...result.rows);
5243
5338
  }
@@ -5246,18 +5341,18 @@ var BaseOperationHandler = class {
5246
5341
  rows
5247
5342
  };
5248
5343
  }
5249
- async executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn) {
5344
+ async executeDelete(kysely$30, model, where, limit, filterModel, fieldsToReturn) {
5250
5345
  const modelDef = this.requireModel(model);
5251
5346
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
5252
5347
  let needIdFilter = false;
5253
5348
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
5254
5349
  if (modelDef.isDelegate || modelDef.baseModel) needIdFilter = true;
5255
- const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely$29, model)), "in", eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely$29, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()) : () => this.dialect.buildFilter(model, model, where);
5256
- const query = kysely$29.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({
5257
5352
  model,
5258
5353
  operation: "delete"
5259
5354
  }));
5260
- return this.executeQuery(kysely$29, query, "delete");
5355
+ return this.executeQuery(kysely$30, query, "delete");
5261
5356
  }
5262
5357
  /**
5263
5358
  * Gets the relations whose deletion must be simulated when deleting from the given model: relations
@@ -5315,8 +5410,8 @@ var BaseOperationHandler = class {
5315
5410
  const size = this.requireModel(model).idFields.length === 1 ? DELETE_ID_BATCH_SIZE : DELETE_COMPOUND_ID_BATCH_SIZE;
5316
5411
  for (let i = 0; i < rows.length; i += size) yield rows.slice(i, i + size);
5317
5412
  }
5318
- async processBaseModelDelete(kysely$30, model, where, limit, filterModel, visited) {
5319
- return this.delete(kysely$30, model, where, limit, filterModel, void 0, visited);
5413
+ async processBaseModelDelete(kysely$31, model, where, limit, filterModel, visited) {
5414
+ return this.delete(kysely$31, model, where, limit, filterModel, void 0, visited);
5320
5415
  }
5321
5416
  makeIdSelect(model) {
5322
5417
  return this.requireModel(model).idFields.reduce((acc, f) => {
@@ -5351,14 +5446,14 @@ var BaseOperationHandler = class {
5351
5446
  if (condition) return this.safeTransaction(callback, isolationLevel);
5352
5447
  else return callback(this.kysely);
5353
5448
  }
5354
- getEntityIds(kysely$31, model, uniqueFilter) {
5355
- return this.readUnique(kysely$31, model, {
5449
+ getEntityIds(kysely$32, model, uniqueFilter) {
5450
+ return this.readUnique(kysely$32, model, {
5356
5451
  where: uniqueFilter,
5357
5452
  select: this.makeIdSelect(model)
5358
5453
  });
5359
5454
  }
5360
- getEntitiesIds(kysely$32, model, uniqueFilters) {
5361
- return this.read(kysely$32, model, {
5455
+ getEntitiesIds(kysely$33, model, uniqueFilters) {
5456
+ return this.read(kysely$33, model, {
5362
5457
  where: { OR: uniqueFilters },
5363
5458
  select: this.makeIdSelect(model)
5364
5459
  });
@@ -5378,14 +5473,14 @@ var BaseOperationHandler = class {
5378
5473
  else if (value && (0, _zenstackhq_common_helpers.isPlainObject)(value)) this.doNormalizeArgs(value);
5379
5474
  }
5380
5475
  }
5381
- executeQuery(kysely$33, query, _operation) {
5382
- return kysely$33.executeQuery(query.compile());
5476
+ executeQuery(kysely$34, query, _operation) {
5477
+ return kysely$34.executeQuery(query.compile());
5383
5478
  }
5384
- async executeQueryTakeFirst(kysely$34, query, _operation) {
5385
- 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];
5386
5481
  }
5387
- async executeQueryTakeFirstOrThrow(kysely$35, query, _operation) {
5388
- const result = await kysely$35.executeQuery(query.compile());
5482
+ async executeQueryTakeFirstOrThrow(kysely$36, query, _operation) {
5483
+ const result = await kysely$36.executeQuery(query.compile());
5389
5484
  if (result.rows.length === 0) throw new ORMError(ORMErrorReason.NOT_FOUND, "No rows found");
5390
5485
  return result.rows[0];
5391
5486
  }
@@ -5492,7 +5587,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5492
5587
  if (typeof value === "string") {
5493
5588
  const fieldDef = getField(this.schema, this.model, field);
5494
5589
  if (fieldDef) {
5495
- const type = fieldDef.type;
5590
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5496
5591
  if (op === "_avg") val = parseFloat(val);
5497
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);
5498
5593
  }
@@ -5715,7 +5810,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5715
5810
  if (typeof value === "string") {
5716
5811
  const fieldDef = getField(this.schema, this.model, field);
5717
5812
  if (fieldDef) {
5718
- const type = fieldDef.type;
5813
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5719
5814
  if (op === "_avg") val = parseFloat(val);
5720
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);
5721
5816
  }
@@ -6135,7 +6230,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6135
6230
  return kysely.ColumnNode.create(mappedName);
6136
6231
  }
6137
6232
  transformBinaryOperation(node, queryId) {
6138
- 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))) {
6139
6234
  const columnNode = node.leftOperand.column;
6140
6235
  const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
6141
6236
  if (resolvedScope?.model) {
@@ -6143,6 +6238,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6143
6238
  let resultValue = valueNode;
6144
6239
  if (kysely.ValueNode.is(valueNode)) resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
6145
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));
6146
6242
  return super.transformBinaryOperation({
6147
6243
  ...node,
6148
6244
  rightOperand: resultValue
@@ -6543,7 +6639,11 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6543
6639
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6544
6640
  }
6545
6641
  get hasEntityMutationPluginsWithAfterMutationHooks() {
6546
- 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
+ });
6547
6647
  }
6548
6648
  get hasOnKyselyHooks() {
6549
6649
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onKyselyQuery);
@@ -6648,8 +6748,17 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6648
6748
  const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
6649
6749
  if (this.options.plugins) for (const plugin of this.options.plugins) {
6650
6750
  const onEntityMutation = plugin.onEntityMutation;
6651
- if (!onEntityMutation?.beforeEntityMutation) continue;
6652
- 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({
6653
6762
  model: mutationInfo.model,
6654
6763
  action: mutationInfo.action,
6655
6764
  queryNode,
@@ -6664,10 +6773,16 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6664
6773
  const hooks = [];
6665
6774
  for (const plugin of this.options.plugins ?? []) {
6666
6775
  const onEntityMutation = plugin.onEntityMutation;
6667
- if (!onEntityMutation?.afterEntityMutation) continue;
6668
- if (filterFor === "inTx" && !onEntityMutation.runAfterMutationWithinTransaction) continue;
6669
- if (filterFor === "outTx" && onEntityMutation.runAfterMutationWithinTransaction) continue;
6670
- 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
+ }
6671
6786
  }
6672
6787
  if (hooks.length === 0) return;
6673
6788
  for (const hook of hooks) await hook({
@@ -6682,7 +6797,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6682
6797
  }
6683
6798
  async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
6684
6799
  if (mutationInfo.action === "delete") return;
6685
- if (this.dialect.supportsReturning) return queryResult.rows;
6800
+ if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
6686
6801
  else {
6687
6802
  const mutatedIds = kysely.InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
6688
6803
  if (mutatedIds) {
@@ -7142,8 +7257,12 @@ var SchemaDbPusher = class {
7142
7257
  return kysely.sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
7143
7258
  } else return "text";
7144
7259
  if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") return "serial";
7145
- if (this.isCustomType(fieldDef.type)) return this.jsonType;
7146
- 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
+ }
7147
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(() => {
7148
7267
  throw new Error(`Unsupported field type: ${type}`);
7149
7268
  });
@@ -7335,6 +7454,7 @@ var ResultProcessor = class {
7335
7454
  };
7336
7455
  //#endregion
7337
7456
  //#region src/client/client-impl.ts
7457
+ const warnedPlugins = /* @__PURE__ */ new WeakSet();
7338
7458
  /**
7339
7459
  * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7340
7460
  */
@@ -7365,6 +7485,7 @@ var ClientImpl = class ClientImpl {
7365
7485
  ...functions_exports,
7366
7486
  ...this.$options.functions
7367
7487
  };
7488
+ if (this.$options.plugins) this.$options.plugins = this.normalizePlugins(this.$options.plugins);
7368
7489
  this.validateOptions(baseClient, options);
7369
7490
  if (baseClient) {
7370
7491
  this.kyselyProps = {
@@ -7398,6 +7519,63 @@ var ClientImpl = class ClientImpl {
7398
7519
  this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this, { enabled: this.$options.validateInput !== false });
7399
7520
  return createClientProxy(this);
7400
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
+ }
7401
7579
  validateOptions(baseClient, options) {
7402
7580
  if (!baseClient && !options.skipValidationForComputedFields) this.validateComputedFieldsConfig(options);
7403
7581
  if (options.diagnostics) {