@zenstackhq/orm 3.9.8 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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);
@@ -2391,6 +2436,20 @@ function createQuerySchemaFactory(clientOrSchema, options) {
2391
2436
  return new ZodSchemaFactory(clientOrSchema, options);
2392
2437
  }
2393
2438
  /**
2439
+ * Whether two client options produce the same query-args schemas, i.e. a `ZodSchemaFactory`
2440
+ * built for one can serve the other. Only `omit`, `slicing`, `allowQueryTimeOmitOverride` and
2441
+ * the plugins that extend query args or results shape the schemas; dialect, auth, hooks and
2442
+ * validation flags do not.
2443
+ */
2444
+ function haveSameSchemaInputs(a, b) {
2445
+ if (a === b) return true;
2446
+ if (a.omit !== b.omit || a.slicing !== b.slicing || a.allowQueryTimeOmitOverride !== b.allowQueryTimeOmitOverride) return false;
2447
+ const shaping = (options) => (options.plugins ?? []).filter((plugin) => plugin.queryArgs || plugin.result);
2448
+ const pa = shaping(a);
2449
+ const pb = shaping(b);
2450
+ return pa.length === pb.length && pa.every((plugin, index) => plugin === pb[index]);
2451
+ }
2452
+ /**
2394
2453
  * Builds a `DateTime` value schema that accepts a `Date` object or any string
2395
2454
  * the JS `Date` constructor parses, and coerces it to a `Date`. ISO datetime,
2396
2455
  * ISO date, and time-only strings (e.g. `"09:00:00"` for `@db.Time` fields,
@@ -2565,7 +2624,7 @@ var ZodSchemaFactory = class {
2565
2624
  return result;
2566
2625
  }
2567
2626
  makeScalarSchema(type, attributes) {
2568
- if (this.schema.typeDefs && type in this.schema.typeDefs) return this.makeTypeDefSchema(type);
2627
+ if (this.schema.typeDefs && type in this.schema.typeDefs) return this.schema.typeDefs[type].base ? this.makeTypeDefSchema(type, attributes) : this.makeTypeDefSchema(type);
2569
2628
  else if (this.schema.enums && type in this.schema.enums) return this.makeEnumSchema(type);
2570
2629
  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
2630
  return zod.z.union([
@@ -2601,15 +2660,27 @@ var ZodSchemaFactory = class {
2601
2660
  this.registerSchema(_enum, schema);
2602
2661
  return schema;
2603
2662
  }
2604
- makeTypeDefSchema(type) {
2663
+ /**
2664
+ * Attributes to validate each value of a scalar field against. For typedef list fields, the
2665
+ * field's own attributes (e.g. `@length`) validate the list rather than its items.
2666
+ */
2667
+ getItemAttributes(fieldDef) {
2668
+ return fieldDef.array && isTypeDef(this.schema, fieldDef.type) ? void 0 : fieldDef.attributes;
2669
+ }
2670
+ makeTypeDefSchema(type, fieldAttributes) {
2605
2671
  const typeDef = getTypeDef(this.schema, type);
2606
2672
  (0, _zenstackhq_common_helpers.invariant)(typeDef, `Type definition "${type}" not found in schema`);
2607
- const schema = (typeDef.strict ? zod.z.strictObject : zod.z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2608
- let fieldSchema = isTypeDef(this.schema, def.type) ? zod.z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
2609
- if (def.array) fieldSchema = fieldSchema.array();
2673
+ if (typeDef.base) {
2674
+ const schema = this.makeScalarSchema(typeDef.base, [...typeDef.fields["this"]?.attributes ?? [], ...fieldAttributes ?? []]);
2675
+ return this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addCustomValidation(schema, typeDef.attributes) : schema;
2676
+ }
2677
+ const objectSchema = (typeDef.strict ? zod.z.strictObject : zod.z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2678
+ let fieldSchema = isTypeDef(this.schema, def.type) && !isPrimitiveTypeDef(this.schema, def.type) ? zod.z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type, this.getItemAttributes(def));
2679
+ if (def.array) fieldSchema = _zenstackhq_zod.ZodUtils.addListValidation(fieldSchema.array(), def.attributes);
2610
2680
  if (def.optional) fieldSchema = fieldSchema.nullish();
2611
2681
  return [field, fieldSchema];
2612
2682
  })));
2683
+ const schema = this.extraValidationsEnabled ? _zenstackhq_zod.ZodUtils.addCustomValidation(objectSchema, typeDef.attributes) : objectSchema;
2613
2684
  const finalSchema = zod.z.any().superRefine((value, ctx) => {
2614
2685
  const parseResult = schema.safeParse(value);
2615
2686
  if (!parseResult.success) parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
@@ -2648,8 +2719,8 @@ var ZodSchemaFactory = class {
2648
2719
  if (enumDef) {
2649
2720
  if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, withAggregations, allowedFilterKinds);
2650
2721
  } 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);
2722
+ else if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2723
+ else fieldSchema = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2653
2724
  }
2654
2725
  if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2655
2726
  if (fieldSchema) fields[field] = fieldSchema.optional();
@@ -2692,10 +2763,10 @@ var ZodSchemaFactory = class {
2692
2763
  const candidates = [];
2693
2764
  if (!array) {
2694
2765
  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();
2766
+ 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
2767
  else if (getEnum(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, false, void 0).optional();
2697
2768
  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();
2769
+ else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, false, void 0).optional();
2699
2770
  candidates.push(zod.z.strictObject(fieldSchemas));
2700
2771
  }
2701
2772
  const recursiveSchema = zod.z.lazy(() => this.makeTypedJsonFilterSchema(type, optional, false, allowedFilterKinds)).optional();
@@ -2733,6 +2804,10 @@ var ZodSchemaFactory = class {
2733
2804
  isTypeDefType(type) {
2734
2805
  return this.schema.typeDefs && type in this.schema.typeDefs;
2735
2806
  }
2807
+ getEffectiveFieldType(type) {
2808
+ if (isPrimitiveTypeDef(this.schema, type)) return this.schema.typeDefs[type].base;
2809
+ return type;
2810
+ }
2736
2811
  makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds) {
2737
2812
  const enumDef = getEnum(this.schema, enumName);
2738
2813
  (0, _zenstackhq_common_helpers.invariant)(enumDef, `Enum "${enumName}" not found in schema`);
@@ -3208,7 +3283,7 @@ var ZodSchemaFactory = class {
3208
3283
  checkedVariantFields[field] = fieldSchema;
3209
3284
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3210
3285
  } else {
3211
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3286
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3212
3287
  if (fieldDef.array) {
3213
3288
  fieldSchema = _zenstackhq_zod.ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
3214
3289
  fieldSchema = zod.z.union([fieldSchema, zod.z.strictObject({ set: fieldSchema })]).optional();
@@ -3386,7 +3461,7 @@ var ZodSchemaFactory = class {
3386
3461
  checkedVariantFields[field] = fieldSchema;
3387
3462
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3388
3463
  } else {
3389
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3464
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3390
3465
  if (this.isNumericField(fieldDef)) fieldSchema = zod.z.union([fieldSchema, zod.z.object({
3391
3466
  set: this.nullableIf(zod.z.number().optional(), !!fieldDef.optional).optional(),
3392
3467
  increment: zod.z.number().optional(),
@@ -3627,7 +3702,7 @@ var ZodSchemaFactory = class {
3627
3702
  return canBeArray ? zod.z.union([schema, zod.z.array(schema)]) : schema;
3628
3703
  }
3629
3704
  isNumericField(fieldDef) {
3630
- return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3705
+ return require_constants.NUMERIC_FIELD_TYPES.includes(this.getEffectiveFieldType(fieldDef.type)) && !fieldDef.array;
3631
3706
  }
3632
3707
  get providerSupportsCaseSensitivity() {
3633
3708
  return this.schema.provider.type === "postgresql";
@@ -3747,7 +3822,7 @@ __decorate([
3747
3822
  __decorate([
3748
3823
  cache(),
3749
3824
  __decorateMetadata("design:type", Function),
3750
- __decorateMetadata("design:paramtypes", [String]),
3825
+ __decorateMetadata("design:paramtypes", [String, Array]),
3751
3826
  __decorateMetadata("design:returntype", typeof (_ref2 = typeof zod.ZodType !== "undefined" && zod.ZodType) === "function" ? _ref2 : Object)
3752
3827
  ], ZodSchemaFactory.prototype, "makeTypeDefSchema", null);
3753
3828
  __decorate([
@@ -4157,7 +4232,7 @@ var InputValidator = class {
4157
4232
  enabled;
4158
4233
  constructor(client, options) {
4159
4234
  this.client = client;
4160
- this.zodFactory = new ZodSchemaFactory(client);
4235
+ this.zodFactory = options?.zodFactory ?? new ZodSchemaFactory(client);
4161
4236
  this.enabled = options?.enabled !== false;
4162
4237
  }
4163
4238
  validateFindArgs(model, args, operation) {
@@ -4310,6 +4385,7 @@ var BaseOperationHandler = class {
4310
4385
  try {
4311
4386
  result = (await kysely$4.getExecutor().executeQuery(compiled)).rows;
4312
4387
  } catch (err) {
4388
+ if (err instanceof ORMError) throw err;
4313
4389
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
4314
4390
  }
4315
4391
  return !!result[0]?.$exists;
@@ -4329,6 +4405,7 @@ var BaseOperationHandler = class {
4329
4405
  try {
4330
4406
  result = (await kysely$5.getExecutor().executeQuery(compiled)).rows;
4331
4407
  } catch (err) {
4408
+ if (err instanceof ORMError) throw err;
4332
4409
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
4333
4410
  }
4334
4411
  return result;
@@ -4353,7 +4430,7 @@ var BaseOperationHandler = class {
4353
4430
  result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4354
4431
  } else {
4355
4432
  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);
4433
+ if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, this.dialect.delegateJoinAlias(model, parentAlias, fieldDef.originModel), payload);
4357
4434
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
4358
4435
  }
4359
4436
  }
@@ -4715,16 +4792,9 @@ var BaseOperationHandler = class {
4715
4792
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4716
4793
  const origWhere = combinedWhere;
4717
4794
  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
- }
4795
+ const filled = this.fillUpdatedAtFields(modelDef, data);
4796
+ let finalData = filled.data;
4797
+ const autoUpdatedFields = filled.autoUpdatedFields;
4728
4798
  let thisEntity;
4729
4799
  const loadThisEntity = async () => {
4730
4800
  if (thisEntity === void 0) {
@@ -4873,7 +4943,8 @@ var BaseOperationHandler = class {
4873
4943
  });
4874
4944
  }
4875
4945
  isNumericField(fieldDef) {
4876
- return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
4946
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
4947
+ return require_constants.NUMERIC_FIELD_TYPES.includes(type) && !fieldDef.array;
4877
4948
  }
4878
4949
  makeContextComment(_context) {
4879
4950
  return kysely.sql``;
@@ -4886,11 +4957,13 @@ var BaseOperationHandler = class {
4886
4957
  const parentWhere = await this.buildUpdateParentRelationFilter(kysely$19, fromRelation);
4887
4958
  let combinedWhere = where ?? true;
4888
4959
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4960
+ const { data: finalData } = this.fillUpdatedAtFields(modelDef, data);
4961
+ if (modelDef.baseModel && filterModel === void 0) return this.updateManyByIds(kysely$19, model, combinedWhere, finalData, returnData, fieldsToReturn);
4889
4962
  filterModel ??= model;
4890
4963
  let updateFields = {};
4891
- for (const field in data) {
4964
+ for (const field in finalData) {
4892
4965
  if (isRelationField(this.schema, model, field)) continue;
4893
- updateFields[field] = this.processScalarFieldUpdateData(model, field, data);
4966
+ updateFields[field] = this.processScalarFieldUpdateData(model, field, finalData);
4894
4967
  }
4895
4968
  let resultFromBaseModel = void 0;
4896
4969
  if (modelDef.baseModel) {
@@ -4941,7 +5014,51 @@ var BaseOperationHandler = class {
4941
5014
  }
4942
5015
  }
4943
5016
  }
4944
- async processBaseModelUpdateMany(kysely$20, model, where, updateFields, filterModel) {
5017
+ /**
5018
+ * Runs `updateMany` on a delegate sub model by id. Reads the ids of the rows that match
5019
+ * `where`, then updates them in batches with an id filter. Callers run this inside a
5020
+ * transaction (`needsNestedUpdate` is true for every model with a base model).
5021
+ */
5022
+ async updateManyByIds(kysely$20, model, where, data, returnData, fieldsToReturn) {
5023
+ const idFields = requireIdFields(this.schema, model);
5024
+ const rows = await this.read(kysely$20, model, {
5025
+ where,
5026
+ select: Object.fromEntries(idFields.map((f) => [f, true]))
5027
+ });
5028
+ const batchSize = idFields.length === 1 ? 1e3 : 100;
5029
+ let count = 0;
5030
+ const returned = [];
5031
+ for (let i = 0; i < rows.length; i += batchSize) {
5032
+ const batch = rows.slice(i, i + batchSize);
5033
+ 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]]))) };
5034
+ const result = await this.updateMany(kysely$20, model, idWhere, data, void 0, returnData, model, void 0, fieldsToReturn);
5035
+ if (returnData) returned.push(...result);
5036
+ else count += result.count;
5037
+ }
5038
+ return returnData ? returned : { count };
5039
+ }
5040
+ /**
5041
+ * Sets `@updatedAt` fields to the current time when `data` changes a scalar or foreign key
5042
+ * field that is not in the field's `ignore` list. A value given explicitly in `data` is kept.
5043
+ * Returns the original `data` object when nothing is filled in, otherwise a clone.
5044
+ */
5045
+ fillUpdatedAtFields(modelDef, data) {
5046
+ let result = data;
5047
+ const autoUpdatedFields = [];
5048
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && result[fieldName] === void 0) {
5049
+ const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
5050
+ if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
5051
+ if (result === data) result = (0, _zenstackhq_common_helpers.clone)(data);
5052
+ result[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
5053
+ autoUpdatedFields.push(fieldName);
5054
+ }
5055
+ }
5056
+ return {
5057
+ data: result,
5058
+ autoUpdatedFields
5059
+ };
5060
+ }
5061
+ async processBaseModelUpdateMany(kysely$21, model, where, updateFields, filterModel) {
4945
5062
  const thisUpdateFields = {};
4946
5063
  const remainingFields = {};
4947
5064
  Object.entries(updateFields).forEach(([field, value]) => {
@@ -4949,14 +5066,14 @@ var BaseOperationHandler = class {
4949
5066
  else remainingFields[field] = value;
4950
5067
  });
4951
5068
  return {
4952
- baseResult: await this.updateMany(kysely$20, model, where, thisUpdateFields, void 0, false, filterModel),
5069
+ baseResult: await this.updateMany(kysely$21, model, where, thisUpdateFields, void 0, false, filterModel),
4953
5070
  remainingFields
4954
5071
  };
4955
5072
  }
4956
- buildIdFieldRefs(kysely$21, model) {
4957
- return requireIdFields(this.schema, model).map((f) => kysely$21.dynamic.ref(`${model}.${f}`));
5073
+ buildIdFieldRefs(kysely$22, model) {
5074
+ return requireIdFields(this.schema, model).map((f) => kysely$22.dynamic.ref(`${model}.${f}`));
4958
5075
  }
4959
- async processRelationUpdates(kysely$22, model, field, fieldDef, parentIds, args) {
5076
+ async processRelationUpdates(kysely$23, model, field, fieldDef, parentIds, args) {
4960
5077
  const fieldModel = fieldDef.type;
4961
5078
  const fromRelationContext = {
4962
5079
  model,
@@ -4967,24 +5084,24 @@ var BaseOperationHandler = class {
4967
5084
  for (const [key, value] of Object.entries(args)) switch (key) {
4968
5085
  case "create":
4969
5086
  (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);
5087
+ for (const item of (0, _zenstackhq_common_helpers.enumerate)(value)) await this.create(kysely$23, fieldModel, item, fromRelationContext);
4971
5088
  break;
4972
5089
  case "createMany":
4973
5090
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array for createMany");
4974
- await this.createMany(kysely$22, fieldModel, value, false, fromRelationContext);
5091
+ await this.createMany(kysely$23, fieldModel, value, false, fromRelationContext);
4975
5092
  break;
4976
5093
  case "connect":
4977
- await this.connectRelation(kysely$22, fieldModel, value, fromRelationContext);
5094
+ await this.connectRelation(kysely$23, fieldModel, value, fromRelationContext);
4978
5095
  break;
4979
5096
  case "connectOrCreate":
4980
- await this.connectOrCreateRelation(kysely$22, fieldModel, value, fromRelationContext);
5097
+ await this.connectOrCreateRelation(kysely$23, fieldModel, value, fromRelationContext);
4981
5098
  break;
4982
5099
  case "disconnect":
4983
- await this.disconnectRelation(kysely$22, fieldModel, value, fromRelationContext);
5100
+ await this.disconnectRelation(kysely$23, fieldModel, value, fromRelationContext);
4984
5101
  break;
4985
5102
  case "set":
4986
5103
  (0, _zenstackhq_common_helpers.invariant)(fieldDef.array, "relation must be an array");
4987
- await this.setRelation(kysely$22, fieldModel, value, fromRelationContext);
5104
+ await this.setRelation(kysely$23, fieldModel, value, fromRelationContext);
4988
5105
  break;
4989
5106
  case "update":
4990
5107
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
@@ -4999,76 +5116,76 @@ var BaseOperationHandler = class {
4999
5116
  data = item;
5000
5117
  }
5001
5118
  const throwIfNotFound = !fieldDef.array || !!where;
5002
- await this.update(kysely$22, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5119
+ await this.update(kysely$23, fieldModel, where, data, fromRelationContext, true, throwIfNotFound);
5003
5120
  }
5004
5121
  break;
5005
5122
  case "upsert":
5006
5123
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5007
5124
  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);
5125
+ if (!await this.update(kysely$23, fieldModel, item.where, item.update, fromRelationContext, true, false)) await this.create(kysely$23, fieldModel, item.create, fromRelationContext);
5009
5126
  }
5010
5127
  break;
5011
5128
  case "updateMany":
5012
5129
  for (const _item of (0, _zenstackhq_common_helpers.enumerate)(value)) {
5013
5130
  const item = _item;
5014
- await this.updateMany(kysely$22, fieldModel, item.where, item.data, item.limit, false, fieldModel, fromRelationContext);
5131
+ await this.updateMany(kysely$23, fieldModel, item.where, item.data, item.limit, false, void 0, fromRelationContext);
5015
5132
  }
5016
5133
  break;
5017
5134
  case "delete":
5018
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, true, true);
5135
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, true, true);
5019
5136
  break;
5020
5137
  case "deleteMany":
5021
- await this.deleteRelation(kysely$22, fieldModel, value, fromRelationContext, false, false);
5138
+ await this.deleteRelation(kysely$23, fieldModel, value, fromRelationContext, false, false);
5022
5139
  break;
5023
5140
  default: throw createInvalidInputError(`Invalid relation update operation: ${key}`);
5024
5141
  }
5025
5142
  return fromRelationContext.parentUpdates;
5026
5143
  }
5027
- async connectRelation(kysely$23, model, data, fromRelation) {
5144
+ async connectRelation(kysely$24, model, data, fromRelation) {
5028
5145
  const _data = this.normalizeRelationManipulationInput(model, data);
5029
5146
  if (_data.length === 0) return;
5030
5147
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5031
5148
  if (m2m) {
5032
- const allIds = await this.getEntitiesIds(kysely$23, model, _data);
5149
+ const allIds = await this.getEntitiesIds(kysely$24, model, _data);
5033
5150
  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);
5151
+ await this.handleManyToManyRelation(kysely$24, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5035
5152
  } else {
5036
5153
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5037
5154
  if (ownedByModel) {
5038
5155
  (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] });
5156
+ const target = await this.readUnique(kysely$24, model, { where: _data[0] });
5040
5157
  if (!target) throw createNotFoundError(model);
5041
5158
  for (const { fk, pk } of keyPairs) fromRelation.parentUpdates[fk] = target[pk];
5042
5159
  } else {
5043
5160
  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 }) => ({
5161
+ 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
5162
  ...acc,
5046
5163
  [fk]: null
5047
5164
  }), {})).modifyEnd(this.makeContextComment({
5048
5165
  model: fromRelation.model,
5049
5166
  operation: "update"
5050
5167
  }));
5051
- await this.executeQuery(kysely$23, query, "disconnect");
5168
+ await this.executeQuery(kysely$24, query, "disconnect");
5052
5169
  }
5053
- const query = kysely$23.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5170
+ const query = kysely$24.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5054
5171
  ...acc,
5055
5172
  [fk]: fromRelation.ids[pk]
5056
5173
  }), {})).modifyEnd(this.makeContextComment({
5057
5174
  model,
5058
5175
  operation: "update"
5059
5176
  }));
5060
- const updateResult = await this.executeQuery(kysely$23, query, "connect");
5177
+ const updateResult = await this.executeQuery(kysely$24, query, "connect");
5061
5178
  if (!updateResult.numAffectedRows || _data.length > updateResult.numAffectedRows) throw createNotFoundError(model);
5062
5179
  }
5063
5180
  }
5064
5181
  }
5065
- async connectOrCreateRelation(kysely$24, model, data, fromRelation) {
5182
+ async connectOrCreateRelation(kysely$25, model, data, fromRelation) {
5066
5183
  const _data = (0, _zenstackhq_common_helpers.enumerate)(data);
5067
5184
  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);
5185
+ for (const { where, create } of _data) if (await this.exists(kysely$25, model, where)) await this.connectRelation(kysely$25, model, [where], fromRelation);
5186
+ else await this.create(kysely$25, model, create, fromRelation);
5070
5187
  }
5071
- async disconnectRelation(kysely$25, model, data, fromRelation) {
5188
+ async disconnectRelation(kysely$26, model, data, fromRelation) {
5072
5189
  let disconnectConditions = [];
5073
5190
  if (typeof data === "boolean") if (data === false) return;
5074
5191
  else disconnectConditions = [true];
@@ -5080,8 +5197,8 @@ var BaseOperationHandler = class {
5080
5197
  if (disconnectConditions.length === 0) return;
5081
5198
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5082
5199
  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);
5200
+ const allIds = await this.getEntitiesIds(kysely$26, model, disconnectConditions);
5201
+ if (allIds.length > 0) await this.handleManyToManyRelation(kysely$26, "disconnect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5085
5202
  } else {
5086
5203
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5087
5204
  const eb = (0, kysely.expressionBuilder)();
@@ -5090,39 +5207,39 @@ var BaseOperationHandler = class {
5090
5207
  const condition = disconnectConditions[0];
5091
5208
  if (condition === true) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5092
5209
  else {
5093
- const fromEntity = await this.readUnique(kysely$25, fromRelation.model, {
5210
+ const fromEntity = await this.readUnique(kysely$26, fromRelation.model, {
5094
5211
  where: fromRelation.ids,
5095
5212
  select: fieldsToSelectObject(keyPairs.map(({ fk }) => fk))
5096
5213
  });
5097
5214
  if (!fromEntity || keyPairs.some(({ fk }) => fromEntity[fk] == null)) return;
5098
5215
  const relationFilter = { AND: [condition, Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]]))] };
5099
- if ((await this.read(kysely$25, model, {
5216
+ if ((await this.read(kysely$26, model, {
5100
5217
  where: relationFilter,
5101
5218
  take: 1,
5102
5219
  select: this.makeIdSelect(model)
5103
5220
  })).length > 0) for (const { fk } of keyPairs) fromRelation.parentUpdates[fk] = null;
5104
5221
  }
5105
5222
  } 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 }) => ({
5223
+ 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
5224
  ...acc,
5108
5225
  [fk]: null
5109
5226
  }), {})).modifyEnd(this.makeContextComment({
5110
5227
  model,
5111
5228
  operation: "update"
5112
5229
  }));
5113
- await this.executeQuery(kysely$25, query, "disconnect");
5230
+ await this.executeQuery(kysely$26, query, "disconnect");
5114
5231
  }
5115
5232
  }
5116
5233
  }
5117
- async setRelation(kysely$26, model, data, fromRelation) {
5234
+ async setRelation(kysely$27, model, data, fromRelation) {
5118
5235
  const _data = this.normalizeRelationManipulationInput(model, data);
5119
5236
  const m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
5120
5237
  if (m2m) {
5121
- await this.resetManyToManyRelation(kysely$26, fromRelation.model, fromRelation.field, fromRelation.ids);
5238
+ await this.resetManyToManyRelation(kysely$27, fromRelation.model, fromRelation.field, fromRelation.ids);
5122
5239
  if (_data.length > 0) {
5123
- const allIds = await this.getEntitiesIds(kysely$26, model, _data);
5240
+ const allIds = await this.getEntitiesIds(kysely$27, model, _data);
5124
5241
  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);
5242
+ await this.handleManyToManyRelation(kysely$27, "connect", fromRelation.model, fromRelation.field, fromRelation.ids, m2m.otherModel, m2m.otherField, allIds, m2m.joinTable);
5126
5243
  }
5127
5244
  } else {
5128
5245
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
@@ -5131,28 +5248,28 @@ var BaseOperationHandler = class {
5131
5248
  ...acc,
5132
5249
  [fk]: fromRelation.ids[pk]
5133
5250
  }), {});
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 }) => ({
5251
+ 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
5252
  ...acc,
5136
5253
  [fk]: null
5137
5254
  }), {})).modifyEnd(this.makeContextComment({
5138
5255
  model,
5139
5256
  operation: "update"
5140
5257
  }));
5141
- await this.executeQuery(kysely$26, query, "disconnect");
5258
+ await this.executeQuery(kysely$27, query, "disconnect");
5142
5259
  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 }) => ({
5260
+ const query = kysely$27.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
5144
5261
  ...acc,
5145
5262
  [fk]: fromRelation.ids[pk]
5146
5263
  }), {})).modifyEnd(this.makeContextComment({
5147
5264
  model,
5148
5265
  operation: "update"
5149
5266
  }));
5150
- const r = await this.executeQuery(kysely$26, query, "connect");
5267
+ const r = await this.executeQuery(kysely$27, query, "connect");
5151
5268
  if (!r.numAffectedRows || _data.length > r.numAffectedRows) throw createNotFoundError(model);
5152
5269
  }
5153
5270
  }
5154
5271
  }
5155
- async deleteRelation(kysely$27, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5272
+ async deleteRelation(kysely$28, model, data, fromRelation, uniqueDelete, throwForNotFound) {
5156
5273
  let deleteConditions = [];
5157
5274
  let expectedDeleteCount = -1;
5158
5275
  if (typeof data === "boolean") if (data === false) return;
@@ -5174,18 +5291,18 @@ var BaseOperationHandler = class {
5174
5291
  deleteFromModel = model;
5175
5292
  const fieldDef = this.requireField(fromRelation.model, fromRelation.field);
5176
5293
  (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 }] });
5294
+ deleteResult = await this.delete(kysely$28, model, { AND: [{ [fieldDef.relation.opposite]: { some: fromRelation.ids } }, { OR: deleteConditions }] });
5178
5295
  } else {
5179
5296
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
5180
5297
  if (ownedByModel) {
5181
5298
  deleteFromModel = fromRelation.model;
5182
- const fromEntity = await this.readUnique(kysely$27, fromRelation.model, { where: fromRelation.ids });
5299
+ const fromEntity = await this.readUnique(kysely$28, fromRelation.model, { where: fromRelation.ids });
5183
5300
  if (!fromEntity) throw createNotFoundError(fromRelation.model);
5184
5301
  (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 }] });
5302
+ deleteResult = await this.delete(kysely$28, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [pk, fromEntity[fk]])), { OR: deleteConditions }] });
5186
5303
  } else {
5187
5304
  deleteFromModel = model;
5188
- deleteResult = await this.delete(kysely$27, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]])), { OR: deleteConditions }] });
5305
+ deleteResult = await this.delete(kysely$28, model, { AND: [Object.fromEntries(keyPairs.map(({ fk, pk }) => [fk, fromRelation.ids[pk]])), { OR: deleteConditions }] });
5189
5306
  }
5190
5307
  }
5191
5308
  if (throwForNotFound && expectedDeleteCount >= 0 && expectedDeleteCount > (deleteResult.numAffectedRows ?? 0)) throw createNotFoundError(deleteFromModel);
@@ -5193,27 +5310,22 @@ var BaseOperationHandler = class {
5193
5310
  normalizeRelationManipulationInput(model, data) {
5194
5311
  return (0, _zenstackhq_common_helpers.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
5195
5312
  }
5196
- async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn, visited) {
5313
+ async delete(kysely$29, model, where, limit, filterModel, fieldsToReturn, visited) {
5197
5314
  filterModel ??= model;
5198
5315
  visited ??= /* @__PURE__ */ new Set();
5199
5316
  const modelDef = this.requireModel(model);
5200
5317
  if (modelDef.baseModel) {
5201
5318
  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);
5319
+ return this.processBaseModelDelete(kysely$29, modelDef.baseModel, where, limit, filterModel, visited);
5203
5320
  }
5204
5321
  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
- }
5322
+ if (cascadeRelations.length === 0) return this.executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn);
5211
5323
  const discriminator = getDiscriminatorField(this.schema, model);
5212
- const deletedRows = await this.read(kysely$28, filterModel, {
5324
+ const deletedRows = await this.read(kysely$29, filterModel, {
5213
5325
  where,
5214
5326
  select: {
5215
5327
  ...this.makeIdSelect(filterModel),
5216
- [discriminator]: true
5328
+ ...discriminator ? { [discriminator]: true } : {}
5217
5329
  },
5218
5330
  ...limit !== void 0 ? { take: limit } : {}
5219
5331
  });
@@ -5222,7 +5334,7 @@ var BaseOperationHandler = class {
5222
5334
  const parentRows = discriminatorValue === void 0 ? deletedRows : deletedRows.filter((row) => row[discriminator] === discriminatorValue);
5223
5335
  for (const batch of this.batchRows(model, parentRows)) {
5224
5336
  const childModel = fieldDef.type;
5225
- const pendingRows = (await this.read(kysely$28, childModel, {
5337
+ const pendingRows = (await this.read(kysely$29, childModel, {
5226
5338
  where: this.makeChildFilter(model, fieldDef, batch),
5227
5339
  select: this.makeIdSelect(childModel)
5228
5340
  })).filter((row) => {
@@ -5231,13 +5343,13 @@ var BaseOperationHandler = class {
5231
5343
  visited.add(key);
5232
5344
  return true;
5233
5345
  });
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);
5346
+ 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
5347
  }
5236
5348
  }
5237
5349
  let numAffectedRows = 0n;
5238
5350
  const rows = [];
5239
5351
  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);
5352
+ const result = await this.executeDelete(kysely$29, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
5241
5353
  numAffectedRows += result.numAffectedRows ?? 0n;
5242
5354
  rows.push(...result.rows);
5243
5355
  }
@@ -5246,18 +5358,18 @@ var BaseOperationHandler = class {
5246
5358
  rows
5247
5359
  };
5248
5360
  }
5249
- async executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn) {
5361
+ async executeDelete(kysely$30, model, where, limit, filterModel, fieldsToReturn) {
5250
5362
  const modelDef = this.requireModel(model);
5251
5363
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
5252
5364
  let needIdFilter = false;
5253
5365
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
5254
5366
  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({
5367
+ 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);
5368
+ 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
5369
  model,
5258
5370
  operation: "delete"
5259
5371
  }));
5260
- return this.executeQuery(kysely$29, query, "delete");
5372
+ return this.executeQuery(kysely$30, query, "delete");
5261
5373
  }
5262
5374
  /**
5263
5375
  * Gets the relations whose deletion must be simulated when deleting from the given model: relations
@@ -5315,8 +5427,8 @@ var BaseOperationHandler = class {
5315
5427
  const size = this.requireModel(model).idFields.length === 1 ? DELETE_ID_BATCH_SIZE : DELETE_COMPOUND_ID_BATCH_SIZE;
5316
5428
  for (let i = 0; i < rows.length; i += size) yield rows.slice(i, i + size);
5317
5429
  }
5318
- async processBaseModelDelete(kysely$30, model, where, limit, filterModel, visited) {
5319
- return this.delete(kysely$30, model, where, limit, filterModel, void 0, visited);
5430
+ async processBaseModelDelete(kysely$31, model, where, limit, filterModel, visited) {
5431
+ return this.delete(kysely$31, model, where, limit, filterModel, void 0, visited);
5320
5432
  }
5321
5433
  makeIdSelect(model) {
5322
5434
  return this.requireModel(model).idFields.reduce((acc, f) => {
@@ -5351,14 +5463,14 @@ var BaseOperationHandler = class {
5351
5463
  if (condition) return this.safeTransaction(callback, isolationLevel);
5352
5464
  else return callback(this.kysely);
5353
5465
  }
5354
- getEntityIds(kysely$31, model, uniqueFilter) {
5355
- return this.readUnique(kysely$31, model, {
5466
+ getEntityIds(kysely$32, model, uniqueFilter) {
5467
+ return this.readUnique(kysely$32, model, {
5356
5468
  where: uniqueFilter,
5357
5469
  select: this.makeIdSelect(model)
5358
5470
  });
5359
5471
  }
5360
- getEntitiesIds(kysely$32, model, uniqueFilters) {
5361
- return this.read(kysely$32, model, {
5472
+ getEntitiesIds(kysely$33, model, uniqueFilters) {
5473
+ return this.read(kysely$33, model, {
5362
5474
  where: { OR: uniqueFilters },
5363
5475
  select: this.makeIdSelect(model)
5364
5476
  });
@@ -5378,14 +5490,14 @@ var BaseOperationHandler = class {
5378
5490
  else if (value && (0, _zenstackhq_common_helpers.isPlainObject)(value)) this.doNormalizeArgs(value);
5379
5491
  }
5380
5492
  }
5381
- executeQuery(kysely$33, query, _operation) {
5382
- return kysely$33.executeQuery(query.compile());
5493
+ executeQuery(kysely$34, query, _operation) {
5494
+ return kysely$34.executeQuery(query.compile());
5383
5495
  }
5384
- async executeQueryTakeFirst(kysely$34, query, _operation) {
5385
- return (await kysely$34.executeQuery(query.compile())).rows[0];
5496
+ async executeQueryTakeFirst(kysely$35, query, _operation) {
5497
+ return (await kysely$35.executeQuery(query.compile())).rows[0];
5386
5498
  }
5387
- async executeQueryTakeFirstOrThrow(kysely$35, query, _operation) {
5388
- const result = await kysely$35.executeQuery(query.compile());
5499
+ async executeQueryTakeFirstOrThrow(kysely$36, query, _operation) {
5500
+ const result = await kysely$36.executeQuery(query.compile());
5389
5501
  if (result.rows.length === 0) throw new ORMError(ORMErrorReason.NOT_FOUND, "No rows found");
5390
5502
  return result.rows[0];
5391
5503
  }
@@ -5492,7 +5604,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5492
5604
  if (typeof value === "string") {
5493
5605
  const fieldDef = getField(this.schema, this.model, field);
5494
5606
  if (fieldDef) {
5495
- const type = fieldDef.type;
5607
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5496
5608
  if (op === "_avg") val = parseFloat(val);
5497
5609
  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
5610
  }
@@ -5715,7 +5827,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5715
5827
  if (typeof value === "string") {
5716
5828
  const fieldDef = getField(this.schema, this.model, field);
5717
5829
  if (fieldDef) {
5718
- const type = fieldDef.type;
5830
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5719
5831
  if (op === "_avg") val = parseFloat(val);
5720
5832
  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
5833
  }
@@ -6135,7 +6247,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6135
6247
  return kysely.ColumnNode.create(mappedName);
6136
6248
  }
6137
6249
  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))) {
6250
+ 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
6251
  const columnNode = node.leftOperand.column;
6140
6252
  const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
6141
6253
  if (resolvedScope?.model) {
@@ -6143,6 +6255,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
6143
6255
  let resultValue = valueNode;
6144
6256
  if (kysely.ValueNode.is(valueNode)) resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
6145
6257
  else if (kysely.PrimitiveValueListNode.is(valueNode)) resultValue = kysely.PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
6258
+ 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
6259
  return super.transformBinaryOperation({
6147
6260
  ...node,
6148
6261
  rightOperand: resultValue
@@ -6543,7 +6656,11 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6543
6656
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6544
6657
  }
6545
6658
  get hasEntityMutationPluginsWithAfterMutationHooks() {
6546
- return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
6659
+ return (this.client.$options.plugins ?? []).some((plugin) => {
6660
+ if (!plugin.onEntityMutation) return false;
6661
+ if (plugin.onEntityMutation["$all"]?.afterEntityMutation) return true;
6662
+ return Object.keys(this.client.$schema.models).some((model) => plugin.onEntityMutation?.[model]?.afterEntityMutation);
6663
+ });
6547
6664
  }
6548
6665
  get hasOnKyselyHooks() {
6549
6666
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onKyselyQuery);
@@ -6648,8 +6765,17 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6648
6765
  const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
6649
6766
  if (this.options.plugins) for (const plugin of this.options.plugins) {
6650
6767
  const onEntityMutation = plugin.onEntityMutation;
6651
- if (!onEntityMutation?.beforeEntityMutation) continue;
6652
- await onEntityMutation.beforeEntityMutation({
6768
+ if (!onEntityMutation) continue;
6769
+ if (onEntityMutation["$all"]?.beforeEntityMutation) await onEntityMutation["$all"].beforeEntityMutation({
6770
+ model: mutationInfo.model,
6771
+ action: mutationInfo.action,
6772
+ queryNode,
6773
+ loadBeforeMutationEntities,
6774
+ client,
6775
+ queryId
6776
+ });
6777
+ const modelHooks = onEntityMutation[mutationInfo.model];
6778
+ if (modelHooks?.beforeEntityMutation) await modelHooks.beforeEntityMutation({
6653
6779
  model: mutationInfo.model,
6654
6780
  action: mutationInfo.action,
6655
6781
  queryNode,
@@ -6664,10 +6790,16 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6664
6790
  const hooks = [];
6665
6791
  for (const plugin of this.options.plugins ?? []) {
6666
6792
  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));
6793
+ if (!onEntityMutation) continue;
6794
+ if (onEntityMutation["$all"]?.afterEntityMutation) {
6795
+ const runInTx = onEntityMutation["$all"].runAfterMutationWithinTransaction ?? false;
6796
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(onEntityMutation["$all"].afterEntityMutation.bind(plugin));
6797
+ }
6798
+ const modelHooks = onEntityMutation[mutationInfo.model];
6799
+ if (modelHooks?.afterEntityMutation) {
6800
+ const runInTx = modelHooks.runAfterMutationWithinTransaction ?? false;
6801
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(modelHooks.afterEntityMutation.bind(plugin));
6802
+ }
6671
6803
  }
6672
6804
  if (hooks.length === 0) return;
6673
6805
  for (const hook of hooks) await hook({
@@ -6682,9 +6814,10 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6682
6814
  }
6683
6815
  async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
6684
6816
  if (mutationInfo.action === "delete") return;
6685
- if (this.dialect.supportsReturning) return queryResult.rows;
6817
+ if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
6686
6818
  else {
6687
6819
  const mutatedIds = kysely.InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
6820
+ if (mutatedIds && mutatedIds.length === 0) return [];
6688
6821
  if (mutatedIds) {
6689
6822
  const idFields = requireIdFields(this.client.$schema, mutationInfo.model);
6690
6823
  const eb = (0, kysely.expressionBuilder)();
@@ -7142,8 +7275,12 @@ var SchemaDbPusher = class {
7142
7275
  return kysely.sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
7143
7276
  } else return "text";
7144
7277
  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;
7278
+ let type = fieldDef.type;
7279
+ if (this.isCustomType(type)) {
7280
+ const typeDef = Object.values(this.schema.typeDefs).find((def) => def.name === type);
7281
+ if (typeDef.base) type = typeDef.base;
7282
+ else return this.jsonType;
7283
+ }
7147
7284
  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
7285
  throw new Error(`Unsupported field type: ${type}`);
7149
7286
  });
@@ -7335,6 +7472,7 @@ var ResultProcessor = class {
7335
7472
  };
7336
7473
  //#endregion
7337
7474
  //#region src/client/client-impl.ts
7475
+ const warnedPlugins = /* @__PURE__ */ new WeakSet();
7338
7476
  /**
7339
7477
  * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7340
7478
  */
@@ -7365,6 +7503,7 @@ var ClientImpl = class ClientImpl {
7365
7503
  ...functions_exports,
7366
7504
  ...this.$options.functions
7367
7505
  };
7506
+ if (this.$options.plugins) this.$options.plugins = this.normalizePlugins(this.$options.plugins);
7368
7507
  this.validateOptions(baseClient, options);
7369
7508
  if (baseClient) {
7370
7509
  this.kyselyProps = {
@@ -7398,6 +7537,63 @@ var ClientImpl = class ClientImpl {
7398
7537
  this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this, { enabled: this.$options.validateInput !== false });
7399
7538
  return createClientProxy(this);
7400
7539
  }
7540
+ /**
7541
+ * Normalizes plugin definitions for backward compatibility and validates
7542
+ * `onEntityMutation` keys. Legacy plugins that define hooks directly under
7543
+ * `onEntityMutation` (instead of under `$all`) are converted to the new shape
7544
+ * with a one-time warning.
7545
+ */
7546
+ normalizePlugins(plugins) {
7547
+ let changed = false;
7548
+ const result = plugins.map((plugin) => {
7549
+ const normalized = this.normalizeEntityMutationHooks(plugin);
7550
+ if (normalized !== plugin) changed = true;
7551
+ return normalized;
7552
+ });
7553
+ return changed ? result : plugins;
7554
+ }
7555
+ normalizeEntityMutationHooks(plugin) {
7556
+ const hooks = plugin.onEntityMutation;
7557
+ if (!hooks || typeof hooks !== "object") return plugin;
7558
+ const legacyKeys = [
7559
+ "beforeEntityMutation",
7560
+ "afterEntityMutation",
7561
+ "runAfterMutationWithinTransaction"
7562
+ ];
7563
+ const presentLegacyKeys = legacyKeys.filter((key) => key in hooks);
7564
+ const unknownKeys = Object.keys(hooks).filter((key) => key !== "$all" && !legacyKeys.includes(key) && !(key in this.$schema.models));
7565
+ const warnOnce = (message) => {
7566
+ if (!warnedPlugins.has(hooks)) console.warn(message);
7567
+ };
7568
+ 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.`);
7569
+ if (presentLegacyKeys.length === 0) {
7570
+ warnedPlugins.add(hooks);
7571
+ return plugin;
7572
+ }
7573
+ 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.`);
7574
+ warnedPlugins.add(hooks);
7575
+ const legacy = {};
7576
+ const rest = {};
7577
+ for (const [key, value] of Object.entries(hooks)) if (legacyKeys.includes(key)) legacy[key] = value;
7578
+ else rest[key] = value;
7579
+ for (const key of ["beforeEntityMutation", "afterEntityMutation"]) if (typeof legacy[key] === "function") legacy[key] = legacy[key].bind(plugin);
7580
+ const normalizedHooks = {
7581
+ ...rest,
7582
+ $all: {
7583
+ ...legacy,
7584
+ ...rest["$all"]
7585
+ }
7586
+ };
7587
+ warnedPlugins.add(normalizedHooks);
7588
+ const copy = Object.create(Object.getPrototypeOf(plugin), Object.getOwnPropertyDescriptors(plugin));
7589
+ Object.defineProperty(copy, "onEntityMutation", {
7590
+ value: normalizedHooks,
7591
+ enumerable: true,
7592
+ configurable: true,
7593
+ writable: true
7594
+ });
7595
+ return copy;
7596
+ }
7401
7597
  validateOptions(baseClient, options) {
7402
7598
  if (!baseClient && !options.skipValidationForComputedFields) this.validateComputedFieldsConfig(options);
7403
7599
  if (options.diagnostics) {
@@ -7540,7 +7736,7 @@ var ClientImpl = class ClientImpl {
7540
7736
  plugins: newPlugins
7541
7737
  };
7542
7738
  const newClient = new ClientImpl(this.schema, newOptions, this);
7543
- newClient.inputValidator = new InputValidator(newClient, { enabled: newOptions.validateInput !== false });
7739
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7544
7740
  return newClient;
7545
7741
  }
7546
7742
  $unuse(pluginId) {
@@ -7551,7 +7747,7 @@ var ClientImpl = class ClientImpl {
7551
7747
  plugins: newPlugins
7552
7748
  };
7553
7749
  const newClient = new ClientImpl(this.schema, newOptions, this);
7554
- newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });
7750
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7555
7751
  return newClient;
7556
7752
  }
7557
7753
  $unuseAll() {
@@ -7560,9 +7756,22 @@ var ClientImpl = class ClientImpl {
7560
7756
  plugins: []
7561
7757
  };
7562
7758
  const newClient = new ClientImpl(this.schema, newOptions, this);
7563
- newClient.inputValidator = new InputValidator(newClient, { enabled: newOptions.validateInput !== false });
7759
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7564
7760
  return newClient;
7565
7761
  }
7762
+ /**
7763
+ * Validator for a client derived from this one. The derived client reuses this client's Zod
7764
+ * schema factory, and so its schema cache, whenever its options shape the same query-args
7765
+ * schemas; it only gets a fresh factory when a plugin that extends query args or results was
7766
+ * added or removed, or `omit`/`slicing` changed. The validator itself is always new because
7767
+ * `validateInput` may differ.
7768
+ */
7769
+ deriveInputValidator(newClient) {
7770
+ return new InputValidator(newClient, {
7771
+ enabled: newClient.$options.validateInput !== false,
7772
+ zodFactory: haveSameSchemaInputs(this.$options, newClient.$options) ? this.inputValidator.zodFactory : void 0
7773
+ });
7774
+ }
7566
7775
  $setAuth(auth) {
7567
7776
  if (auth !== void 0 && (typeof auth !== "object" || auth === null || Array.isArray(auth))) throw new Error("Invalid auth object");
7568
7777
  const newClient = new ClientImpl(this.schema, this.$options, this);
@@ -7584,7 +7793,7 @@ var ClientImpl = class ClientImpl {
7584
7793
  }
7585
7794
  $setOptions(options) {
7586
7795
  const newClient = new ClientImpl(this.schema, options, this);
7587
- newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });
7796
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7588
7797
  return newClient;
7589
7798
  }
7590
7799
  $setInputValidation(enable) {