@zenstackhq/orm 3.9.0-beta.1 → 3.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -24,26 +24,6 @@ function formatError(error) {
24
24
  return fromError(error).toString();
25
25
  }
26
26
  //#endregion
27
- //#region src/utils/object-utils.ts
28
- /**
29
- * Extract fields from an object.
30
- */
31
- function extractFields(obj, fields) {
32
- return Object.fromEntries(Object.entries(obj).filter(([key]) => fields.includes(key)));
33
- }
34
- /**
35
- * Create an object with fields as keys and true values.
36
- */
37
- function fieldsToSelectObject(fields) {
38
- return Object.fromEntries(fields.map((f) => [f, true]));
39
- }
40
- /**
41
- * Checks if the given value is an empty plain object.
42
- */
43
- function isEmptyObject(x) {
44
- return isPlainObject(x) && Object.keys(x).length === 0;
45
- }
46
- //#endregion
47
27
  //#region src/client/executor/error-processor.ts
48
28
  /**
49
29
  * Extracts database error code from an error thrown by the database driver.
@@ -177,6 +157,26 @@ function createInternalError(message, model, options) {
177
157
  return error;
178
158
  }
179
159
  //#endregion
160
+ //#region src/utils/object-utils.ts
161
+ /**
162
+ * Extract fields from an object.
163
+ */
164
+ function extractFields(obj, fields) {
165
+ return Object.fromEntries(Object.entries(obj).filter(([key]) => fields.includes(key)));
166
+ }
167
+ /**
168
+ * Create an object with fields as keys and true values.
169
+ */
170
+ function fieldsToSelectObject(fields) {
171
+ return Object.fromEntries(fields.map((f) => [f, true]));
172
+ }
173
+ /**
174
+ * Checks if the given value is an empty plain object.
175
+ */
176
+ function isEmptyObject(x) {
177
+ return isPlainObject(x) && Object.keys(x).length === 0;
178
+ }
179
+ //#endregion
180
180
  //#region src/client/query-utils.ts
181
181
  var query_utils_exports = /* @__PURE__ */ __exportAll({
182
182
  TEMP_ALIAS_PREFIX: () => "$$_",
@@ -215,6 +215,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
215
215
  requireIdFields: () => requireIdFields,
216
216
  requireModel: () => requireModel,
217
217
  requireTypeDef: () => requireTypeDef,
218
+ schemaHasMappedNames: () => schemaHasMappedNames,
218
219
  stripAlias: () => stripAlias,
219
220
  tmpAlias: () => tmpAlias
220
221
  });
@@ -244,6 +245,22 @@ function getModel(schema, model) {
244
245
  function getTypeDef(schema, type) {
245
246
  return schema.typeDefs?.[type];
246
247
  }
248
+ /**
249
+ * Whether any model, type def, or field in the schema carries `@@map`/`@map`. Answering it walks
250
+ * every model and field, and it is asked once per query-executor construction, so the (immutable)
251
+ * answer is memoized per schema alongside the other structural lookups. See issue #2773.
252
+ */
253
+ function schemaHasMappedNames(schema) {
254
+ const cache = getSchemaLookupCache(schema);
255
+ if (cache.hasMappedNames === void 0) {
256
+ const hasMapAttr = (decl) => {
257
+ if (decl.attributes?.some((attr) => attr.name === "@@map")) return true;
258
+ return Object.values(decl.fields ?? {}).some((field) => field.attributes?.some((attr) => attr.name === "@map"));
259
+ };
260
+ cache.hasMappedNames = Object.values(schema.models).some(hasMapAttr) || Object.values(schema.typeDefs ?? {}).some(hasMapAttr) || Object.values(schema.enums ?? {}).some(hasMapAttr);
261
+ }
262
+ return cache.hasMappedNames;
263
+ }
247
264
  function requireModel(schema, model) {
248
265
  const modelDef = getModel(schema, model);
249
266
  if (!modelDef) throw createInternalError(`Model "${model}" not found in schema`, model);
@@ -635,9 +652,23 @@ const CRUD_EXT = [...CRUD, "post-update"];
635
652
  //#region src/client/crud/dialects/base-dialect.ts
636
653
  var BaseCrudDialect = class {
637
654
  eb = expressionBuilder();
638
- constructor(schema, options) {
639
- this.schema = schema;
640
- this.options = options;
655
+ schema;
656
+ options;
657
+ /**
658
+ * The client executing the query. Unset only when the dialect was constructed from a
659
+ * standalone schema/options pair, in which case it cannot evaluate computed fields.
660
+ */
661
+ client;
662
+ constructor(...args) {
663
+ if (args.length === 1) {
664
+ const [client] = args;
665
+ this.client = client;
666
+ this.schema = client.$schema;
667
+ this.options = client.$options;
668
+ } else {
669
+ [this.schema, this.options] = args;
670
+ this.client = void 0;
671
+ }
641
672
  }
642
673
  /**
643
674
  * Transforms input value before sending to database.
@@ -696,6 +727,8 @@ var BaseCrudDialect = class {
696
727
  if (typeof ob !== "object" || ob === null) return void 0;
697
728
  if ("_fuzzyRelevance" in ob) return "_fuzzyRelevance";
698
729
  if ("_ftsRelevance" in ob) return "_ftsRelevance";
730
+ const argsEntry = Object.entries(ob).find(([, v]) => v !== null && typeof v === "object" && "args" in v);
731
+ if (argsEntry) return argsEntry[0];
699
732
  }).find((k) => k !== void 0);
700
733
  if (offendingKey) throw createNotSupportedError(`cursor pagination cannot be combined with "${offendingKey}" ordering`);
701
734
  }
@@ -718,9 +751,16 @@ var BaseCrudDialect = class {
718
751
  const fieldDef = requireField(this.schema, model, key);
719
752
  if (fieldDef.relation) result = this.and(result, this.buildRelationFilter(model, modelAlias, key, fieldDef, payload));
720
753
  else {
721
- const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias);
722
- if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, payload));
723
- else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, payload));
754
+ let computedArgs;
755
+ let filterPayload = payload;
756
+ if (fieldDef.computed && fieldDef.params && payload && typeof payload === "object" && "args" in payload) {
757
+ computedArgs = payload.args;
758
+ const { args: _args, ...rest } = payload;
759
+ filterPayload = rest;
760
+ }
761
+ const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias, true, computedArgs);
762
+ if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
763
+ else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
724
764
  }
725
765
  }
726
766
  if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb));
@@ -778,7 +818,7 @@ var BaseCrudDialect = class {
778
818
  }
779
819
  const joinAlias = tmpAlias(`${modelAlias}$${field}`);
780
820
  const joinPairs = buildJoinPairs(this.schema, model, fieldDef.originModel ?? modelAlias, field, joinAlias);
781
- const baseJoin = this.eb.selectFrom(`${fieldDef.type} as ${joinAlias}`).select(this.eb.lit(1).as("_")).where(() => this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), "=", this.eb.ref(right)))));
821
+ const baseJoin = this.buildSelectModel(fieldDef.type, joinAlias).select(this.eb.lit(1).as("_")).where(() => this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), "=", this.eb.ref(right)))));
782
822
  const existsSelect = (extraFilter) => {
783
823
  const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
784
824
  return this.buildExistsExpression(q);
@@ -979,7 +1019,7 @@ var BaseCrudDialect = class {
979
1019
  else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
980
1020
  else {
981
1021
  let _receiver = fieldReceiver;
982
- if (fieldDef.type === "String") _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
1022
+ if (fieldDef.type === "String" || isEnum(this.schema, fieldDef.type)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
983
1023
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
984
1024
  }
985
1025
  }
@@ -1121,9 +1161,9 @@ var BaseCrudDialect = class {
1121
1161
  buildOrderBy(query, model, modelAlias, orderBy, negated, take) {
1122
1162
  if (!orderBy) return query;
1123
1163
  let result = query;
1124
- const buildFieldRef = (model, field, modelAlias) => {
1164
+ const buildFieldRef = (model, field, modelAlias, computedArgs) => {
1125
1165
  const fieldDef = requireField(this.schema, model, field);
1126
- return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel) : this.fieldRef(model, field, modelAlias);
1166
+ return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel, true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1127
1167
  };
1128
1168
  enumerate(orderBy).forEach((orderBy, index) => {
1129
1169
  for (const [field, value] of Object.entries(orderBy)) {
@@ -1179,7 +1219,7 @@ var BaseCrudDialect = class {
1179
1219
  return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
1180
1220
  }
1181
1221
  applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
1182
- const fieldRef = buildFieldRef(model, field, modelAlias);
1222
+ const fieldRef = buildFieldRef(model, field, modelAlias, value && typeof value === "object" && "args" in value ? value.args : void 0);
1183
1223
  if (value === "asc" || value === "desc") return query.orderBy(fieldRef, this.negateSort(value, negated));
1184
1224
  if (typeof value === "object" && "sort" in value && (value.sort === "asc" || value.sort === "desc")) {
1185
1225
  const sort = this.negateSort(value.sort, negated);
@@ -1189,11 +1229,15 @@ var BaseCrudDialect = class {
1189
1229
  return query;
1190
1230
  }
1191
1231
  applyAggregationOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
1192
- invariant(typeof value === "object", `invalid orderBy value for field "${field}"`);
1232
+ if (!isPlainObject(value)) throw createInvalidInputError(`invalid orderBy value for field "${field}"`);
1193
1233
  let result = query;
1194
1234
  for (const [k, v] of Object.entries(value)) {
1195
- invariant(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
1196
- result = result.orderBy((eb) => aggregate(eb, buildFieldRef(model, k, modelAlias), field), this.negateSort(v, negated));
1235
+ const sort = isPlainObject(v) ? v["sort"] : v;
1236
+ if (sort !== "asc" && sort !== "desc") throw createInvalidInputError(`invalid orderBy value for field "${field}"`);
1237
+ const computedArgs = isPlainObject(v) && "args" in v ? v["args"] : void 0;
1238
+ const aggExpr = aggregate(this.eb, buildFieldRef(model, k, modelAlias, computedArgs), field);
1239
+ const nulls = isPlainObject(v) ? v["nulls"] : void 0;
1240
+ result = nulls === "first" || nulls === "last" ? this.buildOrderByField(result, aggExpr, this.negateSort(sort, negated), nulls) : result.orderBy(aggExpr, this.negateSort(sort, negated));
1197
1241
  }
1198
1242
  return result;
1199
1243
  }
@@ -1228,6 +1272,7 @@ var BaseCrudDialect = class {
1228
1272
  computed: true
1229
1273
  })) {
1230
1274
  if (this.shouldOmitField(omit, model, fieldDef.name)) continue;
1275
+ if (fieldDef.computed && fieldDef.params) continue;
1231
1276
  result = this.buildSelectField(result, model, modelAlias, fieldDef.name);
1232
1277
  }
1233
1278
  const descendants = getDelegateDescendantModels(this.schema, model);
@@ -1237,6 +1282,7 @@ var BaseCrudDialect = class {
1237
1282
  const jsonObject = {};
1238
1283
  for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
1239
1284
  if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
1285
+ if (fieldDef.computed && fieldDef.params) continue;
1240
1286
  jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1241
1287
  }
1242
1288
  return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
@@ -1257,11 +1303,11 @@ var BaseCrudDialect = class {
1257
1303
  if (payload && typeof payload === "object") subQuery = this.buildFilterSortTake(model, payload, subQuery, subQueryAlias);
1258
1304
  return subQuery;
1259
1305
  }
1260
- buildSelectField(query, model, modelAlias, field) {
1306
+ buildSelectField(query, model, modelAlias, field, computedArgs) {
1261
1307
  const fieldDef = requireField(this.schema, model, field);
1262
1308
  const fieldModel = fieldDef.originModel ?? model;
1263
1309
  const alias = fieldDef.originModel ?? modelAlias;
1264
- return query.select(() => this.fieldRef(fieldModel, field, alias).as(field));
1310
+ return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
1265
1311
  }
1266
1312
  buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1267
1313
  const idFields = requireIdFields(this.schema, thisModel);
@@ -1328,7 +1374,7 @@ var BaseCrudDialect = class {
1328
1374
  not(...args) {
1329
1375
  return this.eb.not(this.and(...args));
1330
1376
  }
1331
- fieldRef(model, field, modelAlias, inlineComputedField = true) {
1377
+ fieldRef(model, field, modelAlias, inlineComputedField = true, computedArgs) {
1332
1378
  const fieldDef = requireField(this.schema, model, field);
1333
1379
  if (!fieldDef.computed) return this.eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
1334
1380
  else {
@@ -1340,7 +1386,11 @@ var BaseCrudDialect = class {
1340
1386
  computer = computedFields?.[lowerCaseFirst(computedModel)]?.[field] ?? computedFields?.[computedModel]?.[field];
1341
1387
  }
1342
1388
  if (!computer) throw createConfigError(`Computed field "${field}" implementation not provided for model "${model}"`);
1343
- return computer(this.eb, { modelAlias });
1389
+ invariant(this.client, `computed field "${field}" of model "${model}" needs a client to be evaluated`);
1390
+ return this.eb.parens(computer(this.eb, {
1391
+ modelAlias,
1392
+ client: this.client
1393
+ }, computedArgs));
1344
1394
  }
1345
1395
  }
1346
1396
  canJoinWithoutNestedSelect(modelDef, payload) {
@@ -1476,18 +1526,21 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1476
1526
  if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1477
1527
  if (payload === true || !payload.select) {
1478
1528
  const omit = typeof payload === "object" ? payload.omit : void 0;
1479
- Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
1529
+ Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
1480
1530
  } else if (payload.select) Object.assign(objArgs, ...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1481
1531
  if (field === "_count") {
1482
1532
  const subJson = this.buildCountJson(relationModel, eb, relationModelAlias, value);
1483
1533
  return { [field]: subJson };
1484
1534
  } else {
1485
- const fieldValue = requireField(this.schema, relationModel, field).relation ? eb.ref(`${parentResultName}$${field}.$data`) : this.fieldRef(relationModel, field, relationModelAlias, false);
1535
+ const fieldDef = requireField(this.schema, relationModel, field);
1536
+ const fieldValue = fieldDef.relation ? eb.ref(`${parentResultName}$${field}.$data`) : fieldDef.computed && fieldDef.params ? this.fieldRef(relationModel, field, relationModelAlias, true, value.args) : this.fieldRef(relationModel, field, relationModelAlias, false);
1486
1537
  return { [field]: fieldValue };
1487
1538
  }
1488
1539
  }));
1489
1540
  if (typeof payload === "object" && payload.include && typeof payload.include === "object") Object.assign(objArgs, ...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
1490
1541
  if (field === "_count") return { [field]: this.buildCountJson(relationModel, eb, relationModelAlias, value) };
1542
+ const fieldDef = requireField(this.schema, relationModel, field);
1543
+ if (fieldDef.computed && fieldDef.params) return { [field]: this.fieldRef(relationModel, field, relationModelAlias, true, value.args) };
1491
1544
  return { [field]: eb.ref(`${parentResultName}$${field}.$data`) };
1492
1545
  }));
1493
1546
  return objArgs;
@@ -1506,9 +1559,6 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1506
1559
  //#endregion
1507
1560
  //#region src/client/crud/dialects/mysql.ts
1508
1561
  var MySqlCrudDialect = class extends LateralJoinDialectBase {
1509
- constructor(schema, options) {
1510
- super(schema, options);
1511
- }
1512
1562
  get provider() {
1513
1563
  return "mysql";
1514
1564
  }
@@ -1736,8 +1786,8 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1736
1786
  "@db.Decimal": "decimal",
1737
1787
  "@db.Boolean": "boolean"
1738
1788
  };
1739
- constructor(schema, options) {
1740
- super(schema, options);
1789
+ constructor(...args) {
1790
+ super(...args);
1741
1791
  this.overrideTypeParsers();
1742
1792
  }
1743
1793
  get provider() {
@@ -2153,21 +2203,27 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2153
2203
  if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2154
2204
  if (payload === true || !payload.select) {
2155
2205
  const omit = typeof payload === "object" ? payload.omit : void 0;
2156
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
2206
+ objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
2157
2207
  } else if (payload.select) objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
2158
2208
  if (field === "_count") {
2159
2209
  const subJson = this.buildCountJson(relationModel, eb, tmpAlias(`${parentAlias}$${relationField}`), value);
2160
2210
  return [sql.lit(field), subJson];
2161
- } else if (requireField(this.schema, relationModel, field).relation) {
2162
- const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2163
- return [sql.lit(field), subJson];
2164
- } else return [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)];
2211
+ } else {
2212
+ const fieldDef = requireField(this.schema, relationModel, field);
2213
+ if (fieldDef.relation) {
2214
+ const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2215
+ return [sql.lit(field), subJson];
2216
+ } else if (fieldDef.computed && fieldDef.params) return [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, true, value.args)];
2217
+ else return [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)];
2218
+ }
2165
2219
  }).flatMap((v) => v));
2166
2220
  if (typeof payload === "object" && payload.include && typeof payload.include === "object") objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
2167
2221
  if (field === "_count") {
2168
2222
  const subJson = this.buildCountJson(relationModel, eb, tmpAlias(`${parentAlias}$${relationField}`), value);
2169
2223
  return [sql.lit(field), subJson];
2170
2224
  }
2225
+ const fieldDef = requireField(this.schema, relationModel, field);
2226
+ if (fieldDef.computed && fieldDef.params) return [sql.lit(field), this.fieldRef(relationModel, field, subQueryName, true, value.args)];
2171
2227
  const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2172
2228
  return [sql.lit(field), subJson];
2173
2229
  }).flatMap((v) => v));
@@ -2280,8 +2336,8 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2280
2336
  };
2281
2337
  //#endregion
2282
2338
  //#region src/client/crud/dialects/index.ts
2283
- function getCrudDialect(schema, options) {
2284
- return match(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).with("mysql", () => new MySqlCrudDialect(schema, options)).exhaustive();
2339
+ function getCrudDialect(...args) {
2340
+ return match((args.length === 1 ? args[0].$schema : args[0]).provider.type).with("sqlite", () => new SqliteCrudDialect(...args)).with("postgresql", () => new PostgresCrudDialect(...args)).with("mysql", () => new MySqlCrudDialect(...args)).exhaustive();
2285
2341
  }
2286
2342
  //#endregion
2287
2343
  //#region src/client/zod/cache-decorator.ts
@@ -2516,6 +2572,25 @@ var ZodSchemaFactory = class {
2516
2572
  ]);
2517
2573
  }).with("DateTime", () => this.makeDateTimeValueSchema()).with("Bytes", () => z$1.instanceof(Uint8Array)).with("Json", () => this.makeJsonValueSchema()).otherwise(() => z$1.unknown());
2518
2574
  }
2575
+ isParameterizedComputedField(fieldDef) {
2576
+ return !!(fieldDef.computed && fieldDef.params);
2577
+ }
2578
+ makeFieldArgsSchema(params) {
2579
+ return z$1.strictObject(Object.fromEntries(Object.entries(params).map(([name, param]) => {
2580
+ let paramSchema = this.makeScalarSchema(param.type);
2581
+ if (param.array) paramSchema = paramSchema.array();
2582
+ if (param.optional) paramSchema = paramSchema.optional();
2583
+ return [name, paramSchema];
2584
+ })));
2585
+ }
2586
+ addComputedArgsToFilter(filterSchema, params) {
2587
+ const objectMembers = (filterSchema instanceof z$1.ZodUnion ? filterSchema.options : [filterSchema]).filter((m) => m instanceof z$1.ZodObject);
2588
+ const components = Object.assign({}, ...objectMembers.map((o) => o.shape));
2589
+ return z$1.strictObject({
2590
+ args: this.makeFieldArgsSchema(params),
2591
+ ...components
2592
+ });
2593
+ }
2519
2594
  makeEnumSchema(_enum) {
2520
2595
  const enumDef = getEnum(this.schema, _enum);
2521
2596
  invariant(enumDef, `Enum "${_enum}" not found in schema`);
@@ -2573,6 +2648,7 @@ var ZodSchemaFactory = class {
2573
2648
  else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2574
2649
  else fieldSchema = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2575
2650
  }
2651
+ if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2576
2652
  if (fieldSchema) fields[field] = fieldSchema.optional();
2577
2653
  }
2578
2654
  if (unique) {
@@ -2890,11 +2966,17 @@ var ZodSchemaFactory = class {
2890
2966
  }
2891
2967
  makeSelectSchema(model, options) {
2892
2968
  const fields = {};
2893
- for (const [field, fieldDef] of this.getModelFields(model)) if (fieldDef.relation) {
2894
- if (!this.shouldIncludeRelations(options)) continue;
2895
- if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
2896
- } else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = z$1.literal(false).optional();
2897
- else fields[field] = z$1.boolean().optional();
2969
+ for (const [field, fieldDef] of this.getModelFields(model)) {
2970
+ if (this.isParameterizedComputedField(fieldDef)) {
2971
+ fields[field] = z$1.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
2972
+ continue;
2973
+ }
2974
+ if (fieldDef.relation) {
2975
+ if (!this.shouldIncludeRelations(options)) continue;
2976
+ if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
2977
+ } else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = z$1.literal(false).optional();
2978
+ else fields[field] = z$1.boolean().optional();
2979
+ }
2898
2980
  if (this.shouldIncludeRelations(options)) {
2899
2981
  const _countSchema = this.makeCountSelectionSchema(model, options);
2900
2982
  if (!(_countSchema instanceof z$1.ZodNever)) fields["_count"] = _countSchema;
@@ -2951,8 +3033,11 @@ var ZodSchemaFactory = class {
2951
3033
  }
2952
3034
  makeOmitSchema(model) {
2953
3035
  const fields = {};
2954
- for (const [field, fieldDef] of this.getModelFields(model)) if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = z$1.boolean().optional();
2955
- else fields[field] = z$1.literal(true).optional();
3036
+ for (const [field, fieldDef] of this.getModelFields(model)) {
3037
+ if (this.isParameterizedComputedField(fieldDef)) continue;
3038
+ if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = z$1.boolean().optional();
3039
+ else fields[field] = z$1.literal(true).optional();
3040
+ }
2956
3041
  this.addExtResultFields(model, fields);
2957
3042
  const result = z$1.strictObject(fields);
2958
3043
  this.registerSchema(`${model}OmitInput`, result);
@@ -2975,7 +3060,7 @@ var ZodSchemaFactory = class {
2975
3060
  if (fieldDef.relation) {
2976
3061
  if (!this.shouldIncludeRelations(options)) continue;
2977
3062
  if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
2978
- }
3063
+ } else if (this.isParameterizedComputedField(fieldDef)) fields[field] = z$1.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
2979
3064
  }
2980
3065
  if (this.shouldIncludeRelations(options)) {
2981
3066
  const _countSchema = this.makeCountSelectionSchema(model, options);
@@ -2996,7 +3081,12 @@ var ZodSchemaFactory = class {
2996
3081
  if (fieldDef.array) relationOrderBy = refineAtMostOneKey(relationOrderBy.safeExtend({ _count: sort }));
2997
3082
  return relationOrderBy;
2998
3083
  }).optional();
2999
- } else if (fieldDef.optional) fields[field] = z$1.union([sort, z$1.strictObject({
3084
+ } else if (fieldDef.computed && fieldDef.params) fields[field] = z$1.strictObject({
3085
+ args: this.makeFieldArgsSchema(fieldDef.params),
3086
+ sort,
3087
+ nulls: z$1.union([z$1.literal("first"), z$1.literal("last")]).optional()
3088
+ }).optional();
3089
+ else if (fieldDef.optional) fields[field] = z$1.union([sort, z$1.strictObject({
3000
3090
  sort,
3001
3091
  nulls: z$1.union([z$1.literal("first"), z$1.literal("last")]).optional()
3002
3092
  })]).optional();
@@ -3040,7 +3130,7 @@ var ZodSchemaFactory = class {
3040
3130
  return schema;
3041
3131
  }
3042
3132
  makeDistinctSchema(model) {
3043
- const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation).map(([name]) => name);
3133
+ const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
3044
3134
  const schema = nonRelationFields.length > 0 ? this.orArray(z$1.enum(nonRelationFields), true) : z$1.never();
3045
3135
  this.registerSchema(`${model}DistinctInput`, schema);
3046
3136
  return schema;
@@ -3361,8 +3451,8 @@ var ZodSchemaFactory = class {
3361
3451
  makeCountAggregateInputSchema(model) {
3362
3452
  const schema = z$1.union([z$1.literal(true), z$1.strictObject({
3363
3453
  _all: z$1.literal(true).optional(),
3364
- ...this.getModelFields(model).reduce((acc, [field]) => {
3365
- acc[field] = z$1.literal(true).optional();
3454
+ ...this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3455
+ acc[field] = this.isParameterizedComputedField(fieldDef) ? z$1.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z$1.literal(true).optional();
3366
3456
  return acc;
3367
3457
  }, {})
3368
3458
  })]);
@@ -3386,7 +3476,7 @@ var ZodSchemaFactory = class {
3386
3476
  }
3387
3477
  makeSumAvgInputSchema(model) {
3388
3478
  const schema = z$1.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3389
- if (this.isNumericField(fieldDef)) acc[field] = z$1.literal(true).optional();
3479
+ if (this.isNumericField(fieldDef)) acc[field] = this.isParameterizedComputedField(fieldDef) ? z$1.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z$1.literal(true).optional();
3390
3480
  return acc;
3391
3481
  }, {}));
3392
3482
  this.registerSchema(`${model}SumAvgAggregateInput`, schema);
@@ -3394,15 +3484,22 @@ var ZodSchemaFactory = class {
3394
3484
  }
3395
3485
  makeMinMaxInputSchema(model) {
3396
3486
  const schema = z$1.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3397
- if (!fieldDef.relation && !fieldDef.array) acc[field] = z$1.literal(true).optional();
3487
+ if (!fieldDef.relation && !fieldDef.array) acc[field] = this.isParameterizedComputedField(fieldDef) ? z$1.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z$1.literal(true).optional();
3398
3488
  return acc;
3399
3489
  }, {}));
3400
3490
  this.registerSchema(`${model}MinMaxAggregateInput`, schema);
3401
3491
  return schema;
3402
3492
  }
3403
3493
  makeGroupBySchema(model, options) {
3404
- const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation).map(([name]) => name);
3405
- const bySchema = nonRelationFields.length > 0 ? this.orArray(z$1.enum(nonRelationFields), true) : z$1.never();
3494
+ const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
3495
+ const byMembers = [];
3496
+ if (nonRelationFields.length > 0) byMembers.push(z$1.enum(nonRelationFields));
3497
+ for (const [field, fieldDef] of this.getModelFields(model)) if (this.isParameterizedComputedField(fieldDef)) byMembers.push(z$1.strictObject({
3498
+ field: z$1.literal(field),
3499
+ args: this.makeFieldArgsSchema(fieldDef.params)
3500
+ }));
3501
+ const byElement = byMembers.length === 0 ? void 0 : byMembers.length === 1 ? byMembers[0] : z$1.union(byMembers);
3502
+ const bySchema = byElement ? this.orArray(byElement, true) : z$1.never();
3406
3503
  const baseSchema = z$1.strictObject({
3407
3504
  where: this.makeWhereSchema(model, false, false, false, options).optional(),
3408
3505
  orderBy: this.orArray(this.makeOrderBySchema(model, false, true, options), true).optional(),
@@ -3418,7 +3515,7 @@ var ZodSchemaFactory = class {
3418
3515
  });
3419
3516
  let schema = this.mergePluginArgsSchema(baseSchema, "groupBy");
3420
3517
  schema = schema.refine((value) => {
3421
- const bys = enumerate(value.by);
3518
+ const bys = enumerate(value.by).map((b) => typeof b === "string" ? b : b?.field);
3422
3519
  if (value.having && typeof value.having === "object") for (const [key, val] of Object.entries(value.having)) {
3423
3520
  if (AggregateOperators.includes(key)) continue;
3424
3521
  if (bys.includes(key)) continue;
@@ -3428,7 +3525,7 @@ var ZodSchemaFactory = class {
3428
3525
  return true;
3429
3526
  }, "fields in \"having\" must be in \"by\"");
3430
3527
  schema = schema.refine((value) => {
3431
- const bys = enumerate(value.by);
3528
+ const bys = enumerate(value.by).map((b) => typeof b === "string" ? b : b?.field);
3432
3529
  for (const orderBy of enumerate(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3433
3530
  return true;
3434
3531
  }, "fields in \"orderBy\" must be in \"by\"");
@@ -4246,7 +4343,7 @@ var BaseOperationHandler = class {
4246
4343
  this.client = client;
4247
4344
  this.model = model;
4248
4345
  this.inputValidator = inputValidator;
4249
- this.dialect = getCrudDialect(this.schema, this.client.$options);
4346
+ this.dialect = getCrudDialect(this.client);
4250
4347
  }
4251
4348
  get schema() {
4252
4349
  return this.client.$schema;
@@ -4329,8 +4426,10 @@ var BaseOperationHandler = class {
4329
4426
  continue;
4330
4427
  }
4331
4428
  const fieldDef = this.requireField(model, field);
4332
- if (!fieldDef.relation) result = this.dialect.buildSelectField(result, model, parentAlias, field);
4333
- else {
4429
+ if (!fieldDef.relation) {
4430
+ const computedArgs = fieldDef.computed && fieldDef.params && typeof payload === "object" && "args" in payload ? payload.args : void 0;
4431
+ result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4432
+ } else {
4334
4433
  if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
4335
4434
  if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, fieldDef.originModel, payload);
4336
4435
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
@@ -5312,6 +5411,7 @@ var BaseOperationHandler = class {
5312
5411
  };
5313
5412
  //#endregion
5314
5413
  //#region src/client/crud/operations/aggregate.ts
5414
+ const argsKey = (v) => JSON.stringify(v, (_k, val) => typeof val === "bigint" ? `${val}n` : val);
5315
5415
  var AggregateOperationHandler = class extends BaseOperationHandler {
5316
5416
  async handle(_operation, args) {
5317
5417
  const normalizedArgs = this.normalizeArgs(args);
@@ -5319,10 +5419,18 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5319
5419
  let query = this.kysely.selectFrom((eb) => {
5320
5420
  let subQuery = this.dialect.buildSelectModel(this.model, this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5321
5421
  const selectedFields = [];
5322
- for (const [key, value] of Object.entries(parsedArgs)) if (key.startsWith("_") && value && typeof value === "object") Object.entries(value).filter(([field]) => field !== "_all").filter(([, val]) => val === true).forEach(([field]) => {
5422
+ const computedArgsByField = {};
5423
+ for (const [key, value] of Object.entries(parsedArgs)) if (key.startsWith("_") && value && typeof value === "object") Object.entries(value).filter(([field]) => field !== "_all").forEach(([field, val]) => {
5424
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5425
+ if (val !== true && args === void 0) return;
5323
5426
  if (!selectedFields.includes(field)) selectedFields.push(field);
5427
+ if (args !== void 0) {
5428
+ const prev = computedArgsByField[field];
5429
+ if (prev !== void 0 && argsKey(prev) !== argsKey(args)) throw createInvalidInputError(`computed field "${field}" is aggregated with conflicting "args"; the same field can only be aggregated with one set of arguments per query`);
5430
+ computedArgsByField[field] = args;
5431
+ }
5324
5432
  });
5325
- if (selectedFields.length > 0) for (const field of selectedFields) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, field);
5433
+ if (selectedFields.length > 0) for (const field of selectedFields) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, field, computedArgsByField[field]);
5326
5434
  else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5327
5435
  const skip = parsedArgs?.skip;
5328
5436
  let take = parsedArgs?.take;
@@ -5339,7 +5447,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5339
5447
  case "_count":
5340
5448
  if (value === true) query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
5341
5449
  else Object.entries(value).forEach(([field, val]) => {
5342
- if (val === true) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5450
+ if (val === true || val && typeof val === "object" && "args" in val) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5343
5451
  else query = query.select((eb) => this.dialect.castInt(eb.fn.count(eb.ref(`$sub.${field}`))).as(`${key}.${field}`));
5344
5452
  });
5345
5453
  break;
@@ -5348,7 +5456,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5348
5456
  case "_max":
5349
5457
  case "_min":
5350
5458
  Object.entries(value).forEach(([field, val]) => {
5351
- if (val === true) query = query.select((eb) => {
5459
+ if (val === true || val && typeof val === "object" && "args" in val) query = query.select((eb) => {
5352
5460
  return match(key).with("_sum", () => eb.fn.sum).with("_avg", () => eb.fn.avg).with("_max", () => eb.fn.max).with("_min", () => eb.fn.min).exhaustive()(eb.ref(`$sub.${field}`)).as(`${key}.${field}`);
5353
5461
  });
5354
5462
  });
@@ -5391,9 +5499,12 @@ var CountOperationHandler = class extends BaseOperationHandler {
5391
5499
  const subQueryName = "$sub";
5392
5500
  let query = this.kysely.selectFrom((eb) => {
5393
5501
  let subQuery = this.dialect.buildSelectModel(this.model, this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5394
- if (parsedArgs?.select && typeof parsedArgs.select === "object") {
5395
- for (const [key, value] of Object.entries(parsedArgs.select)) if (key !== "_all" && value === true) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key);
5396
- } else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5502
+ if (parsedArgs?.select && typeof parsedArgs.select === "object") for (const [key, value] of Object.entries(parsedArgs.select)) {
5503
+ if (key === "_all") continue;
5504
+ if (value === true) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key);
5505
+ else if (value && typeof value === "object" && "args" in value) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key, value.args);
5506
+ }
5507
+ else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5397
5508
  subQuery = this.dialect.buildSkipTake(subQuery, parsedArgs?.skip, parsedArgs?.take);
5398
5509
  return subQuery.as(subQueryName);
5399
5510
  });
@@ -5534,9 +5645,17 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5534
5645
  const normalizedArgs = this.normalizeArgs(args);
5535
5646
  const parsedArgs = this.inputValidator.validateGroupByArgs(this.model, normalizedArgs);
5536
5647
  let query = this.kysely.selectFrom(this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5537
- const fieldRef = (field) => this.dialect.fieldRef(this.model, field);
5538
- const bys = typeof parsedArgs.by === "string" ? [parsedArgs.by] : parsedArgs.by;
5539
- query = query.groupBy(bys.map((by) => fieldRef(by)));
5648
+ const fieldRef = (field, computedArgs) => this.dialect.fieldRef(this.model, field, this.model, true, computedArgs);
5649
+ const byEntries = (Array.isArray(parsedArgs.by) ? parsedArgs.by : [parsedArgs.by]).map((by) => typeof by === "string" ? {
5650
+ field: by,
5651
+ args: void 0
5652
+ } : {
5653
+ field: by.field,
5654
+ args: by.args
5655
+ });
5656
+ query = query.groupBy(byEntries.map((e) => {
5657
+ return getField(this.schema, this.model, e.field)?.computed ? sql.ref(e.field) : fieldRef(e.field);
5658
+ }));
5540
5659
  const skip = parsedArgs?.skip;
5541
5660
  let take = parsedArgs?.take;
5542
5661
  let negateOrderBy = false;
@@ -5547,13 +5666,14 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5547
5666
  query = this.dialect.buildSkipTake(query, skip, take);
5548
5667
  query = this.dialect.buildOrderBy(query, this.model, this.model, parsedArgs.orderBy, negateOrderBy, take);
5549
5668
  if (parsedArgs.having) query = query.having(() => this.dialect.buildFilter(this.model, this.model, parsedArgs.having));
5550
- for (const by of bys) query = query.select(() => fieldRef(by).as(by));
5669
+ for (const e of byEntries) query = query.select(() => fieldRef(e.field, e.args).as(e.field));
5551
5670
  for (const [key, value] of Object.entries(parsedArgs)) switch (key) {
5552
5671
  case "_count":
5553
5672
  if (value === true) query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
5554
5673
  else Object.entries(value).forEach(([field, val]) => {
5555
- if (val === true) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5556
- else query = query.select((eb) => this.dialect.castInt(eb.fn.count(fieldRef(field))).as(`${key}.${field}`));
5674
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5675
+ if (val === true || args !== void 0) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5676
+ else query = query.select((eb) => this.dialect.castInt(eb.fn.count(fieldRef(field, args))).as(`${key}.${field}`));
5557
5677
  });
5558
5678
  break;
5559
5679
  case "_sum":
@@ -5561,7 +5681,8 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5561
5681
  case "_max":
5562
5682
  case "_min":
5563
5683
  Object.entries(value).forEach(([field, val]) => {
5564
- if (val === true) query = query.select((eb) => aggregate(eb, fieldRef(field), key).as(`${key}.${field}`));
5684
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5685
+ if (val === true || args !== void 0) query = query.select((eb) => aggregate(eb, fieldRef(field, args), key).as(`${key}.${field}`));
5565
5686
  });
5566
5687
  break;
5567
5688
  }
@@ -5855,7 +5976,7 @@ var QueryNameMapper = class extends OperationNodeTransformer {
5855
5976
  constructor(client) {
5856
5977
  super();
5857
5978
  this.client = client;
5858
- this.dialect = getCrudDialect(client.$schema, client.$options);
5979
+ this.dialect = getCrudDialect(client);
5859
5980
  for (const [modelName, modelDef] of Object.entries(client.$schema.models)) {
5860
5981
  const mappedName = this.getMappedName(modelDef);
5861
5982
  if (mappedName) this.modelToTableMap.set(modelName, mappedName);
@@ -6318,22 +6439,22 @@ const DEFAULT_MAX_SLOW_RECORDS = 100;
6318
6439
  var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExecutor {
6319
6440
  nameMapper;
6320
6441
  dialect;
6321
- constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false) {
6442
+ constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false, nameMapper) {
6322
6443
  super(compiler, adapter, connectionProvider, plugins);
6323
6444
  this.client = client;
6324
6445
  this.driver = driver;
6325
6446
  this.compiler = compiler;
6326
6447
  this.connectionProvider = connectionProvider;
6327
6448
  this.suppressMutationHooks = suppressMutationHooks;
6328
- if (client.$schema.provider.type === "postgresql" || this.schemaHasMappedNames(client.$schema)) this.nameMapper = new QueryNameMapper(client);
6329
- this.dialect = getCrudDialect(client.$schema, client.$options);
6449
+ this.nameMapper = nameMapper ?? (client.$schema.provider.type === "postgresql" || schemaHasMappedNames(client.$schema) ? new QueryNameMapper(client.$contract) : void 0);
6450
+ this.dialect = getCrudDialect(client.$contract);
6330
6451
  }
6331
- schemaHasMappedNames(schema) {
6332
- const hasMapAttr = (decl) => {
6333
- if (decl.attributes?.some((attr) => attr.name === "@@map")) return true;
6334
- return Object.values(decl.fields).some((field) => field.attributes?.some((attr) => attr.name === "@map"));
6335
- };
6336
- return Object.values(schema.models).some(hasMapAttr) || Object.values(schema.typeDefs ?? []).some(hasMapAttr);
6452
+ /**
6453
+ * The name mapper built for this executor's schema, if the schema needs one. Exposed so that
6454
+ * derived clients built from the same schema and options can reuse it instead of rebuilding it.
6455
+ */
6456
+ getNameMapper() {
6457
+ return this.nameMapper;
6337
6458
  }
6338
6459
  get kysely() {
6339
6460
  return this.client.$qb;
@@ -6380,7 +6501,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6380
6501
  proceed = async (query) => {
6381
6502
  const _p = (q) => _proceed(q);
6382
6503
  return await hook({
6383
- client: this.client,
6504
+ client: this.client.$contract,
6384
6505
  schema: this.client.$schema,
6385
6506
  query,
6386
6507
  proceed: _p
@@ -6618,7 +6739,7 @@ In such cases, ZenStack cannot reliably determine the IDs of the mutated entitie
6618
6739
  innerExecutor.suppressMutationHooks = true;
6619
6740
  const innerClient = this.client.withExecutor(innerExecutor);
6620
6741
  if (inTx) innerClient.forceTransaction();
6621
- return innerClient;
6742
+ return innerClient.$contract;
6622
6743
  }
6623
6744
  andNodes(condition1, condition2) {
6624
6745
  if (condition1 && condition2) return WhereNode.create(AndNode.create(condition1, condition2));
@@ -6670,19 +6791,19 @@ In such cases, ZenStack cannot reliably determine the IDs of the mutated entitie
6670
6791
  return finalResult;
6671
6792
  }
6672
6793
  withPlugin(plugin) {
6673
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, plugin], this.suppressMutationHooks);
6794
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, plugin], this.suppressMutationHooks, this.nameMapper);
6674
6795
  }
6675
6796
  withPlugins(plugins) {
6676
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, ...plugins], this.suppressMutationHooks);
6797
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, ...plugins], this.suppressMutationHooks, this.nameMapper);
6677
6798
  }
6678
6799
  withPluginAtFront(plugin) {
6679
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [plugin, ...this.plugins], this.suppressMutationHooks);
6800
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [plugin, ...this.plugins], this.suppressMutationHooks, this.nameMapper);
6680
6801
  }
6681
6802
  withoutPlugins() {
6682
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks);
6803
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks, this.nameMapper);
6683
6804
  }
6684
6805
  withConnectionProvider(connectionProvider) {
6685
- const newExecutor = new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks);
6806
+ const newExecutor = new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks, this.nameMapper);
6686
6807
  newExecutor.client = this.client.withExecutor(newExecutor);
6687
6808
  return newExecutor;
6688
6809
  }
@@ -7138,6 +7259,12 @@ var ResultProcessor = class {
7138
7259
  //#endregion
7139
7260
  //#region src/client/client-impl.ts
7140
7261
  /**
7262
+ * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7263
+ */
7264
+ function getExecutorNameMapper(executor) {
7265
+ return executor instanceof ZenStackQueryExecutor ? executor.getNameMapper() : void 0;
7266
+ }
7267
+ /**
7141
7268
  * ZenStack ORM client.
7142
7269
  */
7143
7270
  const ZenStackClient = function(schema, options) {
@@ -7165,7 +7292,7 @@ var ClientImpl = class ClientImpl {
7165
7292
  if (baseClient) {
7166
7293
  this.kyselyProps = {
7167
7294
  ...baseClient.kyselyProps,
7168
- executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new DefaultConnectionProvider(baseClient.kyselyProps.driver))
7295
+ executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new DefaultConnectionProvider(baseClient.kyselyProps.driver), [], false, baseClient.$schema === schema && baseClient.$options === options ? getExecutorNameMapper(baseClient.kyselyProps.executor) : void 0)
7169
7296
  };
7170
7297
  this.kyselyRaw = baseClient.kyselyRaw;
7171
7298
  this.auth = baseClient.auth;
@@ -7242,14 +7369,14 @@ var ClientImpl = class ClientImpl {
7242
7369
  if (!this.kysely.isTransaction) this.kysely = new Transaction(this.kyselyProps);
7243
7370
  }
7244
7371
  async interactiveTransaction(callback, options) {
7245
- if (this.kysely.isTransaction) return callback(this);
7372
+ if (this.kysely.isTransaction) return callback(this.$contract);
7246
7373
  else {
7247
7374
  let txBuilder = this.kysely.transaction();
7248
7375
  if (options?.isolationLevel) txBuilder = txBuilder.setIsolationLevel(options.isolationLevel);
7249
7376
  return txBuilder.execute((tx) => {
7250
7377
  const txClient = new ClientImpl(this.schema, this.$options, this);
7251
7378
  txClient.kysely = tx;
7252
- return callback(txClient);
7379
+ return callback(txClient.$contract);
7253
7380
  });
7254
7381
  }
7255
7382
  }
@@ -7266,7 +7393,7 @@ var ClientImpl = class ClientImpl {
7266
7393
  const result = [];
7267
7394
  for (const promise of arg) {
7268
7395
  const cb = this.getPromiseCallback(promise);
7269
- result.push(await cb(txClient));
7396
+ result.push(await cb(txClient.$contract));
7270
7397
  }
7271
7398
  return result;
7272
7399
  };
@@ -7367,6 +7494,16 @@ var ClientImpl = class ClientImpl {
7367
7494
  get $auth() {
7368
7495
  return this.auth;
7369
7496
  }
7497
+ /**
7498
+ * This client viewed through its public typed contract. `ClientImpl` is intentionally
7499
+ * untyped internally — the model accessors are added by the runtime proxy — so this
7500
+ * getter is the single sanctioned bridge to `ClientContract`. The proxy invokes it
7501
+ * with the proxy as `this` (`Reflect.get` with receiver), so the returned reference
7502
+ * keeps the model accessors.
7503
+ */
7504
+ get $contract() {
7505
+ return this;
7506
+ }
7370
7507
  $setOptions(options) {
7371
7508
  const newClient = new ClientImpl(this.schema, options, this);
7372
7509
  newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });