@zenstackhq/orm 3.3.0-beta.2 → 3.3.0-beta.3

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
@@ -40,7 +40,7 @@ __export(src_exports, {
40
40
  CRUD: () => CRUD,
41
41
  CRUD_EXT: () => CRUD_EXT,
42
42
  CoreCreateOperations: () => CoreCreateOperations,
43
- CoreCrudOperations: () => CoreCrudOperations,
43
+ CoreCrudOperations: () => CoreCrudOperations2,
44
44
  CoreDeleteOperations: () => CoreDeleteOperations,
45
45
  CoreReadOperations: () => CoreReadOperations,
46
46
  CoreUpdateOperations: () => CoreUpdateOperations,
@@ -64,11 +64,11 @@ __export(src_exports, {
64
64
  module.exports = __toCommonJS(src_exports);
65
65
 
66
66
  // src/client/client-impl.ts
67
- var import_common_helpers12 = require("@zenstackhq/common-helpers");
68
- var import_kysely10 = require("kysely");
67
+ var import_common_helpers14 = require("@zenstackhq/common-helpers");
68
+ var import_kysely11 = require("kysely");
69
69
 
70
70
  // src/client/crud/operations/aggregate.ts
71
- var import_ts_pattern7 = require("ts-pattern");
71
+ var import_ts_pattern8 = require("ts-pattern");
72
72
 
73
73
  // src/client/query-utils.ts
74
74
  var query_utils_exports = {};
@@ -89,6 +89,7 @@ __export(query_utils_exports, {
89
89
  getIdValues: () => getIdValues,
90
90
  getManyToManyRelation: () => getManyToManyRelation,
91
91
  getModel: () => getModel,
92
+ getModelFields: () => getModelFields,
92
93
  getRelationForeignKeyFieldPairs: () => getRelationForeignKeyFieldPairs,
93
94
  getTypeDef: () => getTypeDef,
94
95
  getUniqueFields: () => getUniqueFields,
@@ -203,13 +204,13 @@ function createInvalidInputError(message, model, options) {
203
204
  return error;
204
205
  }
205
206
  __name(createInvalidInputError, "createInvalidInputError");
206
- function createDBQueryError(message, dbError, sql8, parameters) {
207
+ function createDBQueryError(message, dbError, sql9, parameters) {
207
208
  const error = new ORMError("db-query-error", message, {
208
209
  cause: dbError
209
210
  });
210
211
  error.dbErrorCode = getDbErrorCode(dbError);
211
212
  error.dbErrorMessage = dbError instanceof Error ? dbError.message : void 0;
212
- error.sql = sql8;
213
+ error.sql = sql9;
213
214
  error.sqlParams = parameters;
214
215
  return error;
215
216
  }
@@ -286,6 +287,22 @@ function requireField(schema, modelOrType, field) {
286
287
  throw createInternalError(`Model or type "${modelOrType}" not found in schema`, modelOrType);
287
288
  }
288
289
  __name(requireField, "requireField");
290
+ function getModelFields(schema, model, options) {
291
+ const modelDef = requireModel(schema, model);
292
+ return Object.values(modelDef.fields).filter((f) => {
293
+ if (f.relation && !options?.relations) {
294
+ return false;
295
+ }
296
+ if (f.computed && !options?.computed) {
297
+ return false;
298
+ }
299
+ if (f.originModel && !options?.inherited) {
300
+ return false;
301
+ }
302
+ return true;
303
+ });
304
+ }
305
+ __name(getModelFields, "getModelFields");
289
306
  function getIdFields(schema, model) {
290
307
  const modelDef = getModel(schema, model);
291
308
  return modelDef?.idFields;
@@ -606,11 +623,11 @@ __name(extractFieldName, "extractFieldName");
606
623
 
607
624
  // src/client/crud/operations/base.ts
608
625
  var import_cuid2 = require("@paralleldrive/cuid2");
609
- var import_common_helpers5 = require("@zenstackhq/common-helpers");
626
+ var import_common_helpers7 = require("@zenstackhq/common-helpers");
610
627
  var import_cuid = __toESM(require("cuid"), 1);
611
- var import_kysely5 = require("kysely");
628
+ var import_kysely6 = require("kysely");
612
629
  var import_nanoid = require("nanoid");
613
- var import_ts_pattern6 = require("ts-pattern");
630
+ var import_ts_pattern7 = require("ts-pattern");
614
631
  var import_ulid = require("ulid");
615
632
  var uuid = __toESM(require("uuid"), 1);
616
633
 
@@ -656,15 +673,13 @@ var CRUD_EXT = [
656
673
  ];
657
674
 
658
675
  // src/client/crud/dialects/index.ts
659
- var import_ts_pattern5 = require("ts-pattern");
676
+ var import_ts_pattern6 = require("ts-pattern");
660
677
 
661
- // src/client/crud/dialects/postgresql.ts
662
- var import_common_helpers3 = require("@zenstackhq/common-helpers");
678
+ // src/client/crud/dialects/mysql.ts
679
+ var import_common_helpers4 = require("@zenstackhq/common-helpers");
663
680
  var import_decimal = __toESM(require("decimal.js"), 1);
664
681
  var import_kysely3 = require("kysely");
665
- var import_postgres_array = require("postgres-array");
666
682
  var import_ts_pattern3 = require("ts-pattern");
667
- var import_zod = __toESM(require("zod"), 1);
668
683
 
669
684
  // src/common-types.ts
670
685
  var DbNullClass = class {
@@ -692,6 +707,9 @@ var AnyNullClass = class {
692
707
  };
693
708
  var AnyNull = new AnyNullClass();
694
709
 
710
+ // src/client/crud/dialects/lateral-join-dialect-base.ts
711
+ var import_common_helpers3 = require("@zenstackhq/common-helpers");
712
+
695
713
  // src/client/crud/dialects/base-dialect.ts
696
714
  var import_common_helpers2 = require("@zenstackhq/common-helpers");
697
715
  var import_kysely2 = require("kysely");
@@ -707,12 +725,21 @@ var BaseCrudDialect = class {
707
725
  this.schema = schema;
708
726
  this.options = options;
709
727
  }
710
- transformPrimitive(value, _type, _forArrayField) {
728
+ // #endregion
729
+ // #region value transformation
730
+ /**
731
+ * Transforms input value before sending to database.
732
+ */
733
+ transformInput(value, _type, _forArrayField) {
711
734
  return value;
712
735
  }
736
+ /**
737
+ * Transforms output value received from database.
738
+ */
713
739
  transformOutput(value, _type, _array) {
714
740
  return value;
715
741
  }
742
+ // #endregion
716
743
  // #region common query builders
717
744
  buildSelectModel(model, modelAlias) {
718
745
  const modelDef = requireModel(this.schema, model);
@@ -737,7 +764,7 @@ var BaseCrudDialect = class {
737
764
  take = -take;
738
765
  }
739
766
  result = this.buildSkipTake(result, skip, take);
740
- result = this.buildOrderBy(result, model, modelAlias, args.orderBy, negateOrderBy);
767
+ result = this.buildOrderBy(result, model, modelAlias, args.orderBy, negateOrderBy, take);
741
768
  if ("distinct" in args && args.distinct) {
742
769
  const distinct = ensureArray(args.distinct);
743
770
  if (this.supportsDistinctOn) {
@@ -901,17 +928,21 @@ var BaseCrudDialect = class {
901
928
  if (!subPayload) {
902
929
  continue;
903
930
  }
931
+ const countSelect = /* @__PURE__ */ __name((negate) => {
932
+ const filter = this.buildFilter(relationModel, relationFilterSelectAlias, subPayload);
933
+ return this.eb.selectFrom(this.buildSelectModel(relationModel, relationFilterSelectAlias).select(() => this.eb.fn.count(this.eb.lit(1)).as("$count")).where(buildPkFkWhereRefs(this.eb)).where(() => negate ? this.eb.not(filter) : filter).as("$sub")).select("$count");
934
+ }, "countSelect");
904
935
  switch (key) {
905
936
  case "some": {
906
- result = this.and(result, this.eb(this.buildSelectModel(relationModel, relationFilterSelectAlias).select(() => this.eb.fn.count(this.eb.lit(1)).as("$count")).where(buildPkFkWhereRefs(this.eb)).where(() => this.buildFilter(relationModel, relationFilterSelectAlias, subPayload)), ">", 0));
937
+ result = this.and(result, this.eb(countSelect(false), ">", 0));
907
938
  break;
908
939
  }
909
940
  case "every": {
910
- result = this.and(result, this.eb(this.buildSelectModel(relationModel, relationFilterSelectAlias).select((eb1) => eb1.fn.count(eb1.lit(1)).as("$count")).where(buildPkFkWhereRefs(this.eb)).where(() => this.eb.not(this.buildFilter(relationModel, relationFilterSelectAlias, subPayload))), "=", 0));
941
+ result = this.and(result, this.eb(countSelect(true), "=", 0));
911
942
  break;
912
943
  }
913
944
  case "none": {
914
- result = this.and(result, this.eb(this.buildSelectModel(relationModel, relationFilterSelectAlias).select(() => this.eb.fn.count(this.eb.lit(1)).as("$count")).where(buildPkFkWhereRefs(this.eb)).where(() => this.buildFilter(relationModel, relationFilterSelectAlias, subPayload)), "=", 0));
945
+ result = this.and(result, this.eb(countSelect(false), "=", 0));
915
946
  break;
916
947
  }
917
948
  }
@@ -925,7 +956,7 @@ var BaseCrudDialect = class {
925
956
  if (_value === void 0) {
926
957
  continue;
927
958
  }
928
- const value = this.transformPrimitive(_value, fieldType, !!fieldDef.array);
959
+ const value = this.transformInput(_value, fieldType, !!fieldDef.array);
929
960
  switch (key) {
930
961
  case "equals": {
931
962
  clauses.push(this.buildLiteralFilter(fieldRef, fieldType, this.eb.val(value)));
@@ -994,7 +1025,7 @@ var BaseCrudDialect = class {
994
1025
  const clauses = [];
995
1026
  const path = filter.path;
996
1027
  const jsonReceiver = this.buildJsonPathSelection(receiver, path);
997
- const stringReceiver = this.eb.cast(jsonReceiver, "text");
1028
+ const stringReceiver = this.castText(jsonReceiver);
998
1029
  const mode = filter.mode ?? "default";
999
1030
  (0, import_common_helpers2.invariant)(mode === "default" || mode === "insensitive", "Invalid JSON filter mode");
1000
1031
  for (const [key, value] of Object.entries(filter)) {
@@ -1078,7 +1109,7 @@ var BaseCrudDialect = class {
1078
1109
  buildTypeJsonNonArrayFilter(receiver, filter, typeDefName) {
1079
1110
  const clauses = [];
1080
1111
  if (filter === null) {
1081
- return this.eb(receiver, "=", "null");
1112
+ return this.eb(receiver, "=", this.transformInput(null, "Json", false));
1082
1113
  }
1083
1114
  (0, import_common_helpers2.invariant)(filter && typeof filter === "object", "Typed JSON filter payload must be an object");
1084
1115
  if ("is" in filter || "isNot" in filter) {
@@ -1102,10 +1133,7 @@ var BaseCrudDialect = class {
1102
1133
  } else {
1103
1134
  let _receiver = fieldReceiver;
1104
1135
  if (fieldDef.type === "String") {
1105
- _receiver = this.eb.fn("trim", [
1106
- this.eb.cast(fieldReceiver, "text"),
1107
- import_kysely2.sql.lit('"')
1108
- ]);
1136
+ _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
1109
1137
  }
1110
1138
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
1111
1139
  }
@@ -1119,20 +1147,23 @@ var BaseCrudDialect = class {
1119
1147
  return this.eb(lhs, "is", null);
1120
1148
  } else if (value instanceof JsonNullClass) {
1121
1149
  return this.eb.and([
1122
- this.eb(lhs, "=", "null"),
1150
+ this.eb(lhs, "=", this.transformInput(null, "Json", false)),
1123
1151
  this.eb(lhs, "is not", null)
1124
1152
  ]);
1125
1153
  } else if (value instanceof AnyNullClass) {
1126
1154
  return this.eb.or([
1127
1155
  this.eb(lhs, "is", null),
1128
- this.eb(lhs, "=", "null")
1156
+ this.eb(lhs, "=", this.transformInput(null, "Json", false))
1129
1157
  ]);
1130
1158
  } else {
1131
- return this.buildLiteralFilter(lhs, "Json", value);
1159
+ return this.buildJsonEqualityFilter(lhs, value);
1132
1160
  }
1133
1161
  }
1162
+ buildJsonEqualityFilter(lhs, rhs) {
1163
+ return this.buildLiteralFilter(lhs, "Json", rhs);
1164
+ }
1134
1165
  buildLiteralFilter(lhs, type, rhs) {
1135
- return this.eb(lhs, "=", rhs !== null && rhs !== void 0 ? this.transformPrimitive(rhs, type, false) : rhs);
1166
+ return this.eb(lhs, "=", rhs !== null && rhs !== void 0 ? this.transformInput(rhs, type, false) : rhs);
1136
1167
  }
1137
1168
  buildStandardFilter(type, payload, lhs, getRhs, recurse, throwIfInvalid = false, onlyForKeys = void 0, excludeKeys = []) {
1138
1169
  if (payload === null || !(0, import_common_helpers2.isPlainObject)(payload)) {
@@ -1232,7 +1263,7 @@ var BaseCrudDialect = class {
1232
1263
  buildStringLike(receiver, pattern, insensitive) {
1233
1264
  const { supportsILike } = this.getStringCasingBehavior();
1234
1265
  const op = insensitive && supportsILike ? "ilike" : "like";
1235
- return import_kysely2.sql`${receiver} ${import_kysely2.sql.raw(op)} ${import_kysely2.sql.val(pattern)} escape '\\'`;
1266
+ return import_kysely2.sql`${receiver} ${import_kysely2.sql.raw(op)} ${import_kysely2.sql.val(pattern)} escape ${import_kysely2.sql.val("\\")}`;
1236
1267
  }
1237
1268
  prepStringCasing(eb, value, mode) {
1238
1269
  if (!mode || mode === "default") {
@@ -1249,22 +1280,22 @@ var BaseCrudDialect = class {
1249
1280
  }
1250
1281
  }
1251
1282
  buildNumberFilter(fieldRef, type, payload) {
1252
- const { conditions } = this.buildStandardFilter(type, payload, fieldRef, (value) => this.transformPrimitive(value, type, false), (value) => this.buildNumberFilter(fieldRef, type, value));
1283
+ const { conditions } = this.buildStandardFilter(type, payload, fieldRef, (value) => this.transformInput(value, type, false), (value) => this.buildNumberFilter(fieldRef, type, value));
1253
1284
  return this.and(...conditions);
1254
1285
  }
1255
1286
  buildBooleanFilter(fieldRef, payload) {
1256
- const { conditions } = this.buildStandardFilter("Boolean", payload, fieldRef, (value) => this.transformPrimitive(value, "Boolean", false), (value) => this.buildBooleanFilter(fieldRef, value), true, [
1287
+ const { conditions } = this.buildStandardFilter("Boolean", payload, fieldRef, (value) => this.transformInput(value, "Boolean", false), (value) => this.buildBooleanFilter(fieldRef, value), true, [
1257
1288
  "equals",
1258
1289
  "not"
1259
1290
  ]);
1260
1291
  return this.and(...conditions);
1261
1292
  }
1262
1293
  buildDateTimeFilter(fieldRef, payload) {
1263
- const { conditions } = this.buildStandardFilter("DateTime", payload, fieldRef, (value) => this.transformPrimitive(value, "DateTime", false), (value) => this.buildDateTimeFilter(fieldRef, value), true);
1294
+ const { conditions } = this.buildStandardFilter("DateTime", payload, fieldRef, (value) => this.transformInput(value, "DateTime", false), (value) => this.buildDateTimeFilter(fieldRef, value), true);
1264
1295
  return this.and(...conditions);
1265
1296
  }
1266
1297
  buildBytesFilter(fieldRef, payload) {
1267
- const conditions = this.buildStandardFilter("Bytes", payload, fieldRef, (value) => this.transformPrimitive(value, "Bytes", false), (value) => this.buildBytesFilter(fieldRef, value), true, [
1298
+ const conditions = this.buildStandardFilter("Bytes", payload, fieldRef, (value) => this.transformInput(value, "Bytes", false), (value) => this.buildBytesFilter(fieldRef, value), true, [
1268
1299
  "equals",
1269
1300
  "in",
1270
1301
  "notIn",
@@ -1281,7 +1312,7 @@ var BaseCrudDialect = class {
1281
1312
  ]);
1282
1313
  return this.and(...conditions.conditions);
1283
1314
  }
1284
- buildOrderBy(query, model, modelAlias, orderBy, negated) {
1315
+ buildOrderBy(query, model, modelAlias, orderBy, negated, take) {
1285
1316
  if (!orderBy) {
1286
1317
  return query;
1287
1318
  }
@@ -1302,37 +1333,20 @@ var BaseCrudDialect = class {
1302
1333
  "_min",
1303
1334
  "_max"
1304
1335
  ].includes(field)) {
1305
- (0, import_common_helpers2.invariant)(value && typeof value === "object", `invalid orderBy value for field "${field}"`);
1336
+ (0, import_common_helpers2.invariant)(typeof value === "object", `invalid orderBy value for field "${field}"`);
1306
1337
  for (const [k, v] of Object.entries(value)) {
1307
1338
  (0, import_common_helpers2.invariant)(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
1308
1339
  result = result.orderBy((eb) => aggregate(eb, buildFieldRef(model, k, modelAlias), field), this.negateSort(v, negated));
1309
1340
  }
1310
1341
  continue;
1311
1342
  }
1312
- switch (field) {
1313
- case "_count": {
1314
- (0, import_common_helpers2.invariant)(value && typeof value === "object", 'invalid orderBy value for field "_count"');
1315
- for (const [k, v] of Object.entries(value)) {
1316
- (0, import_common_helpers2.invariant)(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
1317
- result = result.orderBy((eb) => eb.fn.count(buildFieldRef(model, k, modelAlias)), this.negateSort(v, negated));
1318
- }
1319
- continue;
1320
- }
1321
- default:
1322
- break;
1323
- }
1324
1343
  const fieldDef = requireField(this.schema, model, field);
1325
1344
  if (!fieldDef.relation) {
1326
1345
  const fieldRef = buildFieldRef(model, field, modelAlias);
1327
1346
  if (value === "asc" || value === "desc") {
1328
1347
  result = result.orderBy(fieldRef, this.negateSort(value, negated));
1329
- } else if (value && typeof value === "object" && "nulls" in value && "sort" in value && (value.sort === "asc" || value.sort === "desc") && (value.nulls === "first" || value.nulls === "last")) {
1330
- result = result.orderBy(fieldRef, (ob) => {
1331
- const dir = this.negateSort(value.sort, negated);
1332
- ob = dir === "asc" ? ob.asc() : ob.desc();
1333
- ob = value.nulls === "first" ? ob.nullsFirst() : ob.nullsLast();
1334
- return ob;
1335
- });
1348
+ } else if (typeof value === "object" && "nulls" in value && "sort" in value && (value.sort === "asc" || value.sort === "desc") && (value.nulls === "first" || value.nulls === "last")) {
1349
+ result = this.buildOrderByField(result, fieldRef, this.negateSort(value.sort, negated), value.nulls);
1336
1350
  }
1337
1351
  } else {
1338
1352
  const relationModel = fieldDef.type;
@@ -1358,7 +1372,7 @@ var BaseCrudDialect = class {
1358
1372
  const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, joinAlias);
1359
1373
  return join.on((eb) => this.and(...joinPairs.map(([left, right]) => eb(this.eb.ref(left), "=", this.eb.ref(right)))));
1360
1374
  });
1361
- result = this.buildOrderBy(result, relationModel, joinAlias, value, negated);
1375
+ result = this.buildOrderBy(result, relationModel, joinAlias, value, negated, take);
1362
1376
  }
1363
1377
  }
1364
1378
  }
@@ -1463,10 +1477,10 @@ var BaseCrudDialect = class {
1463
1477
  return negated ? sort === "asc" ? "desc" : "asc" : sort;
1464
1478
  }
1465
1479
  true() {
1466
- return this.eb.lit(this.transformPrimitive(true, "Boolean", false));
1480
+ return this.eb.lit(this.transformInput(true, "Boolean", false));
1467
1481
  }
1468
1482
  false() {
1469
- return this.eb.lit(this.transformPrimitive(false, "Boolean", false));
1483
+ return this.eb.lit(this.transformInput(false, "Boolean", false));
1470
1484
  }
1471
1485
  isTrue(expression) {
1472
1486
  const node = expression.toOperationNode();
@@ -1540,120 +1554,10 @@ var BaseCrudDialect = class {
1540
1554
  }
1541
1555
  };
1542
1556
 
1543
- // src/client/crud/dialects/postgresql.ts
1544
- var PostgresCrudDialect = class extends BaseCrudDialect {
1557
+ // src/client/crud/dialects/lateral-join-dialect-base.ts
1558
+ var LateralJoinDialectBase = class extends BaseCrudDialect {
1545
1559
  static {
1546
- __name(this, "PostgresCrudDialect");
1547
- }
1548
- isoDateSchema = import_zod.default.iso.datetime({
1549
- local: true,
1550
- offset: true
1551
- });
1552
- constructor(schema, options) {
1553
- super(schema, options);
1554
- }
1555
- get provider() {
1556
- return "postgresql";
1557
- }
1558
- transformPrimitive(value, type, forArrayField) {
1559
- if (value === void 0) {
1560
- return value;
1561
- }
1562
- if (value instanceof JsonNullClass) {
1563
- return "null";
1564
- } else if (value instanceof DbNullClass) {
1565
- return null;
1566
- } else if (value instanceof AnyNullClass) {
1567
- (0, import_common_helpers3.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1568
- }
1569
- if (isTypeDef(this.schema, type)) {
1570
- if (typeof value !== "string") {
1571
- return JSON.stringify(value);
1572
- } else {
1573
- return value;
1574
- }
1575
- } else if (Array.isArray(value)) {
1576
- if (type === "Json" && !forArrayField) {
1577
- return JSON.stringify(value);
1578
- }
1579
- if (isEnum(this.schema, type)) {
1580
- return this.eb.cast(import_kysely3.sql`ARRAY[${import_kysely3.sql.join(value.map((v) => this.transformPrimitive(v, type, false)), import_kysely3.sql.raw(","))}]`, this.createSchemaQualifiedEnumType(type, true));
1581
- } else {
1582
- return value.map((v) => this.transformPrimitive(v, type, false));
1583
- }
1584
- } else {
1585
- return (0, import_ts_pattern3.match)(type).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value !== null ? value.toString() : value).with("Json", () => {
1586
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1587
- return JSON.stringify(value);
1588
- } else {
1589
- return value;
1590
- }
1591
- }).otherwise(() => value);
1592
- }
1593
- }
1594
- createSchemaQualifiedEnumType(type, array) {
1595
- let qualified = type;
1596
- const enumDef = getEnum(this.schema, type);
1597
- if (enumDef) {
1598
- const schemaAttr = enumDef.attributes?.find((attr) => attr.name === "@@schema");
1599
- if (schemaAttr) {
1600
- const mapArg = schemaAttr.args?.find((arg) => arg.name === "map");
1601
- if (mapArg && mapArg.value.kind === "literal") {
1602
- const schemaName = mapArg.value.value;
1603
- qualified = `"${schemaName}"."${type}"`;
1604
- }
1605
- } else {
1606
- const defaultSchema = this.schema.provider.defaultSchema ?? "public";
1607
- qualified = `"${defaultSchema}"."${type}"`;
1608
- }
1609
- }
1610
- return array ? import_kysely3.sql.raw(`${qualified}[]`) : import_kysely3.sql.raw(qualified);
1611
- }
1612
- transformOutput(value, type, array) {
1613
- if (value === null || value === void 0) {
1614
- return value;
1615
- }
1616
- return (0, import_ts_pattern3.match)(type).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Decimal", () => this.transformDecimal(value)).when((type2) => isEnum(this.schema, type2), () => this.transformOutputEnum(value, array)).otherwise(() => super.transformOutput(value, type, array));
1617
- }
1618
- transformOutputBigInt(value) {
1619
- if (typeof value === "bigint") {
1620
- return value;
1621
- }
1622
- (0, import_common_helpers3.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
1623
- return BigInt(value);
1624
- }
1625
- transformDecimal(value) {
1626
- if (value instanceof import_decimal.default) {
1627
- return value;
1628
- }
1629
- (0, import_common_helpers3.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal.default, `Expected string, number or Decimal, got ${typeof value}`);
1630
- return new import_decimal.default(value);
1631
- }
1632
- transformOutputDate(value) {
1633
- if (typeof value === "string") {
1634
- if (this.isoDateSchema.safeParse(value).success) {
1635
- const hasOffset = value.endsWith("Z") || /[+-]\d{2}:\d{2}$/.test(value);
1636
- return new Date(hasOffset ? value : `${value}Z`);
1637
- } else {
1638
- return value;
1639
- }
1640
- } else if (value instanceof Date && this.options.fixPostgresTimezone !== false) {
1641
- return new Date(value.getTime() - value.getTimezoneOffset() * 60 * 1e3);
1642
- } else {
1643
- return value;
1644
- }
1645
- }
1646
- transformOutputBytes(value) {
1647
- return Buffer.isBuffer(value) ? Uint8Array.from(value) : typeof value === "string" && value.startsWith("\\x") ? Uint8Array.from(Buffer.from(value.slice(2), "hex")) : value;
1648
- }
1649
- transformOutputEnum(value, array) {
1650
- if (array && typeof value === "string") {
1651
- try {
1652
- return (0, import_postgres_array.parse)(value);
1653
- } catch {
1654
- }
1655
- }
1656
- return value;
1560
+ __name(this, "LateralJoinDialectBase");
1657
1561
  }
1658
1562
  buildRelationSelection(query, model, relationField, parentAlias, payload) {
1659
1563
  const relationResultName = `${parentAlias}$${relationField}`;
@@ -1674,6 +1578,9 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1674
1578
  tbl = eb.selectFrom(() => {
1675
1579
  let subQuery = this.buildModelSelect(relationModel, `${relationSelectName}$t`, payload, true);
1676
1580
  subQuery = this.buildRelationJoinFilter(subQuery, model, relationField, relationModel, `${relationSelectName}$t`, parentAlias);
1581
+ if (typeof payload !== "object" || payload.take === void 0) {
1582
+ subQuery = subQuery.limit(Number.MAX_SAFE_INTEGER);
1583
+ }
1677
1584
  return subQuery.as(relationSelectName);
1678
1585
  });
1679
1586
  }
@@ -1700,53 +1607,47 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1700
1607
  qb = qb.select((eb) => {
1701
1608
  const objArgs = this.buildRelationObjectArgs(relationModel, relationModelAlias, eb, payload, parentResultName);
1702
1609
  if (relationFieldDef.array) {
1703
- return eb.fn.coalesce(import_kysely3.sql`jsonb_agg(jsonb_build_object(${import_kysely3.sql.join(objArgs)}))`, import_kysely3.sql`'[]'::jsonb`).as("$data");
1610
+ return this.buildArrayAgg(this.buildJsonObject(objArgs)).as("$data");
1704
1611
  } else {
1705
- return import_kysely3.sql`jsonb_build_object(${import_kysely3.sql.join(objArgs)})`.as("$data");
1612
+ return this.buildJsonObject(objArgs).as("$data");
1706
1613
  }
1707
1614
  });
1708
1615
  return qb;
1709
1616
  }
1710
1617
  buildRelationObjectArgs(relationModel, relationModelAlias, eb, payload, parentResultName) {
1711
1618
  const relationModelDef = requireModel(this.schema, relationModel);
1712
- const objArgs = [];
1619
+ const objArgs = {};
1713
1620
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1714
1621
  if (descendantModels.length > 0) {
1715
- objArgs.push(...descendantModels.map((subModel) => [
1716
- import_kysely3.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`),
1717
- eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)
1718
- ]).flatMap((v) => v));
1622
+ Object.assign(objArgs, ...descendantModels.map((subModel) => ({
1623
+ [`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)
1624
+ })));
1719
1625
  }
1720
1626
  if (payload === true || !payload.select) {
1721
1627
  const omit = typeof payload === "object" ? payload.omit : void 0;
1722
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [
1723
- import_kysely3.sql.lit(field),
1724
- this.fieldRef(relationModel, field, relationModelAlias, false)
1725
- ]).flatMap((v) => v));
1628
+ Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({
1629
+ [field]: this.fieldRef(relationModel, field, relationModelAlias, false)
1630
+ })));
1726
1631
  } else if (payload.select) {
1727
- objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1632
+ Object.assign(objArgs, ...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1728
1633
  if (field === "_count") {
1729
1634
  const subJson = this.buildCountJson(relationModel, eb, relationModelAlias, value);
1730
- return [
1731
- import_kysely3.sql.lit(field),
1732
- subJson
1733
- ];
1635
+ return {
1636
+ [field]: subJson
1637
+ };
1734
1638
  } else {
1735
1639
  const fieldDef = requireField(this.schema, relationModel, field);
1736
1640
  const fieldValue = fieldDef.relation ? eb.ref(`${parentResultName}$${field}.$data`) : this.fieldRef(relationModel, field, relationModelAlias, false);
1737
- return [
1738
- import_kysely3.sql.lit(field),
1739
- fieldValue
1740
- ];
1641
+ return {
1642
+ [field]: fieldValue
1643
+ };
1741
1644
  }
1742
- }).flatMap((v) => v));
1645
+ }));
1743
1646
  }
1744
1647
  if (typeof payload === "object" && payload.include && typeof payload.include === "object") {
1745
- objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field]) => [
1746
- import_kysely3.sql.lit(field),
1747
- // reference the synthesized JSON field
1748
- eb.ref(`${parentResultName}$${field}.$data`)
1749
- ]).flatMap((v) => v));
1648
+ Object.assign(objArgs, ...Object.entries(payload.include).filter(([, value]) => value).map(([field]) => ({
1649
+ [field]: eb.ref(`${parentResultName}$${field}.$data`)
1650
+ })));
1750
1651
  }
1751
1652
  return objArgs;
1752
1653
  }
@@ -1762,45 +1663,170 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1762
1663
  }
1763
1664
  return result;
1764
1665
  }
1666
+ };
1667
+
1668
+ // src/client/crud/dialects/mysql.ts
1669
+ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1670
+ static {
1671
+ __name(this, "MySqlCrudDialect");
1672
+ }
1673
+ constructor(schema, options) {
1674
+ super(schema, options);
1675
+ }
1676
+ get provider() {
1677
+ return "mysql";
1678
+ }
1679
+ // #region capabilities
1680
+ get supportsUpdateWithLimit() {
1681
+ return true;
1682
+ }
1683
+ get supportsDeleteWithLimit() {
1684
+ return true;
1685
+ }
1686
+ get supportsDistinctOn() {
1687
+ return false;
1688
+ }
1689
+ get supportsReturning() {
1690
+ return false;
1691
+ }
1692
+ get supportsInsertDefaultValues() {
1693
+ return false;
1694
+ }
1695
+ get supportsDefaultAsFieldValue() {
1696
+ return true;
1697
+ }
1698
+ get insertIgnoreMethod() {
1699
+ return "ignore";
1700
+ }
1701
+ // #endregion
1702
+ // #region value transformation
1703
+ transformInput(value, type, forArrayField) {
1704
+ if (value === void 0) {
1705
+ return value;
1706
+ }
1707
+ if (value instanceof JsonNullClass) {
1708
+ return this.eb.cast(import_kysely3.sql.lit("null"), "json");
1709
+ } else if (value instanceof DbNullClass) {
1710
+ return null;
1711
+ } else if (value instanceof AnyNullClass) {
1712
+ (0, import_common_helpers4.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1713
+ }
1714
+ if (isTypeDef(this.schema, type)) {
1715
+ if (typeof value !== "string") {
1716
+ return this.transformInput(value, "Json", forArrayField);
1717
+ } else {
1718
+ return value;
1719
+ }
1720
+ } else if (Array.isArray(value)) {
1721
+ if (type === "Json") {
1722
+ return JSON.stringify(value);
1723
+ } else {
1724
+ throw createNotSupportedError(`MySQL does not support array literals`);
1725
+ }
1726
+ } else {
1727
+ return (0, import_ts_pattern3.match)(type).with("Boolean", () => value ? 1 : 0).with("DateTime", () => {
1728
+ if (value instanceof Date) {
1729
+ return value.toISOString().replace("Z", "+00:00");
1730
+ } else if (typeof value === "string") {
1731
+ return new Date(value).toISOString().replace("Z", "+00:00");
1732
+ } else {
1733
+ return value;
1734
+ }
1735
+ }).with("Decimal", () => value !== null ? value.toString() : value).with("Json", () => {
1736
+ return this.eb.cast(this.eb.val(JSON.stringify(value)), "json");
1737
+ }).with("Bytes", () => Buffer.isBuffer(value) ? value : value instanceof Uint8Array ? Buffer.from(value) : value).otherwise(() => value);
1738
+ }
1739
+ }
1740
+ transformOutput(value, type, array) {
1741
+ if (value === null || value === void 0) {
1742
+ return value;
1743
+ }
1744
+ return (0, import_ts_pattern3.match)(type).with("Boolean", () => this.transformOutputBoolean(value)).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Decimal", () => this.transformDecimal(value)).otherwise(() => super.transformOutput(value, type, array));
1745
+ }
1746
+ transformOutputBoolean(value) {
1747
+ return !!value;
1748
+ }
1749
+ transformOutputBigInt(value) {
1750
+ if (typeof value === "bigint") {
1751
+ return value;
1752
+ }
1753
+ (0, import_common_helpers4.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
1754
+ return BigInt(value);
1755
+ }
1756
+ transformDecimal(value) {
1757
+ if (value instanceof import_decimal.default) {
1758
+ return value;
1759
+ }
1760
+ (0, import_common_helpers4.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal.default, `Expected string, number or Decimal, got ${typeof value}`);
1761
+ return new import_decimal.default(value);
1762
+ }
1763
+ transformOutputDate(value) {
1764
+ if (typeof value === "string") {
1765
+ return new Date(!value.endsWith("Z") ? value + "Z" : value);
1766
+ } else if (value instanceof Date) {
1767
+ return value;
1768
+ } else {
1769
+ return value;
1770
+ }
1771
+ }
1772
+ transformOutputBytes(value) {
1773
+ return Buffer.isBuffer(value) ? Uint8Array.from(value) : value;
1774
+ }
1775
+ // #endregion
1776
+ // #region other overrides
1777
+ buildArrayAgg(arg) {
1778
+ return this.eb.fn.coalesce(import_kysely3.sql`JSON_ARRAYAGG(${arg})`, import_kysely3.sql`JSON_ARRAY()`);
1779
+ }
1765
1780
  buildSkipTake(query, skip, take) {
1766
1781
  if (take !== void 0) {
1767
1782
  query = query.limit(take);
1768
1783
  }
1769
1784
  if (skip !== void 0) {
1770
1785
  query = query.offset(skip);
1786
+ if (take === void 0) {
1787
+ query = query.limit(Number.MAX_SAFE_INTEGER);
1788
+ }
1771
1789
  }
1772
1790
  return query;
1773
1791
  }
1774
1792
  buildJsonObject(value) {
1775
- return this.eb.fn("jsonb_build_object", Object.entries(value).flatMap(([key, value2]) => [
1793
+ return this.eb.fn("JSON_OBJECT", Object.entries(value).flatMap(([key, value2]) => [
1776
1794
  import_kysely3.sql.lit(key),
1777
1795
  value2
1778
1796
  ]));
1779
1797
  }
1780
- get supportsUpdateWithLimit() {
1781
- return false;
1798
+ castInt(expression) {
1799
+ return this.eb.cast(expression, import_kysely3.sql.raw("unsigned"));
1782
1800
  }
1783
- get supportsDeleteWithLimit() {
1784
- return false;
1801
+ castText(expression) {
1802
+ return import_kysely3.sql`CAST(${expression} AS CHAR CHARACTER SET utf8mb4)`;
1785
1803
  }
1786
- get supportsDistinctOn() {
1787
- return true;
1804
+ trimTextQuotes(expression) {
1805
+ return import_kysely3.sql`TRIM(BOTH ${import_kysely3.sql.lit('"')} FROM ${expression})`;
1788
1806
  }
1789
1807
  buildArrayLength(array) {
1790
- return this.eb.fn("array_length", [
1808
+ return this.eb.fn("JSON_LENGTH", [
1791
1809
  array
1792
1810
  ]);
1793
1811
  }
1794
- buildArrayLiteralSQL(values) {
1795
- if (values.length === 0) {
1796
- return "{}";
1797
- } else {
1798
- return `ARRAY[${values.map((v) => typeof v === "string" ? `'${v}'` : v)}]`;
1799
- }
1812
+ buildArrayLiteralSQL(_values) {
1813
+ throw new Error("MySQL does not support array literals");
1814
+ }
1815
+ buildJsonEqualityFilter(lhs, rhs) {
1816
+ return this.eb.and([
1817
+ this.eb.fn("JSON_CONTAINS", [
1818
+ lhs,
1819
+ this.eb.val(JSON.stringify(rhs))
1820
+ ]),
1821
+ this.eb.fn("JSON_CONTAINS", [
1822
+ this.eb.val(JSON.stringify(rhs)),
1823
+ lhs
1824
+ ])
1825
+ ]);
1800
1826
  }
1801
1827
  buildJsonPathSelection(receiver, path) {
1802
1828
  if (path) {
1803
- return this.eb.fn("jsonb_path_query_first", [
1829
+ return this.eb.fn("JSON_EXTRACT", [
1804
1830
  receiver,
1805
1831
  this.eb.val(path)
1806
1832
  ]);
@@ -1813,23 +1839,281 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1813
1839
  const v = Array.isArray(value) ? value : [
1814
1840
  value
1815
1841
  ];
1816
- return import_kysely3.sql`${lhs} @> ${import_kysely3.sql.val(JSON.stringify(v))}::jsonb`;
1817
- }).with("array_starts_with", () => this.eb(this.eb.fn("jsonb_extract_path", [
1818
- lhs,
1819
- this.eb.val("0")
1820
- ]), "=", this.transformPrimitive(value, "Json", false))).with("array_ends_with", () => this.eb(this.eb.fn("jsonb_extract_path", [
1842
+ return import_kysely3.sql`JSON_CONTAINS(${lhs}, ${import_kysely3.sql.val(JSON.stringify(v))})`;
1843
+ }).with("array_starts_with", () => this.eb(this.eb.fn("JSON_EXTRACT", [
1821
1844
  lhs,
1822
- import_kysely3.sql`(jsonb_array_length(${lhs}) - 1)::text`
1823
- ]), "=", this.transformPrimitive(value, "Json", false))).exhaustive();
1845
+ this.eb.val("$[0]")
1846
+ ]), "=", this.transformInput(value, "Json", false))).with("array_ends_with", () => this.eb(import_kysely3.sql`JSON_EXTRACT(${lhs}, CONCAT('$[', JSON_LENGTH(${lhs}) - 1, ']'))`, "=", this.transformInput(value, "Json", false))).exhaustive();
1847
+ }
1848
+ buildJsonArrayExistsPredicate(receiver, buildFilter) {
1849
+ return this.eb.exists(this.eb.selectFrom(import_kysely3.sql`JSON_TABLE(${receiver}, '$[*]' COLUMNS(value JSON PATH '$'))`.as("$items")).select(this.eb.lit(1).as("$t")).where(buildFilter(this.eb.ref("$items.value"))));
1850
+ }
1851
+ getFieldSqlType(fieldDef) {
1852
+ if (fieldDef.relation) {
1853
+ throw createInternalError("Cannot get SQL type of a relation field");
1854
+ }
1855
+ let result;
1856
+ if (this.schema.enums?.[fieldDef.type]) {
1857
+ result = "varchar(255)";
1858
+ } else {
1859
+ result = (0, import_ts_pattern3.match)(fieldDef.type).with("String", () => "varchar(255)").with("Boolean", () => "tinyint(1)").with("Int", () => "int").with("BigInt", () => "bigint").with("Float", () => "double").with("Decimal", () => "decimal").with("DateTime", () => "datetime").with("Bytes", () => "blob").with("Json", () => "json").otherwise(() => "text");
1860
+ }
1861
+ if (fieldDef.array) {
1862
+ result = "json";
1863
+ }
1864
+ return result;
1865
+ }
1866
+ getStringCasingBehavior() {
1867
+ return {
1868
+ supportsILike: false,
1869
+ likeCaseSensitive: false
1870
+ };
1871
+ }
1872
+ buildValuesTableSelect(fields, rows) {
1873
+ const cols = rows[0]?.length ?? 0;
1874
+ if (fields.length !== cols) {
1875
+ throw createInvalidInputError("Number of fields must match number of columns in each row");
1876
+ }
1877
+ for (const row of rows) {
1878
+ if (row.length !== cols) {
1879
+ throw createInvalidInputError("All rows must have the same number of columns");
1880
+ }
1881
+ }
1882
+ const aliasWithColumns = `$values(${fields.map((f) => f.name).join(", ")})`;
1883
+ const eb = (0, import_kysely3.expressionBuilder)();
1884
+ return eb.selectFrom(import_kysely3.sql`(VALUES ${import_kysely3.sql.join(rows.map((row) => import_kysely3.sql`ROW(${import_kysely3.sql.join(row.map((v) => import_kysely3.sql.val(v)))})`), import_kysely3.sql.raw(", "))}) as ${import_kysely3.sql.raw(aliasWithColumns)}`).selectAll();
1885
+ }
1886
+ buildOrderByField(query, field, sort, nulls) {
1887
+ let result = query;
1888
+ if (nulls === "first") {
1889
+ result = result.orderBy(import_kysely3.sql`${field} IS NULL`, "desc");
1890
+ result = result.orderBy(field, sort);
1891
+ } else {
1892
+ result = result.orderBy(import_kysely3.sql`${field} IS NULL`, "asc");
1893
+ result = result.orderBy(field, sort);
1894
+ }
1895
+ return result;
1896
+ }
1897
+ };
1898
+
1899
+ // src/client/crud/dialects/postgresql.ts
1900
+ var import_common_helpers5 = require("@zenstackhq/common-helpers");
1901
+ var import_decimal2 = __toESM(require("decimal.js"), 1);
1902
+ var import_kysely4 = require("kysely");
1903
+ var import_postgres_array = require("postgres-array");
1904
+ var import_ts_pattern4 = require("ts-pattern");
1905
+ var import_zod = __toESM(require("zod"), 1);
1906
+ var PostgresCrudDialect = class extends LateralJoinDialectBase {
1907
+ static {
1908
+ __name(this, "PostgresCrudDialect");
1909
+ }
1910
+ isoDateSchema = import_zod.default.iso.datetime({
1911
+ local: true,
1912
+ offset: true
1913
+ });
1914
+ constructor(schema, options) {
1915
+ super(schema, options);
1916
+ }
1917
+ get provider() {
1918
+ return "postgresql";
1919
+ }
1920
+ // #region capabilities
1921
+ get supportsUpdateWithLimit() {
1922
+ return false;
1923
+ }
1924
+ get supportsDeleteWithLimit() {
1925
+ return false;
1926
+ }
1927
+ get supportsDistinctOn() {
1928
+ return true;
1929
+ }
1930
+ get supportsReturning() {
1931
+ return true;
1932
+ }
1933
+ get supportsDefaultAsFieldValue() {
1934
+ return true;
1935
+ }
1936
+ get supportsInsertDefaultValues() {
1937
+ return true;
1938
+ }
1939
+ get insertIgnoreMethod() {
1940
+ return "onConflict";
1941
+ }
1942
+ // #endregion
1943
+ // #region value transformation
1944
+ transformInput(value, type, forArrayField) {
1945
+ if (value === void 0) {
1946
+ return value;
1947
+ }
1948
+ if (value instanceof JsonNullClass) {
1949
+ return "null";
1950
+ } else if (value instanceof DbNullClass) {
1951
+ return null;
1952
+ } else if (value instanceof AnyNullClass) {
1953
+ (0, import_common_helpers5.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1954
+ }
1955
+ if (isTypeDef(this.schema, type)) {
1956
+ if (typeof value !== "string") {
1957
+ return JSON.stringify(value);
1958
+ } else {
1959
+ return value;
1960
+ }
1961
+ } else if (Array.isArray(value)) {
1962
+ if (type === "Json" && !forArrayField) {
1963
+ return JSON.stringify(value);
1964
+ }
1965
+ if (isEnum(this.schema, type)) {
1966
+ return this.eb.cast(import_kysely4.sql`ARRAY[${import_kysely4.sql.join(value.map((v) => this.transformInput(v, type, false)), import_kysely4.sql.raw(","))}]`, this.createSchemaQualifiedEnumType(type, true));
1967
+ } else {
1968
+ return value.map((v) => this.transformInput(v, type, false));
1969
+ }
1970
+ } else {
1971
+ return (0, import_ts_pattern4.match)(type).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value !== null ? value.toString() : value).with("Json", () => {
1972
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1973
+ return JSON.stringify(value);
1974
+ } else {
1975
+ return value;
1976
+ }
1977
+ }).otherwise(() => value);
1978
+ }
1979
+ }
1980
+ createSchemaQualifiedEnumType(type, array) {
1981
+ let qualified = type;
1982
+ const enumDef = getEnum(this.schema, type);
1983
+ if (enumDef) {
1984
+ const schemaAttr = enumDef.attributes?.find((attr) => attr.name === "@@schema");
1985
+ if (schemaAttr) {
1986
+ const mapArg = schemaAttr.args?.find((arg) => arg.name === "map");
1987
+ if (mapArg && mapArg.value.kind === "literal") {
1988
+ const schemaName = mapArg.value.value;
1989
+ qualified = `"${schemaName}"."${type}"`;
1990
+ }
1991
+ } else {
1992
+ const defaultSchema = this.schema.provider.defaultSchema ?? "public";
1993
+ qualified = `"${defaultSchema}"."${type}"`;
1994
+ }
1995
+ }
1996
+ return array ? import_kysely4.sql.raw(`${qualified}[]`) : import_kysely4.sql.raw(qualified);
1997
+ }
1998
+ transformOutput(value, type, array) {
1999
+ if (value === null || value === void 0) {
2000
+ return value;
2001
+ }
2002
+ return (0, import_ts_pattern4.match)(type).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Decimal", () => this.transformDecimal(value)).when((type2) => isEnum(this.schema, type2), () => this.transformOutputEnum(value, array)).otherwise(() => super.transformOutput(value, type, array));
2003
+ }
2004
+ transformOutputBigInt(value) {
2005
+ if (typeof value === "bigint") {
2006
+ return value;
2007
+ }
2008
+ (0, import_common_helpers5.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
2009
+ return BigInt(value);
2010
+ }
2011
+ transformDecimal(value) {
2012
+ if (value instanceof import_decimal2.default) {
2013
+ return value;
2014
+ }
2015
+ (0, import_common_helpers5.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal2.default, `Expected string, number or Decimal, got ${typeof value}`);
2016
+ return new import_decimal2.default(value);
2017
+ }
2018
+ transformOutputDate(value) {
2019
+ if (typeof value === "string") {
2020
+ if (this.isoDateSchema.safeParse(value).success) {
2021
+ const hasOffset = value.endsWith("Z") || /[+-]\d{2}:\d{2}$/.test(value);
2022
+ return new Date(hasOffset ? value : `${value}Z`);
2023
+ } else {
2024
+ return value;
2025
+ }
2026
+ } else if (value instanceof Date && this.options.fixPostgresTimezone !== false) {
2027
+ return new Date(value.getTime() - value.getTimezoneOffset() * 60 * 1e3);
2028
+ } else {
2029
+ return value;
2030
+ }
2031
+ }
2032
+ transformOutputBytes(value) {
2033
+ return Buffer.isBuffer(value) ? Uint8Array.from(value) : typeof value === "string" && value.startsWith("\\x") ? Uint8Array.from(Buffer.from(value.slice(2), "hex")) : value;
2034
+ }
2035
+ transformOutputEnum(value, array) {
2036
+ if (array && typeof value === "string") {
2037
+ try {
2038
+ return (0, import_postgres_array.parse)(value);
2039
+ } catch {
2040
+ }
2041
+ }
2042
+ return value;
2043
+ }
2044
+ // #endregion
2045
+ // #region other overrides
2046
+ buildArrayAgg(arg) {
2047
+ return this.eb.fn.coalesce(import_kysely4.sql`jsonb_agg(${arg})`, import_kysely4.sql`'[]'::jsonb`);
2048
+ }
2049
+ buildSkipTake(query, skip, take) {
2050
+ if (take !== void 0) {
2051
+ query = query.limit(take);
2052
+ }
2053
+ if (skip !== void 0) {
2054
+ query = query.offset(skip);
2055
+ }
2056
+ return query;
2057
+ }
2058
+ buildJsonObject(value) {
2059
+ return this.eb.fn("jsonb_build_object", Object.entries(value).flatMap(([key, value2]) => [
2060
+ import_kysely4.sql.lit(key),
2061
+ value2
2062
+ ]));
2063
+ }
2064
+ castInt(expression) {
2065
+ return this.eb.cast(expression, "integer");
2066
+ }
2067
+ castText(expression) {
2068
+ return this.eb.cast(expression, "text");
2069
+ }
2070
+ trimTextQuotes(expression) {
2071
+ return this.eb.fn("trim", [
2072
+ expression,
2073
+ import_kysely4.sql.lit('"')
2074
+ ]);
2075
+ }
2076
+ buildArrayLength(array) {
2077
+ return this.eb.fn("array_length", [
2078
+ array
2079
+ ]);
2080
+ }
2081
+ buildArrayLiteralSQL(values) {
2082
+ if (values.length === 0) {
2083
+ return import_kysely4.sql`{}`;
2084
+ } else {
2085
+ return import_kysely4.sql`ARRAY[${import_kysely4.sql.join(values.map((v) => import_kysely4.sql.val(v)), import_kysely4.sql.raw(","))}]`;
2086
+ }
2087
+ }
2088
+ buildJsonPathSelection(receiver, path) {
2089
+ if (path) {
2090
+ return this.eb.fn("jsonb_path_query_first", [
2091
+ receiver,
2092
+ this.eb.val(path)
2093
+ ]);
2094
+ } else {
2095
+ return receiver;
2096
+ }
2097
+ }
2098
+ buildJsonArrayFilter(lhs, operation, value) {
2099
+ return (0, import_ts_pattern4.match)(operation).with("array_contains", () => {
2100
+ const v = Array.isArray(value) ? value : [
2101
+ value
2102
+ ];
2103
+ return import_kysely4.sql`${lhs} @> ${import_kysely4.sql.val(JSON.stringify(v))}::jsonb`;
2104
+ }).with("array_starts_with", () => this.eb(this.eb.fn("jsonb_extract_path", [
2105
+ lhs,
2106
+ this.eb.val("0")
2107
+ ]), "=", this.transformInput(value, "Json", false))).with("array_ends_with", () => this.eb(this.eb.fn("jsonb_extract_path", [
2108
+ lhs,
2109
+ import_kysely4.sql`(jsonb_array_length(${lhs}) - 1)::text`
2110
+ ]), "=", this.transformInput(value, "Json", false))).exhaustive();
1824
2111
  }
1825
2112
  buildJsonArrayExistsPredicate(receiver, buildFilter) {
1826
2113
  return this.eb.exists(this.eb.selectFrom(this.eb.fn("jsonb_array_elements", [
1827
2114
  receiver
1828
2115
  ]).as("$items")).select(this.eb.lit(1).as("$t")).where(buildFilter(this.eb.ref("$items.value"))));
1829
2116
  }
1830
- get supportInsertWithDefault() {
1831
- return true;
1832
- }
1833
2117
  getFieldSqlType(fieldDef) {
1834
2118
  if (fieldDef.relation) {
1835
2119
  throw createInternalError("Cannot get SQL type of a relation field");
@@ -1838,7 +2122,7 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1838
2122
  if (this.schema.enums?.[fieldDef.type]) {
1839
2123
  result = "text";
1840
2124
  } else {
1841
- result = (0, import_ts_pattern3.match)(fieldDef.type).with("String", () => "text").with("Boolean", () => "boolean").with("Int", () => "integer").with("BigInt", () => "bigint").with("Float", () => "double precision").with("Decimal", () => "decimal").with("DateTime", () => "timestamp").with("Bytes", () => "bytea").with("Json", () => "jsonb").otherwise(() => "text");
2125
+ result = (0, import_ts_pattern4.match)(fieldDef.type).with("String", () => "text").with("Boolean", () => "boolean").with("Int", () => "integer").with("BigInt", () => "bigint").with("Float", () => "double precision").with("Decimal", () => "decimal").with("DateTime", () => "timestamp").with("Bytes", () => "bytea").with("Json", () => "jsonb").otherwise(() => "text");
1842
2126
  }
1843
2127
  if (fieldDef.array) {
1844
2128
  result += "[]";
@@ -1851,13 +2135,36 @@ var PostgresCrudDialect = class extends BaseCrudDialect {
1851
2135
  likeCaseSensitive: true
1852
2136
  };
1853
2137
  }
2138
+ buildValuesTableSelect(fields, rows) {
2139
+ if (rows.length === 0) {
2140
+ throw createInvalidInputError("At least one row is required to build values table");
2141
+ }
2142
+ const rowLength = rows[0].length;
2143
+ if (fields.length !== rowLength) {
2144
+ throw createInvalidInputError("Number of fields must match number of columns in each row");
2145
+ }
2146
+ for (const row of rows) {
2147
+ if (row.length !== rowLength) {
2148
+ throw createInvalidInputError("All rows must have the same number of columns");
2149
+ }
2150
+ }
2151
+ const eb = (0, import_kysely4.expressionBuilder)();
2152
+ return eb.selectFrom(import_kysely4.sql`(VALUES ${import_kysely4.sql.join(rows.map((row) => import_kysely4.sql`(${import_kysely4.sql.join(row.map((v) => import_kysely4.sql.val(v)))})`), import_kysely4.sql.raw(", "))})`.as("$values")).select(fields.map((f, i) => import_kysely4.sql`CAST(${import_kysely4.sql.ref(`$values.column${i + 1}`)} AS ${import_kysely4.sql.raw(this.getFieldSqlType(f))})`.as(f.name)));
2153
+ }
2154
+ buildOrderByField(query, field, sort, nulls) {
2155
+ return query.orderBy(field, (ob) => {
2156
+ ob = sort === "asc" ? ob.asc() : ob.desc();
2157
+ ob = nulls === "first" ? ob.nullsFirst() : ob.nullsLast();
2158
+ return ob;
2159
+ });
2160
+ }
1854
2161
  };
1855
2162
 
1856
2163
  // src/client/crud/dialects/sqlite.ts
1857
- var import_common_helpers4 = require("@zenstackhq/common-helpers");
1858
- var import_decimal2 = __toESM(require("decimal.js"), 1);
1859
- var import_kysely4 = require("kysely");
1860
- var import_ts_pattern4 = require("ts-pattern");
2164
+ var import_common_helpers6 = require("@zenstackhq/common-helpers");
2165
+ var import_decimal3 = __toESM(require("decimal.js"), 1);
2166
+ var import_kysely5 = require("kysely");
2167
+ var import_ts_pattern5 = require("ts-pattern");
1861
2168
  var SqliteCrudDialect = class extends BaseCrudDialect {
1862
2169
  static {
1863
2170
  __name(this, "SqliteCrudDialect");
@@ -1865,7 +2172,31 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1865
2172
  get provider() {
1866
2173
  return "sqlite";
1867
2174
  }
1868
- transformPrimitive(value, type, _forArrayField) {
2175
+ // #region capabilities
2176
+ get supportsUpdateWithLimit() {
2177
+ return false;
2178
+ }
2179
+ get supportsDeleteWithLimit() {
2180
+ return false;
2181
+ }
2182
+ get supportsDistinctOn() {
2183
+ return false;
2184
+ }
2185
+ get supportsReturning() {
2186
+ return true;
2187
+ }
2188
+ get supportsDefaultAsFieldValue() {
2189
+ return false;
2190
+ }
2191
+ get supportsInsertDefaultValues() {
2192
+ return true;
2193
+ }
2194
+ get insertIgnoreMethod() {
2195
+ return "onConflict";
2196
+ }
2197
+ // #endregion
2198
+ // #region value transformation
2199
+ transformInput(value, type, _forArrayField) {
1869
2200
  if (value === void 0) {
1870
2201
  return value;
1871
2202
  }
@@ -1874,15 +2205,15 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1874
2205
  } else if (value instanceof DbNullClass) {
1875
2206
  return null;
1876
2207
  } else if (value instanceof AnyNullClass) {
1877
- (0, import_common_helpers4.invariant)(false, "should not reach here: AnyNull is not a valid input value");
2208
+ (0, import_common_helpers6.invariant)(false, "should not reach here: AnyNull is not a valid input value");
1878
2209
  }
1879
2210
  if (type === "Json" || this.schema.typeDefs && type in this.schema.typeDefs) {
1880
2211
  return JSON.stringify(value);
1881
2212
  }
1882
2213
  if (Array.isArray(value)) {
1883
- return value.map((v) => this.transformPrimitive(v, type, false));
2214
+ return value.map((v) => this.transformInput(v, type, false));
1884
2215
  } else {
1885
- return (0, import_ts_pattern4.match)(type).with("Boolean", () => value ? 1 : 0).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value.toString()).with("Bytes", () => Buffer.from(value)).otherwise(() => value);
2216
+ return (0, import_ts_pattern5.match)(type).with("Boolean", () => value ? 1 : 0).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value.toString()).with("Bytes", () => Buffer.from(value)).otherwise(() => value);
1886
2217
  }
1887
2218
  }
1888
2219
  transformOutput(value, type, array) {
@@ -1891,21 +2222,21 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1891
2222
  } else if (this.schema.typeDefs && type in this.schema.typeDefs) {
1892
2223
  return this.transformOutputJson(value);
1893
2224
  } else {
1894
- return (0, import_ts_pattern4.match)(type).with("Boolean", () => this.transformOutputBoolean(value)).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("Decimal", () => this.transformOutputDecimal(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Json", () => this.transformOutputJson(value)).otherwise(() => super.transformOutput(value, type, array));
2225
+ return (0, import_ts_pattern5.match)(type).with("Boolean", () => this.transformOutputBoolean(value)).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("Decimal", () => this.transformOutputDecimal(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Json", () => this.transformOutputJson(value)).otherwise(() => super.transformOutput(value, type, array));
1895
2226
  }
1896
2227
  }
1897
2228
  transformOutputDecimal(value) {
1898
- if (value instanceof import_decimal2.default) {
2229
+ if (value instanceof import_decimal3.default) {
1899
2230
  return value;
1900
2231
  }
1901
- (0, import_common_helpers4.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal2.default, `Expected string, number or Decimal, got ${typeof value}`);
1902
- return new import_decimal2.default(value);
2232
+ (0, import_common_helpers6.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal3.default, `Expected string, number or Decimal, got ${typeof value}`);
2233
+ return new import_decimal3.default(value);
1903
2234
  }
1904
2235
  transformOutputBigInt(value) {
1905
2236
  if (typeof value === "bigint") {
1906
2237
  return value;
1907
2238
  }
1908
- (0, import_common_helpers4.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
2239
+ (0, import_common_helpers6.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
1909
2240
  return BigInt(value);
1910
2241
  }
1911
2242
  transformOutputBoolean(value) {
@@ -1935,6 +2266,8 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1935
2266
  }
1936
2267
  return value;
1937
2268
  }
2269
+ // #endregion
2270
+ // #region other overrides
1938
2271
  buildRelationSelection(query, model, relationField, parentAlias, payload) {
1939
2272
  return query.select((eb) => this.buildRelationJSON(model, eb, relationField, parentAlias, payload).as(relationField));
1940
2273
  }
@@ -1960,14 +2293,14 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1960
2293
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1961
2294
  if (descendantModels.length > 0) {
1962
2295
  objArgs.push(...descendantModels.map((subModel) => [
1963
- import_kysely4.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`),
2296
+ import_kysely5.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`),
1964
2297
  eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)
1965
2298
  ]).flatMap((v) => v));
1966
2299
  }
1967
2300
  if (payload === true || !payload.select) {
1968
2301
  const omit = typeof payload === "object" ? payload.omit : void 0;
1969
2302
  objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [
1970
- import_kysely4.sql.lit(field),
2303
+ import_kysely5.sql.lit(field),
1971
2304
  this.fieldRef(relationModel, field, subQueryName, false)
1972
2305
  ]).flatMap((v) => v));
1973
2306
  } else if (payload.select) {
@@ -1975,7 +2308,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1975
2308
  if (field === "_count") {
1976
2309
  const subJson = this.buildCountJson(relationModel, eb, `${parentAlias}$${relationField}`, value);
1977
2310
  return [
1978
- import_kysely4.sql.lit(field),
2311
+ import_kysely5.sql.lit(field),
1979
2312
  subJson
1980
2313
  ];
1981
2314
  } else {
@@ -1983,12 +2316,12 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1983
2316
  if (fieldDef.relation) {
1984
2317
  const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentAlias}$${relationField}`, value);
1985
2318
  return [
1986
- import_kysely4.sql.lit(field),
2319
+ import_kysely5.sql.lit(field),
1987
2320
  subJson
1988
2321
  ];
1989
2322
  } else {
1990
2323
  return [
1991
- import_kysely4.sql.lit(field),
2324
+ import_kysely5.sql.lit(field),
1992
2325
  this.fieldRef(relationModel, field, subQueryName, false)
1993
2326
  ];
1994
2327
  }
@@ -1999,15 +2332,15 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
1999
2332
  objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
2000
2333
  const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentAlias}$${relationField}`, value);
2001
2334
  return [
2002
- import_kysely4.sql.lit(field),
2335
+ import_kysely5.sql.lit(field),
2003
2336
  subJson
2004
2337
  ];
2005
2338
  }).flatMap((v) => v));
2006
2339
  }
2007
2340
  if (relationFieldDef.array) {
2008
- return eb.fn.coalesce(import_kysely4.sql`json_group_array(json_object(${import_kysely4.sql.join(objArgs)}))`, import_kysely4.sql`json_array()`).as("$data");
2341
+ return eb.fn.coalesce(import_kysely5.sql`json_group_array(json_object(${import_kysely5.sql.join(objArgs)}))`, import_kysely5.sql`json_array()`).as("$data");
2009
2342
  } else {
2010
- return import_kysely4.sql`json_object(${import_kysely4.sql.join(objArgs)})`.as("$data");
2343
+ return import_kysely5.sql`json_object(${import_kysely5.sql.join(objArgs)})`.as("$data");
2011
2344
  }
2012
2345
  });
2013
2346
  return tbl;
@@ -2019,8 +2352,8 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2019
2352
  if (m2m) {
2020
2353
  const parentIds = requireIdFields(this.schema, model);
2021
2354
  const relationIds = requireIdFields(this.schema, relationModel);
2022
- (0, import_common_helpers4.invariant)(parentIds.length === 1, "many-to-many relation must have exactly one id field");
2023
- (0, import_common_helpers4.invariant)(relationIds.length === 1, "many-to-many relation must have exactly one id field");
2355
+ (0, import_common_helpers6.invariant)(parentIds.length === 1, "many-to-many relation must have exactly one id field");
2356
+ (0, import_common_helpers6.invariant)(relationIds.length === 1, "many-to-many relation must have exactly one id field");
2024
2357
  selectModelQuery = selectModelQuery.where((eb) => eb(eb.ref(`${relationModelAlias}.${relationIds[0]}`), "in", eb.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(`${parentAlias}.${parentIds[0]}`, "=", `${m2m.joinTable}.${m2m.parentFkName}`)));
2025
2358
  } else {
2026
2359
  const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(this.schema, model, relationField);
@@ -2048,7 +2381,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2048
2381
  }
2049
2382
  buildJsonObject(value) {
2050
2383
  return this.eb.fn("json_object", Object.entries(value).flatMap(([key, value2]) => [
2051
- import_kysely4.sql.lit(key),
2384
+ import_kysely5.sql.lit(key),
2052
2385
  value2
2053
2386
  ]));
2054
2387
  }
@@ -2056,35 +2389,26 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2056
2389
  if (!path) {
2057
2390
  return receiver;
2058
2391
  } else {
2059
- return import_kysely4.sql`${receiver} -> ${this.eb.val(path)}`;
2392
+ return import_kysely5.sql`${receiver} -> ${this.eb.val(path)}`;
2060
2393
  }
2061
2394
  }
2062
2395
  buildJsonArrayFilter(lhs, operation, value) {
2063
- return (0, import_ts_pattern4.match)(operation).with("array_contains", () => {
2396
+ return (0, import_ts_pattern5.match)(operation).with("array_contains", () => {
2064
2397
  if (Array.isArray(value)) {
2065
2398
  throw createNotSupportedError('SQLite "array_contains" only supports checking for a single value, not an array of values');
2066
2399
  } else {
2067
- return import_kysely4.sql`EXISTS (SELECT 1 FROM json_each(${lhs}) WHERE value = ${value})`;
2400
+ return import_kysely5.sql`EXISTS (SELECT 1 FROM json_each(${lhs}) WHERE value = ${value})`;
2068
2401
  }
2069
2402
  }).with("array_starts_with", () => this.eb(this.eb.fn("json_extract", [
2070
2403
  lhs,
2071
2404
  this.eb.val("$[0]")
2072
- ]), "=", value)).with("array_ends_with", () => this.eb(import_kysely4.sql`json_extract(${lhs}, '$[' || (json_array_length(${lhs}) - 1) || ']')`, "=", value)).exhaustive();
2405
+ ]), "=", value)).with("array_ends_with", () => this.eb(import_kysely5.sql`json_extract(${lhs}, '$[' || (json_array_length(${lhs}) - 1) || ']')`, "=", value)).exhaustive();
2073
2406
  }
2074
2407
  buildJsonArrayExistsPredicate(receiver, buildFilter) {
2075
2408
  return this.eb.exists(this.eb.selectFrom(this.eb.fn("json_each", [
2076
2409
  receiver
2077
2410
  ]).as("$items")).select(this.eb.lit(1).as("$t")).where(buildFilter(this.eb.ref("$items.value"))));
2078
2411
  }
2079
- get supportsUpdateWithLimit() {
2080
- return false;
2081
- }
2082
- get supportsDeleteWithLimit() {
2083
- return false;
2084
- }
2085
- get supportsDistinctOn() {
2086
- return false;
2087
- }
2088
2412
  buildArrayLength(array) {
2089
2413
  return this.eb.fn("json_array_length", [
2090
2414
  array
@@ -2093,8 +2417,17 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2093
2417
  buildArrayLiteralSQL(_values) {
2094
2418
  throw new Error("SQLite does not support array literals");
2095
2419
  }
2096
- get supportInsertWithDefault() {
2097
- return false;
2420
+ castInt(expression) {
2421
+ return expression;
2422
+ }
2423
+ castText(expression) {
2424
+ return this.eb.cast(expression, "text");
2425
+ }
2426
+ trimTextQuotes(expression) {
2427
+ return this.eb.fn("trim", [
2428
+ expression,
2429
+ import_kysely5.sql.lit('"')
2430
+ ]);
2098
2431
  }
2099
2432
  getFieldSqlType(fieldDef) {
2100
2433
  if (fieldDef.relation) {
@@ -2106,7 +2439,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2106
2439
  if (this.schema.enums?.[fieldDef.type]) {
2107
2440
  return "text";
2108
2441
  }
2109
- return (0, import_ts_pattern4.match)(fieldDef.type).with("String", () => "text").with("Boolean", () => "integer").with("Int", () => "integer").with("BigInt", () => "integer").with("Float", () => "real").with("Decimal", () => "decimal").with("DateTime", () => "numeric").with("Bytes", () => "blob").with("Json", () => "jsonb").otherwise(() => "text");
2442
+ return (0, import_ts_pattern5.match)(fieldDef.type).with("String", () => "text").with("Boolean", () => "integer").with("Int", () => "integer").with("BigInt", () => "integer").with("Float", () => "real").with("Decimal", () => "decimal").with("DateTime", () => "numeric").with("Bytes", () => "blob").with("Json", () => "jsonb").otherwise(() => "text");
2110
2443
  }
2111
2444
  getStringCasingBehavior() {
2112
2445
  return {
@@ -2114,16 +2447,39 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2114
2447
  likeCaseSensitive: false
2115
2448
  };
2116
2449
  }
2450
+ buildValuesTableSelect(fields, rows) {
2451
+ if (rows.length === 0) {
2452
+ throw createInvalidInputError("At least one row is required to build values table");
2453
+ }
2454
+ const rowLength = rows[0].length;
2455
+ if (fields.length !== rowLength) {
2456
+ throw createInvalidInputError("Number of fields must match number of columns in each row");
2457
+ }
2458
+ for (const row of rows) {
2459
+ if (row.length !== rowLength) {
2460
+ throw createInvalidInputError("All rows must have the same number of columns");
2461
+ }
2462
+ }
2463
+ const eb = (0, import_kysely5.expressionBuilder)();
2464
+ return eb.selectFrom(import_kysely5.sql`(VALUES ${import_kysely5.sql.join(rows.map((row) => import_kysely5.sql`(${import_kysely5.sql.join(row.map((v) => import_kysely5.sql.val(v)))})`), import_kysely5.sql.raw(", "))})`.as("$values")).select(fields.map((f, i) => eb.ref(`$values.column${i + 1}`).as(f.name)));
2465
+ }
2466
+ buildOrderByField(query, field, sort, nulls) {
2467
+ return query.orderBy(field, (ob) => {
2468
+ ob = sort === "asc" ? ob.asc() : ob.desc();
2469
+ ob = nulls === "first" ? ob.nullsFirst() : ob.nullsLast();
2470
+ return ob;
2471
+ });
2472
+ }
2117
2473
  };
2118
2474
 
2119
2475
  // src/client/crud/dialects/index.ts
2120
2476
  function getCrudDialect(schema, options) {
2121
- return (0, import_ts_pattern5.match)(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).exhaustive();
2477
+ return (0, import_ts_pattern6.match)(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).with("mysql", () => new MySqlCrudDialect(schema, options)).exhaustive();
2122
2478
  }
2123
2479
  __name(getCrudDialect, "getCrudDialect");
2124
2480
 
2125
2481
  // src/client/crud/operations/base.ts
2126
- var CoreCrudOperations = [
2482
+ var CoreCrudOperations2 = [
2127
2483
  "findMany",
2128
2484
  "findUnique",
2129
2485
  "findFirst",
@@ -2178,7 +2534,7 @@ var CoreDeleteOperations = [
2178
2534
  "deleteMany"
2179
2535
  ];
2180
2536
  var AllCrudOperations = [
2181
- ...CoreCrudOperations,
2537
+ ...CoreCrudOperations2,
2182
2538
  "findUniqueOrThrow",
2183
2539
  "findFirstOrThrow"
2184
2540
  ];
@@ -2236,12 +2592,12 @@ var BaseOperationHandler = class {
2236
2592
  });
2237
2593
  }
2238
2594
  async existsNonUnique(kysely, model, filter) {
2239
- const query = kysely.selectNoFrom((eb) => eb.exists(this.dialect.buildSelectModel(model, model).select(import_kysely5.sql.lit(1).as("$t")).where(() => this.dialect.buildFilter(model, model, filter))).as("exists")).modifyEnd(this.makeContextComment({
2595
+ const query = kysely.selectNoFrom((eb) => eb.exists(this.dialect.buildSelectModel(model, model).select(import_kysely6.sql.lit(1).as("$t")).where(() => this.dialect.buildFilter(model, model, filter))).as("exists")).modifyEnd(this.makeContextComment({
2240
2596
  model,
2241
2597
  operation: "read"
2242
2598
  }));
2243
2599
  let result = [];
2244
- const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), (0, import_kysely5.createQueryId)());
2600
+ const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), (0, import_kysely6.createQueryId)());
2245
2601
  try {
2246
2602
  const r = await kysely.getExecutor().executeQuery(compiled);
2247
2603
  result = r.rows;
@@ -2268,7 +2624,7 @@ var BaseOperationHandler = class {
2268
2624
  operation: "read"
2269
2625
  }));
2270
2626
  let result = [];
2271
- const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), (0, import_kysely5.createQueryId)());
2627
+ const compiled = kysely.getExecutor().compileQuery(query.toOperationNode(), (0, import_kysely6.createQueryId)());
2272
2628
  try {
2273
2629
  const r = await kysely.getExecutor().executeQuery(compiled);
2274
2630
  result = r.rows;
@@ -2342,9 +2698,9 @@ var BaseOperationHandler = class {
2342
2698
  const fieldDef = this.requireField(model, field);
2343
2699
  if (isScalarField(this.schema, model, field) || isForeignKeyField(this.schema, model, field)) {
2344
2700
  if (fieldDef.array && value && typeof value === "object" && "set" in value && Array.isArray(value.set)) {
2345
- createFields[field] = this.dialect.transformPrimitive(value.set, fieldDef.type, true);
2701
+ createFields[field] = this.dialect.transformInput(value.set, fieldDef.type, true);
2346
2702
  } else {
2347
- createFields[field] = this.dialect.transformPrimitive(value, fieldDef.type, !!fieldDef.array);
2703
+ createFields[field] = this.dialect.transformInput(value, fieldDef.type, !!fieldDef.array);
2348
2704
  }
2349
2705
  } else {
2350
2706
  const subM2M = getManyToManyRelation(this.schema, model, field);
@@ -2367,11 +2723,37 @@ var BaseOperationHandler = class {
2367
2723
  }
2368
2724
  const updatedData = this.fillGeneratedAndDefaultValues(modelDef, createFields);
2369
2725
  returnFields = returnFields ?? requireIdFields(this.schema, model);
2370
- const query = kysely.insertInto(model).$if(Object.keys(updatedData).length === 0, (qb) => qb.defaultValues()).$if(Object.keys(updatedData).length > 0, (qb) => qb.values(updatedData)).returning(returnFields).modifyEnd(this.makeContextComment({
2371
- model,
2372
- operation: "create"
2373
- }));
2374
- const createdEntity = await this.executeQueryTakeFirst(kysely, query, "create");
2726
+ let createdEntity;
2727
+ if (this.dialect.supportsReturning) {
2728
+ const query = kysely.insertInto(model).$if(Object.keys(updatedData).length === 0, (qb) => qb.$if(this.dialect.supportsInsertDefaultValues, () => qb.defaultValues()).$if(!this.dialect.supportsInsertDefaultValues, () => qb.values({}))).$if(Object.keys(updatedData).length > 0, (qb) => qb.values(updatedData)).returning(returnFields).modifyEnd(this.makeContextComment({
2729
+ model,
2730
+ operation: "create"
2731
+ }));
2732
+ createdEntity = await this.executeQueryTakeFirst(kysely, query, "create");
2733
+ } else {
2734
+ const insertQuery = kysely.insertInto(model).$if(Object.keys(updatedData).length === 0, (qb) => qb.$if(this.dialect.supportsInsertDefaultValues, () => qb.defaultValues()).$if(!this.dialect.supportsInsertDefaultValues, () => qb.values({}))).$if(Object.keys(updatedData).length > 0, (qb) => qb.values(updatedData)).modifyEnd(this.makeContextComment({
2735
+ model,
2736
+ operation: "create"
2737
+ }));
2738
+ const insertResult = await this.executeQuery(kysely, insertQuery, "create");
2739
+ const idFields = requireIdFields(this.schema, model);
2740
+ const idValues = {};
2741
+ for (const idField of idFields) {
2742
+ if (insertResult.insertId !== void 0 && insertResult.insertId !== null) {
2743
+ const fieldDef = this.requireField(model, idField);
2744
+ if (this.isAutoIncrementField(fieldDef)) {
2745
+ idValues[idField] = insertResult.insertId;
2746
+ continue;
2747
+ }
2748
+ }
2749
+ if (updatedData[idField] !== void 0) {
2750
+ idValues[idField] = updatedData[idField];
2751
+ } else {
2752
+ throw createInternalError(`Cannot determine ID field "${idField}" value for created model "${model}"`);
2753
+ }
2754
+ }
2755
+ createdEntity = idValues;
2756
+ }
2375
2757
  if (Object.keys(postCreateRelations).length > 0) {
2376
2758
  for (const [field, subPayload] of Object.entries(postCreateRelations)) {
2377
2759
  await this.processNoneOwnedRelationForCreate(kysely, model, field, subPayload, createdEntity);
@@ -2385,6 +2767,9 @@ var BaseOperationHandler = class {
2385
2767
  }
2386
2768
  return createdEntity;
2387
2769
  }
2770
+ isAutoIncrementField(fieldDef) {
2771
+ return fieldDef.default && schema_exports.ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "autoincrement";
2772
+ }
2388
2773
  async processBaseModelCreate(kysely, model, createFields, forModel) {
2389
2774
  const thisCreateFields = {};
2390
2775
  const remainingFields = {};
@@ -2397,7 +2782,7 @@ var BaseOperationHandler = class {
2397
2782
  }
2398
2783
  });
2399
2784
  const discriminatorField = getDiscriminatorField(this.schema, model);
2400
- (0, import_common_helpers5.invariant)(discriminatorField, `Base model "${model}" must have a discriminator field`);
2785
+ (0, import_common_helpers7.invariant)(discriminatorField, `Base model "${model}" must have a discriminator field`);
2401
2786
  thisCreateFields[discriminatorField] = forModel;
2402
2787
  const baseEntity = await this.create(kysely, model, thisCreateFields, void 0, true);
2403
2788
  const idValues = extractIdFields(baseEntity, this.schema, model);
@@ -2409,8 +2794,8 @@ var BaseOperationHandler = class {
2409
2794
  }
2410
2795
  async buildFkAssignments(kysely, model, relationField, entity) {
2411
2796
  const parentFkFields = {};
2412
- (0, import_common_helpers5.invariant)(relationField, "parentField must be defined if parentModel is defined");
2413
- (0, import_common_helpers5.invariant)(entity, "parentEntity must be defined if parentModel is defined");
2797
+ (0, import_common_helpers7.invariant)(relationField, "parentField must be defined if parentModel is defined");
2798
+ (0, import_common_helpers7.invariant)(entity, "parentEntity must be defined if parentModel is defined");
2414
2799
  const { keyPairs } = getRelationForeignKeyFieldPairs(this.schema, model, relationField);
2415
2800
  for (const pair of keyPairs) {
2416
2801
  if (!(pair.pk in entity)) {
@@ -2452,29 +2837,29 @@ var BaseOperationHandler = class {
2452
2837
  ));
2453
2838
  const firstIds = requireIdFields(this.schema, sortedRecords[0].model);
2454
2839
  const secondIds = requireIdFields(this.schema, sortedRecords[1].model);
2455
- (0, import_common_helpers5.invariant)(firstIds.length === 1, "many-to-many relation must have exactly one id field");
2456
- (0, import_common_helpers5.invariant)(secondIds.length === 1, "many-to-many relation must have exactly one id field");
2840
+ (0, import_common_helpers7.invariant)(firstIds.length === 1, "many-to-many relation must have exactly one id field");
2841
+ (0, import_common_helpers7.invariant)(secondIds.length === 1, "many-to-many relation must have exactly one id field");
2457
2842
  if (action === "connect") {
2458
2843
  const result = await kysely.insertInto(joinTable).values({
2459
2844
  A: sortedRecords[0].entity[firstIds[0]],
2460
2845
  B: sortedRecords[1].entity[secondIds[0]]
2461
- }).onConflict((oc) => oc.columns([
2846
+ }).$if(this.dialect.insertIgnoreMethod === "onConflict", (qb) => qb.onConflict((oc) => oc.columns([
2462
2847
  "A",
2463
2848
  "B"
2464
- ]).doNothing()).execute();
2849
+ ]).doNothing())).$if(this.dialect.insertIgnoreMethod === "ignore", (qb) => qb.ignore()).execute();
2465
2850
  return result[0];
2466
2851
  } else {
2467
- const eb = (0, import_kysely5.expressionBuilder)();
2852
+ const eb = (0, import_kysely6.expressionBuilder)();
2468
2853
  const result = await kysely.deleteFrom(joinTable).where(eb(`${joinTable}.A`, "=", sortedRecords[0].entity[firstIds[0]])).where(eb(`${joinTable}.B`, "=", sortedRecords[1].entity[secondIds[0]])).execute();
2469
2854
  return result[0];
2470
2855
  }
2471
2856
  }
2472
2857
  resetManyToManyRelation(kysely, model, field, parentIds) {
2473
- (0, import_common_helpers5.invariant)(Object.keys(parentIds).length === 1, "parentIds must have exactly one field");
2858
+ (0, import_common_helpers7.invariant)(Object.keys(parentIds).length === 1, "parentIds must have exactly one field");
2474
2859
  const parentId = Object.values(parentIds)[0];
2475
2860
  const m2m = getManyToManyRelation(this.schema, model, field);
2476
- (0, import_common_helpers5.invariant)(m2m, "not a many-to-many relation");
2477
- const eb = (0, import_kysely5.expressionBuilder)();
2861
+ (0, import_common_helpers7.invariant)(m2m, "not a many-to-many relation");
2862
+ const eb = (0, import_kysely6.expressionBuilder)();
2478
2863
  return kysely.deleteFrom(m2m.joinTable).where(eb(`${m2m.joinTable}.${m2m.parentFkName}`, "=", parentId)).execute();
2479
2864
  }
2480
2865
  async processOwnedRelationForCreate(kysely, relationField, payload) {
@@ -2495,7 +2880,7 @@ var BaseOperationHandler = class {
2495
2880
  }
2496
2881
  case "connect": {
2497
2882
  const referencedPkFields = relationField.relation.references;
2498
- (0, import_common_helpers5.invariant)(referencedPkFields, "relation must have fields info");
2883
+ (0, import_common_helpers7.invariant)(referencedPkFields, "relation must have fields info");
2499
2884
  const extractedFks = extractFields(subPayload, referencedPkFields);
2500
2885
  if (Object.keys(extractedFks).length === referencedPkFields.length) {
2501
2886
  result = extractedFks;
@@ -2542,13 +2927,13 @@ var BaseOperationHandler = class {
2542
2927
  }
2543
2928
  switch (action) {
2544
2929
  case "create": {
2545
- for (const item of (0, import_common_helpers5.enumerate)(subPayload)) {
2930
+ for (const item of (0, import_common_helpers7.enumerate)(subPayload)) {
2546
2931
  await this.create(kysely, relationModel, item, fromRelationContext);
2547
2932
  }
2548
2933
  break;
2549
2934
  }
2550
2935
  case "createMany": {
2551
- (0, import_common_helpers5.invariant)(relationFieldDef.array, "relation must be an array for createMany");
2936
+ (0, import_common_helpers7.invariant)(relationFieldDef.array, "relation must be an array for createMany");
2552
2937
  await this.createMany(kysely, relationModel, subPayload, false, fromRelationContext);
2553
2938
  break;
2554
2939
  }
@@ -2557,7 +2942,7 @@ var BaseOperationHandler = class {
2557
2942
  break;
2558
2943
  }
2559
2944
  case "connectOrCreate": {
2560
- for (const item of (0, import_common_helpers5.enumerate)(subPayload)) {
2945
+ for (const item of (0, import_common_helpers7.enumerate)(subPayload)) {
2561
2946
  const found = await this.exists(kysely, relationModel, item.where);
2562
2947
  if (!found) {
2563
2948
  await this.create(kysely, relationModel, item.create, fromRelationContext);
@@ -2579,20 +2964,20 @@ var BaseOperationHandler = class {
2579
2964
  };
2580
2965
  }
2581
2966
  const modelDef = this.requireModel(model);
2582
- let relationKeyPairs = [];
2967
+ const relationKeyPairs = [];
2583
2968
  if (fromRelation) {
2584
2969
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
2585
2970
  if (ownedByModel) {
2586
2971
  throw createInvalidInputError("incorrect relation hierarchy for createMany", model);
2587
2972
  }
2588
- relationKeyPairs = keyPairs;
2973
+ relationKeyPairs.push(...keyPairs);
2589
2974
  }
2590
- let createData = (0, import_common_helpers5.enumerate)(input.data).map((item) => {
2975
+ let createData = (0, import_common_helpers7.enumerate)(input.data).map((item) => {
2591
2976
  const newItem = {};
2592
2977
  for (const [name, value] of Object.entries(item)) {
2593
2978
  const fieldDef = this.requireField(model, name);
2594
- (0, import_common_helpers5.invariant)(!fieldDef.relation, "createMany does not support relations");
2595
- newItem[name] = this.dialect.transformPrimitive(value, fieldDef.type, !!fieldDef.array);
2979
+ (0, import_common_helpers7.invariant)(!fieldDef.relation, "createMany does not support relations");
2980
+ newItem[name] = this.dialect.transformInput(value, fieldDef.type, !!fieldDef.array);
2596
2981
  }
2597
2982
  if (fromRelation) {
2598
2983
  for (const { fk, pk } of relationKeyPairs) {
@@ -2601,7 +2986,7 @@ var BaseOperationHandler = class {
2601
2986
  }
2602
2987
  return this.fillGeneratedAndDefaultValues(modelDef, newItem);
2603
2988
  });
2604
- if (!this.dialect.supportInsertWithDefault) {
2989
+ if (!this.dialect.supportsDefaultAsFieldValue) {
2605
2990
  const allPassedFields = createData.reduce((acc, item) => {
2606
2991
  Object.keys(item).forEach((field) => {
2607
2992
  if (!acc.includes(field)) {
@@ -2618,7 +3003,7 @@ var BaseOperationHandler = class {
2618
3003
  if (!(field in item)) {
2619
3004
  const fieldDef = this.requireField(model, field);
2620
3005
  if (fieldDef.default !== void 0 && fieldDef.default !== null && typeof fieldDef.default !== "object") {
2621
- item[field] = this.dialect.transformPrimitive(fieldDef.default, fieldDef.type, !!fieldDef.array);
3006
+ item[field] = this.dialect.transformInput(fieldDef.default, fieldDef.type, !!fieldDef.array);
2622
3007
  }
2623
3008
  }
2624
3009
  }
@@ -2631,7 +3016,7 @@ var BaseOperationHandler = class {
2631
3016
  const baseCreateResult = await this.processBaseModelCreateMany(kysely, modelDef.baseModel, createData, !!input.skipDuplicates, model);
2632
3017
  createData = baseCreateResult.remainingFieldRows;
2633
3018
  }
2634
- const query = kysely.insertInto(model).values(createData).$if(!!input.skipDuplicates, (qb) => qb.onConflict((oc) => oc.doNothing())).modifyEnd(this.makeContextComment({
3019
+ const query = kysely.insertInto(model).values(createData).$if(!!input.skipDuplicates, (qb) => qb.$if(this.dialect.insertIgnoreMethod === "onConflict", () => qb.onConflict((oc) => oc.doNothing())).$if(this.dialect.insertIgnoreMethod === "ignore", () => qb.ignore())).modifyEnd(this.makeContextComment({
2635
3020
  model,
2636
3021
  operation: "create"
2637
3022
  }));
@@ -2642,15 +3027,19 @@ var BaseOperationHandler = class {
2642
3027
  };
2643
3028
  } else {
2644
3029
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
2645
- const result = await query.returning(fieldsToReturn).execute();
2646
- return result;
3030
+ if (this.dialect.supportsReturning) {
3031
+ const result = await query.returning(fieldsToReturn).execute();
3032
+ return result;
3033
+ } else {
3034
+ throw createNotSupportedError(`\`createManyAndReturn\` is not supported for ${this.dialect.provider}. Use multiple \`create\` calls or query the records after insertion.`);
3035
+ }
2647
3036
  }
2648
3037
  }
2649
3038
  async processBaseModelCreateMany(kysely, model, createRows, skipDuplicates, forModel) {
2650
3039
  const thisCreateRows = [];
2651
3040
  const remainingFieldRows = [];
2652
3041
  const discriminatorField = getDiscriminatorField(this.schema, model);
2653
- (0, import_common_helpers5.invariant)(discriminatorField, `Base model "${model}" must have a discriminator field`);
3042
+ (0, import_common_helpers7.invariant)(discriminatorField, `Base model "${model}" must have a discriminator field`);
2654
3043
  for (const createFields of createRows) {
2655
3044
  const thisCreateFields = {};
2656
3045
  const remainingFields = {};
@@ -2666,10 +3055,18 @@ var BaseOperationHandler = class {
2666
3055
  thisCreateRows.push(thisCreateFields);
2667
3056
  remainingFieldRows.push(remainingFields);
2668
3057
  }
2669
- const baseEntities = await this.createMany(kysely, model, {
2670
- data: thisCreateRows,
2671
- skipDuplicates
2672
- }, true);
3058
+ let baseEntities;
3059
+ if (this.dialect.supportsReturning) {
3060
+ baseEntities = await this.createMany(kysely, model, {
3061
+ data: thisCreateRows,
3062
+ skipDuplicates
3063
+ }, true);
3064
+ } else {
3065
+ baseEntities = [];
3066
+ for (const row of thisCreateRows) {
3067
+ baseEntities.push(await this.create(kysely, model, row, void 0, true));
3068
+ }
3069
+ }
2673
3070
  for (let i = 0; i < baseEntities.length; i++) {
2674
3071
  const idValues = extractIdFields(baseEntities[i], this.schema, model);
2675
3072
  Object.assign(remainingFieldRows[i], idValues);
@@ -2681,7 +3078,7 @@ var BaseOperationHandler = class {
2681
3078
  }
2682
3079
  fillGeneratedAndDefaultValues(modelDef, data) {
2683
3080
  const fields = modelDef.fields;
2684
- const values = (0, import_common_helpers5.clone)(data);
3081
+ const values = (0, import_common_helpers7.clone)(data);
2685
3082
  for (const [field, fieldDef] of Object.entries(fields)) {
2686
3083
  if (fieldDef.originModel) {
2687
3084
  continue;
@@ -2690,10 +3087,10 @@ var BaseOperationHandler = class {
2690
3087
  if (typeof fieldDef?.default === "object" && "kind" in fieldDef.default) {
2691
3088
  const generated = this.evalGenerator(fieldDef.default);
2692
3089
  if (generated !== void 0) {
2693
- values[field] = this.dialect.transformPrimitive(generated, fieldDef.type, !!fieldDef.array);
3090
+ values[field] = this.dialect.transformInput(generated, fieldDef.type, !!fieldDef.array);
2694
3091
  }
2695
3092
  } else if (fieldDef?.updatedAt) {
2696
- values[field] = this.dialect.transformPrimitive(/* @__PURE__ */ new Date(), "DateTime", false);
3093
+ values[field] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false);
2697
3094
  } else if (fieldDef?.default !== void 0) {
2698
3095
  let value = fieldDef.default;
2699
3096
  if (fieldDef.type === "Json") {
@@ -2703,7 +3100,7 @@ var BaseOperationHandler = class {
2703
3100
  value = JSON.parse(value);
2704
3101
  }
2705
3102
  }
2706
- values[field] = this.dialect.transformPrimitive(value, fieldDef.type, !!fieldDef.array);
3103
+ values[field] = this.dialect.transformInput(value, fieldDef.type, !!fieldDef.array);
2707
3104
  }
2708
3105
  }
2709
3106
  }
@@ -2712,7 +3109,7 @@ var BaseOperationHandler = class {
2712
3109
  evalGenerator(defaultValue) {
2713
3110
  if (schema_exports.ExpressionUtils.isCall(defaultValue)) {
2714
3111
  const firstArgVal = defaultValue.args?.[0] && schema_exports.ExpressionUtils.isLiteral(defaultValue.args[0]) ? defaultValue.args[0].value : void 0;
2715
- return (0, import_ts_pattern6.match)(defaultValue.function).with("cuid", () => {
3112
+ return (0, import_ts_pattern7.match)(defaultValue.function).with("cuid", () => {
2716
3113
  const version = firstArgVal;
2717
3114
  const generated = version === 2 ? (0, import_cuid2.createId)() : (0, import_cuid.default)();
2718
3115
  return this.formatGeneratedValue(generated, defaultValue.args?.[1]);
@@ -2745,32 +3142,7 @@ var BaseOperationHandler = class {
2745
3142
  if (!data || typeof data !== "object") {
2746
3143
  throw createInvalidInputError("data must be an object");
2747
3144
  }
2748
- const parentWhere = {};
2749
- let m2m = void 0;
2750
- if (fromRelation) {
2751
- m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
2752
- if (!m2m) {
2753
- const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
2754
- if (ownedByModel) {
2755
- const fromEntity = await this.readUnique(kysely, fromRelation.model, {
2756
- where: fromRelation.ids
2757
- });
2758
- for (const { fk, pk } of keyPairs) {
2759
- parentWhere[pk] = fromEntity[fk];
2760
- }
2761
- } else {
2762
- for (const { fk, pk } of keyPairs) {
2763
- parentWhere[fk] = fromRelation.ids[pk];
2764
- }
2765
- }
2766
- } else {
2767
- const fromRelationFieldDef = this.requireField(fromRelation.model, fromRelation.field);
2768
- (0, import_common_helpers5.invariant)(fromRelationFieldDef.relation?.opposite);
2769
- parentWhere[fromRelationFieldDef.relation.opposite] = {
2770
- some: fromRelation.ids
2771
- };
2772
- }
2773
- }
3145
+ const parentWhere = await this.buildUpdateParentRelationFilter(kysely, fromRelation);
2774
3146
  let combinedWhere = where ?? {};
2775
3147
  if (Object.keys(parentWhere).length > 0) {
2776
3148
  combinedWhere = Object.keys(combinedWhere).length > 0 ? {
@@ -2784,11 +3156,11 @@ var BaseOperationHandler = class {
2784
3156
  let finalData = data;
2785
3157
  const autoUpdatedFields = [];
2786
3158
  for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
2787
- if (fieldDef.updatedAt) {
3159
+ if (fieldDef.updatedAt && finalData[fieldName] === void 0) {
2788
3160
  if (finalData === data) {
2789
- finalData = (0, import_common_helpers5.clone)(data);
3161
+ finalData = (0, import_common_helpers7.clone)(data);
2790
3162
  }
2791
- finalData[fieldName] = this.dialect.transformPrimitive(/* @__PURE__ */ new Date(), "DateTime", false);
3163
+ finalData[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false);
2792
3164
  autoUpdatedFields.push(fieldName);
2793
3165
  }
2794
3166
  }
@@ -2804,8 +3176,13 @@ var BaseOperationHandler = class {
2804
3176
  return thisEntity;
2805
3177
  }
2806
3178
  let needIdRead = false;
2807
- if (modelDef.baseModel && !this.isIdFilter(model, combinedWhere)) {
2808
- needIdRead = true;
3179
+ if (!this.isIdFilter(model, combinedWhere)) {
3180
+ if (modelDef.baseModel) {
3181
+ needIdRead = true;
3182
+ }
3183
+ if (!this.dialect.supportsReturning) {
3184
+ needIdRead = true;
3185
+ }
2809
3186
  }
2810
3187
  if (needIdRead) {
2811
3188
  const readResult = await this.readUnique(kysely, model, {
@@ -2852,20 +3229,84 @@ var BaseOperationHandler = class {
2852
3229
  return thisEntity;
2853
3230
  } else {
2854
3231
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
2855
- const query = kysely.updateTable(model).where(() => this.dialect.buildFilter(model, model, combinedWhere)).set(updateFields).returning(fieldsToReturn).modifyEnd(this.makeContextComment({
2856
- model,
2857
- operation: "update"
2858
- }));
2859
- const updatedEntity = await this.executeQueryTakeFirst(kysely, query, "update");
3232
+ let updatedEntity;
3233
+ if (this.dialect.supportsReturning) {
3234
+ const query = kysely.updateTable(model).where(() => this.dialect.buildFilter(model, model, combinedWhere)).set(updateFields).returning(fieldsToReturn).modifyEnd(this.makeContextComment({
3235
+ model,
3236
+ operation: "update"
3237
+ }));
3238
+ updatedEntity = await this.executeQueryTakeFirst(kysely, query, "update");
3239
+ } else {
3240
+ const updateQuery = kysely.updateTable(model).where(() => this.dialect.buildFilter(model, model, combinedWhere)).set(updateFields).modifyEnd(this.makeContextComment({
3241
+ model,
3242
+ operation: "update"
3243
+ }));
3244
+ const updateResult = await this.executeQuery(kysely, updateQuery, "update");
3245
+ if (!updateResult.numAffectedRows) {
3246
+ updatedEntity = null;
3247
+ } else {
3248
+ const idFields = requireIdFields(this.schema, model);
3249
+ const filterIdValues = {};
3250
+ for (const key of idFields) {
3251
+ if (combinedWhere[key] !== void 0 && typeof combinedWhere[key] !== "object") {
3252
+ filterIdValues[key] = combinedWhere[key];
3253
+ }
3254
+ }
3255
+ const updatingIdFields = idFields.some((idField) => idField in updateFields);
3256
+ if (Object.keys(filterIdValues).length === idFields.length && !updatingIdFields) {
3257
+ updatedEntity = filterIdValues;
3258
+ } else {
3259
+ const readFilter = {
3260
+ ...combinedWhere
3261
+ };
3262
+ for (const idField of idFields) {
3263
+ if (idField in updateFields && updateFields[idField] !== void 0) {
3264
+ readFilter[idField] = updateFields[idField];
3265
+ }
3266
+ }
3267
+ const selectQuery = kysely.selectFrom(model).select(fieldsToReturn).where(() => this.dialect.buildFilter(model, model, readFilter));
3268
+ updatedEntity = await this.executeQueryTakeFirst(kysely, selectQuery, "update");
3269
+ }
3270
+ }
3271
+ }
2860
3272
  if (!updatedEntity) {
2861
3273
  if (throwIfNotFound) {
2862
3274
  throw createNotFoundError(model);
2863
3275
  } else {
2864
- return null;
3276
+ return null;
3277
+ }
3278
+ }
3279
+ return updatedEntity;
3280
+ }
3281
+ }
3282
+ async buildUpdateParentRelationFilter(kysely, fromRelation) {
3283
+ const parentWhere = {};
3284
+ let m2m = void 0;
3285
+ if (fromRelation) {
3286
+ m2m = getManyToManyRelation(this.schema, fromRelation.model, fromRelation.field);
3287
+ if (!m2m) {
3288
+ const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
3289
+ if (ownedByModel) {
3290
+ const fromEntity = await this.readUnique(kysely, fromRelation.model, {
3291
+ where: fromRelation.ids
3292
+ });
3293
+ for (const { fk, pk } of keyPairs) {
3294
+ parentWhere[pk] = fromEntity[fk];
3295
+ }
3296
+ } else {
3297
+ for (const { fk, pk } of keyPairs) {
3298
+ parentWhere[fk] = fromRelation.ids[pk];
3299
+ }
2865
3300
  }
3301
+ } else {
3302
+ const fromRelationFieldDef = this.requireField(fromRelation.model, fromRelation.field);
3303
+ (0, import_common_helpers7.invariant)(fromRelationFieldDef.relation?.opposite);
3304
+ parentWhere[fromRelationFieldDef.relation.opposite] = {
3305
+ some: fromRelation.ids
3306
+ };
2866
3307
  }
2867
- return updatedEntity;
2868
3308
  }
3309
+ return parentWhere;
2869
3310
  }
2870
3311
  processScalarFieldUpdateData(model, field, data) {
2871
3312
  const fieldDef = this.requireField(model, field);
@@ -2875,7 +3316,7 @@ var BaseOperationHandler = class {
2875
3316
  if (fieldDef.array && typeof data[field] === "object" && !Array.isArray(data[field]) && data[field]) {
2876
3317
  return this.transformScalarListUpdate(model, field, fieldDef, data[field]);
2877
3318
  }
2878
- return this.dialect.transformPrimitive(data[field], fieldDef.type, !!fieldDef.array);
3319
+ return this.dialect.transformInput(data[field], fieldDef.type, !!fieldDef.array);
2879
3320
  }
2880
3321
  isNumericIncrementalUpdate(fieldDef, value) {
2881
3322
  if (!this.isNumericField(fieldDef)) {
@@ -2917,22 +3358,22 @@ var BaseOperationHandler = class {
2917
3358
  };
2918
3359
  }
2919
3360
  transformIncrementalUpdate(model, field, fieldDef, payload) {
2920
- (0, import_common_helpers5.invariant)(Object.keys(payload).length === 1, 'Only one of "set", "increment", "decrement", "multiply", or "divide" can be provided');
3361
+ (0, import_common_helpers7.invariant)(Object.keys(payload).length === 1, 'Only one of "set", "increment", "decrement", "multiply", or "divide" can be provided');
2921
3362
  const key = Object.keys(payload)[0];
2922
- const value = this.dialect.transformPrimitive(payload[key], fieldDef.type, false);
2923
- const eb = (0, import_kysely5.expressionBuilder)();
3363
+ const value = this.dialect.transformInput(payload[key], fieldDef.type, false);
3364
+ const eb = (0, import_kysely6.expressionBuilder)();
2924
3365
  const fieldRef = this.dialect.fieldRef(model, field);
2925
- return (0, import_ts_pattern6.match)(key).with("set", () => value).with("increment", () => eb(fieldRef, "+", value)).with("decrement", () => eb(fieldRef, "-", value)).with("multiply", () => eb(fieldRef, "*", value)).with("divide", () => eb(fieldRef, "/", value)).otherwise(() => {
3366
+ return (0, import_ts_pattern7.match)(key).with("set", () => value).with("increment", () => eb(fieldRef, "+", value)).with("decrement", () => eb(fieldRef, "-", value)).with("multiply", () => eb(fieldRef, "*", value)).with("divide", () => eb(fieldRef, "/", value)).otherwise(() => {
2926
3367
  throw createInvalidInputError(`Invalid incremental update operation: ${key}`);
2927
3368
  });
2928
3369
  }
2929
3370
  transformScalarListUpdate(model, field, fieldDef, payload) {
2930
- (0, import_common_helpers5.invariant)(Object.keys(payload).length === 1, 'Only one of "set", "push" can be provided');
3371
+ (0, import_common_helpers7.invariant)(Object.keys(payload).length === 1, 'Only one of "set", "push" can be provided');
2931
3372
  const key = Object.keys(payload)[0];
2932
- const value = this.dialect.transformPrimitive(payload[key], fieldDef.type, true);
2933
- const eb = (0, import_kysely5.expressionBuilder)();
3373
+ const value = this.dialect.transformInput(payload[key], fieldDef.type, true);
3374
+ const eb = (0, import_kysely6.expressionBuilder)();
2934
3375
  const fieldRef = this.dialect.fieldRef(model, field);
2935
- return (0, import_ts_pattern6.match)(key).with("set", () => value).with("push", () => {
3376
+ return (0, import_ts_pattern7.match)(key).with("set", () => value).with("push", () => {
2936
3377
  return eb(fieldRef, "||", eb.val(ensureArray(value)));
2937
3378
  }).otherwise(() => {
2938
3379
  throw createInvalidInputError(`Invalid array update operation: ${key}`);
@@ -2942,9 +3383,9 @@ var BaseOperationHandler = class {
2942
3383
  return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
2943
3384
  }
2944
3385
  makeContextComment(_context) {
2945
- return import_kysely5.sql``;
3386
+ return import_kysely6.sql``;
2946
3387
  }
2947
- async updateMany(kysely, model, where, data, limit, returnData, filterModel, fieldsToReturn) {
3388
+ async updateMany(kysely, model, where, data, limit, returnData, filterModel, fromRelation, fieldsToReturn) {
2948
3389
  if (typeof data !== "object") {
2949
3390
  throw createInvalidInputError("data must be an object");
2950
3391
  }
@@ -2957,6 +3398,16 @@ var BaseOperationHandler = class {
2957
3398
  if (modelDef.baseModel && limit !== void 0) {
2958
3399
  throw createNotSupportedError("Updating with a limit is not supported for polymorphic models");
2959
3400
  }
3401
+ const parentWhere = await this.buildUpdateParentRelationFilter(kysely, fromRelation);
3402
+ let combinedWhere = where ?? {};
3403
+ if (Object.keys(parentWhere).length > 0) {
3404
+ combinedWhere = Object.keys(combinedWhere).length > 0 ? {
3405
+ AND: [
3406
+ parentWhere,
3407
+ combinedWhere
3408
+ ]
3409
+ } : parentWhere;
3410
+ }
2960
3411
  filterModel ??= model;
2961
3412
  let updateFields = {};
2962
3413
  for (const field in data) {
@@ -2965,16 +3416,9 @@ var BaseOperationHandler = class {
2965
3416
  }
2966
3417
  updateFields[field] = this.processScalarFieldUpdateData(model, field, data);
2967
3418
  }
2968
- let shouldFallbackToIdFilter = false;
2969
- if (limit !== void 0 && !this.dialect.supportsUpdateWithLimit) {
2970
- shouldFallbackToIdFilter = true;
2971
- }
2972
- if (modelDef.isDelegate || modelDef.baseModel) {
2973
- shouldFallbackToIdFilter = true;
2974
- }
2975
3419
  let resultFromBaseModel = void 0;
2976
3420
  if (modelDef.baseModel) {
2977
- const baseResult = await this.processBaseModelUpdateMany(kysely, modelDef.baseModel, where, updateFields, filterModel);
3421
+ const baseResult = await this.processBaseModelUpdateMany(kysely, modelDef.baseModel, combinedWhere, updateFields, filterModel);
2978
3422
  updateFields = baseResult.remainingFields;
2979
3423
  resultFromBaseModel = baseResult.baseResult;
2980
3424
  }
@@ -2983,13 +3427,25 @@ var BaseOperationHandler = class {
2983
3427
  count: 0
2984
3428
  });
2985
3429
  }
3430
+ let shouldFallbackToIdFilter = false;
3431
+ if (limit !== void 0 && !this.dialect.supportsUpdateWithLimit) {
3432
+ shouldFallbackToIdFilter = true;
3433
+ }
3434
+ if (modelDef.isDelegate || modelDef.baseModel) {
3435
+ shouldFallbackToIdFilter = true;
3436
+ }
2986
3437
  let query = kysely.updateTable(model).set(updateFields);
2987
3438
  if (!shouldFallbackToIdFilter) {
2988
- query = query.where(() => this.dialect.buildFilter(model, model, where)).$if(limit !== void 0, (qb) => qb.limit(limit));
3439
+ query = query.where(() => this.dialect.buildFilter(model, model, combinedWhere)).$if(limit !== void 0, (qb) => qb.limit(limit));
2989
3440
  } else {
2990
- query = query.where((eb) => eb(eb.refTuple(
2991
- ...this.buildIdFieldRefs(kysely, model)
2992
- ), "in", this.dialect.buildSelectModel(filterModel, filterModel).where(this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit))));
3441
+ query = query.where((eb) => eb(
3442
+ eb.refTuple(
3443
+ ...this.buildIdFieldRefs(kysely, model)
3444
+ ),
3445
+ "in",
3446
+ // the outer "select *" is needed to isolate the sub query (as needed for dialects like mysql)
3447
+ eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(this.dialect.buildFilter(filterModel, filterModel, combinedWhere)).select(this.buildIdFieldRefs(kysely, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()
3448
+ ));
2993
3449
  }
2994
3450
  query = query.modifyEnd(this.makeContextComment({
2995
3451
  model,
@@ -3002,9 +3458,42 @@ var BaseOperationHandler = class {
3002
3458
  };
3003
3459
  } else {
3004
3460
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
3005
- const finalQuery = query.returning(fieldsToReturn);
3006
- const result = await this.executeQuery(kysely, finalQuery, "update");
3007
- return result.rows;
3461
+ if (this.dialect.supportsReturning) {
3462
+ const finalQuery = query.returning(fieldsToReturn);
3463
+ const result = await this.executeQuery(kysely, finalQuery, "update");
3464
+ return result.rows;
3465
+ } else {
3466
+ let selectQuery = kysely.selectFrom(model).selectAll();
3467
+ if (!shouldFallbackToIdFilter) {
3468
+ selectQuery = selectQuery.where(() => this.dialect.buildFilter(model, model, combinedWhere)).$if(limit !== void 0, (qb) => qb.limit(limit));
3469
+ } else {
3470
+ selectQuery = selectQuery.where((eb) => eb(eb.refTuple(
3471
+ ...this.buildIdFieldRefs(kysely, model)
3472
+ ), "in", this.dialect.buildSelectModel(filterModel, filterModel).where(this.dialect.buildFilter(filterModel, filterModel, combinedWhere)).select(this.buildIdFieldRefs(kysely, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit))));
3473
+ }
3474
+ const recordsToUpdate = await this.executeQuery(kysely, selectQuery, "update");
3475
+ await this.executeQuery(kysely, query, "update");
3476
+ if (recordsToUpdate.rows.length === 0) {
3477
+ return [];
3478
+ }
3479
+ const idFields = requireIdFields(this.schema, model);
3480
+ const updatedIds = recordsToUpdate.rows.map((row) => {
3481
+ const id = {};
3482
+ for (const idField of idFields) {
3483
+ id[idField] = row[idField];
3484
+ }
3485
+ return id;
3486
+ });
3487
+ const resultQuery = kysely.selectFrom(model).selectAll().where((eb) => {
3488
+ const conditions = updatedIds.map((id) => {
3489
+ const idConditions = Object.entries(id).map(([field, value]) => eb.eb(field, "=", value));
3490
+ return eb.and(idConditions);
3491
+ });
3492
+ return eb.or(conditions);
3493
+ });
3494
+ const result = await this.executeQuery(kysely, resultQuery, "update");
3495
+ return result.rows;
3496
+ }
3008
3497
  }
3009
3498
  }
3010
3499
  async processBaseModelUpdateMany(kysely, model, where, updateFields, filterModel) {
@@ -3039,14 +3528,14 @@ var BaseOperationHandler = class {
3039
3528
  for (const [key, value] of Object.entries(args)) {
3040
3529
  switch (key) {
3041
3530
  case "create": {
3042
- (0, import_common_helpers5.invariant)(!Array.isArray(value) || fieldDef.array, "relation must be an array if create is an array");
3043
- for (const item of (0, import_common_helpers5.enumerate)(value)) {
3531
+ (0, import_common_helpers7.invariant)(!Array.isArray(value) || fieldDef.array, "relation must be an array if create is an array");
3532
+ for (const item of (0, import_common_helpers7.enumerate)(value)) {
3044
3533
  await this.create(kysely, fieldModel, item, fromRelationContext);
3045
3534
  }
3046
3535
  break;
3047
3536
  }
3048
3537
  case "createMany": {
3049
- (0, import_common_helpers5.invariant)(fieldDef.array, "relation must be an array for createMany");
3538
+ (0, import_common_helpers7.invariant)(fieldDef.array, "relation must be an array for createMany");
3050
3539
  await this.createMany(kysely, fieldModel, value, false, fromRelationContext);
3051
3540
  break;
3052
3541
  }
@@ -3063,12 +3552,12 @@ var BaseOperationHandler = class {
3063
3552
  break;
3064
3553
  }
3065
3554
  case "set": {
3066
- (0, import_common_helpers5.invariant)(fieldDef.array, "relation must be an array");
3555
+ (0, import_common_helpers7.invariant)(fieldDef.array, "relation must be an array");
3067
3556
  await this.setRelation(kysely, fieldModel, value, fromRelationContext);
3068
3557
  break;
3069
3558
  }
3070
3559
  case "update": {
3071
- for (const _item of (0, import_common_helpers5.enumerate)(value)) {
3560
+ for (const _item of (0, import_common_helpers7.enumerate)(value)) {
3072
3561
  const item = _item;
3073
3562
  let where;
3074
3563
  let data;
@@ -3085,7 +3574,7 @@ var BaseOperationHandler = class {
3085
3574
  break;
3086
3575
  }
3087
3576
  case "upsert": {
3088
- for (const _item of (0, import_common_helpers5.enumerate)(value)) {
3577
+ for (const _item of (0, import_common_helpers7.enumerate)(value)) {
3089
3578
  const item = _item;
3090
3579
  const updated = await this.update(kysely, fieldModel, item.where, item.update, fromRelationContext, true, false);
3091
3580
  if (!updated) {
@@ -3095,9 +3584,9 @@ var BaseOperationHandler = class {
3095
3584
  break;
3096
3585
  }
3097
3586
  case "updateMany": {
3098
- for (const _item of (0, import_common_helpers5.enumerate)(value)) {
3587
+ for (const _item of (0, import_common_helpers7.enumerate)(value)) {
3099
3588
  const item = _item;
3100
- await this.update(kysely, fieldModel, item.where, item.data, fromRelationContext, false, false);
3589
+ await this.updateMany(kysely, fieldModel, item.where, item.data, item.limit, false, fieldModel, fromRelationContext);
3101
3590
  }
3102
3591
  break;
3103
3592
  }
@@ -3139,7 +3628,7 @@ var BaseOperationHandler = class {
3139
3628
  } else {
3140
3629
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
3141
3630
  if (ownedByModel) {
3142
- (0, import_common_helpers5.invariant)(_data.length === 1, "only one entity can be connected");
3631
+ (0, import_common_helpers7.invariant)(_data.length === 1, "only one entity can be connected");
3143
3632
  const target = await this.readUnique(kysely, model, {
3144
3633
  where: _data[0]
3145
3634
  });
@@ -3176,7 +3665,7 @@ var BaseOperationHandler = class {
3176
3665
  }
3177
3666
  }
3178
3667
  async connectOrCreateRelation(kysely, model, data, fromRelation) {
3179
- const _data = (0, import_common_helpers5.enumerate)(data);
3668
+ const _data = (0, import_common_helpers7.enumerate)(data);
3180
3669
  if (_data.length === 0) {
3181
3670
  return;
3182
3671
  }
@@ -3221,9 +3710,9 @@ var BaseOperationHandler = class {
3221
3710
  }
3222
3711
  } else {
3223
3712
  const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, fromRelation.model, fromRelation.field);
3224
- const eb = (0, import_kysely5.expressionBuilder)();
3713
+ const eb = (0, import_kysely6.expressionBuilder)();
3225
3714
  if (ownedByModel) {
3226
- (0, import_common_helpers5.invariant)(disconnectConditions.length === 1, "only one entity can be disconnected");
3715
+ (0, import_common_helpers7.invariant)(disconnectConditions.length === 1, "only one entity can be disconnected");
3227
3716
  const condition = disconnectConditions[0];
3228
3717
  if (condition === true) {
3229
3718
  for (const { fk } of keyPairs) {
@@ -3355,7 +3844,7 @@ var BaseOperationHandler = class {
3355
3844
  if (m2m) {
3356
3845
  deleteFromModel = model;
3357
3846
  const fieldDef = this.requireField(fromRelation.model, fromRelation.field);
3358
- (0, import_common_helpers5.invariant)(fieldDef.relation?.opposite);
3847
+ (0, import_common_helpers7.invariant)(fieldDef.relation?.opposite);
3359
3848
  deleteResult = await this.delete(kysely, model, {
3360
3849
  AND: [
3361
3850
  {
@@ -3379,7 +3868,7 @@ var BaseOperationHandler = class {
3379
3868
  throw createNotFoundError(fromRelation.model);
3380
3869
  }
3381
3870
  const fieldDef = this.requireField(fromRelation.model, fromRelation.field);
3382
- (0, import_common_helpers5.invariant)(fieldDef.relation?.opposite);
3871
+ (0, import_common_helpers7.invariant)(fieldDef.relation?.opposite);
3383
3872
  deleteResult = await this.delete(kysely, model, {
3384
3873
  AND: [
3385
3874
  // filter for parent
@@ -3407,12 +3896,12 @@ var BaseOperationHandler = class {
3407
3896
  });
3408
3897
  }
3409
3898
  }
3410
- if (throwForNotFound && expectedDeleteCount > deleteResult.rows.length) {
3899
+ if (throwForNotFound && expectedDeleteCount > (deleteResult.numAffectedRows ?? 0)) {
3411
3900
  throw createNotFoundError(deleteFromModel);
3412
3901
  }
3413
3902
  }
3414
3903
  normalizeRelationManipulationInput(model, data) {
3415
- return (0, import_common_helpers5.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
3904
+ return (0, import_common_helpers7.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
3416
3905
  }
3417
3906
  // #endregion
3418
3907
  async delete(kysely, model, where, limit, filterModel, fieldsToReturn) {
@@ -3425,7 +3914,6 @@ var BaseOperationHandler = class {
3425
3914
  return this.processBaseModelDelete(kysely, modelDef.baseModel, where, limit, filterModel);
3426
3915
  }
3427
3916
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
3428
- let query = kysely.deleteFrom(model).returning(fieldsToReturn);
3429
3917
  let needIdFilter = false;
3430
3918
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) {
3431
3919
  needIdFilter = true;
@@ -3433,15 +3921,16 @@ var BaseOperationHandler = class {
3433
3921
  if (modelDef.isDelegate || modelDef.baseModel) {
3434
3922
  needIdFilter = true;
3435
3923
  }
3436
- if (!needIdFilter) {
3437
- query = query.where(() => this.dialect.buildFilter(model, model, where));
3438
- } else {
3439
- query = query.where((eb) => eb(eb.refTuple(
3924
+ const deleteFilter = needIdFilter ? (eb) => eb(
3925
+ eb.refTuple(
3440
3926
  ...this.buildIdFieldRefs(kysely, model)
3441
- ), "in", this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit))));
3442
- }
3927
+ ),
3928
+ "in",
3929
+ // the outer "select *" is needed to isolate the sub query (as needed for dialects like mysql)
3930
+ eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()
3931
+ ) : () => this.dialect.buildFilter(model, model, where);
3443
3932
  await this.processDelegateRelationDelete(kysely, modelDef, where, limit);
3444
- query = query.modifyEnd(this.makeContextComment({
3933
+ const query = kysely.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({
3445
3934
  model,
3446
3935
  operation: "delete"
3447
3936
  }));
@@ -3517,7 +4006,7 @@ var BaseOperationHandler = class {
3517
4006
  if (!args) {
3518
4007
  return;
3519
4008
  }
3520
- const newArgs = (0, import_common_helpers5.clone)(args);
4009
+ const newArgs = (0, import_common_helpers7.clone)(args);
3521
4010
  this.doNormalizeArgs(newArgs);
3522
4011
  return newArgs;
3523
4012
  }
@@ -3526,7 +4015,7 @@ var BaseOperationHandler = class {
3526
4015
  for (const [key, value] of Object.entries(args)) {
3527
4016
  if (value === void 0) {
3528
4017
  delete args[key];
3529
- } else if (value && (0, import_common_helpers5.isPlainObject)(value)) {
4018
+ } else if (value && (0, import_common_helpers7.isPlainObject)(value)) {
3530
4019
  this.doNormalizeArgs(value);
3531
4020
  }
3532
4021
  }
@@ -3553,6 +4042,12 @@ var BaseOperationHandler = class {
3553
4042
  selectedFields: void 0
3554
4043
  };
3555
4044
  }
4045
+ if (!this.dialect.supportsReturning) {
4046
+ return {
4047
+ needReadBack: true,
4048
+ selectedFields: void 0
4049
+ };
4050
+ }
3556
4051
  if (args.include && typeof args.include === "object" && Object.keys(args.include).length > 0) {
3557
4052
  return {
3558
4053
  needReadBack: true,
@@ -3622,21 +4117,21 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
3622
4117
  take = -take;
3623
4118
  }
3624
4119
  subQuery = this.dialect.buildSkipTake(subQuery, skip, take);
3625
- subQuery = this.dialect.buildOrderBy(subQuery, this.model, this.model, parsedArgs.orderBy, negateOrderBy);
4120
+ subQuery = this.dialect.buildOrderBy(subQuery, this.model, this.model, parsedArgs.orderBy, negateOrderBy, take);
3626
4121
  return subQuery.as("$sub");
3627
4122
  });
3628
4123
  for (const [key, value] of Object.entries(parsedArgs)) {
3629
4124
  switch (key) {
3630
4125
  case "_count": {
3631
4126
  if (value === true) {
3632
- query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as("_count"));
4127
+ query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
3633
4128
  } else {
3634
4129
  Object.entries(value).forEach(([field, val]) => {
3635
4130
  if (val === true) {
3636
4131
  if (field === "_all") {
3637
- query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as(`_count._all`));
4132
+ query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
3638
4133
  } else {
3639
- query = query.select((eb) => eb.cast(eb.fn.count(eb.ref(`$sub.${field}`)), "integer").as(`${key}.${field}`));
4134
+ query = query.select((eb) => this.dialect.castInt(eb.fn.count(eb.ref(`$sub.${field}`))).as(`${key}.${field}`));
3640
4135
  }
3641
4136
  }
3642
4137
  });
@@ -3650,7 +4145,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
3650
4145
  Object.entries(value).forEach(([field, val]) => {
3651
4146
  if (val === true) {
3652
4147
  query = query.select((eb) => {
3653
- const fn = (0, import_ts_pattern7.match)(key).with("_sum", () => eb.fn.sum).with("_avg", () => eb.fn.avg).with("_max", () => eb.fn.max).with("_min", () => eb.fn.min).exhaustive();
4148
+ const fn = (0, import_ts_pattern8.match)(key).with("_sum", () => eb.fn.sum).with("_avg", () => eb.fn.avg).with("_max", () => eb.fn.max).with("_min", () => eb.fn.min).exhaustive();
3654
4149
  return fn(eb.ref(`$sub.${field}`)).as(`${key}.${field}`);
3655
4150
  });
3656
4151
  }
@@ -3683,7 +4178,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
3683
4178
  val = parseFloat(val);
3684
4179
  } else {
3685
4180
  if (op === "_sum" || op === "_min" || op === "_max") {
3686
- val = (0, import_ts_pattern7.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
4181
+ val = (0, import_ts_pattern8.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
3687
4182
  }
3688
4183
  }
3689
4184
  }
@@ -3721,11 +4216,11 @@ var CountOperationHandler = class extends BaseOperationHandler {
3721
4216
  return subQuery.as(subQueryName);
3722
4217
  });
3723
4218
  if (parsedArgs?.select && typeof parsedArgs.select === "object") {
3724
- query = query.select((eb) => Object.keys(parsedArgs.select).map((key) => key === "_all" ? eb.cast(eb.fn.countAll(), "integer").as("_all") : eb.cast(eb.fn.count(eb.ref(`${subQueryName}.${key}`)), "integer").as(key)));
4219
+ query = query.select((eb) => Object.keys(parsedArgs.select).map((key) => key === "_all" ? this.dialect.castInt(eb.fn.countAll()).as("_all") : this.dialect.castInt(eb.fn.count(eb.ref(`${subQueryName}.${key}`))).as(key)));
3725
4220
  const result = await this.executeQuery(this.kysely, query, "count");
3726
4221
  return result.rows[0];
3727
4222
  } else {
3728
- query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as("count"));
4223
+ query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("count"));
3729
4224
  const result = await this.executeQuery(this.kysely, query, "count");
3730
4225
  return result.rows[0].count;
3731
4226
  }
@@ -3733,14 +4228,14 @@ var CountOperationHandler = class extends BaseOperationHandler {
3733
4228
  };
3734
4229
 
3735
4230
  // src/client/crud/operations/create.ts
3736
- var import_ts_pattern8 = require("ts-pattern");
4231
+ var import_ts_pattern9 = require("ts-pattern");
3737
4232
  var CreateOperationHandler = class extends BaseOperationHandler {
3738
4233
  static {
3739
4234
  __name(this, "CreateOperationHandler");
3740
4235
  }
3741
4236
  async handle(operation, args) {
3742
4237
  const normalizedArgs = this.normalizeArgs(args);
3743
- return (0, import_ts_pattern8.match)(operation).with("create", () => this.runCreate(this.inputValidator.validateCreateArgs(this.model, normalizedArgs))).with("createMany", () => {
4238
+ return (0, import_ts_pattern9.match)(operation).with("create", () => this.runCreate(this.inputValidator.validateCreateArgs(this.model, normalizedArgs))).with("createMany", () => {
3744
4239
  return this.runCreateMany(this.inputValidator.validateCreateManyArgs(this.model, normalizedArgs));
3745
4240
  }).with("createManyAndReturn", () => {
3746
4241
  return this.runCreateManyAndReturn(this.inputValidator.validateCreateManyAndReturnArgs(this.model, normalizedArgs));
@@ -3772,7 +4267,7 @@ var CreateOperationHandler = class extends BaseOperationHandler {
3772
4267
  count: 0
3773
4268
  };
3774
4269
  }
3775
- return this.createMany(this.kysely, this.model, args, false);
4270
+ return this.safeTransaction((tx) => this.createMany(tx, this.model, args, false));
3776
4271
  }
3777
4272
  async runCreateManyAndReturn(args) {
3778
4273
  if (args === void 0) {
@@ -3797,14 +4292,14 @@ var CreateOperationHandler = class extends BaseOperationHandler {
3797
4292
  };
3798
4293
 
3799
4294
  // src/client/crud/operations/delete.ts
3800
- var import_ts_pattern9 = require("ts-pattern");
4295
+ var import_ts_pattern10 = require("ts-pattern");
3801
4296
  var DeleteOperationHandler = class extends BaseOperationHandler {
3802
4297
  static {
3803
4298
  __name(this, "DeleteOperationHandler");
3804
4299
  }
3805
4300
  async handle(operation, args) {
3806
4301
  const normalizedArgs = this.normalizeArgs(args);
3807
- return (0, import_ts_pattern9.match)(operation).with("delete", () => this.runDelete(this.inputValidator.validateDeleteArgs(this.model, normalizedArgs))).with("deleteMany", () => this.runDeleteMany(this.inputValidator.validateDeleteManyArgs(this.model, normalizedArgs))).exhaustive();
4302
+ return (0, import_ts_pattern10.match)(operation).with("delete", () => this.runDelete(this.inputValidator.validateDeleteArgs(this.model, normalizedArgs))).with("deleteMany", () => this.runDeleteMany(this.inputValidator.validateDeleteManyArgs(this.model, normalizedArgs))).exhaustive();
3808
4303
  }
3809
4304
  async runDelete(args) {
3810
4305
  const { needReadBack, selectedFields } = this.mutationNeedsReadBack(this.model, args);
@@ -3819,7 +4314,7 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
3819
4314
  });
3820
4315
  }
3821
4316
  const deleteResult = await this.delete(tx, this.model, args.where, void 0, void 0, selectedFields);
3822
- if (deleteResult.rows.length === 0) {
4317
+ if (!deleteResult.numAffectedRows) {
3823
4318
  throw createNotFoundError(this.model);
3824
4319
  }
3825
4320
  return needReadBack ? preDeleteRead : deleteResult.rows[0];
@@ -3833,7 +4328,7 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
3833
4328
  return await this.safeTransaction(async (tx) => {
3834
4329
  const result = await this.delete(tx, this.model, args?.where, args?.limit);
3835
4330
  return {
3836
- count: result.rows.length
4331
+ count: Number(result.numAffectedRows ?? 0)
3837
4332
  };
3838
4333
  });
3839
4334
  }
@@ -3871,7 +4366,7 @@ var FindOperationHandler = class extends BaseOperationHandler {
3871
4366
  };
3872
4367
 
3873
4368
  // src/client/crud/operations/group-by.ts
3874
- var import_ts_pattern10 = require("ts-pattern");
4369
+ var import_ts_pattern11 = require("ts-pattern");
3875
4370
  var GroupByOperationHandler = class extends BaseOperationHandler {
3876
4371
  static {
3877
4372
  __name(this, "GroupByOperationHandler");
@@ -3893,7 +4388,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
3893
4388
  take = -take;
3894
4389
  }
3895
4390
  query = this.dialect.buildSkipTake(query, skip, take);
3896
- query = this.dialect.buildOrderBy(query, this.model, this.model, parsedArgs.orderBy, negateOrderBy);
4391
+ query = this.dialect.buildOrderBy(query, this.model, this.model, parsedArgs.orderBy, negateOrderBy, take);
3897
4392
  if (parsedArgs.having) {
3898
4393
  query = query.having(() => this.dialect.buildFilter(this.model, this.model, parsedArgs.having));
3899
4394
  }
@@ -3904,14 +4399,14 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
3904
4399
  switch (key) {
3905
4400
  case "_count": {
3906
4401
  if (value === true) {
3907
- query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as("_count"));
4402
+ query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
3908
4403
  } else {
3909
4404
  Object.entries(value).forEach(([field, val]) => {
3910
4405
  if (val === true) {
3911
4406
  if (field === "_all") {
3912
- query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as(`_count._all`));
4407
+ query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
3913
4408
  } else {
3914
- query = query.select((eb) => eb.cast(eb.fn.count(fieldRef(field)), "integer").as(`${key}.${field}`));
4409
+ query = query.select((eb) => this.dialect.castInt(eb.fn.count(fieldRef(field))).as(`${key}.${field}`));
3915
4410
  }
3916
4411
  }
3917
4412
  });
@@ -3959,7 +4454,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
3959
4454
  val = parseFloat(val);
3960
4455
  } else {
3961
4456
  if (op === "_sum" || op === "_min" || op === "_max") {
3962
- val = (0, import_ts_pattern10.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
4457
+ val = (0, import_ts_pattern11.match)(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
3963
4458
  }
3964
4459
  }
3965
4460
  }
@@ -3974,14 +4469,14 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
3974
4469
  };
3975
4470
 
3976
4471
  // src/client/crud/operations/update.ts
3977
- var import_ts_pattern11 = require("ts-pattern");
4472
+ var import_ts_pattern12 = require("ts-pattern");
3978
4473
  var UpdateOperationHandler = class extends BaseOperationHandler {
3979
4474
  static {
3980
4475
  __name(this, "UpdateOperationHandler");
3981
4476
  }
3982
4477
  async handle(operation, args) {
3983
4478
  const normalizedArgs = this.normalizeArgs(args);
3984
- return (0, import_ts_pattern11.match)(operation).with("update", () => this.runUpdate(this.inputValidator.validateUpdateArgs(this.model, normalizedArgs))).with("updateMany", () => this.runUpdateMany(this.inputValidator.validateUpdateManyArgs(this.model, normalizedArgs))).with("updateManyAndReturn", () => this.runUpdateManyAndReturn(this.inputValidator.validateUpdateManyAndReturnArgs(this.model, normalizedArgs))).with("upsert", () => this.runUpsert(this.inputValidator.validateUpsertArgs(this.model, normalizedArgs))).exhaustive();
4479
+ return (0, import_ts_pattern12.match)(operation).with("update", () => this.runUpdate(this.inputValidator.validateUpdateArgs(this.model, normalizedArgs))).with("updateMany", () => this.runUpdateMany(this.inputValidator.validateUpdateManyArgs(this.model, normalizedArgs))).with("updateManyAndReturn", () => this.runUpdateManyAndReturn(this.inputValidator.validateUpdateManyAndReturnArgs(this.model, normalizedArgs))).with("upsert", () => this.runUpsert(this.inputValidator.validateUpsertArgs(this.model, normalizedArgs))).exhaustive();
3985
4480
  }
3986
4481
  async runUpdate(args) {
3987
4482
  const { needReadBack, selectedFields } = this.needReadBack(args);
@@ -4022,7 +4517,7 @@ var UpdateOperationHandler = class extends BaseOperationHandler {
4022
4517
  }
4023
4518
  const { needReadBack, selectedFields } = this.needReadBack(args);
4024
4519
  const { readBackResult, updateResult } = await this.safeTransaction(async (tx) => {
4025
- const updateResult2 = await this.updateMany(tx, this.model, args.where, args.data, args.limit, true, void 0, selectedFields);
4520
+ const updateResult2 = await this.updateMany(tx, this.model, args.where, args.data, args.limit, true, void 0, void 0, selectedFields);
4026
4521
  if (needReadBack) {
4027
4522
  const readBackResult2 = await this.read(tx, this.model, {
4028
4523
  select: args.select,
@@ -4075,6 +4570,12 @@ var UpdateOperationHandler = class extends BaseOperationHandler {
4075
4570
  if (baseResult.needReadBack) {
4076
4571
  return baseResult;
4077
4572
  }
4573
+ if (!this.dialect.supportsReturning) {
4574
+ return {
4575
+ needReadBack: true,
4576
+ selectedFields: void 0
4577
+ };
4578
+ }
4078
4579
  const modelDef = this.requireModel(this.model);
4079
4580
  const nonRelationFields = Object.entries(modelDef.fields).filter(([_, def]) => !def.relation).map(([name, _]) => name);
4080
4581
  if (args.data && !Object.keys(args.data).some((field) => nonRelationFields.includes(field))) {
@@ -4094,10 +4595,9 @@ var UpdateOperationHandler = class extends BaseOperationHandler {
4094
4595
  };
4095
4596
 
4096
4597
  // src/client/crud/validator/index.ts
4097
- var import_common_helpers7 = require("@zenstackhq/common-helpers");
4098
- var import_decimal4 = __toESM(require("decimal.js"), 1);
4099
- var import_json_stable_stringify = __toESM(require("json-stable-stringify"), 1);
4100
- var import_ts_pattern13 = require("ts-pattern");
4598
+ var import_common_helpers9 = require("@zenstackhq/common-helpers");
4599
+ var import_decimal5 = __toESM(require("decimal.js"), 1);
4600
+ var import_ts_pattern14 = require("ts-pattern");
4101
4601
  var import_zod3 = require("zod");
4102
4602
 
4103
4603
  // src/utils/zod-utils.ts
@@ -4107,10 +4607,42 @@ function formatError(error) {
4107
4607
  }
4108
4608
  __name(formatError, "formatError");
4109
4609
 
4610
+ // src/client/crud/validator/cache-decorator.ts
4611
+ var import_json_stable_stringify = __toESM(require("json-stable-stringify"), 1);
4612
+ function cache() {
4613
+ return function(_target, propertyKey, descriptor) {
4614
+ const originalMethod = descriptor.value;
4615
+ descriptor.value = function(...args) {
4616
+ const cacheKeyObj = {
4617
+ $call: propertyKey,
4618
+ $args: args.map((arg) => {
4619
+ if (Array.isArray(arg)) {
4620
+ return [
4621
+ ...arg
4622
+ ].sort();
4623
+ } else {
4624
+ return arg;
4625
+ }
4626
+ })
4627
+ };
4628
+ const cacheKey = (0, import_json_stable_stringify.default)(cacheKeyObj);
4629
+ const cached = this.getCache(cacheKey);
4630
+ if (cached !== void 0) {
4631
+ return cached;
4632
+ }
4633
+ const result = originalMethod.apply(this, args);
4634
+ this.setCache(cacheKey, result);
4635
+ return result;
4636
+ };
4637
+ return descriptor;
4638
+ };
4639
+ }
4640
+ __name(cache, "cache");
4641
+
4110
4642
  // src/client/crud/validator/utils.ts
4111
- var import_common_helpers6 = require("@zenstackhq/common-helpers");
4112
- var import_decimal3 = __toESM(require("decimal.js"), 1);
4113
- var import_ts_pattern12 = require("ts-pattern");
4643
+ var import_common_helpers8 = require("@zenstackhq/common-helpers");
4644
+ var import_decimal4 = __toESM(require("decimal.js"), 1);
4645
+ var import_ts_pattern13 = require("ts-pattern");
4114
4646
  var import_zod2 = require("zod");
4115
4647
  var import_v3 = require("zod/v3");
4116
4648
  function getArgValue(expr) {
@@ -4126,7 +4658,7 @@ function addStringValidation(schema, attributes) {
4126
4658
  }
4127
4659
  let result = schema;
4128
4660
  for (const attr of attributes) {
4129
- (0, import_ts_pattern12.match)(attr.name).with("@length", () => {
4661
+ (0, import_ts_pattern13.match)(attr.name).with("@length", () => {
4130
4662
  const min = getArgValue(attr.args?.[0]?.value);
4131
4663
  if (min !== void 0) {
4132
4664
  result = result.min(min);
@@ -4182,7 +4714,7 @@ function addNumberValidation(schema, attributes) {
4182
4714
  if (val === void 0) {
4183
4715
  continue;
4184
4716
  }
4185
- (0, import_ts_pattern12.match)(attr.name).with("@gt", () => {
4717
+ (0, import_ts_pattern13.match)(attr.name).with("@gt", () => {
4186
4718
  result = result.gt(val);
4187
4719
  }).with("@gte", () => {
4188
4720
  result = result.gte(val);
@@ -4205,7 +4737,7 @@ function addBigIntValidation(schema, attributes) {
4205
4737
  if (val === void 0) {
4206
4738
  continue;
4207
4739
  }
4208
- (0, import_ts_pattern12.match)(attr.name).with("@gt", () => {
4740
+ (0, import_ts_pattern13.match)(attr.name).with("@gt", () => {
4209
4741
  result = result.gt(BigInt(val));
4210
4742
  }).with("@gte", () => {
4211
4743
  result = result.gte(BigInt(val));
@@ -4223,14 +4755,14 @@ function addDecimalValidation(schema, attributes, addExtraValidation) {
4223
4755
  if (schema instanceof import_zod2.z.ZodString) {
4224
4756
  result = schema.superRefine((v, ctx) => {
4225
4757
  try {
4226
- new import_decimal3.default(v);
4758
+ new import_decimal4.default(v);
4227
4759
  } catch (err) {
4228
4760
  ctx.addIssue({
4229
4761
  code: import_zod2.z.ZodIssueCode.custom,
4230
4762
  message: `Invalid decimal: ${err}`
4231
4763
  });
4232
4764
  }
4233
- }).transform((val) => new import_decimal3.default(val));
4765
+ }).transform((val) => new import_decimal4.default(val));
4234
4766
  }
4235
4767
  function refine(schema2, op, value) {
4236
4768
  return schema2.superRefine((v, ctx) => {
@@ -4266,7 +4798,7 @@ function addDecimalValidation(schema, attributes, addExtraValidation) {
4266
4798
  if (val === void 0) {
4267
4799
  continue;
4268
4800
  }
4269
- (0, import_ts_pattern12.match)(attr.name).with("@gt", () => {
4801
+ (0, import_ts_pattern13.match)(attr.name).with("@gt", () => {
4270
4802
  result = refine(result, "gt", val);
4271
4803
  }).with("@gte", () => {
4272
4804
  result = refine(result, "gte", val);
@@ -4286,7 +4818,7 @@ function addListValidation(schema, attributes) {
4286
4818
  }
4287
4819
  let result = schema;
4288
4820
  for (const attr of attributes) {
4289
- (0, import_ts_pattern12.match)(attr.name).with("@length", () => {
4821
+ (0, import_ts_pattern13.match)(attr.name).with("@length", () => {
4290
4822
  const min = getArgValue(attr.args?.[0]?.value);
4291
4823
  if (min !== void 0) {
4292
4824
  result = result.min(min);
@@ -4335,7 +4867,7 @@ function applyValidation(schema, expr, message, path) {
4335
4867
  }
4336
4868
  __name(applyValidation, "applyValidation");
4337
4869
  function evalExpression(data, expr) {
4338
- return (0, import_ts_pattern12.match)(expr).with({
4870
+ return (0, import_ts_pattern13.match)(expr).with({
4339
4871
  kind: "literal"
4340
4872
  }, (e) => e.value).with({
4341
4873
  kind: "array"
@@ -4353,7 +4885,11 @@ function evalExpression(data, expr) {
4353
4885
  kind: "this"
4354
4886
  }, () => data ?? null).with({
4355
4887
  kind: "null"
4356
- }, () => null).exhaustive();
4888
+ }, () => null).with({
4889
+ kind: "binding"
4890
+ }, () => {
4891
+ throw new Error("Binding expression is not supported in validation expressions");
4892
+ }).exhaustive();
4357
4893
  }
4358
4894
  __name(evalExpression, "evalExpression");
4359
4895
  function evalField(data, e) {
@@ -4373,7 +4909,7 @@ __name(evalUnary, "evalUnary");
4373
4909
  function evalBinary(data, expr) {
4374
4910
  const left = evalExpression(data, expr.left);
4375
4911
  const right = evalExpression(data, expr.right);
4376
- return (0, import_ts_pattern12.match)(expr.op).with("&&", () => Boolean(left) && Boolean(right)).with("||", () => Boolean(left) || Boolean(right)).with("==", () => left == right).with("!=", () => left != right).with("<", () => left < right).with("<=", () => left <= right).with(">", () => left > right).with(">=", () => left >= right).with("?", () => {
4912
+ return (0, import_ts_pattern13.match)(expr.op).with("&&", () => Boolean(left) && Boolean(right)).with("||", () => Boolean(left) || Boolean(right)).with("==", () => left == right).with("!=", () => left != right).with("<", () => left < right).with("<=", () => left <= right).with(">", () => left > right).with(">=", () => left >= right).with("?", () => {
4377
4913
  if (!Array.isArray(left)) {
4378
4914
  return false;
4379
4915
  }
@@ -4409,49 +4945,49 @@ function evalMember(data, expr) {
4409
4945
  __name(evalMember, "evalMember");
4410
4946
  function evalCall(data, expr) {
4411
4947
  const fieldArg = expr.args?.[0] ? evalExpression(data, expr.args[0]) : void 0;
4412
- return (0, import_ts_pattern12.match)(expr.function).with("length", (f) => {
4948
+ return (0, import_ts_pattern13.match)(expr.function).with("length", (f) => {
4413
4949
  if (fieldArg === void 0 || fieldArg === null) {
4414
4950
  return false;
4415
4951
  }
4416
- (0, import_common_helpers6.invariant)(typeof fieldArg === "string" || Array.isArray(fieldArg), `"${f}" first argument must be a string or a list`);
4952
+ (0, import_common_helpers8.invariant)(typeof fieldArg === "string" || Array.isArray(fieldArg), `"${f}" first argument must be a string or a list`);
4417
4953
  return fieldArg.length;
4418
- }).with(import_ts_pattern12.P.union("startsWith", "endsWith", "contains"), (f) => {
4954
+ }).with(import_ts_pattern13.P.union("startsWith", "endsWith", "contains"), (f) => {
4419
4955
  if (fieldArg === void 0 || fieldArg === null) {
4420
4956
  return false;
4421
4957
  }
4422
- (0, import_common_helpers6.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4423
- (0, import_common_helpers6.invariant)(expr.args?.[1], `"${f}" requires a search argument`);
4958
+ (0, import_common_helpers8.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4959
+ (0, import_common_helpers8.invariant)(expr.args?.[1], `"${f}" requires a search argument`);
4424
4960
  const search2 = getArgValue(expr.args?.[1]);
4425
4961
  const caseInsensitive = getArgValue(expr.args?.[2]) ?? false;
4426
- const matcher = /* @__PURE__ */ __name((x, y) => (0, import_ts_pattern12.match)(f).with("startsWith", () => x.startsWith(y)).with("endsWith", () => x.endsWith(y)).with("contains", () => x.includes(y)).exhaustive(), "matcher");
4962
+ const matcher = /* @__PURE__ */ __name((x, y) => (0, import_ts_pattern13.match)(f).with("startsWith", () => x.startsWith(y)).with("endsWith", () => x.endsWith(y)).with("contains", () => x.includes(y)).exhaustive(), "matcher");
4427
4963
  return caseInsensitive ? matcher(fieldArg.toLowerCase(), search2.toLowerCase()) : matcher(fieldArg, search2);
4428
4964
  }).with("regex", (f) => {
4429
4965
  if (fieldArg === void 0 || fieldArg === null) {
4430
4966
  return false;
4431
4967
  }
4432
- (0, import_common_helpers6.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4968
+ (0, import_common_helpers8.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4433
4969
  const pattern = getArgValue(expr.args?.[1]);
4434
- (0, import_common_helpers6.invariant)(pattern !== void 0, `"${f}" requires a pattern argument`);
4970
+ (0, import_common_helpers8.invariant)(pattern !== void 0, `"${f}" requires a pattern argument`);
4435
4971
  return new RegExp(pattern).test(fieldArg);
4436
- }).with(import_ts_pattern12.P.union("isEmail", "isUrl", "isDateTime"), (f) => {
4972
+ }).with(import_ts_pattern13.P.union("isEmail", "isUrl", "isDateTime"), (f) => {
4437
4973
  if (fieldArg === void 0 || fieldArg === null) {
4438
4974
  return false;
4439
4975
  }
4440
- (0, import_common_helpers6.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4441
- const fn = (0, import_ts_pattern12.match)(f).with("isEmail", () => "email").with("isUrl", () => "url").with("isDateTime", () => "datetime").exhaustive();
4976
+ (0, import_common_helpers8.invariant)(typeof fieldArg === "string", `"${f}" first argument must be a string`);
4977
+ const fn = (0, import_ts_pattern13.match)(f).with("isEmail", () => "email").with("isUrl", () => "url").with("isDateTime", () => "datetime").exhaustive();
4442
4978
  return import_zod2.z.string()[fn]().safeParse(fieldArg).success;
4443
- }).with(import_ts_pattern12.P.union("has", "hasEvery", "hasSome"), (f) => {
4444
- (0, import_common_helpers6.invariant)(expr.args?.[1], `${f} requires a search argument`);
4979
+ }).with(import_ts_pattern13.P.union("has", "hasEvery", "hasSome"), (f) => {
4980
+ (0, import_common_helpers8.invariant)(expr.args?.[1], `${f} requires a search argument`);
4445
4981
  if (fieldArg === void 0 || fieldArg === null) {
4446
4982
  return false;
4447
4983
  }
4448
- (0, import_common_helpers6.invariant)(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
4984
+ (0, import_common_helpers8.invariant)(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
4449
4985
  const search2 = evalExpression(data, expr.args?.[1]);
4450
- const matcher = /* @__PURE__ */ __name((x, y) => (0, import_ts_pattern12.match)(f).with("has", () => x.some((item) => item === y)).with("hasEvery", () => {
4451
- (0, import_common_helpers6.invariant)(Array.isArray(y), "hasEvery second argument must be an array");
4986
+ const matcher = /* @__PURE__ */ __name((x, y) => (0, import_ts_pattern13.match)(f).with("has", () => x.some((item) => item === y)).with("hasEvery", () => {
4987
+ (0, import_common_helpers8.invariant)(Array.isArray(y), "hasEvery second argument must be an array");
4452
4988
  return y.every((v) => x.some((item) => item === v));
4453
4989
  }).with("hasSome", () => {
4454
- (0, import_common_helpers6.invariant)(Array.isArray(y), "hasSome second argument must be an array");
4990
+ (0, import_common_helpers8.invariant)(Array.isArray(y), "hasSome second argument must be an array");
4455
4991
  return y.some((v) => x.some((item) => item === v));
4456
4992
  }).exhaustive(), "matcher");
4457
4993
  return matcher(fieldArg, search2);
@@ -4459,7 +4995,7 @@ function evalCall(data, expr) {
4459
4995
  if (fieldArg === void 0 || fieldArg === null) {
4460
4996
  return false;
4461
4997
  }
4462
- (0, import_common_helpers6.invariant)(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
4998
+ (0, import_common_helpers8.invariant)(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
4463
4999
  return fieldArg.length === 0;
4464
5000
  }).otherwise(() => {
4465
5001
  throw createNotSupportedError(`Unsupported function "${expr.function}"`);
@@ -4468,6 +5004,17 @@ function evalCall(data, expr) {
4468
5004
  __name(evalCall, "evalCall");
4469
5005
 
4470
5006
  // src/client/crud/validator/index.ts
5007
+ function _ts_decorate(decorators, target, key, desc) {
5008
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5009
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5010
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5011
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
5012
+ }
5013
+ __name(_ts_decorate, "_ts_decorate");
5014
+ function _ts_metadata(k, v) {
5015
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5016
+ }
5017
+ __name(_ts_metadata, "_ts_metadata");
4471
5018
  var InputValidator = class {
4472
5019
  static {
4473
5020
  __name(this, "InputValidator");
@@ -4486,9 +5033,53 @@ var InputValidator = class {
4486
5033
  get extraValidationsEnabled() {
4487
5034
  return this.client.$options.validateInput !== false;
4488
5035
  }
5036
+ // #region Entry points
5037
+ validateFindArgs(model, args, operation) {
5038
+ return this.validate(model, operation, (model2) => this.makeFindSchema(model2, operation), args);
5039
+ }
5040
+ validateExistsArgs(model, args) {
5041
+ return this.validate(model, "exists", (model2) => this.makeExistsSchema(model2), args);
5042
+ }
5043
+ validateCreateArgs(model, args) {
5044
+ return this.validate(model, "create", (model2) => this.makeCreateSchema(model2), args);
5045
+ }
5046
+ validateCreateManyArgs(model, args) {
5047
+ return this.validate(model, "createMany", (model2) => this.makeCreateManySchema(model2), args);
5048
+ }
5049
+ validateCreateManyAndReturnArgs(model, args) {
5050
+ return this.validate(model, "createManyAndReturn", (model2) => this.makeCreateManyAndReturnSchema(model2), args);
5051
+ }
5052
+ validateUpdateArgs(model, args) {
5053
+ return this.validate(model, "update", (model2) => this.makeUpdateSchema(model2), args);
5054
+ }
5055
+ validateUpdateManyArgs(model, args) {
5056
+ return this.validate(model, "updateMany", (model2) => this.makeUpdateManySchema(model2), args);
5057
+ }
5058
+ validateUpdateManyAndReturnArgs(model, args) {
5059
+ return this.validate(model, "updateManyAndReturn", (model2) => this.makeUpdateManyAndReturnSchema(model2), args);
5060
+ }
5061
+ validateUpsertArgs(model, args) {
5062
+ return this.validate(model, "upsert", (model2) => this.makeUpsertSchema(model2), args);
5063
+ }
5064
+ validateDeleteArgs(model, args) {
5065
+ return this.validate(model, "delete", (model2) => this.makeDeleteSchema(model2), args);
5066
+ }
5067
+ validateDeleteManyArgs(model, args) {
5068
+ return this.validate(model, "deleteMany", (model2) => this.makeDeleteManySchema(model2), args);
5069
+ }
5070
+ validateCountArgs(model, args) {
5071
+ return this.validate(model, "count", (model2) => this.makeCountSchema(model2), args);
5072
+ }
5073
+ validateAggregateArgs(model, args) {
5074
+ return this.validate(model, "aggregate", (model2) => this.makeAggregateSchema(model2), args);
5075
+ }
5076
+ validateGroupByArgs(model, args) {
5077
+ return this.validate(model, "groupBy", (model2) => this.makeGroupBySchema(model2), args);
5078
+ }
5079
+ // TODO: turn it into a Zod schema and cache
4489
5080
  validateProcedureInput(proc, input) {
4490
5081
  const procDef = (this.schema.procedures ?? {})[proc];
4491
- (0, import_common_helpers7.invariant)(procDef, `Procedure "${proc}" not found in schema`);
5082
+ (0, import_common_helpers9.invariant)(procDef, `Procedure "${proc}" not found in schema`);
4492
5083
  const params = Object.values(procDef.params ?? {});
4493
5084
  if (typeof input === "undefined") {
4494
5085
  if (params.length === 0) {
@@ -4499,7 +5090,7 @@ var InputValidator = class {
4499
5090
  }
4500
5091
  throw createInvalidInputError("Missing procedure arguments", `$procs.${proc}`);
4501
5092
  }
4502
- if (typeof input !== "object") {
5093
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
4503
5094
  throw createInvalidInputError("Procedure input must be an object", `$procs.${proc}`);
4504
5095
  }
4505
5096
  const envelope = input;
@@ -4548,88 +5139,10 @@ var InputValidator = class {
4548
5139
  }
4549
5140
  return input;
4550
5141
  }
4551
- makeProcedureParamSchema(param) {
4552
- let schema;
4553
- if (isTypeDef(this.schema, param.type)) {
4554
- schema = this.makeTypeDefSchema(param.type);
4555
- } else if (isEnum(this.schema, param.type)) {
4556
- schema = this.makeEnumSchema(param.type);
4557
- } else if (param.type in (this.schema.models ?? {})) {
4558
- schema = import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown());
4559
- } else {
4560
- schema = this.makeScalarSchema(param.type);
4561
- if (schema instanceof import_zod3.z.ZodUnknown) {
4562
- throw createInternalError(`Unsupported procedure parameter type: ${param.type}`);
4563
- }
4564
- }
4565
- if (param.array) {
4566
- schema = schema.array();
4567
- }
4568
- if (param.optional) {
4569
- schema = schema.optional();
4570
- }
4571
- return schema;
4572
- }
4573
- validateFindArgs(model, args, operation) {
4574
- return this.validate(model, operation, (model2) => this.makeFindSchema(model2, operation), args);
4575
- }
4576
- validateExistsArgs(model, args) {
4577
- return this.validate(model, "exists", (model2) => this.makeExistsSchema(model2), args);
4578
- }
4579
- validateCreateArgs(model, args) {
4580
- return this.validate(model, "create", (model2) => this.makeCreateSchema(model2), args);
4581
- }
4582
- validateCreateManyArgs(model, args) {
4583
- return this.validate(model, "createMany", (model2) => this.makeCreateManySchema(model2), args);
4584
- }
4585
- validateCreateManyAndReturnArgs(model, args) {
4586
- return this.validate(model, "createManyAndReturn", (model2) => this.makeCreateManyAndReturnSchema(model2), args);
4587
- }
4588
- validateUpdateArgs(model, args) {
4589
- return this.validate(model, "update", (model2) => this.makeUpdateSchema(model2), args);
4590
- }
4591
- validateUpdateManyArgs(model, args) {
4592
- return this.validate(model, "updateMany", (model2) => this.makeUpdateManySchema(model2), args);
4593
- }
4594
- validateUpdateManyAndReturnArgs(model, args) {
4595
- return this.validate(model, "updateManyAndReturn", (model2) => this.makeUpdateManyAndReturnSchema(model2), args);
4596
- }
4597
- validateUpsertArgs(model, args) {
4598
- return this.validate(model, "upsert", (model2) => this.makeUpsertSchema(model2), args);
4599
- }
4600
- validateDeleteArgs(model, args) {
4601
- return this.validate(model, "delete", (model2) => this.makeDeleteSchema(model2), args);
4602
- }
4603
- validateDeleteManyArgs(model, args) {
4604
- return this.validate(model, "deleteMany", (model2) => this.makeDeleteManySchema(model2), args);
4605
- }
4606
- validateCountArgs(model, args) {
4607
- return this.validate(model, "count", (model2) => this.makeCountSchema(model2), args);
4608
- }
4609
- validateAggregateArgs(model, args) {
4610
- return this.validate(model, "aggregate", (model2) => this.makeAggregateSchema(model2), args);
4611
- }
4612
- validateGroupByArgs(model, args) {
4613
- return this.validate(model, "groupBy", (model2) => this.makeGroupBySchema(model2), args);
4614
- }
4615
- getSchemaCache(cacheKey) {
4616
- return this.schemaCache.get(cacheKey);
4617
- }
4618
- setSchemaCache(cacheKey, schema) {
4619
- return this.schemaCache.set(cacheKey, schema);
4620
- }
5142
+ // #endregion
5143
+ // #region Validation helpers
4621
5144
  validate(model, operation, getSchema, args) {
4622
- const cacheKey = (0, import_json_stable_stringify.default)({
4623
- type: "model",
4624
- model,
4625
- operation,
4626
- extraValidationsEnabled: this.extraValidationsEnabled
4627
- });
4628
- let schema = this.getSchemaCache(cacheKey);
4629
- if (!schema) {
4630
- schema = getSchema(model);
4631
- this.setSchemaCache(cacheKey, schema);
4632
- }
5145
+ const schema = getSchema(model);
4633
5146
  const { error, data } = schema.safeParse(args);
4634
5147
  if (error) {
4635
5148
  throw createInvalidInputError(`Invalid ${operation} args for model "${model}": ${formatError(error)}`, model, {
@@ -4661,8 +5174,8 @@ var InputValidator = class {
4661
5174
  const createSchema = "$create" in plugin.queryArgs && plugin.queryArgs["$create"] ? plugin.queryArgs["$create"] : void 0;
4662
5175
  const updateSchema = "$update" in plugin.queryArgs && plugin.queryArgs["$update"] ? plugin.queryArgs["$update"] : void 0;
4663
5176
  if (createSchema && updateSchema) {
4664
- (0, import_common_helpers7.invariant)(createSchema instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
4665
- (0, import_common_helpers7.invariant)(updateSchema instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
5177
+ (0, import_common_helpers9.invariant)(createSchema instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
5178
+ (0, import_common_helpers9.invariant)(updateSchema instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
4666
5179
  result = createSchema.extend(updateSchema.shape);
4667
5180
  } else if (createSchema) {
4668
5181
  result = createSchema;
@@ -4683,9 +5196,10 @@ var InputValidator = class {
4683
5196
  } else if ("$all" in plugin.queryArgs && plugin.queryArgs["$all"]) {
4684
5197
  result = plugin.queryArgs["$all"];
4685
5198
  }
4686
- (0, import_common_helpers7.invariant)(result === void 0 || result instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
5199
+ (0, import_common_helpers9.invariant)(result === void 0 || result instanceof import_zod3.z.ZodObject, "Plugin extended query args schema must be a Zod object");
4687
5200
  return result;
4688
5201
  }
5202
+ // #endregion
4689
5203
  // #region Find
4690
5204
  makeFindSchema(model, operation) {
4691
5205
  const fields = {};
@@ -4732,13 +5246,13 @@ var InputValidator = class {
4732
5246
  } else if (this.schema.enums && type in this.schema.enums) {
4733
5247
  return this.makeEnumSchema(type);
4734
5248
  } else {
4735
- return (0, import_ts_pattern13.match)(type).with("String", () => this.extraValidationsEnabled ? addStringValidation(import_zod3.z.string(), attributes) : import_zod3.z.string()).with("Int", () => this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number().int(), attributes) : import_zod3.z.number().int()).with("Float", () => this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number(), attributes) : import_zod3.z.number()).with("Boolean", () => import_zod3.z.boolean()).with("BigInt", () => import_zod3.z.union([
5249
+ return (0, import_ts_pattern14.match)(type).with("String", () => this.extraValidationsEnabled ? addStringValidation(import_zod3.z.string(), attributes) : import_zod3.z.string()).with("Int", () => this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number().int(), attributes) : import_zod3.z.number().int()).with("Float", () => this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number(), attributes) : import_zod3.z.number()).with("Boolean", () => import_zod3.z.boolean()).with("BigInt", () => import_zod3.z.union([
4736
5250
  this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number().int(), attributes) : import_zod3.z.number().int(),
4737
5251
  this.extraValidationsEnabled ? addBigIntValidation(import_zod3.z.bigint(), attributes) : import_zod3.z.bigint()
4738
5252
  ])).with("Decimal", () => {
4739
5253
  return import_zod3.z.union([
4740
5254
  this.extraValidationsEnabled ? addNumberValidation(import_zod3.z.number(), attributes) : import_zod3.z.number(),
4741
- addDecimalValidation(import_zod3.z.instanceof(import_decimal4.default), attributes, this.extraValidationsEnabled),
5255
+ addDecimalValidation(import_zod3.z.instanceof(import_decimal5.default), attributes, this.extraValidationsEnabled),
4742
5256
  addDecimalValidation(import_zod3.z.string(), attributes, this.extraValidationsEnabled)
4743
5257
  ]);
4744
5258
  }).with("DateTime", () => import_zod3.z.union([
@@ -4748,33 +5262,14 @@ var InputValidator = class {
4748
5262
  }
4749
5263
  }
4750
5264
  makeEnumSchema(type) {
4751
- const key = (0, import_json_stable_stringify.default)({
4752
- type: "enum",
4753
- name: type
4754
- });
4755
- let schema = this.getSchemaCache(key);
4756
- if (schema) {
4757
- return schema;
4758
- }
4759
5265
  const enumDef = getEnum(this.schema, type);
4760
- (0, import_common_helpers7.invariant)(enumDef, `Enum "${type}" not found in schema`);
4761
- schema = import_zod3.z.enum(Object.keys(enumDef.values));
4762
- this.setSchemaCache(key, schema);
4763
- return schema;
5266
+ (0, import_common_helpers9.invariant)(enumDef, `Enum "${type}" not found in schema`);
5267
+ return import_zod3.z.enum(Object.keys(enumDef.values));
4764
5268
  }
4765
5269
  makeTypeDefSchema(type) {
4766
- const key = (0, import_json_stable_stringify.default)({
4767
- type: "typedef",
4768
- name: type,
4769
- extraValidationsEnabled: this.extraValidationsEnabled
4770
- });
4771
- let schema = this.getSchemaCache(key);
4772
- if (schema) {
4773
- return schema;
4774
- }
4775
5270
  const typeDef = getTypeDef(this.schema, type);
4776
- (0, import_common_helpers7.invariant)(typeDef, `Type definition "${type}" not found in schema`);
4777
- schema = import_zod3.z.looseObject(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
5271
+ (0, import_common_helpers9.invariant)(typeDef, `Type definition "${type}" not found in schema`);
5272
+ const schema = import_zod3.z.looseObject(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
4778
5273
  let fieldSchema = this.makeScalarSchema(def.type);
4779
5274
  if (def.array) {
4780
5275
  fieldSchema = fieldSchema.array();
@@ -4793,7 +5288,6 @@ var InputValidator = class {
4793
5288
  parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
4794
5289
  }
4795
5290
  });
4796
- this.setSchemaCache(key, finalSchema);
4797
5291
  return finalSchema;
4798
5292
  }
4799
5293
  makeWhereSchema(model, unique, withoutRelationFields = false, withAggregations = false) {
@@ -4830,7 +5324,7 @@ var InputValidator = class {
4830
5324
  const enumDef = getEnum(this.schema, fieldDef.type);
4831
5325
  if (enumDef) {
4832
5326
  if (Object.keys(enumDef.values).length > 0) {
4833
- fieldSchema = this.makeEnumFilterSchema(enumDef, !!fieldDef.optional, withAggregations, !!fieldDef.array);
5327
+ fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, !!fieldDef.array);
4834
5328
  }
4835
5329
  } else if (fieldDef.array) {
4836
5330
  fieldSchema = this.makeArrayFilterSchema(fieldDef.type);
@@ -4849,12 +5343,12 @@ var InputValidator = class {
4849
5343
  for (const uniqueField of uniqueFields) {
4850
5344
  if ("defs" in uniqueField) {
4851
5345
  fields[uniqueField.name] = import_zod3.z.object(Object.fromEntries(Object.entries(uniqueField.defs).map(([key, def]) => {
4852
- (0, import_common_helpers7.invariant)(!def.relation, "unique field cannot be a relation");
5346
+ (0, import_common_helpers9.invariant)(!def.relation, "unique field cannot be a relation");
4853
5347
  let fieldSchema;
4854
5348
  const enumDef = getEnum(this.schema, def.type);
4855
5349
  if (enumDef) {
4856
5350
  if (Object.keys(enumDef.values).length > 0) {
4857
- fieldSchema = this.makeEnumFilterSchema(enumDef, !!def.optional, false, false);
5351
+ fieldSchema = this.makeEnumFilterSchema(def.type, !!def.optional, false, false);
4858
5352
  } else {
4859
5353
  fieldSchema = import_zod3.z.never();
4860
5354
  }
@@ -4896,7 +5390,7 @@ var InputValidator = class {
4896
5390
  }
4897
5391
  makeTypedJsonFilterSchema(type, optional, array) {
4898
5392
  const typeDef = getTypeDef(this.schema, type);
4899
- (0, import_common_helpers7.invariant)(typeDef, `Type definition "${type}" not found in schema`);
5393
+ (0, import_common_helpers9.invariant)(typeDef, `Type definition "${type}" not found in schema`);
4900
5394
  const candidates = [];
4901
5395
  if (!array) {
4902
5396
  const fieldSchemas = {};
@@ -4906,7 +5400,7 @@ var InputValidator = class {
4906
5400
  } else {
4907
5401
  const enumDef = getEnum(this.schema, fieldDef.type);
4908
5402
  if (enumDef) {
4909
- fieldSchemas[fieldName] = this.makeEnumFilterSchema(enumDef, !!fieldDef.optional, false, !!fieldDef.array).optional();
5403
+ fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, false, !!fieldDef.array).optional();
4910
5404
  } else if (fieldDef.array) {
4911
5405
  fieldSchemas[fieldName] = this.makeArrayFilterSchema(fieldDef.type).optional();
4912
5406
  } else {
@@ -4938,12 +5432,14 @@ var InputValidator = class {
4938
5432
  isTypeDefType(type) {
4939
5433
  return this.schema.typeDefs && type in this.schema.typeDefs;
4940
5434
  }
4941
- makeEnumFilterSchema(enumDef, optional, withAggregations, array) {
5435
+ makeEnumFilterSchema(enumName, optional, withAggregations, array) {
5436
+ const enumDef = getEnum(this.schema, enumName);
5437
+ (0, import_common_helpers9.invariant)(enumDef, `Enum "${enumName}" not found in schema`);
4942
5438
  const baseSchema = import_zod3.z.enum(Object.keys(enumDef.values));
4943
5439
  if (array) {
4944
5440
  return this.internalMakeArrayFilterSchema(baseSchema);
4945
5441
  }
4946
- const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => import_zod3.z.lazy(() => this.makeEnumFilterSchema(enumDef, optional, withAggregations, array)), [
5442
+ const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => import_zod3.z.lazy(() => this.makeEnumFilterSchema(enumName, optional, withAggregations, array)), [
4947
5443
  "equals",
4948
5444
  "in",
4949
5445
  "notIn",
@@ -4971,7 +5467,7 @@ var InputValidator = class {
4971
5467
  });
4972
5468
  }
4973
5469
  makePrimitiveFilterSchema(type, optional, withAggregations) {
4974
- return (0, import_ts_pattern13.match)(type).with("String", () => this.makeStringFilterSchema(optional, withAggregations)).with(import_ts_pattern13.P.union("Int", "Float", "Decimal", "BigInt"), (type2) => this.makeNumberFilterSchema(this.makeScalarSchema(type2), optional, withAggregations)).with("Boolean", () => this.makeBooleanFilterSchema(optional, withAggregations)).with("DateTime", () => this.makeDateTimeFilterSchema(optional, withAggregations)).with("Bytes", () => this.makeBytesFilterSchema(optional, withAggregations)).with("Json", () => this.makeJsonFilterSchema(optional)).with("Unsupported", () => import_zod3.z.never()).exhaustive();
5470
+ return (0, import_ts_pattern14.match)(type).with("String", () => this.makeStringFilterSchema(optional, withAggregations)).with(import_ts_pattern14.P.union("Int", "Float", "Decimal", "BigInt"), (type2) => this.makeNumberFilterSchema(this.makeScalarSchema(type2), optional, withAggregations)).with("Boolean", () => this.makeBooleanFilterSchema(optional, withAggregations)).with("DateTime", () => this.makeDateTimeFilterSchema(optional, withAggregations)).with("Bytes", () => this.makeBytesFilterSchema(optional, withAggregations)).with("Json", () => this.makeJsonFilterSchema(optional)).with("Unsupported", () => import_zod3.z.never()).exhaustive();
4975
5471
  }
4976
5472
  makeJsonValueSchema(nullable, forFilter) {
4977
5473
  const options = [
@@ -5142,18 +5638,19 @@ var InputValidator = class {
5142
5638
  for (const field of Object.keys(modelDef.fields)) {
5143
5639
  const fieldDef = requireField(this.schema, model, field);
5144
5640
  if (fieldDef.relation) {
5145
- fields[field] = this.makeRelationSelectIncludeSchema(fieldDef).optional();
5641
+ fields[field] = this.makeRelationSelectIncludeSchema(model, field).optional();
5146
5642
  } else {
5147
5643
  fields[field] = import_zod3.z.boolean().optional();
5148
5644
  }
5149
5645
  }
5150
- const _countSchema = this.makeCountSelectionSchema(modelDef);
5151
- if (_countSchema) {
5646
+ const _countSchema = this.makeCountSelectionSchema(model);
5647
+ if (!(_countSchema instanceof import_zod3.z.ZodNever)) {
5152
5648
  fields["_count"] = _countSchema;
5153
5649
  }
5154
5650
  return import_zod3.z.strictObject(fields);
5155
5651
  }
5156
- makeCountSelectionSchema(modelDef) {
5652
+ makeCountSelectionSchema(model) {
5653
+ const modelDef = requireModel(this.schema, model);
5157
5654
  const toManyRelations = Object.values(modelDef.fields).filter((def) => def.relation && def.array);
5158
5655
  if (toManyRelations.length > 0) {
5159
5656
  return import_zod3.z.union([
@@ -5171,10 +5668,11 @@ var InputValidator = class {
5171
5668
  })
5172
5669
  ]).optional();
5173
5670
  } else {
5174
- return void 0;
5671
+ return import_zod3.z.never();
5175
5672
  }
5176
5673
  }
5177
- makeRelationSelectIncludeSchema(fieldDef) {
5674
+ makeRelationSelectIncludeSchema(model, field) {
5675
+ const fieldDef = requireField(this.schema, model, field);
5178
5676
  let objSchema = import_zod3.z.strictObject({
5179
5677
  ...fieldDef.array || fieldDef.optional ? {
5180
5678
  // to-many relations and optional to-one relations are filterable
@@ -5220,11 +5718,11 @@ var InputValidator = class {
5220
5718
  for (const field of Object.keys(modelDef.fields)) {
5221
5719
  const fieldDef = requireField(this.schema, model, field);
5222
5720
  if (fieldDef.relation) {
5223
- fields[field] = this.makeRelationSelectIncludeSchema(fieldDef).optional();
5721
+ fields[field] = this.makeRelationSelectIncludeSchema(model, field).optional();
5224
5722
  }
5225
5723
  }
5226
- const _countSchema = this.makeCountSelectionSchema(modelDef);
5227
- if (_countSchema) {
5724
+ const _countSchema = this.makeCountSelectionSchema(model);
5725
+ if (!(_countSchema instanceof import_zod3.z.ZodNever)) {
5228
5726
  fields["_count"] = _countSchema;
5229
5727
  }
5230
5728
  return import_zod3.z.strictObject(fields);
@@ -5345,7 +5843,7 @@ var InputValidator = class {
5345
5843
  excludeFields.push(...oppositeFieldDef.relation.fields);
5346
5844
  }
5347
5845
  }
5348
- let fieldSchema = import_zod3.z.lazy(() => this.makeRelationManipulationSchema(fieldDef, excludeFields, "create"));
5846
+ let fieldSchema = import_zod3.z.lazy(() => this.makeRelationManipulationSchema(model, field, excludeFields, "create"));
5349
5847
  if (fieldDef.optional || fieldDef.array) {
5350
5848
  fieldSchema = fieldSchema.optional();
5351
5849
  } else {
@@ -5421,7 +5919,8 @@ var InputValidator = class {
5421
5919
  const discriminatorField = getDiscriminatorField(this.schema, fieldDef.originModel);
5422
5920
  return discriminatorField === fieldDef.name;
5423
5921
  }
5424
- makeRelationManipulationSchema(fieldDef, withoutFields, mode) {
5922
+ makeRelationManipulationSchema(model, field, withoutFields, mode) {
5923
+ const fieldDef = requireField(this.schema, model, field);
5425
5924
  const fieldType = fieldDef.type;
5426
5925
  const array = !!fieldDef.array;
5427
5926
  const fields = {
@@ -5571,7 +6070,7 @@ var InputValidator = class {
5571
6070
  excludeFields.push(...oppositeFieldDef.relation.fields);
5572
6071
  }
5573
6072
  }
5574
- let fieldSchema = import_zod3.z.lazy(() => this.makeRelationManipulationSchema(fieldDef, excludeFields, "update")).optional();
6073
+ let fieldSchema = import_zod3.z.lazy(() => this.makeRelationManipulationSchema(model, field, excludeFields, "update")).optional();
5575
6074
  if (fieldDef.optional && !fieldDef.array) {
5576
6075
  fieldSchema = fieldSchema.nullable();
5577
6076
  }
@@ -5771,7 +6270,7 @@ var InputValidator = class {
5771
6270
  continue;
5772
6271
  }
5773
6272
  if (LOGICAL_COMBINATORS.includes(key)) {
5774
- if ((0, import_common_helpers7.enumerate)(value).every((v) => this.onlyAggregationFields(v))) {
6273
+ if ((0, import_common_helpers9.enumerate)(value).every((v) => this.onlyAggregationFields(v))) {
5775
6274
  continue;
5776
6275
  }
5777
6276
  }
@@ -5783,6 +6282,47 @@ var InputValidator = class {
5783
6282
  return this.makeWhereSchema(model, false, true, true);
5784
6283
  }
5785
6284
  // #endregion
6285
+ // #region Procedures
6286
+ makeProcedureParamSchema(param) {
6287
+ let schema;
6288
+ if (isTypeDef(this.schema, param.type)) {
6289
+ schema = this.makeTypeDefSchema(param.type);
6290
+ } else if (isEnum(this.schema, param.type)) {
6291
+ schema = this.makeEnumSchema(param.type);
6292
+ } else if (param.type in (this.schema.models ?? {})) {
6293
+ schema = import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown());
6294
+ } else {
6295
+ schema = this.makeScalarSchema(param.type);
6296
+ if (schema instanceof import_zod3.z.ZodUnknown) {
6297
+ throw createInternalError(`Unsupported procedure parameter type: ${param.type}`);
6298
+ }
6299
+ }
6300
+ if (param.array) {
6301
+ schema = schema.array();
6302
+ }
6303
+ if (param.optional) {
6304
+ schema = schema.optional();
6305
+ }
6306
+ return schema;
6307
+ }
6308
+ // #endregion
6309
+ // #region Cache Management
6310
+ getCache(cacheKey) {
6311
+ return this.schemaCache.get(cacheKey);
6312
+ }
6313
+ setCache(cacheKey, schema) {
6314
+ return this.schemaCache.set(cacheKey, schema);
6315
+ }
6316
+ // @ts-ignore
6317
+ printCacheStats(detailed = false) {
6318
+ console.log("Schema cache size:", this.schemaCache.size);
6319
+ if (detailed) {
6320
+ for (const key of this.schemaCache.keys()) {
6321
+ console.log(` ${key}`);
6322
+ }
6323
+ }
6324
+ }
6325
+ // #endregion
5786
6326
  // #region Helpers
5787
6327
  makeSkipSchema() {
5788
6328
  return import_zod3.z.number().int().nonnegative();
@@ -5812,6 +6352,411 @@ var InputValidator = class {
5812
6352
  return this.schema.provider.type === "postgresql";
5813
6353
  }
5814
6354
  };
6355
+ _ts_decorate([
6356
+ cache(),
6357
+ _ts_metadata("design:type", Function),
6358
+ _ts_metadata("design:paramtypes", [
6359
+ String,
6360
+ typeof CoreCrudOperations === "undefined" ? Object : CoreCrudOperations
6361
+ ]),
6362
+ _ts_metadata("design:returntype", void 0)
6363
+ ], InputValidator.prototype, "makeFindSchema", null);
6364
+ _ts_decorate([
6365
+ cache(),
6366
+ _ts_metadata("design:type", Function),
6367
+ _ts_metadata("design:paramtypes", [
6368
+ String
6369
+ ]),
6370
+ _ts_metadata("design:returntype", void 0)
6371
+ ], InputValidator.prototype, "makeExistsSchema", null);
6372
+ _ts_decorate([
6373
+ cache(),
6374
+ _ts_metadata("design:type", Function),
6375
+ _ts_metadata("design:paramtypes", [
6376
+ String
6377
+ ]),
6378
+ _ts_metadata("design:returntype", void 0)
6379
+ ], InputValidator.prototype, "makeEnumSchema", null);
6380
+ _ts_decorate([
6381
+ cache(),
6382
+ _ts_metadata("design:type", Function),
6383
+ _ts_metadata("design:paramtypes", [
6384
+ String
6385
+ ]),
6386
+ _ts_metadata("design:returntype", typeof import_zod3.z === "undefined" || typeof import_zod3.z.ZodType === "undefined" ? Object : import_zod3.z.ZodType)
6387
+ ], InputValidator.prototype, "makeTypeDefSchema", null);
6388
+ _ts_decorate([
6389
+ cache(),
6390
+ _ts_metadata("design:type", Function),
6391
+ _ts_metadata("design:paramtypes", [
6392
+ String,
6393
+ Boolean,
6394
+ void 0,
6395
+ void 0
6396
+ ]),
6397
+ _ts_metadata("design:returntype", typeof import_zod3.ZodType === "undefined" ? Object : import_zod3.ZodType)
6398
+ ], InputValidator.prototype, "makeWhereSchema", null);
6399
+ _ts_decorate([
6400
+ cache(),
6401
+ _ts_metadata("design:type", Function),
6402
+ _ts_metadata("design:paramtypes", [
6403
+ String,
6404
+ Boolean,
6405
+ Boolean
6406
+ ]),
6407
+ _ts_metadata("design:returntype", void 0)
6408
+ ], InputValidator.prototype, "makeTypedJsonFilterSchema", null);
6409
+ _ts_decorate([
6410
+ cache(),
6411
+ _ts_metadata("design:type", Function),
6412
+ _ts_metadata("design:paramtypes", [
6413
+ String,
6414
+ Boolean,
6415
+ Boolean,
6416
+ Boolean
6417
+ ]),
6418
+ _ts_metadata("design:returntype", void 0)
6419
+ ], InputValidator.prototype, "makeEnumFilterSchema", null);
6420
+ _ts_decorate([
6421
+ cache(),
6422
+ _ts_metadata("design:type", Function),
6423
+ _ts_metadata("design:paramtypes", [
6424
+ typeof BuiltinType === "undefined" ? Object : BuiltinType
6425
+ ]),
6426
+ _ts_metadata("design:returntype", void 0)
6427
+ ], InputValidator.prototype, "makeArrayFilterSchema", null);
6428
+ _ts_decorate([
6429
+ cache(),
6430
+ _ts_metadata("design:type", Function),
6431
+ _ts_metadata("design:paramtypes", [
6432
+ typeof BuiltinType === "undefined" ? Object : BuiltinType,
6433
+ Boolean,
6434
+ Boolean
6435
+ ]),
6436
+ _ts_metadata("design:returntype", void 0)
6437
+ ], InputValidator.prototype, "makePrimitiveFilterSchema", null);
6438
+ _ts_decorate([
6439
+ cache(),
6440
+ _ts_metadata("design:type", Function),
6441
+ _ts_metadata("design:paramtypes", [
6442
+ Boolean
6443
+ ]),
6444
+ _ts_metadata("design:returntype", void 0)
6445
+ ], InputValidator.prototype, "makeJsonFilterSchema", null);
6446
+ _ts_decorate([
6447
+ cache(),
6448
+ _ts_metadata("design:type", Function),
6449
+ _ts_metadata("design:paramtypes", [
6450
+ Boolean,
6451
+ Boolean
6452
+ ]),
6453
+ _ts_metadata("design:returntype", typeof import_zod3.ZodType === "undefined" ? Object : import_zod3.ZodType)
6454
+ ], InputValidator.prototype, "makeDateTimeFilterSchema", null);
6455
+ _ts_decorate([
6456
+ cache(),
6457
+ _ts_metadata("design:type", Function),
6458
+ _ts_metadata("design:paramtypes", [
6459
+ Boolean,
6460
+ Boolean
6461
+ ]),
6462
+ _ts_metadata("design:returntype", typeof import_zod3.ZodType === "undefined" ? Object : import_zod3.ZodType)
6463
+ ], InputValidator.prototype, "makeBooleanFilterSchema", null);
6464
+ _ts_decorate([
6465
+ cache(),
6466
+ _ts_metadata("design:type", Function),
6467
+ _ts_metadata("design:paramtypes", [
6468
+ Boolean,
6469
+ Boolean
6470
+ ]),
6471
+ _ts_metadata("design:returntype", typeof import_zod3.ZodType === "undefined" ? Object : import_zod3.ZodType)
6472
+ ], InputValidator.prototype, "makeBytesFilterSchema", null);
6473
+ _ts_decorate([
6474
+ cache(),
6475
+ _ts_metadata("design:type", Function),
6476
+ _ts_metadata("design:paramtypes", [
6477
+ String
6478
+ ]),
6479
+ _ts_metadata("design:returntype", void 0)
6480
+ ], InputValidator.prototype, "makeSelectSchema", null);
6481
+ _ts_decorate([
6482
+ cache(),
6483
+ _ts_metadata("design:type", Function),
6484
+ _ts_metadata("design:paramtypes", [
6485
+ String
6486
+ ]),
6487
+ _ts_metadata("design:returntype", void 0)
6488
+ ], InputValidator.prototype, "makeCountSelectionSchema", null);
6489
+ _ts_decorate([
6490
+ cache(),
6491
+ _ts_metadata("design:type", Function),
6492
+ _ts_metadata("design:paramtypes", [
6493
+ String,
6494
+ String
6495
+ ]),
6496
+ _ts_metadata("design:returntype", void 0)
6497
+ ], InputValidator.prototype, "makeRelationSelectIncludeSchema", null);
6498
+ _ts_decorate([
6499
+ cache(),
6500
+ _ts_metadata("design:type", Function),
6501
+ _ts_metadata("design:paramtypes", [
6502
+ String
6503
+ ]),
6504
+ _ts_metadata("design:returntype", void 0)
6505
+ ], InputValidator.prototype, "makeOmitSchema", null);
6506
+ _ts_decorate([
6507
+ cache(),
6508
+ _ts_metadata("design:type", Function),
6509
+ _ts_metadata("design:paramtypes", [
6510
+ String
6511
+ ]),
6512
+ _ts_metadata("design:returntype", void 0)
6513
+ ], InputValidator.prototype, "makeIncludeSchema", null);
6514
+ _ts_decorate([
6515
+ cache(),
6516
+ _ts_metadata("design:type", Function),
6517
+ _ts_metadata("design:paramtypes", [
6518
+ String,
6519
+ Boolean,
6520
+ Boolean
6521
+ ]),
6522
+ _ts_metadata("design:returntype", void 0)
6523
+ ], InputValidator.prototype, "makeOrderBySchema", null);
6524
+ _ts_decorate([
6525
+ cache(),
6526
+ _ts_metadata("design:type", Function),
6527
+ _ts_metadata("design:paramtypes", [
6528
+ String
6529
+ ]),
6530
+ _ts_metadata("design:returntype", void 0)
6531
+ ], InputValidator.prototype, "makeDistinctSchema", null);
6532
+ _ts_decorate([
6533
+ cache(),
6534
+ _ts_metadata("design:type", Function),
6535
+ _ts_metadata("design:paramtypes", [
6536
+ String
6537
+ ]),
6538
+ _ts_metadata("design:returntype", void 0)
6539
+ ], InputValidator.prototype, "makeCreateSchema", null);
6540
+ _ts_decorate([
6541
+ cache(),
6542
+ _ts_metadata("design:type", Function),
6543
+ _ts_metadata("design:paramtypes", [
6544
+ String
6545
+ ]),
6546
+ _ts_metadata("design:returntype", void 0)
6547
+ ], InputValidator.prototype, "makeCreateManySchema", null);
6548
+ _ts_decorate([
6549
+ cache(),
6550
+ _ts_metadata("design:type", Function),
6551
+ _ts_metadata("design:paramtypes", [
6552
+ String
6553
+ ]),
6554
+ _ts_metadata("design:returntype", void 0)
6555
+ ], InputValidator.prototype, "makeCreateManyAndReturnSchema", null);
6556
+ _ts_decorate([
6557
+ cache(),
6558
+ _ts_metadata("design:type", Function),
6559
+ _ts_metadata("design:paramtypes", [
6560
+ String,
6561
+ Boolean,
6562
+ Array,
6563
+ void 0
6564
+ ]),
6565
+ _ts_metadata("design:returntype", void 0)
6566
+ ], InputValidator.prototype, "makeCreateDataSchema", null);
6567
+ _ts_decorate([
6568
+ cache(),
6569
+ _ts_metadata("design:type", Function),
6570
+ _ts_metadata("design:paramtypes", [
6571
+ String,
6572
+ String,
6573
+ Array,
6574
+ String
6575
+ ]),
6576
+ _ts_metadata("design:returntype", void 0)
6577
+ ], InputValidator.prototype, "makeRelationManipulationSchema", null);
6578
+ _ts_decorate([
6579
+ cache(),
6580
+ _ts_metadata("design:type", Function),
6581
+ _ts_metadata("design:paramtypes", [
6582
+ String,
6583
+ Boolean
6584
+ ]),
6585
+ _ts_metadata("design:returntype", void 0)
6586
+ ], InputValidator.prototype, "makeSetDataSchema", null);
6587
+ _ts_decorate([
6588
+ cache(),
6589
+ _ts_metadata("design:type", Function),
6590
+ _ts_metadata("design:paramtypes", [
6591
+ String,
6592
+ Boolean
6593
+ ]),
6594
+ _ts_metadata("design:returntype", void 0)
6595
+ ], InputValidator.prototype, "makeConnectDataSchema", null);
6596
+ _ts_decorate([
6597
+ cache(),
6598
+ _ts_metadata("design:type", Function),
6599
+ _ts_metadata("design:paramtypes", [
6600
+ String,
6601
+ Boolean
6602
+ ]),
6603
+ _ts_metadata("design:returntype", void 0)
6604
+ ], InputValidator.prototype, "makeDisconnectDataSchema", null);
6605
+ _ts_decorate([
6606
+ cache(),
6607
+ _ts_metadata("design:type", Function),
6608
+ _ts_metadata("design:paramtypes", [
6609
+ String,
6610
+ Boolean,
6611
+ Boolean
6612
+ ]),
6613
+ _ts_metadata("design:returntype", void 0)
6614
+ ], InputValidator.prototype, "makeDeleteRelationDataSchema", null);
6615
+ _ts_decorate([
6616
+ cache(),
6617
+ _ts_metadata("design:type", Function),
6618
+ _ts_metadata("design:paramtypes", [
6619
+ String,
6620
+ Boolean,
6621
+ Array
6622
+ ]),
6623
+ _ts_metadata("design:returntype", void 0)
6624
+ ], InputValidator.prototype, "makeConnectOrCreateDataSchema", null);
6625
+ _ts_decorate([
6626
+ cache(),
6627
+ _ts_metadata("design:type", Function),
6628
+ _ts_metadata("design:paramtypes", [
6629
+ String,
6630
+ Array
6631
+ ]),
6632
+ _ts_metadata("design:returntype", void 0)
6633
+ ], InputValidator.prototype, "makeCreateManyDataSchema", null);
6634
+ _ts_decorate([
6635
+ cache(),
6636
+ _ts_metadata("design:type", Function),
6637
+ _ts_metadata("design:paramtypes", [
6638
+ String
6639
+ ]),
6640
+ _ts_metadata("design:returntype", void 0)
6641
+ ], InputValidator.prototype, "makeUpdateSchema", null);
6642
+ _ts_decorate([
6643
+ cache(),
6644
+ _ts_metadata("design:type", Function),
6645
+ _ts_metadata("design:paramtypes", [
6646
+ String
6647
+ ]),
6648
+ _ts_metadata("design:returntype", void 0)
6649
+ ], InputValidator.prototype, "makeUpdateManySchema", null);
6650
+ _ts_decorate([
6651
+ cache(),
6652
+ _ts_metadata("design:type", Function),
6653
+ _ts_metadata("design:paramtypes", [
6654
+ String
6655
+ ]),
6656
+ _ts_metadata("design:returntype", void 0)
6657
+ ], InputValidator.prototype, "makeUpdateManyAndReturnSchema", null);
6658
+ _ts_decorate([
6659
+ cache(),
6660
+ _ts_metadata("design:type", Function),
6661
+ _ts_metadata("design:paramtypes", [
6662
+ String
6663
+ ]),
6664
+ _ts_metadata("design:returntype", void 0)
6665
+ ], InputValidator.prototype, "makeUpsertSchema", null);
6666
+ _ts_decorate([
6667
+ cache(),
6668
+ _ts_metadata("design:type", Function),
6669
+ _ts_metadata("design:paramtypes", [
6670
+ String,
6671
+ Array,
6672
+ void 0
6673
+ ]),
6674
+ _ts_metadata("design:returntype", void 0)
6675
+ ], InputValidator.prototype, "makeUpdateDataSchema", null);
6676
+ _ts_decorate([
6677
+ cache(),
6678
+ _ts_metadata("design:type", Function),
6679
+ _ts_metadata("design:paramtypes", [
6680
+ String
6681
+ ]),
6682
+ _ts_metadata("design:returntype", void 0)
6683
+ ], InputValidator.prototype, "makeDeleteSchema", null);
6684
+ _ts_decorate([
6685
+ cache(),
6686
+ _ts_metadata("design:type", Function),
6687
+ _ts_metadata("design:paramtypes", [
6688
+ String
6689
+ ]),
6690
+ _ts_metadata("design:returntype", void 0)
6691
+ ], InputValidator.prototype, "makeDeleteManySchema", null);
6692
+ _ts_decorate([
6693
+ cache(),
6694
+ _ts_metadata("design:type", Function),
6695
+ _ts_metadata("design:paramtypes", [
6696
+ String
6697
+ ]),
6698
+ _ts_metadata("design:returntype", void 0)
6699
+ ], InputValidator.prototype, "makeCountSchema", null);
6700
+ _ts_decorate([
6701
+ cache(),
6702
+ _ts_metadata("design:type", Function),
6703
+ _ts_metadata("design:paramtypes", [
6704
+ String
6705
+ ]),
6706
+ _ts_metadata("design:returntype", void 0)
6707
+ ], InputValidator.prototype, "makeCountAggregateInputSchema", null);
6708
+ _ts_decorate([
6709
+ cache(),
6710
+ _ts_metadata("design:type", Function),
6711
+ _ts_metadata("design:paramtypes", [
6712
+ String
6713
+ ]),
6714
+ _ts_metadata("design:returntype", void 0)
6715
+ ], InputValidator.prototype, "makeAggregateSchema", null);
6716
+ _ts_decorate([
6717
+ cache(),
6718
+ _ts_metadata("design:type", Function),
6719
+ _ts_metadata("design:paramtypes", [
6720
+ String
6721
+ ]),
6722
+ _ts_metadata("design:returntype", void 0)
6723
+ ], InputValidator.prototype, "makeSumAvgInputSchema", null);
6724
+ _ts_decorate([
6725
+ cache(),
6726
+ _ts_metadata("design:type", Function),
6727
+ _ts_metadata("design:paramtypes", [
6728
+ String
6729
+ ]),
6730
+ _ts_metadata("design:returntype", void 0)
6731
+ ], InputValidator.prototype, "makeMinMaxInputSchema", null);
6732
+ _ts_decorate([
6733
+ cache(),
6734
+ _ts_metadata("design:type", Function),
6735
+ _ts_metadata("design:paramtypes", [
6736
+ String
6737
+ ]),
6738
+ _ts_metadata("design:returntype", void 0)
6739
+ ], InputValidator.prototype, "makeGroupBySchema", null);
6740
+ _ts_decorate([
6741
+ cache(),
6742
+ _ts_metadata("design:type", Function),
6743
+ _ts_metadata("design:paramtypes", [
6744
+ Object
6745
+ ]),
6746
+ _ts_metadata("design:returntype", typeof import_zod3.z === "undefined" || typeof import_zod3.z.ZodType === "undefined" ? Object : import_zod3.z.ZodType)
6747
+ ], InputValidator.prototype, "makeProcedureParamSchema", null);
6748
+ _ts_decorate([
6749
+ cache(),
6750
+ _ts_metadata("design:type", Function),
6751
+ _ts_metadata("design:paramtypes", []),
6752
+ _ts_metadata("design:returntype", void 0)
6753
+ ], InputValidator.prototype, "makeSkipSchema", null);
6754
+ _ts_decorate([
6755
+ cache(),
6756
+ _ts_metadata("design:type", Function),
6757
+ _ts_metadata("design:paramtypes", []),
6758
+ _ts_metadata("design:returntype", void 0)
6759
+ ], InputValidator.prototype, "makeTakeSchema", null);
5815
6760
 
5816
6761
  // src/client/executor/zenstack-driver.ts
5817
6762
  var ZenStackDriver = class {
@@ -5997,24 +6942,26 @@ function performanceNow() {
5997
6942
  __name(performanceNow, "performanceNow");
5998
6943
 
5999
6944
  // src/client/executor/zenstack-query-executor.ts
6000
- var import_common_helpers9 = require("@zenstackhq/common-helpers");
6001
- var import_kysely7 = require("kysely");
6002
- var import_ts_pattern14 = require("ts-pattern");
6945
+ var import_common_helpers11 = require("@zenstackhq/common-helpers");
6946
+ var import_kysely8 = require("kysely");
6947
+ var import_ts_pattern15 = require("ts-pattern");
6003
6948
 
6004
6949
  // src/client/executor/name-mapper.ts
6005
- var import_common_helpers8 = require("@zenstackhq/common-helpers");
6006
- var import_kysely6 = require("kysely");
6007
- var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6950
+ var import_common_helpers10 = require("@zenstackhq/common-helpers");
6951
+ var import_kysely7 = require("kysely");
6952
+ var QueryNameMapper = class extends import_kysely7.OperationNodeTransformer {
6008
6953
  static {
6009
6954
  __name(this, "QueryNameMapper");
6010
6955
  }
6011
- schema;
6956
+ client;
6012
6957
  modelToTableMap = /* @__PURE__ */ new Map();
6013
6958
  fieldToColumnMap = /* @__PURE__ */ new Map();
6014
6959
  scopes = [];
6015
- constructor(schema) {
6016
- super(), this.schema = schema;
6017
- for (const [modelName, modelDef] of Object.entries(schema.models)) {
6960
+ dialect;
6961
+ constructor(client) {
6962
+ super(), this.client = client;
6963
+ this.dialect = getCrudDialect(client.$schema, client.$options);
6964
+ for (const [modelName, modelDef] of Object.entries(client.$schema.models)) {
6018
6965
  const mappedName = this.getMappedName(modelDef);
6019
6966
  if (mappedName) {
6020
6967
  this.modelToTableMap.set(modelName, mappedName);
@@ -6027,6 +6974,9 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6027
6974
  }
6028
6975
  }
6029
6976
  }
6977
+ get schema() {
6978
+ return this.client.$schema;
6979
+ }
6030
6980
  // #region overrides
6031
6981
  transformSelectQuery(node) {
6032
6982
  if (!node.from?.froms) {
@@ -6052,7 +7002,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6052
7002
  const baseResult = super.transformSelectQuery(node);
6053
7003
  return {
6054
7004
  ...baseResult,
6055
- from: import_kysely6.FromNode.create(processedFroms.map((f) => f.node)),
7005
+ from: import_kysely7.FromNode.create(processedFroms.map((f) => f.node)),
6056
7006
  joins,
6057
7007
  selections
6058
7008
  };
@@ -6063,7 +7013,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6063
7013
  return super.transformInsertQuery(node);
6064
7014
  }
6065
7015
  const model = extractModelName(node.into);
6066
- (0, import_common_helpers8.invariant)(model, 'InsertQueryNode must have a model name in the "into" clause');
7016
+ (0, import_common_helpers10.invariant)(model, 'InsertQueryNode must have a model name in the "into" clause');
6067
7017
  return this.withScope({
6068
7018
  model
6069
7019
  }, () => {
@@ -6091,7 +7041,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6091
7041
  };
6092
7042
  }
6093
7043
  transformReference(node) {
6094
- if (!import_kysely6.ColumnNode.is(node.column)) {
7044
+ if (!import_kysely7.ColumnNode.is(node.column)) {
6095
7045
  return super.transformReference(node);
6096
7046
  }
6097
7047
  const scope = this.resolveFieldFromScopes(node.column.column.name, node.table?.table.identifier.name);
@@ -6099,12 +7049,12 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6099
7049
  const mappedFieldName = this.mapFieldName(scope.model, node.column.column.name);
6100
7050
  let mappedTableName = node.table?.table.identifier.name;
6101
7051
  if (mappedTableName) {
6102
- if (scope.alias && import_kysely6.IdentifierNode.is(scope.alias) && scope.alias.name === mappedTableName) {
7052
+ if (scope.alias && import_kysely7.IdentifierNode.is(scope.alias) && scope.alias.name === mappedTableName) {
6103
7053
  } else if (scope.model === mappedTableName) {
6104
7054
  mappedTableName = this.mapTableName(scope.model);
6105
7055
  }
6106
7056
  }
6107
- return import_kysely6.ReferenceNode.create(import_kysely6.ColumnNode.create(mappedFieldName), mappedTableName ? this.createTableNode(mappedTableName, void 0) : void 0);
7057
+ return import_kysely7.ReferenceNode.create(import_kysely7.ColumnNode.create(mappedFieldName), mappedTableName ? this.createTableNode(mappedTableName, void 0) : void 0);
6108
7058
  } else {
6109
7059
  return node;
6110
7060
  }
@@ -6115,19 +7065,19 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6115
7065
  return super.transformColumn(node);
6116
7066
  }
6117
7067
  const mappedName = this.mapFieldName(scope.model, node.column.name);
6118
- return import_kysely6.ColumnNode.create(mappedName);
7068
+ return import_kysely7.ColumnNode.create(mappedName);
6119
7069
  }
6120
7070
  transformBinaryOperation(node) {
6121
- if (import_kysely6.ReferenceNode.is(node.leftOperand) && import_kysely6.ColumnNode.is(node.leftOperand.column) && (import_kysely6.ValueNode.is(node.rightOperand) || import_kysely6.PrimitiveValueListNode.is(node.rightOperand))) {
7071
+ if (import_kysely7.ReferenceNode.is(node.leftOperand) && import_kysely7.ColumnNode.is(node.leftOperand.column) && (import_kysely7.ValueNode.is(node.rightOperand) || import_kysely7.PrimitiveValueListNode.is(node.rightOperand))) {
6122
7072
  const columnNode = node.leftOperand.column;
6123
7073
  const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
6124
7074
  if (resolvedScope?.model) {
6125
7075
  const valueNode = node.rightOperand;
6126
7076
  let resultValue = valueNode;
6127
- if (import_kysely6.ValueNode.is(valueNode)) {
7077
+ if (import_kysely7.ValueNode.is(valueNode)) {
6128
7078
  resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
6129
- } else if (import_kysely6.PrimitiveValueListNode.is(valueNode)) {
6130
- resultValue = import_kysely6.PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
7079
+ } else if (import_kysely7.PrimitiveValueListNode.is(valueNode)) {
7080
+ resultValue = import_kysely7.PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
6131
7081
  }
6132
7082
  return super.transformBinaryOperation({
6133
7083
  ...node,
@@ -6142,20 +7092,20 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6142
7092
  return super.transformUpdateQuery(node);
6143
7093
  }
6144
7094
  const { alias, node: innerTable } = stripAlias(node.table);
6145
- if (!innerTable || !import_kysely6.TableNode.is(innerTable)) {
7095
+ if (!innerTable || !import_kysely7.TableNode.is(innerTable)) {
6146
7096
  return super.transformUpdateQuery(node);
6147
7097
  }
6148
7098
  const model = extractModelName(innerTable);
6149
- (0, import_common_helpers8.invariant)(model, 'UpdateQueryNode must have a model name in the "table" clause');
7099
+ (0, import_common_helpers10.invariant)(model, 'UpdateQueryNode must have a model name in the "table" clause');
6150
7100
  return this.withScope({
6151
7101
  model,
6152
7102
  alias
6153
7103
  }, () => {
6154
7104
  const baseResult = super.transformUpdateQuery(node);
6155
7105
  const updates = baseResult.updates?.map((update, i) => {
6156
- if (import_kysely6.ColumnNode.is(update.column)) {
7106
+ if (import_kysely7.ColumnNode.is(update.column)) {
6157
7107
  const origColumn = node.updates[i].column;
6158
- return import_kysely6.ColumnUpdateNode.create(update.column, this.processEnumMappingForValue(model, origColumn, update.value));
7108
+ return import_kysely7.ColumnUpdateNode.create(update.column, this.processEnumMappingForValue(model, origColumn, update.value));
6159
7109
  } else {
6160
7110
  return update;
6161
7111
  }
@@ -6179,7 +7129,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6179
7129
  });
6180
7130
  const froms = node.from.froms.map((from) => {
6181
7131
  const { alias, node: innerNode } = stripAlias(from);
6182
- if (import_kysely6.TableNode.is(innerNode)) {
7132
+ if (import_kysely7.TableNode.is(innerNode)) {
6183
7133
  return this.wrapAlias(this.processTableRef(innerNode), alias);
6184
7134
  } else {
6185
7135
  return super.transformNode(from);
@@ -6188,7 +7138,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6188
7138
  return this.withScopes(scopes, () => {
6189
7139
  return {
6190
7140
  ...super.transformDeleteQuery(node),
6191
- from: import_kysely6.FromNode.create(froms)
7141
+ from: import_kysely7.FromNode.create(froms)
6192
7142
  };
6193
7143
  });
6194
7144
  }
@@ -6198,7 +7148,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6198
7148
  const selections = [];
6199
7149
  for (const selection of node.selections ?? []) {
6200
7150
  const processedSelections = [];
6201
- if (import_kysely6.SelectAllNode.is(selection.selection)) {
7151
+ if (import_kysely7.SelectAllNode.is(selection.selection)) {
6202
7152
  const scope = this.requireCurrentScope();
6203
7153
  if (scope?.model && !scope.namesMapped) {
6204
7154
  processedSelections.push(...this.createSelectAllFields(scope.model, scope.alias));
@@ -6208,25 +7158,25 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6208
7158
  selection: super.transformSelection(selection)
6209
7159
  });
6210
7160
  }
6211
- } else if (import_kysely6.ReferenceNode.is(selection.selection) || import_kysely6.ColumnNode.is(selection.selection)) {
7161
+ } else if (import_kysely7.ReferenceNode.is(selection.selection) || import_kysely7.ColumnNode.is(selection.selection)) {
6212
7162
  const transformed = this.transformNode(selection.selection);
6213
7163
  const originalField = extractFieldName(selection.selection);
6214
- if (import_kysely6.AliasNode.is(transformed)) {
7164
+ if (import_kysely7.AliasNode.is(transformed)) {
6215
7165
  processedSelections.push({
6216
7166
  originalField,
6217
- selection: import_kysely6.SelectionNode.create(transformed)
7167
+ selection: import_kysely7.SelectionNode.create(transformed)
6218
7168
  });
6219
7169
  } else {
6220
7170
  const fieldName = extractFieldName(transformed);
6221
7171
  if (fieldName !== originalField) {
6222
7172
  processedSelections.push({
6223
7173
  originalField,
6224
- selection: import_kysely6.SelectionNode.create(this.wrapAlias(transformed, originalField ? import_kysely6.IdentifierNode.create(originalField) : void 0))
7174
+ selection: import_kysely7.SelectionNode.create(this.wrapAlias(transformed, originalField ? import_kysely7.IdentifierNode.create(originalField) : void 0))
6225
7175
  });
6226
7176
  } else {
6227
7177
  processedSelections.push({
6228
7178
  originalField,
6229
- selection: import_kysely6.SelectionNode.create(transformed)
7179
+ selection: import_kysely7.SelectionNode.create(transformed)
6230
7180
  });
6231
7181
  }
6232
7182
  }
@@ -6241,7 +7191,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6241
7191
  if (!originalField) {
6242
7192
  return selection2;
6243
7193
  } else {
6244
- return import_kysely6.SelectionNode.create(this.processEnumSelection(selection2.selection, originalField));
7194
+ return import_kysely7.SelectionNode.create(this.processEnumSelection(selection2.selection, originalField));
6245
7195
  }
6246
7196
  });
6247
7197
  selections.push(...enumProcessedSelections);
@@ -6253,7 +7203,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6253
7203
  const scope = this.scopes[i];
6254
7204
  if (qualifier) {
6255
7205
  if (scope.alias) {
6256
- if (scope.alias && import_kysely6.IdentifierNode.is(scope.alias) && scope.alias.name === qualifier) {
7206
+ if (scope.alias && import_kysely7.IdentifierNode.is(scope.alias) && scope.alias.name === qualifier) {
6257
7207
  return scope;
6258
7208
  } else {
6259
7209
  continue;
@@ -6299,13 +7249,13 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6299
7249
  }
6300
7250
  }
6301
7251
  wrapAlias(node, alias) {
6302
- return alias ? import_kysely6.AliasNode.create(node, alias) : node;
7252
+ return alias ? import_kysely7.AliasNode.create(node, alias) : node;
6303
7253
  }
6304
7254
  processTableRef(node) {
6305
7255
  if (!node) {
6306
7256
  return node;
6307
7257
  }
6308
- if (!import_kysely6.TableNode.is(node)) {
7258
+ if (!import_kysely7.TableNode.is(node)) {
6309
7259
  return super.transformNode(node);
6310
7260
  }
6311
7261
  const mappedName = this.mapTableName(node.table.identifier.name);
@@ -6346,15 +7296,15 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6346
7296
  // convert a "from" node to a nested query if there are columns with name mapping
6347
7297
  processSelectTable(node) {
6348
7298
  const { alias, node: innerNode } = stripAlias(node);
6349
- if (innerNode && import_kysely6.TableNode.is(innerNode)) {
7299
+ if (innerNode && import_kysely7.TableNode.is(innerNode)) {
6350
7300
  const modelName = innerNode.table.identifier.name;
6351
7301
  const mappedName = this.mapTableName(modelName);
6352
- const finalAlias = alias ?? (mappedName !== modelName ? import_kysely6.IdentifierNode.create(modelName) : void 0);
7302
+ const finalAlias = alias ?? (mappedName !== modelName ? import_kysely7.IdentifierNode.create(modelName) : void 0);
6353
7303
  const tableSchema = this.getTableSchema(modelName);
6354
7304
  return {
6355
7305
  node: this.wrapAlias(this.createTableNode(mappedName, tableSchema), finalAlias),
6356
7306
  scope: {
6357
- alias: alias ?? import_kysely6.IdentifierNode.create(modelName),
7307
+ alias: alias ?? import_kysely7.IdentifierNode.create(modelName),
6358
7308
  model: modelName,
6359
7309
  namesMapped: !this.hasMappedColumns(modelName)
6360
7310
  }
@@ -6388,17 +7338,17 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6388
7338
  const modelDef = requireModel(this.schema, model);
6389
7339
  return this.getModelFields(modelDef).map((fieldDef) => {
6390
7340
  const columnName = this.mapFieldName(model, fieldDef.name);
6391
- const columnRef = import_kysely6.ReferenceNode.create(import_kysely6.ColumnNode.create(columnName), alias && import_kysely6.IdentifierNode.is(alias) ? import_kysely6.TableNode.create(alias.name) : void 0);
7341
+ const columnRef = import_kysely7.ReferenceNode.create(import_kysely7.ColumnNode.create(columnName), alias && import_kysely7.IdentifierNode.is(alias) ? import_kysely7.TableNode.create(alias.name) : void 0);
6392
7342
  if (columnName !== fieldDef.name) {
6393
- const aliased = import_kysely6.AliasNode.create(columnRef, import_kysely6.IdentifierNode.create(fieldDef.name));
7343
+ const aliased = import_kysely7.AliasNode.create(columnRef, import_kysely7.IdentifierNode.create(fieldDef.name));
6394
7344
  return {
6395
7345
  originalField: fieldDef.name,
6396
- selection: import_kysely6.SelectionNode.create(aliased)
7346
+ selection: import_kysely7.SelectionNode.create(aliased)
6397
7347
  };
6398
7348
  } else {
6399
7349
  return {
6400
7350
  originalField: fieldDef.name,
6401
- selection: import_kysely6.SelectionNode.create(columnRef)
7351
+ selection: import_kysely7.SelectionNode.create(columnRef)
6402
7352
  };
6403
7353
  }
6404
7354
  });
@@ -6409,15 +7359,15 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6409
7359
  processSelections(selections) {
6410
7360
  const result = [];
6411
7361
  selections.forEach((selection) => {
6412
- if (import_kysely6.SelectAllNode.is(selection.selection)) {
7362
+ if (import_kysely7.SelectAllNode.is(selection.selection)) {
6413
7363
  const processed = this.processSelectAll(selection.selection);
6414
7364
  if (Array.isArray(processed)) {
6415
- result.push(...processed.map((s) => import_kysely6.SelectionNode.create(s)));
7365
+ result.push(...processed.map((s) => import_kysely7.SelectionNode.create(s)));
6416
7366
  } else {
6417
- result.push(import_kysely6.SelectionNode.create(processed));
7367
+ result.push(import_kysely7.SelectionNode.create(processed));
6418
7368
  }
6419
7369
  } else {
6420
- result.push(import_kysely6.SelectionNode.create(this.processSelection(selection.selection)));
7370
+ result.push(import_kysely7.SelectionNode.create(this.processSelection(selection.selection)));
6421
7371
  }
6422
7372
  });
6423
7373
  return result;
@@ -6429,8 +7379,8 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6429
7379
  if (originalField) {
6430
7380
  result = this.processEnumSelection(result, originalField);
6431
7381
  }
6432
- if (!import_kysely6.AliasNode.is(result)) {
6433
- const addAlias = alias ?? (originalField ? import_kysely6.IdentifierNode.create(originalField) : void 0);
7382
+ if (!import_kysely7.AliasNode.is(result)) {
7383
+ const addAlias = alias ?? (originalField ? import_kysely7.IdentifierNode.create(originalField) : void 0);
6434
7384
  if (addAlias) {
6435
7385
  result = this.wrapAlias(result, addAlias);
6436
7386
  }
@@ -6445,17 +7395,17 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6445
7395
  const modelDef = requireModel(this.schema, scope.model);
6446
7396
  return this.getModelFields(modelDef).map((fieldDef) => {
6447
7397
  const columnName = this.mapFieldName(modelDef.name, fieldDef.name);
6448
- const columnRef = import_kysely6.ReferenceNode.create(import_kysely6.ColumnNode.create(columnName));
7398
+ const columnRef = import_kysely7.ReferenceNode.create(import_kysely7.ColumnNode.create(columnName));
6449
7399
  const enumProcessed = this.processEnumSelection(columnRef, fieldDef.name);
6450
- return columnName !== fieldDef.name && !import_kysely6.AliasNode.is(enumProcessed) ? this.wrapAlias(enumProcessed, import_kysely6.IdentifierNode.create(fieldDef.name)) : enumProcessed;
7400
+ return columnName !== fieldDef.name && !import_kysely7.AliasNode.is(enumProcessed) ? this.wrapAlias(enumProcessed, import_kysely7.IdentifierNode.create(fieldDef.name)) : enumProcessed;
6451
7401
  });
6452
7402
  }
6453
7403
  createTableNode(tableName, schemaName) {
6454
- return schemaName ? import_kysely6.TableNode.createWithSchema(schemaName, tableName) : import_kysely6.TableNode.create(tableName);
7404
+ return schemaName ? import_kysely7.TableNode.createWithSchema(schemaName, tableName) : import_kysely7.TableNode.create(tableName);
6455
7405
  }
6456
7406
  requireCurrentScope() {
6457
7407
  const scope = this.scopes[this.scopes.length - 1];
6458
- (0, import_common_helpers8.invariant)(scope, "No scope available");
7408
+ (0, import_common_helpers10.invariant)(scope, "No scope available");
6459
7409
  return scope;
6460
7410
  }
6461
7411
  // #endregion
@@ -6484,16 +7434,16 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6484
7434
  return mapping;
6485
7435
  }
6486
7436
  processEnumMappingForColumns(model, columns, values) {
6487
- if (import_kysely6.ValuesNode.is(values)) {
6488
- return import_kysely6.ValuesNode.create(values.values.map((valueItems) => {
6489
- if (import_kysely6.PrimitiveValueListNode.is(valueItems)) {
6490
- return import_kysely6.PrimitiveValueListNode.create(this.processEnumMappingForValues(model, columns, valueItems.values));
7437
+ if (import_kysely7.ValuesNode.is(values)) {
7438
+ return import_kysely7.ValuesNode.create(values.values.map((valueItems) => {
7439
+ if (import_kysely7.PrimitiveValueListNode.is(valueItems)) {
7440
+ return import_kysely7.PrimitiveValueListNode.create(this.processEnumMappingForValues(model, columns, valueItems.values));
6491
7441
  } else {
6492
- return import_kysely6.ValueListNode.create(this.processEnumMappingForValues(model, columns, valueItems.values));
7442
+ return import_kysely7.ValueListNode.create(this.processEnumMappingForValues(model, columns, valueItems.values));
6493
7443
  }
6494
7444
  }));
6495
- } else if (import_kysely6.PrimitiveValueListNode.is(values)) {
6496
- return import_kysely6.PrimitiveValueListNode.create(this.processEnumMappingForValues(model, columns, values.values));
7445
+ } else if (import_kysely7.PrimitiveValueListNode.is(values)) {
7446
+ return import_kysely7.PrimitiveValueListNode.create(this.processEnumMappingForValues(model, columns, values.values));
6497
7447
  } else {
6498
7448
  return values;
6499
7449
  }
@@ -6523,10 +7473,10 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6523
7473
  return value;
6524
7474
  }
6525
7475
  const enumValueMapping = this.getEnumValueMapping(enumDef);
6526
- if (this.isOperationNode(value) && import_kysely6.ValueNode.is(value) && typeof value.value === "string") {
7476
+ if (this.isOperationNode(value) && import_kysely7.ValueNode.is(value) && typeof value.value === "string") {
6527
7477
  const mappedValue = enumValueMapping[value.value];
6528
7478
  if (mappedValue) {
6529
- return import_kysely6.ValueNode.create(mappedValue);
7479
+ return import_kysely7.ValueNode.create(mappedValue);
6530
7480
  }
6531
7481
  } else if (typeof value === "string") {
6532
7482
  const mappedValue = enumValueMapping[value];
@@ -6542,7 +7492,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6542
7492
  if (!fieldScope || !fieldScope.model) {
6543
7493
  return selection;
6544
7494
  }
6545
- const aliasName = alias && import_kysely6.IdentifierNode.is(alias) ? alias.name : fieldName;
7495
+ const aliasName = alias && import_kysely7.IdentifierNode.is(alias) ? alias.name : fieldName;
6546
7496
  const fieldDef = getField(this.schema, fieldScope.model, fieldName);
6547
7497
  if (!fieldDef) {
6548
7498
  return selection;
@@ -6555,17 +7505,17 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6555
7505
  if (Object.keys(enumValueMapping).length === 0) {
6556
7506
  return selection;
6557
7507
  }
6558
- const eb = (0, import_kysely6.expressionBuilder)();
7508
+ const eb = (0, import_kysely7.expressionBuilder)();
6559
7509
  const caseBuilder = eb.case();
6560
7510
  let caseWhen;
6561
7511
  for (const [key, value] of Object.entries(enumValueMapping)) {
6562
7512
  if (!caseWhen) {
6563
- caseWhen = caseBuilder.when(new import_kysely6.ExpressionWrapper(node), "=", value).then(key);
7513
+ caseWhen = caseBuilder.when(new import_kysely7.ExpressionWrapper(node), "=", value).then(key);
6564
7514
  } else {
6565
- caseWhen = caseWhen.when(new import_kysely6.ExpressionWrapper(node), "=", value).then(key);
7515
+ caseWhen = caseWhen.when(new import_kysely7.ExpressionWrapper(node), "=", value).then(key);
6566
7516
  }
6567
7517
  }
6568
- const finalExpr = caseWhen.else(eb.cast(new import_kysely6.ExpressionWrapper(node), "text")).end();
7518
+ const finalExpr = caseWhen.else(this.dialect.castText(new import_kysely7.ExpressionWrapper(node))).end();
6569
7519
  if (aliasName) {
6570
7520
  return finalExpr.as(aliasName).toOperationNode();
6571
7521
  } else {
@@ -6575,7 +7525,7 @@ var QueryNameMapper = class extends import_kysely6.OperationNodeTransformer {
6575
7525
  };
6576
7526
 
6577
7527
  // src/client/executor/zenstack-query-executor.ts
6578
- var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.DefaultQueryExecutor {
7528
+ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely8.DefaultQueryExecutor {
6579
7529
  static {
6580
7530
  __name(this, "ZenStackQueryExecutor");
6581
7531
  }
@@ -6584,13 +7534,16 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6584
7534
  compiler;
6585
7535
  connectionProvider;
6586
7536
  suppressMutationHooks;
7537
+ // #region constructor, fields and props
6587
7538
  nameMapper;
7539
+ dialect;
6588
7540
  constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false) {
6589
7541
  super(compiler, adapter, connectionProvider, plugins), this.client = client, this.driver = driver, this.compiler = compiler, this.connectionProvider = connectionProvider, this.suppressMutationHooks = suppressMutationHooks;
6590
7542
  if (client.$schema.provider.type === "postgresql" || // postgres queries need to be schema-qualified
6591
7543
  this.schemaHasMappedNames(client.$schema)) {
6592
- this.nameMapper = new QueryNameMapper(client.$schema);
7544
+ this.nameMapper = new QueryNameMapper(client);
6593
7545
  }
7546
+ this.dialect = getCrudDialect(client.$schema, client.$options);
6594
7547
  }
6595
7548
  schemaHasMappedNames(schema) {
6596
7549
  const hasMapAttr = /* @__PURE__ */ __name((decl) => {
@@ -6607,9 +7560,17 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6607
7560
  get options() {
6608
7561
  return this.client.$options;
6609
7562
  }
6610
- executeQuery(compiledQuery) {
7563
+ get hasEntityMutationPlugins() {
7564
+ return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
7565
+ }
7566
+ get hasEntityMutationPluginsWithAfterMutationHooks() {
7567
+ return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
7568
+ }
7569
+ // #endregion
7570
+ // #region main entry point
7571
+ async executeQuery(compiledQuery) {
6611
7572
  const queryParams = compiledQuery.$raw ? compiledQuery.parameters : void 0;
6612
- return this.provideConnection(async (connection) => {
7573
+ const result = await this.provideConnection(async (connection) => {
6613
7574
  let startedTx = false;
6614
7575
  try {
6615
7576
  if (this.isMutationNode(compiledQuery.query) && !this.driver.isTransactionConnection(connection)) {
@@ -6618,11 +7579,11 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6618
7579
  });
6619
7580
  startedTx = true;
6620
7581
  }
6621
- const result = await this.proceedQueryWithKyselyInterceptors(connection, compiledQuery.query, queryParams, compiledQuery.queryId);
7582
+ const result2 = await this.proceedQueryWithKyselyInterceptors(connection, compiledQuery.query, queryParams, compiledQuery.queryId);
6622
7583
  if (startedTx) {
6623
7584
  await this.driver.commitTransaction(connection);
6624
7585
  }
6625
- return result;
7586
+ return result2;
6626
7587
  } catch (err) {
6627
7588
  if (startedTx) {
6628
7589
  await this.driver.rollbackTransaction(connection);
@@ -6634,6 +7595,7 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6634
7595
  }
6635
7596
  }
6636
7597
  });
7598
+ return this.ensureProperQueryResult(compiledQuery.query, result);
6637
7599
  }
6638
7600
  async proceedQueryWithKyselyInterceptors(connection, queryNode, parameters, queryId) {
6639
7601
  let proceed = /* @__PURE__ */ __name((q) => this.proceedQuery(connection, q, parameters, queryId), "proceed");
@@ -6659,139 +7621,81 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6659
7621
  const result = await proceed(queryNode);
6660
7622
  return result;
6661
7623
  }
6662
- getMutationInfo(queryNode) {
6663
- const model = this.getMutationModel(queryNode);
6664
- const { action, where } = (0, import_ts_pattern14.match)(queryNode).when(import_kysely7.InsertQueryNode.is, () => ({
6665
- action: "create",
6666
- where: void 0
6667
- })).when(import_kysely7.UpdateQueryNode.is, (node) => ({
6668
- action: "update",
6669
- where: node.where
6670
- })).when(import_kysely7.DeleteQueryNode.is, (node) => ({
6671
- action: "delete",
6672
- where: node.where
6673
- })).exhaustive();
6674
- return {
6675
- model,
6676
- action,
6677
- where
6678
- };
6679
- }
6680
7624
  async proceedQuery(connection, query, parameters, queryId) {
6681
- let compiled;
6682
7625
  if (this.suppressMutationHooks || !this.isMutationNode(query) || !this.hasEntityMutationPlugins) {
6683
- const finalQuery2 = this.processNameMapping(query);
6684
- compiled = this.compileQuery(finalQuery2, queryId);
6685
- if (parameters) {
6686
- compiled = {
6687
- ...compiled,
6688
- parameters
7626
+ return this.internalExecuteQuery(query, connection, queryId, parameters);
7627
+ }
7628
+ let preUpdateIds;
7629
+ const mutationModel = this.getMutationModel(query);
7630
+ const needLoadAfterMutationEntities = (import_kysely8.InsertQueryNode.is(query) || import_kysely8.UpdateQueryNode.is(query)) && this.hasEntityMutationPluginsWithAfterMutationHooks;
7631
+ if (needLoadAfterMutationEntities) {
7632
+ if (this.dialect.supportsReturning) {
7633
+ query = {
7634
+ ...query,
7635
+ returning: import_kysely8.ReturningNode.create([
7636
+ import_kysely8.SelectionNode.createSelectAll()
7637
+ ])
6689
7638
  };
7639
+ } else {
7640
+ if (import_kysely8.UpdateQueryNode.is(query)) {
7641
+ preUpdateIds = await this.getPreUpdateIds(mutationModel, query, connection);
7642
+ }
6690
7643
  }
6691
- return this.internalExecuteQuery(connection, compiled);
6692
- }
6693
- if ((import_kysely7.InsertQueryNode.is(query) || import_kysely7.UpdateQueryNode.is(query)) && this.hasEntityMutationPluginsWithAfterMutationHooks) {
6694
- query = {
6695
- ...query,
6696
- returning: import_kysely7.ReturningNode.create([
6697
- import_kysely7.SelectionNode.createSelectAll()
6698
- ])
6699
- };
6700
- }
6701
- const finalQuery = this.processNameMapping(query);
6702
- compiled = this.compileQuery(finalQuery, queryId);
6703
- if (parameters) {
6704
- compiled = {
6705
- ...compiled,
6706
- parameters
6707
- };
6708
7644
  }
6709
7645
  const currentlyInTx = this.driver.isTransactionConnection(connection);
6710
7646
  const connectionClient = this.createClientForConnection(connection, currentlyInTx);
6711
- const mutationInfo = this.getMutationInfo(finalQuery);
7647
+ const mutationInfo = this.getMutationInfo(query);
6712
7648
  let beforeMutationEntities;
6713
7649
  const loadBeforeMutationEntities = /* @__PURE__ */ __name(async () => {
6714
- if (beforeMutationEntities === void 0 && (import_kysely7.UpdateQueryNode.is(query) || import_kysely7.DeleteQueryNode.is(query))) {
6715
- beforeMutationEntities = await this.loadEntities(mutationInfo.model, mutationInfo.where, connection);
7650
+ if (beforeMutationEntities === void 0 && (import_kysely8.UpdateQueryNode.is(query) || import_kysely8.DeleteQueryNode.is(query))) {
7651
+ beforeMutationEntities = await this.loadEntities(mutationInfo.model, mutationInfo.where, connection, void 0);
6716
7652
  }
6717
7653
  return beforeMutationEntities;
6718
7654
  }, "loadBeforeMutationEntities");
6719
- await this.callBeforeMutationHooks(finalQuery, mutationInfo, loadBeforeMutationEntities, connectionClient, queryId);
6720
- const result = await this.internalExecuteQuery(connection, compiled);
7655
+ await this.callBeforeMutationHooks({
7656
+ queryNode: query,
7657
+ mutationInfo,
7658
+ loadBeforeMutationEntities,
7659
+ client: connectionClient,
7660
+ queryId
7661
+ });
7662
+ const result = await this.internalExecuteQuery(query, connection, queryId, parameters);
7663
+ let afterMutationEntities;
7664
+ if (needLoadAfterMutationEntities) {
7665
+ afterMutationEntities = await this.loadAfterMutationEntities(mutationInfo, query, result, connection, preUpdateIds);
7666
+ }
7667
+ const baseArgs = {
7668
+ queryResult: result,
7669
+ queryNode: query,
7670
+ mutationInfo,
7671
+ filterFor: "all",
7672
+ client: connectionClient,
7673
+ connection,
7674
+ queryId,
7675
+ beforeMutationEntities,
7676
+ afterMutationEntities
7677
+ };
6721
7678
  if (!this.driver.isTransactionConnection(connection)) {
6722
- await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "all", queryId);
7679
+ await this.callAfterMutationHooks({
7680
+ ...baseArgs,
7681
+ filterFor: "all"
7682
+ });
6723
7683
  } else {
6724
- await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "inTx", queryId);
6725
- this.driver.registerTransactionCommitCallback(connection, () => this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "outTx", queryId));
7684
+ await this.callAfterMutationHooks({
7685
+ ...baseArgs,
7686
+ filterFor: "inTx"
7687
+ });
7688
+ this.driver.registerTransactionCommitCallback(connection, () => this.callAfterMutationHooks({
7689
+ ...baseArgs,
7690
+ filterFor: "outTx"
7691
+ }));
6726
7692
  }
6727
7693
  return result;
6728
7694
  }
6729
- processNameMapping(query) {
6730
- return this.nameMapper?.transformNode(query) ?? query;
6731
- }
6732
- createClientForConnection(connection, inTx) {
6733
- const innerExecutor = this.withConnectionProvider(new import_kysely7.SingleConnectionProvider(connection));
6734
- innerExecutor.suppressMutationHooks = true;
6735
- const innerClient = this.client.withExecutor(innerExecutor);
6736
- if (inTx) {
6737
- innerClient.forceTransaction();
6738
- }
6739
- return innerClient;
6740
- }
6741
- get hasEntityMutationPlugins() {
6742
- return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6743
- }
6744
- get hasEntityMutationPluginsWithAfterMutationHooks() {
6745
- return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
6746
- }
6747
- isMutationNode(queryNode) {
6748
- return import_kysely7.InsertQueryNode.is(queryNode) || import_kysely7.UpdateQueryNode.is(queryNode) || import_kysely7.DeleteQueryNode.is(queryNode);
6749
- }
6750
- withPlugin(plugin) {
6751
- return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6752
- ...this.plugins,
6753
- plugin
6754
- ], this.suppressMutationHooks);
6755
- }
6756
- withPlugins(plugins) {
6757
- return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6758
- ...this.plugins,
6759
- ...plugins
6760
- ], this.suppressMutationHooks);
6761
- }
6762
- withPluginAtFront(plugin) {
6763
- return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6764
- plugin,
6765
- ...this.plugins
6766
- ], this.suppressMutationHooks);
6767
- }
6768
- withoutPlugins() {
6769
- return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks);
6770
- }
6771
- withConnectionProvider(connectionProvider) {
6772
- const newExecutor = new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks);
6773
- newExecutor.client = this.client.withExecutor(newExecutor);
6774
- return newExecutor;
6775
- }
6776
- getMutationModel(queryNode) {
6777
- return (0, import_ts_pattern14.match)(queryNode).when(import_kysely7.InsertQueryNode.is, (node) => {
6778
- (0, import_common_helpers9.invariant)(node.into, "InsertQueryNode must have an into clause");
6779
- return node.into.table.identifier.name;
6780
- }).when(import_kysely7.UpdateQueryNode.is, (node) => {
6781
- (0, import_common_helpers9.invariant)(node.table, "UpdateQueryNode must have a table");
6782
- const { node: tableNode } = stripAlias(node.table);
6783
- (0, import_common_helpers9.invariant)(import_kysely7.TableNode.is(tableNode), "UpdateQueryNode must use a TableNode");
6784
- return tableNode.table.identifier.name;
6785
- }).when(import_kysely7.DeleteQueryNode.is, (node) => {
6786
- (0, import_common_helpers9.invariant)(node.from.froms.length === 1, "Delete query must have exactly one from table");
6787
- const { node: tableNode } = stripAlias(node.from.froms[0]);
6788
- (0, import_common_helpers9.invariant)(import_kysely7.TableNode.is(tableNode), "DeleteQueryNode must use a TableNode");
6789
- return tableNode.table.identifier.name;
6790
- }).otherwise((node) => {
6791
- throw createInternalError(`Invalid query node: ${node}`);
6792
- });
6793
- }
6794
- async callBeforeMutationHooks(queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId) {
7695
+ // #endregion
7696
+ // #region before and after mutation hooks
7697
+ async callBeforeMutationHooks(args) {
7698
+ const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
6795
7699
  if (this.options.plugins) {
6796
7700
  for (const plugin of this.options.plugins) {
6797
7701
  const onEntityMutation = plugin.onEntityMutation;
@@ -6809,7 +7713,8 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6809
7713
  }
6810
7714
  }
6811
7715
  }
6812
- async callAfterMutationHooks(queryResult, queryNode, mutationInfo, client, filterFor, queryId) {
7716
+ async callAfterMutationHooks(args) {
7717
+ const { queryNode, mutationInfo, client, filterFor, queryId, beforeMutationEntities, afterMutationEntities } = args;
6813
7718
  const hooks = [];
6814
7719
  for (const plugin of this.options.plugins ?? []) {
6815
7720
  const onEntityMutation = plugin.onEntityMutation;
@@ -6827,52 +7732,249 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely7.
6827
7732
  if (hooks.length === 0) {
6828
7733
  return;
6829
7734
  }
6830
- const mutationModel = this.getMutationModel(queryNode);
6831
- const loadAfterMutationEntities = /* @__PURE__ */ __name(async () => {
6832
- if (mutationInfo.action === "delete") {
6833
- return void 0;
6834
- } else {
6835
- return queryResult.rows;
6836
- }
6837
- }, "loadAfterMutationEntities");
6838
7735
  for (const hook of hooks) {
6839
7736
  await hook({
6840
- model: mutationModel,
7737
+ model: mutationInfo.model,
6841
7738
  action: mutationInfo.action,
6842
7739
  queryNode,
6843
- loadAfterMutationEntities,
7740
+ loadAfterMutationEntities: /* @__PURE__ */ __name(() => Promise.resolve(afterMutationEntities), "loadAfterMutationEntities"),
7741
+ beforeMutationEntities,
6844
7742
  client,
6845
7743
  queryId
6846
7744
  });
6847
7745
  }
6848
7746
  }
6849
- async loadEntities(model, where, connection) {
6850
- const selectQuery = this.kysely.selectFrom(model).selectAll();
7747
+ async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
7748
+ if (mutationInfo.action === "delete") {
7749
+ return void 0;
7750
+ }
7751
+ if (this.dialect.supportsReturning) {
7752
+ return queryResult.rows;
7753
+ } else {
7754
+ const mutatedIds = import_kysely8.InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
7755
+ if (mutatedIds) {
7756
+ const idFields = requireIdFields(this.client.$schema, mutationInfo.model);
7757
+ const eb = (0, import_kysely8.expressionBuilder)();
7758
+ const filter = eb(
7759
+ // @ts-ignore
7760
+ eb.refTuple(...idFields),
7761
+ "in",
7762
+ mutatedIds.map((idObj) => eb.tuple(
7763
+ ...idFields.map((idField) => eb.val(idObj[idField]))
7764
+ ))
7765
+ );
7766
+ const entities = await this.loadEntities(mutationInfo.model, import_kysely8.WhereNode.create(filter.toOperationNode()), connection, void 0);
7767
+ return entities;
7768
+ } else {
7769
+ console.warn(`Unable to load after-mutation entities for hooks: model "${mutationInfo.model}", operation "${mutationInfo.action}".
7770
+ This happens when the following conditions are met:
7771
+
7772
+ 1. The database does not support RETURNING clause for INSERT/UPDATE, e.g., MySQL.
7773
+ 2. The mutation creates or updates multiple entities at once.
7774
+ 3. For create: the model does not have all ID fields explicitly set in the mutation data.
7775
+ 4. For update: the mutation modifies ID fields.
7776
+
7777
+ In such cases, ZenStack cannot reliably determine the IDs of the mutated entities to reload them.
7778
+ `);
7779
+ return [];
7780
+ }
7781
+ }
7782
+ }
7783
+ async getPreUpdateIds(mutationModel, query, connection) {
7784
+ const idFields = requireIdFields(this.client.$schema, mutationModel);
7785
+ if (query.updates) {
7786
+ for (const update of query.updates) {
7787
+ if (import_kysely8.ColumnUpdateNode.is(update)) {
7788
+ const columnNode = update.column;
7789
+ if (import_kysely8.ColumnNode.is(columnNode)) {
7790
+ const columnName = columnNode.column.name;
7791
+ if (idFields.includes(columnName)) {
7792
+ return void 0;
7793
+ }
7794
+ }
7795
+ }
7796
+ }
7797
+ }
7798
+ return await this.loadEntities(this.getMutationModel(query), query.where, connection, idFields);
7799
+ }
7800
+ getInsertIds(mutationModel, query, queryResult) {
7801
+ const idFields = requireIdFields(this.client.$schema, mutationModel);
7802
+ if (import_kysely8.InsertQueryNode.is(query) && queryResult.numAffectedRows === 1n && queryResult.insertId && idFields.length === 1) {
7803
+ return [
7804
+ {
7805
+ [idFields[0]]: queryResult.insertId
7806
+ }
7807
+ ];
7808
+ }
7809
+ const columns = query.columns;
7810
+ if (!columns) {
7811
+ return void 0;
7812
+ }
7813
+ const values = query.values;
7814
+ if (!values || !import_kysely8.ValuesNode.is(values)) {
7815
+ return void 0;
7816
+ }
7817
+ const allIds = [];
7818
+ for (const valuesItem of values.values) {
7819
+ const rowIds = {};
7820
+ if (import_kysely8.PrimitiveValueListNode.is(valuesItem)) {
7821
+ (0, import_common_helpers11.invariant)(valuesItem.values.length === columns.length, "Values count must match columns count");
7822
+ for (const idField of idFields) {
7823
+ const colIndex = columns.findIndex((col) => col.column.name === idField);
7824
+ if (colIndex === -1) {
7825
+ return void 0;
7826
+ }
7827
+ rowIds[idField] = valuesItem.values[colIndex];
7828
+ }
7829
+ } else {
7830
+ (0, import_common_helpers11.invariant)(valuesItem.values.length === columns.length, "Values count must match columns count");
7831
+ for (const idField of idFields) {
7832
+ const colIndex = columns.findIndex((col) => col.column.name === idField);
7833
+ if (colIndex === -1) {
7834
+ return void 0;
7835
+ }
7836
+ const valueNode = valuesItem.values[colIndex];
7837
+ if (!valueNode || !import_kysely8.ValueNode.is(valueNode)) {
7838
+ return void 0;
7839
+ }
7840
+ rowIds[idField] = valueNode.value;
7841
+ }
7842
+ }
7843
+ allIds.push(rowIds);
7844
+ }
7845
+ return allIds;
7846
+ }
7847
+ async loadEntities(model, where, connection, fieldsToLoad) {
7848
+ let selectQuery = this.kysely.selectFrom(model);
7849
+ if (fieldsToLoad) {
7850
+ selectQuery = selectQuery.select(fieldsToLoad);
7851
+ } else {
7852
+ selectQuery = selectQuery.selectAll();
7853
+ }
6851
7854
  let selectQueryNode = selectQuery.toOperationNode();
6852
7855
  selectQueryNode = {
6853
7856
  ...selectQueryNode,
6854
7857
  where: this.andNodes(selectQueryNode.where, where)
6855
7858
  };
6856
- const compiled = this.compileQuery(selectQueryNode, (0, import_kysely7.createQueryId)());
6857
- const result = await this.internalExecuteQuery(connection, compiled);
7859
+ const result = await this.internalExecuteQuery(selectQueryNode, connection);
6858
7860
  return result.rows;
6859
7861
  }
7862
+ // #endregion
7863
+ // #region utilities
7864
+ getMutationInfo(queryNode) {
7865
+ const model = this.getMutationModel(queryNode);
7866
+ const { action, where } = (0, import_ts_pattern15.match)(queryNode).when(import_kysely8.InsertQueryNode.is, () => ({
7867
+ action: "create",
7868
+ where: void 0
7869
+ })).when(import_kysely8.UpdateQueryNode.is, (node) => ({
7870
+ action: "update",
7871
+ where: node.where
7872
+ })).when(import_kysely8.DeleteQueryNode.is, (node) => ({
7873
+ action: "delete",
7874
+ where: node.where
7875
+ })).exhaustive();
7876
+ return {
7877
+ model,
7878
+ action,
7879
+ where
7880
+ };
7881
+ }
7882
+ isMutationNode(queryNode) {
7883
+ return import_kysely8.InsertQueryNode.is(queryNode) || import_kysely8.UpdateQueryNode.is(queryNode) || import_kysely8.DeleteQueryNode.is(queryNode);
7884
+ }
7885
+ getMutationModel(queryNode) {
7886
+ return (0, import_ts_pattern15.match)(queryNode).when(import_kysely8.InsertQueryNode.is, (node) => {
7887
+ (0, import_common_helpers11.invariant)(node.into, "InsertQueryNode must have an into clause");
7888
+ return node.into.table.identifier.name;
7889
+ }).when(import_kysely8.UpdateQueryNode.is, (node) => {
7890
+ (0, import_common_helpers11.invariant)(node.table, "UpdateQueryNode must have a table");
7891
+ const { node: tableNode } = stripAlias(node.table);
7892
+ (0, import_common_helpers11.invariant)(import_kysely8.TableNode.is(tableNode), "UpdateQueryNode must use a TableNode");
7893
+ return tableNode.table.identifier.name;
7894
+ }).when(import_kysely8.DeleteQueryNode.is, (node) => {
7895
+ (0, import_common_helpers11.invariant)(node.from.froms.length === 1, "Delete query must have exactly one from table");
7896
+ const { node: tableNode } = stripAlias(node.from.froms[0]);
7897
+ (0, import_common_helpers11.invariant)(import_kysely8.TableNode.is(tableNode), "DeleteQueryNode must use a TableNode");
7898
+ return tableNode.table.identifier.name;
7899
+ }).otherwise((node) => {
7900
+ throw createInternalError(`Invalid query node: ${node}`);
7901
+ });
7902
+ }
7903
+ processNameMapping(query) {
7904
+ return this.nameMapper?.transformNode(query) ?? query;
7905
+ }
7906
+ createClientForConnection(connection, inTx) {
7907
+ const innerExecutor = this.withConnectionProvider(new import_kysely8.SingleConnectionProvider(connection));
7908
+ innerExecutor.suppressMutationHooks = true;
7909
+ const innerClient = this.client.withExecutor(innerExecutor);
7910
+ if (inTx) {
7911
+ innerClient.forceTransaction();
7912
+ }
7913
+ return innerClient;
7914
+ }
6860
7915
  andNodes(condition1, condition2) {
6861
7916
  if (condition1 && condition2) {
6862
- return import_kysely7.WhereNode.create(import_kysely7.AndNode.create(condition1, condition2));
7917
+ return import_kysely8.WhereNode.create(import_kysely8.AndNode.create(condition1, condition2));
6863
7918
  } else if (condition1) {
6864
- return import_kysely7.WhereNode.create(condition1);
7919
+ return import_kysely8.WhereNode.create(condition1);
6865
7920
  } else {
6866
7921
  return condition2;
6867
7922
  }
6868
7923
  }
6869
- async internalExecuteQuery(connection, compiledQuery) {
7924
+ async internalExecuteQuery(query, connection, queryId, parameters) {
7925
+ const finalQuery = this.processNameMapping(query);
7926
+ let compiledQuery = this.compileQuery(finalQuery, queryId ?? (0, import_kysely8.createQueryId)());
7927
+ if (parameters) {
7928
+ compiledQuery = {
7929
+ ...compiledQuery,
7930
+ parameters
7931
+ };
7932
+ }
6870
7933
  try {
6871
- return await connection.executeQuery(compiledQuery);
7934
+ const result = await connection.executeQuery(compiledQuery);
7935
+ return this.ensureProperQueryResult(compiledQuery.query, result);
6872
7936
  } catch (err) {
6873
7937
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiledQuery.sql, compiledQuery.parameters);
6874
7938
  }
6875
7939
  }
7940
+ ensureProperQueryResult(query, result) {
7941
+ let finalResult = result;
7942
+ if (this.isMutationNode(query)) {
7943
+ finalResult = {
7944
+ ...result,
7945
+ numAffectedRows: result.numAffectedRows ?? BigInt(result.rows.length)
7946
+ };
7947
+ }
7948
+ return finalResult;
7949
+ }
7950
+ // #endregion
7951
+ // #region other overrides
7952
+ withPlugin(plugin) {
7953
+ return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
7954
+ ...this.plugins,
7955
+ plugin
7956
+ ], this.suppressMutationHooks);
7957
+ }
7958
+ withPlugins(plugins) {
7959
+ return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
7960
+ ...this.plugins,
7961
+ ...plugins
7962
+ ], this.suppressMutationHooks);
7963
+ }
7964
+ withPluginAtFront(plugin) {
7965
+ return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
7966
+ plugin,
7967
+ ...this.plugins
7968
+ ], this.suppressMutationHooks);
7969
+ }
7970
+ withoutPlugins() {
7971
+ return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks);
7972
+ }
7973
+ withConnectionProvider(connectionProvider) {
7974
+ const newExecutor = new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks);
7975
+ newExecutor.client = this.client.withExecutor(newExecutor);
7976
+ return newExecutor;
7977
+ }
6876
7978
  };
6877
7979
 
6878
7980
  // src/client/functions.ts
@@ -6890,9 +7992,9 @@ __export(functions_exports, {
6890
7992
  search: () => search,
6891
7993
  startsWith: () => startsWith
6892
7994
  });
6893
- var import_common_helpers10 = require("@zenstackhq/common-helpers");
6894
- var import_kysely8 = require("kysely");
6895
- var import_ts_pattern15 = require("ts-pattern");
7995
+ var import_common_helpers12 = require("@zenstackhq/common-helpers");
7996
+ var import_kysely9 = require("kysely");
7997
+ var import_ts_pattern16 = require("ts-pattern");
6896
7998
  var contains = /* @__PURE__ */ __name((eb, args, context) => textMatch(eb, args, context, "contains"), "contains");
6897
7999
  var search = /* @__PURE__ */ __name((_eb, _args) => {
6898
8000
  throw new Error(`"search" function is not implemented yet`);
@@ -6929,19 +8031,20 @@ var textMatch = /* @__PURE__ */ __name((eb, args, { dialect }, method) => {
6929
8031
  } else {
6930
8032
  op = "like";
6931
8033
  }
6932
- const escapedSearch = import_kysely8.sql`REPLACE(REPLACE(REPLACE(CAST(${searchExpr} as text), '\\', '\\\\'), '%', '\\%'), '_', '\\_')`;
6933
- searchExpr = (0, import_ts_pattern15.match)(method).with("contains", () => eb.fn("CONCAT", [
6934
- import_kysely8.sql.lit("%"),
8034
+ searchExpr = eb.fn.coalesce(searchExpr, import_kysely9.sql.lit(""));
8035
+ const escapedSearch = import_kysely9.sql`REPLACE(REPLACE(REPLACE(${dialect.castText(searchExpr)}, ${import_kysely9.sql.val("\\")}, ${import_kysely9.sql.val("\\\\")}), ${import_kysely9.sql.val("%")}, ${import_kysely9.sql.val("\\%")}), ${import_kysely9.sql.val("_")}, ${import_kysely9.sql.val("\\_")})`;
8036
+ searchExpr = (0, import_ts_pattern16.match)(method).with("contains", () => eb.fn("CONCAT", [
8037
+ import_kysely9.sql.lit("%"),
6935
8038
  escapedSearch,
6936
- import_kysely8.sql.lit("%")
8039
+ import_kysely9.sql.lit("%")
6937
8040
  ])).with("startsWith", () => eb.fn("CONCAT", [
6938
8041
  escapedSearch,
6939
- import_kysely8.sql.lit("%")
8042
+ import_kysely9.sql.lit("%")
6940
8043
  ])).with("endsWith", () => eb.fn("CONCAT", [
6941
- import_kysely8.sql.lit("%"),
8044
+ import_kysely9.sql.lit("%"),
6942
8045
  escapedSearch
6943
8046
  ])).exhaustive();
6944
- return import_kysely8.sql`${fieldExpr} ${import_kysely8.sql.raw(op)} ${searchExpr} escape '\\'`;
8047
+ return import_kysely9.sql`${fieldExpr} ${import_kysely9.sql.raw(op)} ${searchExpr} escape ${import_kysely9.sql.val("\\")}`;
6945
8048
  }, "textMatch");
6946
8049
  var has = /* @__PURE__ */ __name((eb, args) => {
6947
8050
  const [field, search2] = args;
@@ -6980,16 +8083,16 @@ var isEmpty = /* @__PURE__ */ __name((eb, args, { dialect }) => {
6980
8083
  if (!field) {
6981
8084
  throw new Error('"field" parameter is required');
6982
8085
  }
6983
- return eb(dialect.buildArrayLength(field), "=", import_kysely8.sql.lit(0));
8086
+ return eb(dialect.buildArrayLength(field), "=", import_kysely9.sql.lit(0));
6984
8087
  }, "isEmpty");
6985
- var now = /* @__PURE__ */ __name(() => import_kysely8.sql.raw("CURRENT_TIMESTAMP"), "now");
8088
+ var now = /* @__PURE__ */ __name(() => import_kysely9.sql.raw("CURRENT_TIMESTAMP"), "now");
6986
8089
  var currentModel = /* @__PURE__ */ __name((_eb, args, { model }) => {
6987
8090
  let result = model;
6988
8091
  const [casing] = args;
6989
8092
  if (casing) {
6990
8093
  result = processCasing(casing, result, model);
6991
8094
  }
6992
- return import_kysely8.sql.lit(result);
8095
+ return import_kysely9.sql.lit(result);
6993
8096
  }, "currentModel");
6994
8097
  var currentOperation = /* @__PURE__ */ __name((_eb, args, { operation }) => {
6995
8098
  let result = operation;
@@ -6997,12 +8100,12 @@ var currentOperation = /* @__PURE__ */ __name((_eb, args, { operation }) => {
6997
8100
  if (casing) {
6998
8101
  result = processCasing(casing, result, operation);
6999
8102
  }
7000
- return import_kysely8.sql.lit(result);
8103
+ return import_kysely9.sql.lit(result);
7001
8104
  }, "currentOperation");
7002
8105
  function processCasing(casing, result, model) {
7003
8106
  const opNode = casing.toOperationNode();
7004
- (0, import_common_helpers10.invariant)(import_kysely8.ValueNode.is(opNode) && typeof opNode.value === "string", '"casting" parameter must be a string value');
7005
- result = (0, import_ts_pattern15.match)(opNode.value).with("original", () => model).with("upper", () => result.toUpperCase()).with("lower", () => result.toLowerCase()).with("capitalize", () => (0, import_common_helpers10.upperCaseFirst)(result)).with("uncapitalize", () => (0, import_common_helpers10.lowerCaseFirst)(result)).otherwise(() => {
8107
+ (0, import_common_helpers12.invariant)(import_kysely9.ValueNode.is(opNode) && typeof opNode.value === "string", '"casting" parameter must be a string value');
8108
+ result = (0, import_ts_pattern16.match)(opNode.value).with("original", () => model).with("upper", () => result.toUpperCase()).with("lower", () => result.toLowerCase()).with("capitalize", () => (0, import_common_helpers12.upperCaseFirst)(result)).with("uncapitalize", () => (0, import_common_helpers12.lowerCaseFirst)(result)).otherwise(() => {
7006
8109
  throw new Error(`Invalid casing value: ${opNode.value}. Must be "original", "upper", "lower", "capitalize", or "uncapitalize".`);
7007
8110
  });
7008
8111
  return result;
@@ -7013,16 +8116,16 @@ function readBoolean(expr, defaultValue) {
7013
8116
  return defaultValue;
7014
8117
  }
7015
8118
  const opNode = expr.toOperationNode();
7016
- (0, import_common_helpers10.invariant)(import_kysely8.ValueNode.is(opNode), "expression must be a literal value");
8119
+ (0, import_common_helpers12.invariant)(import_kysely9.ValueNode.is(opNode), "expression must be a literal value");
7017
8120
  return !!opNode.value;
7018
8121
  }
7019
8122
  __name(readBoolean, "readBoolean");
7020
8123
 
7021
8124
  // src/client/helpers/schema-db-pusher.ts
7022
- var import_common_helpers11 = require("@zenstackhq/common-helpers");
7023
- var import_kysely9 = require("kysely");
8125
+ var import_common_helpers13 = require("@zenstackhq/common-helpers");
8126
+ var import_kysely10 = require("kysely");
7024
8127
  var import_toposort = __toESM(require("toposort"), 1);
7025
- var import_ts_pattern16 = require("ts-pattern");
8128
+ var import_ts_pattern17 = require("ts-pattern");
7026
8129
  var SchemaDbPusher = class {
7027
8130
  static {
7028
8131
  __name(this, "SchemaDbPusher");
@@ -7035,7 +8138,7 @@ var SchemaDbPusher = class {
7035
8138
  }
7036
8139
  async push() {
7037
8140
  await this.kysely.transaction().execute(async (tx) => {
7038
- if (this.schema.enums && this.schema.provider.type === "postgresql") {
8141
+ if (this.schema.enums && this.providerSupportsNativeEnum) {
7039
8142
  for (const [name, enumDef] of Object.entries(this.schema.enums)) {
7040
8143
  let enumValues;
7041
8144
  if (enumDef.fields) {
@@ -7045,7 +8148,7 @@ var SchemaDbPusher = class {
7045
8148
  return f.name;
7046
8149
  } else {
7047
8150
  const mappedName = schema_exports.ExpressionUtils.getLiteralValue(mapAttr.args[0].value);
7048
- (0, import_common_helpers11.invariant)(mappedName && typeof mappedName === "string", `Invalid @map attribute for enum field ${f.name}`);
8151
+ (0, import_common_helpers13.invariant)(mappedName && typeof mappedName === "string", `Invalid @map attribute for enum field ${f.name}`);
7049
8152
  return mappedName;
7050
8153
  }
7051
8154
  });
@@ -7064,6 +8167,11 @@ var SchemaDbPusher = class {
7064
8167
  }
7065
8168
  });
7066
8169
  }
8170
+ get providerSupportsNativeEnum() {
8171
+ return [
8172
+ "postgresql"
8173
+ ].includes(this.schema.provider.type);
8174
+ }
7067
8175
  sortModels(models) {
7068
8176
  const graph = [];
7069
8177
  for (const model of models) {
@@ -7109,7 +8217,7 @@ var SchemaDbPusher = class {
7109
8217
  }
7110
8218
  if (modelDef.baseModel) {
7111
8219
  const baseModelDef = requireModel(this.schema, modelDef.baseModel);
7112
- table = table.addForeignKeyConstraint(`fk_${modelDef.baseModel}_delegate`, baseModelDef.idFields, modelDef.baseModel, baseModelDef.idFields, (cb) => cb.onDelete("cascade").onUpdate("cascade"));
8220
+ table = table.addForeignKeyConstraint(`fk_${modelDef.baseModel}_${modelDef.name}_delegate`, baseModelDef.idFields, modelDef.baseModel, baseModelDef.idFields, (cb) => cb.onDelete("cascade").onUpdate("cascade"));
7113
8221
  }
7114
8222
  table = this.addPrimaryKeyConstraint(table, modelDef);
7115
8223
  table = this.addUniqueConstraint(table, modelDef);
@@ -7151,7 +8259,7 @@ var SchemaDbPusher = class {
7151
8259
  }
7152
8260
  addUniqueConstraint(table, modelDef) {
7153
8261
  for (const [key, value] of Object.entries(modelDef.uniqueFields)) {
7154
- (0, import_common_helpers11.invariant)(typeof value === "object", "expecting an object");
8262
+ (0, import_common_helpers13.invariant)(typeof value === "object", "expecting an object");
7155
8263
  if ("type" in value) {
7156
8264
  const fieldDef = modelDef.fields[key];
7157
8265
  if (fieldDef.unique) {
@@ -7180,13 +8288,18 @@ var SchemaDbPusher = class {
7180
8288
  if (fieldDef.id && modelDef.idFields.length === 1) {
7181
8289
  col = col.primaryKey();
7182
8290
  }
7183
- if (fieldDef.default !== void 0) {
8291
+ if (fieldDef.default !== void 0 && this.isDefaultValueSupportedForType(fieldDef.type)) {
7184
8292
  if (typeof fieldDef.default === "object" && "kind" in fieldDef.default) {
7185
8293
  if (schema_exports.ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "now") {
7186
- col = col.defaultTo(import_kysely9.sql`CURRENT_TIMESTAMP`);
8294
+ col = this.schema.provider.type === "mysql" ? col.defaultTo(import_kysely10.sql`CURRENT_TIMESTAMP(3)`) : col.defaultTo(import_kysely10.sql`CURRENT_TIMESTAMP`);
7187
8295
  }
7188
8296
  } else {
7189
- col = col.defaultTo(fieldDef.default);
8297
+ if (this.schema.provider.type === "mysql" && fieldDef.type === "DateTime" && typeof fieldDef.default === "string") {
8298
+ const defaultValue = new Date(fieldDef.default).toISOString().replace("Z", "+00:00");
8299
+ col = col.defaultTo(defaultValue);
8300
+ } else {
8301
+ col = col.defaultTo(fieldDef.default);
8302
+ }
7190
8303
  }
7191
8304
  }
7192
8305
  if (fieldDef.unique) {
@@ -7195,28 +8308,56 @@ var SchemaDbPusher = class {
7195
8308
  if (!fieldDef.optional && !fieldDef.array) {
7196
8309
  col = col.notNull();
7197
8310
  }
7198
- if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "sqlite") {
8311
+ if (this.isAutoIncrement(fieldDef) && this.columnSupportsAutoIncrement()) {
7199
8312
  col = col.autoIncrement();
7200
8313
  }
7201
8314
  return col;
7202
8315
  });
7203
8316
  }
8317
+ isDefaultValueSupportedForType(type) {
8318
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("postgresql", () => true).with("sqlite", () => true).with("mysql", () => ![
8319
+ "Json",
8320
+ "Bytes"
8321
+ ].includes(type)).exhaustive();
8322
+ }
7204
8323
  mapFieldType(fieldDef) {
7205
8324
  if (this.schema.enums?.[fieldDef.type]) {
7206
- return this.schema.provider.type === "postgresql" ? import_kysely9.sql.ref(fieldDef.type) : "text";
8325
+ if (this.schema.provider.type === "postgresql") {
8326
+ return import_kysely10.sql.ref(fieldDef.type);
8327
+ } else if (this.schema.provider.type === "mysql") {
8328
+ const enumDef = this.schema.enums[fieldDef.type];
8329
+ let enumValues;
8330
+ if (enumDef.fields) {
8331
+ enumValues = Object.values(enumDef.fields).map((f) => {
8332
+ const mapAttr = f.attributes?.find((a) => a.name === "@map");
8333
+ if (!mapAttr || !mapAttr.args?.[0]) {
8334
+ return f.name;
8335
+ } else {
8336
+ const mappedName = schema_exports.ExpressionUtils.getLiteralValue(mapAttr.args[0].value);
8337
+ (0, import_common_helpers13.invariant)(mappedName && typeof mappedName === "string", `Invalid @map attribute for enum field ${f.name}`);
8338
+ return mappedName;
8339
+ }
8340
+ });
8341
+ } else {
8342
+ enumValues = Object.values(enumDef.values);
8343
+ }
8344
+ return import_kysely10.sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
8345
+ } else {
8346
+ return "text";
8347
+ }
7207
8348
  }
7208
8349
  if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") {
7209
8350
  return "serial";
7210
8351
  }
7211
8352
  if (this.isCustomType(fieldDef.type)) {
7212
- return "jsonb";
8353
+ return this.jsonType;
7213
8354
  }
7214
8355
  const type = fieldDef.type;
7215
- const result = (0, import_ts_pattern16.match)(type).with("String", () => "text").with("Boolean", () => "boolean").with("Int", () => "integer").with("Float", () => "real").with("BigInt", () => "bigint").with("Decimal", () => "decimal").with("DateTime", () => "timestamp").with("Bytes", () => this.schema.provider.type === "postgresql" ? "bytea" : "blob").with("Json", () => "jsonb").otherwise(() => {
8356
+ const result = (0, import_ts_pattern17.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(() => {
7216
8357
  throw new Error(`Unsupported field type: ${type}`);
7217
8358
  });
7218
8359
  if (fieldDef.array) {
7219
- return import_kysely9.sql.raw(`${result}[]`);
8360
+ return import_kysely10.sql.raw(`${result}[]`);
7220
8361
  } else {
7221
8362
  return result;
7222
8363
  }
@@ -7228,7 +8369,7 @@ var SchemaDbPusher = class {
7228
8369
  return fieldDef.default && schema_exports.ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "autoincrement";
7229
8370
  }
7230
8371
  addForeignKeyConstraint(table, model, fieldName, fieldDef) {
7231
- (0, import_common_helpers11.invariant)(fieldDef.relation, "field must be a relation");
8372
+ (0, import_common_helpers13.invariant)(fieldDef.relation, "field must be a relation");
7232
8373
  if (!fieldDef.relation.fields || !fieldDef.relation.references) {
7233
8374
  return table;
7234
8375
  }
@@ -7252,7 +8393,41 @@ var SchemaDbPusher = class {
7252
8393
  return table;
7253
8394
  }
7254
8395
  mapCascadeAction(action) {
7255
- return (0, import_ts_pattern16.match)(action).with("SetNull", () => "set null").with("Cascade", () => "cascade").with("Restrict", () => "restrict").with("NoAction", () => "no action").with("SetDefault", () => "set default").exhaustive();
8396
+ return (0, import_ts_pattern17.match)(action).with("SetNull", () => "set null").with("Cascade", () => "cascade").with("Restrict", () => "restrict").with("NoAction", () => "no action").with("SetDefault", () => "set default").exhaustive();
8397
+ }
8398
+ // #region Type mappings and capabilities
8399
+ get jsonType() {
8400
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => "json").otherwise(() => "jsonb");
8401
+ }
8402
+ get bytesType() {
8403
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("postgresql", () => "bytea").with("mysql", () => "blob").otherwise(() => "blob");
8404
+ }
8405
+ get stringType() {
8406
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => import_kysely10.sql.raw("varchar(255)")).otherwise(() => "text");
8407
+ }
8408
+ get booleanType() {
8409
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => import_kysely10.sql.raw("tinyint(1)")).otherwise(() => "boolean");
8410
+ }
8411
+ get intType() {
8412
+ return "integer";
8413
+ }
8414
+ get floatType() {
8415
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => import_kysely10.sql.raw("double")).otherwise(() => "real");
8416
+ }
8417
+ get bigIntType() {
8418
+ return "bigint";
8419
+ }
8420
+ get decimalType() {
8421
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => import_kysely10.sql.raw("decimal(65, 30)")).otherwise(() => "decimal");
8422
+ }
8423
+ get dateTimeType() {
8424
+ return (0, import_ts_pattern17.match)(this.schema.provider.type).with("mysql", () => import_kysely10.sql.raw("datetime(3)")).otherwise(() => "timestamp");
8425
+ }
8426
+ columnSupportsAutoIncrement() {
8427
+ return [
8428
+ "sqlite",
8429
+ "mysql"
8430
+ ].includes(this.schema.provider.type);
7256
8431
  }
7257
8432
  };
7258
8433
 
@@ -7434,15 +8609,15 @@ var ClientImpl = class _ClientImpl {
7434
8609
  if (baseClient) {
7435
8610
  this.kyselyProps = {
7436
8611
  ...baseClient.kyselyProps,
7437
- executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new import_kysely10.DefaultConnectionProvider(baseClient.kyselyProps.driver))
8612
+ executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new import_kysely11.DefaultConnectionProvider(baseClient.kyselyProps.driver))
7438
8613
  };
7439
8614
  this.kyselyRaw = baseClient.kyselyRaw;
7440
8615
  this.auth = baseClient.auth;
7441
8616
  } else {
7442
- const driver = new ZenStackDriver(options.dialect.createDriver(), new import_kysely10.Log(this.$options.log ?? []));
8617
+ const driver = new ZenStackDriver(options.dialect.createDriver(), new import_kysely11.Log(this.$options.log ?? []));
7443
8618
  const compiler = options.dialect.createQueryCompiler();
7444
8619
  const adapter = options.dialect.createAdapter();
7445
- const connectionProvider = new import_kysely10.DefaultConnectionProvider(driver);
8620
+ const connectionProvider = new import_kysely11.DefaultConnectionProvider(driver);
7446
8621
  this.kyselyProps = {
7447
8622
  config: {
7448
8623
  dialect: options.dialect,
@@ -7452,12 +8627,12 @@ var ClientImpl = class _ClientImpl {
7452
8627
  driver,
7453
8628
  executor: executor ?? new ZenStackQueryExecutor(this, driver, compiler, adapter, connectionProvider)
7454
8629
  };
7455
- this.kyselyRaw = new import_kysely10.Kysely({
8630
+ this.kyselyRaw = new import_kysely11.Kysely({
7456
8631
  ...this.kyselyProps,
7457
- executor: new import_kysely10.DefaultQueryExecutor(compiler, adapter, connectionProvider, [])
8632
+ executor: new import_kysely11.DefaultQueryExecutor(compiler, adapter, connectionProvider, [])
7458
8633
  });
7459
8634
  }
7460
- this.kysely = new import_kysely10.Kysely(this.kyselyProps);
8635
+ this.kysely = new import_kysely11.Kysely(this.kyselyProps);
7461
8636
  this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this);
7462
8637
  return createClientProxy(this);
7463
8638
  }
@@ -7478,7 +8653,7 @@ var ClientImpl = class _ClientImpl {
7478
8653
  }
7479
8654
  // implementation
7480
8655
  async $transaction(input, options) {
7481
- (0, import_common_helpers12.invariant)(typeof input === "function" || Array.isArray(input) && input.every((p) => p.then && p.cb), "Invalid transaction input, expected a function or an array of ZenStackPromise");
8656
+ (0, import_common_helpers14.invariant)(typeof input === "function" || Array.isArray(input) && input.every((p) => p.then && p.cb), "Invalid transaction input, expected a function or an array of ZenStackPromise");
7482
8657
  if (typeof input === "function") {
7483
8658
  return this.interactiveTransaction(input, options);
7484
8659
  } else {
@@ -7487,7 +8662,7 @@ var ClientImpl = class _ClientImpl {
7487
8662
  }
7488
8663
  forceTransaction() {
7489
8664
  if (!this.kysely.isTransaction) {
7490
- this.kysely = new import_kysely10.Transaction(this.kyselyProps);
8665
+ this.kysely = new import_kysely11.Transaction(this.kyselyProps);
7491
8666
  }
7492
8667
  }
7493
8668
  async interactiveTransaction(callback, options) {
@@ -7575,7 +8750,7 @@ var ClientImpl = class _ClientImpl {
7575
8750
  }
7576
8751
  async $connect() {
7577
8752
  await this.kysely.connection().execute(async (conn) => {
7578
- await conn.executeQuery(import_kysely10.sql`select 1`.compile(this.kysely));
8753
+ await conn.executeQuery(import_kysely11.sql`select 1`.compile(this.kysely));
7579
8754
  });
7580
8755
  }
7581
8756
  async $disconnect() {
@@ -7646,7 +8821,7 @@ var ClientImpl = class _ClientImpl {
7646
8821
  }
7647
8822
  $executeRaw(query, ...values) {
7648
8823
  return createZenStackPromise(async () => {
7649
- const result = await (0, import_kysely10.sql)(query, ...values).execute(this.kysely);
8824
+ const result = await (0, import_kysely11.sql)(query, ...values).execute(this.kysely);
7650
8825
  return Number(result.numAffectedRows ?? 0);
7651
8826
  });
7652
8827
  }
@@ -7659,7 +8834,7 @@ var ClientImpl = class _ClientImpl {
7659
8834
  }
7660
8835
  $queryRaw(query, ...values) {
7661
8836
  return createZenStackPromise(async () => {
7662
- const result = await (0, import_kysely10.sql)(query, ...values).execute(this.kysely);
8837
+ const result = await (0, import_kysely11.sql)(query, ...values).execute(this.kysely);
7663
8838
  return result.rows;
7664
8839
  });
7665
8840
  }
@@ -7671,7 +8846,7 @@ var ClientImpl = class _ClientImpl {
7671
8846
  });
7672
8847
  }
7673
8848
  createRawCompiledQuery(query, values) {
7674
- const q = import_kysely10.CompiledQuery.raw(query, values);
8849
+ const q = import_kysely11.CompiledQuery.raw(query, values);
7675
8850
  return {
7676
8851
  ...q,
7677
8852
  $raw: true
@@ -7768,6 +8943,9 @@ function createModelCrudHandler(client, model, inputValidator, resultProcessor)
7768
8943
  return createPromise("createMany", "createMany", args, new CreateOperationHandler(client, model, inputValidator), false);
7769
8944
  }, "createMany"),
7770
8945
  createManyAndReturn: /* @__PURE__ */ __name((args) => {
8946
+ if (client.$schema.provider.type === "mysql") {
8947
+ throw createNotSupportedError('"createManyAndReturn" is not supported by "mysql" provider. Use "createMany" or multiple "create" calls instead.');
8948
+ }
7771
8949
  return createPromise("createManyAndReturn", "createManyAndReturn", args, new CreateOperationHandler(client, model, inputValidator), true);
7772
8950
  }, "createManyAndReturn"),
7773
8951
  update: /* @__PURE__ */ __name((args) => {
@@ -7777,6 +8955,9 @@ function createModelCrudHandler(client, model, inputValidator, resultProcessor)
7777
8955
  return createPromise("updateMany", "updateMany", args, new UpdateOperationHandler(client, model, inputValidator), false);
7778
8956
  }, "updateMany"),
7779
8957
  updateManyAndReturn: /* @__PURE__ */ __name((args) => {
8958
+ if (client.$schema.provider.type === "mysql") {
8959
+ throw createNotSupportedError('"updateManyAndReturn" is not supported by "mysql" provider. Use "updateMany" or multiple "update" calls instead.');
8960
+ }
7780
8961
  return createPromise("updateManyAndReturn", "updateManyAndReturn", args, new UpdateOperationHandler(client, model, inputValidator), true);
7781
8962
  }, "updateManyAndReturn"),
7782
8963
  upsert: /* @__PURE__ */ __name((args) => {
@@ -7815,8 +8996,8 @@ var kysely_utils_exports = {};
7815
8996
  __export(kysely_utils_exports, {
7816
8997
  DefaultOperationNodeVisitor: () => DefaultOperationNodeVisitor
7817
8998
  });
7818
- var import_kysely11 = require("kysely");
7819
- var DefaultOperationNodeVisitor = class extends import_kysely11.OperationNodeVisitor {
8999
+ var import_kysely12 = require("kysely");
9000
+ var DefaultOperationNodeVisitor = class extends import_kysely12.OperationNodeVisitor {
7820
9001
  static {
7821
9002
  __name(this, "DefaultOperationNodeVisitor");
7822
9003
  }
@@ -8132,13 +9313,13 @@ __export(schema_utils_exports, {
8132
9313
  ExpressionVisitor: () => ExpressionVisitor,
8133
9314
  MatchingExpressionVisitor: () => MatchingExpressionVisitor
8134
9315
  });
8135
- var import_ts_pattern17 = require("ts-pattern");
9316
+ var import_ts_pattern18 = require("ts-pattern");
8136
9317
  var ExpressionVisitor = class {
8137
9318
  static {
8138
9319
  __name(this, "ExpressionVisitor");
8139
9320
  }
8140
9321
  visit(expr) {
8141
- return (0, import_ts_pattern17.match)(expr).with({
9322
+ return (0, import_ts_pattern18.match)(expr).with({
8142
9323
  kind: "literal"
8143
9324
  }, (e) => this.visitLiteral(e)).with({
8144
9325
  kind: "array"
@@ -8153,6 +9334,8 @@ var ExpressionVisitor = class {
8153
9334
  }, (e) => this.visitUnary(e)).with({
8154
9335
  kind: "call"
8155
9336
  }, (e) => this.visitCall(e)).with({
9337
+ kind: "binding"
9338
+ }, (e) => this.visitBinding(e)).with({
8156
9339
  kind: "this"
8157
9340
  }, (e) => this.visitThis(e)).with({
8158
9341
  kind: "null"
@@ -8192,6 +9375,8 @@ var ExpressionVisitor = class {
8192
9375
  }
8193
9376
  }
8194
9377
  }
9378
+ visitBinding(_e) {
9379
+ }
8195
9380
  visitThis(_e) {
8196
9381
  }
8197
9382
  visitNull(_e) {