@zenstackhq/orm 3.9.7 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants-BQEq4CBi.mjs +161 -0
- package/dist/constants-BQEq4CBi.mjs.map +1 -0
- package/dist/constants-CcJSpq4B.cjs +244 -0
- package/dist/constants-CcJSpq4B.cjs.map +1 -0
- package/dist/constants-RUWhnVl4.d.mts +129 -0
- package/dist/constants-lRwcp6Hv.d.cts +129 -0
- package/dist/constants.cjs +11 -0
- package/dist/constants.d.cts +2 -0
- package/dist/constants.d.mts +2 -0
- package/dist/constants.mjs +2 -0
- package/dist/index.cjs +436 -320
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +81 -142
- package/dist/index.d.mts +83 -144
- package/dist/index.mjs +552 -436
- package/dist/index.mjs.map +1 -1
- package/package.json +20 -10
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
|
|
2
|
+
import { a as CoreCreateOperations, c as CoreReadOperations, d as DELEGATE_JOINED_FIELD_PREFIX, f as FILTER_PROPERTY_TO_KIND, i as AllWriteOperations, l as CoreUpdateOperations, m as NUMERIC_FIELD_TYPES, n as AllCrudOperations, o as CoreCrudOperations, p as LOGICAL_COMBINATORS, r as AllReadOperations, s as CoreDeleteOperations, t as AggregateOperators, u as CoreWriteOperations } from "./constants-BQEq4CBi.mjs";
|
|
2
3
|
import { AnyNull, AnyNullClass, DbNull, DbNullClass, JsonNull, JsonNullClass } from "./common-types.mjs";
|
|
3
4
|
import { clone, enumerate, invariant, isPlainObject, lowerCaseFirst, upperCaseFirst } from "@zenstackhq/common-helpers";
|
|
4
5
|
import { AliasNode, AndNode, ColumnNode, ColumnUpdateNode, CompiledQuery, DefaultConnectionProvider, DefaultQueryExecutor, DeleteQueryNode, ExpressionWrapper, FromNode, IdentifierNode, InsertQueryNode, Kysely, Log, OperationNodeTransformer, OperationNodeVisitor, PrimitiveValueListNode, RawNode, ReferenceNode, ReturningNode, SelectAllNode, SelectionNode, SingleConnectionProvider, TableNode, Transaction, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, WhereNode, createQueryId, expressionBuilder, sql } from "kysely";
|
|
5
|
-
import z, { ZodObject, ZodType, z
|
|
6
|
+
import z$1, { ZodObject, ZodType, z } from "zod";
|
|
6
7
|
import { fromError } from "zod-validation-error/v4";
|
|
7
8
|
import { P, match } from "ts-pattern";
|
|
8
9
|
import { ExpressionUtils } from "@zenstackhq/schema";
|
|
@@ -206,6 +207,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
|
|
|
206
207
|
isEnum: () => isEnum,
|
|
207
208
|
isForeignKeyField: () => isForeignKeyField,
|
|
208
209
|
isInheritedField: () => isInheritedField,
|
|
210
|
+
isPrimitiveTypeDef: () => isPrimitiveTypeDef,
|
|
209
211
|
isRelationField: () => isRelationField,
|
|
210
212
|
isScalarField: () => isScalarField,
|
|
211
213
|
isTypeDef: () => isTypeDef,
|
|
@@ -386,6 +388,9 @@ function getEnum(schema, type) {
|
|
|
386
388
|
function isTypeDef(schema, type) {
|
|
387
389
|
return !!schema.typeDefs?.[type];
|
|
388
390
|
}
|
|
391
|
+
function isPrimitiveTypeDef(schema, type) {
|
|
392
|
+
return !!schema.typeDefs?.[type]?.base;
|
|
393
|
+
}
|
|
389
394
|
function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
|
|
390
395
|
const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
|
|
391
396
|
return keyPairs.map(({ fk, pk }) => {
|
|
@@ -541,75 +546,6 @@ function tmpAlias(name) {
|
|
|
541
546
|
else return name;
|
|
542
547
|
}
|
|
543
548
|
//#endregion
|
|
544
|
-
//#region src/client/constants.ts
|
|
545
|
-
/**
|
|
546
|
-
* The types of fields that are numeric.
|
|
547
|
-
*/
|
|
548
|
-
const NUMERIC_FIELD_TYPES = [
|
|
549
|
-
"Int",
|
|
550
|
-
"Float",
|
|
551
|
-
"BigInt",
|
|
552
|
-
"Decimal"
|
|
553
|
-
];
|
|
554
|
-
/**
|
|
555
|
-
* Prefix for JSON field used to store joined delegate rows.
|
|
556
|
-
*/
|
|
557
|
-
const DELEGATE_JOINED_FIELD_PREFIX = "$delegate$";
|
|
558
|
-
/**
|
|
559
|
-
* Logical combinators used in filters.
|
|
560
|
-
*/
|
|
561
|
-
const LOGICAL_COMBINATORS = [
|
|
562
|
-
"AND",
|
|
563
|
-
"OR",
|
|
564
|
-
"NOT"
|
|
565
|
-
];
|
|
566
|
-
/**
|
|
567
|
-
* Aggregation operators.
|
|
568
|
-
*/
|
|
569
|
-
const AggregateOperators = [
|
|
570
|
-
"_count",
|
|
571
|
-
"_sum",
|
|
572
|
-
"_avg",
|
|
573
|
-
"_min",
|
|
574
|
-
"_max"
|
|
575
|
-
];
|
|
576
|
-
/**
|
|
577
|
-
* Mapping of filter operators to their corresponding filter kind categories.
|
|
578
|
-
*/
|
|
579
|
-
const FILTER_PROPERTY_TO_KIND = {
|
|
580
|
-
equals: "Equality",
|
|
581
|
-
not: "Equality",
|
|
582
|
-
in: "Equality",
|
|
583
|
-
notIn: "Equality",
|
|
584
|
-
lt: "Range",
|
|
585
|
-
lte: "Range",
|
|
586
|
-
gt: "Range",
|
|
587
|
-
gte: "Range",
|
|
588
|
-
between: "Range",
|
|
589
|
-
contains: "Like",
|
|
590
|
-
startsWith: "Like",
|
|
591
|
-
endsWith: "Like",
|
|
592
|
-
mode: "Like",
|
|
593
|
-
is: "Relation",
|
|
594
|
-
isNot: "Relation",
|
|
595
|
-
some: "Relation",
|
|
596
|
-
every: "Relation",
|
|
597
|
-
none: "Relation",
|
|
598
|
-
path: "Json",
|
|
599
|
-
string_contains: "Json",
|
|
600
|
-
string_starts_with: "Json",
|
|
601
|
-
string_ends_with: "Json",
|
|
602
|
-
array_contains: "Json",
|
|
603
|
-
array_starts_with: "Json",
|
|
604
|
-
array_ends_with: "Json",
|
|
605
|
-
fuzzy: "Fuzzy",
|
|
606
|
-
fts: "FullText",
|
|
607
|
-
has: "List",
|
|
608
|
-
hasEvery: "List",
|
|
609
|
-
hasSome: "List",
|
|
610
|
-
isEmpty: "List"
|
|
611
|
-
};
|
|
612
|
-
//#endregion
|
|
613
549
|
//#region src/client/contract.ts
|
|
614
550
|
/**
|
|
615
551
|
* Transaction isolation levels.
|
|
@@ -758,12 +694,12 @@ var BaseCrudDialect = class {
|
|
|
758
694
|
const { args: _args, ...rest } = payload;
|
|
759
695
|
filterPayload = rest;
|
|
760
696
|
}
|
|
761
|
-
const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key,
|
|
697
|
+
const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, this.delegateFieldAlias(model, modelAlias, fieldDef), true, computedArgs);
|
|
762
698
|
if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
|
|
763
699
|
else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
|
|
764
700
|
}
|
|
765
701
|
}
|
|
766
|
-
if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb));
|
|
702
|
+
if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb, { modelAlias }));
|
|
767
703
|
return result;
|
|
768
704
|
}
|
|
769
705
|
buildCursorFilter(model, query, cursor, orderBy, negateOrderBy, modelAlias) {
|
|
@@ -778,8 +714,8 @@ var BaseCrudDialect = class {
|
|
|
778
714
|
const [field, order] = orderByItems[j];
|
|
779
715
|
const op = j === i ? (negateOrderBy ? order === "asc" ? "desc" : "asc" : order) === "asc" ? ">=" : "<=" : "=";
|
|
780
716
|
const fieldDef = requireField(this.schema, model, field);
|
|
781
|
-
const outerAlias =
|
|
782
|
-
const subSelectAlias =
|
|
717
|
+
const outerAlias = this.delegateFieldAlias(model, modelAlias, fieldDef);
|
|
718
|
+
const subSelectAlias = this.delegateFieldAlias(model, subQueryAlias, fieldDef);
|
|
783
719
|
andFilters.push(this.eb(this.eb.ref(`${outerAlias}.${field}`), op, this.buildSelectModel(model, subQueryAlias).select(`${subSelectAlias}.${field}`).where(cursorFilter)));
|
|
784
720
|
}
|
|
785
721
|
filters.push(this.eb.and(andFilters));
|
|
@@ -817,7 +753,7 @@ var BaseCrudDialect = class {
|
|
|
817
753
|
else return this.buildToOneRelationFilter(model, modelAlias, field, fieldDef, { is: null });
|
|
818
754
|
}
|
|
819
755
|
const joinAlias = tmpAlias(`${modelAlias}$${field}`);
|
|
820
|
-
const joinPairs = buildJoinPairs(this.schema, model,
|
|
756
|
+
const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
|
|
821
757
|
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)))));
|
|
822
758
|
const existsSelect = (extraFilter) => {
|
|
823
759
|
const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
|
|
@@ -911,11 +847,13 @@ var BaseCrudDialect = class {
|
|
|
911
847
|
buildPrimitiveFilter(fieldRef, fieldDef, payload) {
|
|
912
848
|
if (payload === null) return this.eb(fieldRef, "is", null);
|
|
913
849
|
if (isEnum(this.schema, fieldDef.type)) return this.buildEnumFilter(fieldRef, fieldDef, payload);
|
|
914
|
-
|
|
850
|
+
let type = fieldDef.type;
|
|
851
|
+
if (isTypeDef(this.schema, fieldDef.type)) if (isPrimitiveTypeDef(this.schema, fieldDef.type)) type = this.schema["typeDefs"][fieldDef.type]["base"];
|
|
852
|
+
else {
|
|
915
853
|
if (payload instanceof DbNullClass || payload instanceof JsonNullClass || payload instanceof AnyNullClass) return this.buildJsonValueFilterClause(fieldRef, payload);
|
|
916
854
|
return this.buildJsonFilter(fieldRef, payload, fieldDef);
|
|
917
855
|
}
|
|
918
|
-
return match(
|
|
856
|
+
return match(type).with("String", () => this.buildStringFilter(fieldRef, payload, fieldDef)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(fieldRef, type, payload)).with("Boolean", () => this.buildBooleanFilter(fieldRef, payload)).with("DateTime", () => this.buildDateTimeFilter(fieldRef, payload)).with("Bytes", () => this.buildBytesFilter(fieldRef, payload)).with("Json", () => this.buildJsonFilter(fieldRef, payload, fieldDef)).with("Unsupported", () => {
|
|
919
857
|
throw createInvalidInputError(`Unsupported field cannot be used in filters`);
|
|
920
858
|
}).exhaustive();
|
|
921
859
|
}
|
|
@@ -1015,11 +953,12 @@ var BaseCrudDialect = class {
|
|
|
1015
953
|
const fieldDef = typeDef.fields[key];
|
|
1016
954
|
invariant(fieldDef, `Field "${key}" not found in type definition "${typeDefName}"`);
|
|
1017
955
|
const fieldReceiver = this.buildJsonPathSelection(receiver, `$.${key}`);
|
|
1018
|
-
if (isTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
|
|
956
|
+
if (isTypeDef(this.schema, fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
|
|
1019
957
|
else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
|
|
1020
958
|
else {
|
|
959
|
+
const effectiveType = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
|
|
1021
960
|
let _receiver = fieldReceiver;
|
|
1022
|
-
if (
|
|
961
|
+
if (effectiveType === "String" || isEnum(this.schema, effectiveType)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
|
|
1023
962
|
clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
|
|
1024
963
|
}
|
|
1025
964
|
}
|
|
@@ -1163,7 +1102,7 @@ var BaseCrudDialect = class {
|
|
|
1163
1102
|
let result = query;
|
|
1164
1103
|
const buildFieldRef = (model, field, modelAlias, computedArgs) => {
|
|
1165
1104
|
const fieldDef = requireField(this.schema, model, field);
|
|
1166
|
-
return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel, true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
|
|
1105
|
+
return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, this.delegateJoinAlias(model, modelAlias, fieldDef.originModel), true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
|
|
1167
1106
|
};
|
|
1168
1107
|
enumerate(orderBy).forEach((orderBy, index) => {
|
|
1169
1108
|
for (const [field, value] of Object.entries(orderBy)) {
|
|
@@ -1212,10 +1151,15 @@ var BaseCrudDialect = class {
|
|
|
1212
1151
|
return query;
|
|
1213
1152
|
}
|
|
1214
1153
|
const joinAlias = tmpAlias(`${modelAlias}$ob$${index}`);
|
|
1215
|
-
|
|
1216
|
-
const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, joinAlias);
|
|
1154
|
+
let joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
|
|
1155
|
+
const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
|
|
1217
1156
|
return join.on((eb) => this.and(...joinPairs.map(([left, right]) => eb(this.eb.ref(left), "=", this.eb.ref(right)))));
|
|
1218
1157
|
});
|
|
1158
|
+
let joinBase = requireModel(this.schema, relationModel).baseModel;
|
|
1159
|
+
while (joinBase) {
|
|
1160
|
+
joined = this.buildDelegateJoin(relationModel, joinAlias, joinBase, joined);
|
|
1161
|
+
joinBase = requireModel(this.schema, joinBase).baseModel;
|
|
1162
|
+
}
|
|
1219
1163
|
return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
|
|
1220
1164
|
}
|
|
1221
1165
|
applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
|
|
@@ -1279,12 +1223,13 @@ var BaseCrudDialect = class {
|
|
|
1279
1223
|
const descendants = getDelegateDescendantModels(this.schema, model);
|
|
1280
1224
|
for (const subModel of descendants) {
|
|
1281
1225
|
result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
|
|
1226
|
+
const subModelAlias = this.delegateJoinAlias(model, modelAlias, subModel.name);
|
|
1282
1227
|
result = result.select(() => {
|
|
1283
1228
|
const jsonObject = {};
|
|
1284
1229
|
for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
|
|
1285
1230
|
if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
|
|
1286
1231
|
if (fieldDef.computed && fieldDef.params) continue;
|
|
1287
|
-
jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name,
|
|
1232
|
+
jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModelAlias);
|
|
1288
1233
|
}
|
|
1289
1234
|
return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
|
|
1290
1235
|
});
|
|
@@ -1307,17 +1252,35 @@ var BaseCrudDialect = class {
|
|
|
1307
1252
|
buildSelectField(query, model, modelAlias, field, computedArgs) {
|
|
1308
1253
|
const fieldDef = requireField(this.schema, model, field);
|
|
1309
1254
|
const fieldModel = fieldDef.originModel ?? model;
|
|
1310
|
-
const alias =
|
|
1255
|
+
const alias = this.delegateFieldAlias(model, modelAlias, fieldDef);
|
|
1311
1256
|
return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
|
|
1312
1257
|
}
|
|
1313
|
-
buildDelegateJoin(thisModel, thisModelAlias,
|
|
1258
|
+
buildDelegateJoin(thisModel, thisModelAlias, otherModel, query) {
|
|
1314
1259
|
const idFields = requireIdFields(this.schema, thisModel);
|
|
1315
|
-
|
|
1260
|
+
const otherModelAlias = this.delegateJoinAlias(thisModel, thisModelAlias, otherModel);
|
|
1261
|
+
const table = otherModelAlias === otherModel ? otherModel : `${otherModel} as ${otherModelAlias}`;
|
|
1262
|
+
query = query.leftJoin(table, (qb) => {
|
|
1316
1263
|
for (const idField of idFields) qb = qb.onRef(`${thisModelAlias}.${idField}`, "=", `${otherModelAlias}.${idField}`);
|
|
1317
1264
|
return qb;
|
|
1318
1265
|
});
|
|
1319
1266
|
return query;
|
|
1320
1267
|
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Gets the alias under which a delegate base or sub model is joined to a model selected as `modelAlias`.
|
|
1270
|
+
* A model selected under its own name (a top-level query) has them joined under their own model names.
|
|
1271
|
+
* A model selected under another alias (a relation subquery) has them joined under aliases derived from
|
|
1272
|
+
* it, so they never shadow a table of an enclosing query in the same delegate hierarchy.
|
|
1273
|
+
*/
|
|
1274
|
+
delegateJoinAlias(model, modelAlias, joinedModel) {
|
|
1275
|
+
return modelAlias === model ? joinedModel : tmpAlias(`${modelAlias}$${joinedModel}`);
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Gets the alias of the table holding a field of a model selected as `modelAlias`: the joined base
|
|
1279
|
+
* table for a field inherited from a delegate base, otherwise the model's own table.
|
|
1280
|
+
*/
|
|
1281
|
+
delegateFieldAlias(model, modelAlias, fieldDef) {
|
|
1282
|
+
return fieldDef.originModel ? this.delegateJoinAlias(model, modelAlias, fieldDef.originModel) : modelAlias;
|
|
1283
|
+
}
|
|
1321
1284
|
buildCountJson(model, eb, parentAlias, payload) {
|
|
1322
1285
|
const modelDef = requireModel(this.schema, model);
|
|
1323
1286
|
const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
|
|
@@ -1589,9 +1552,10 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
|
|
|
1589
1552
|
if (value instanceof JsonNullClass) return this.eb.cast(sql.lit("null"), "json");
|
|
1590
1553
|
else if (value instanceof DbNullClass) return null;
|
|
1591
1554
|
else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
|
|
1592
|
-
if (isTypeDef(this.schema, type)) if (
|
|
1555
|
+
if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
|
|
1556
|
+
else if (typeof value !== "string") return this.transformInput(value, "Json", forArrayField);
|
|
1593
1557
|
else return value;
|
|
1594
|
-
|
|
1558
|
+
if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
|
|
1595
1559
|
else throw createNotSupportedError(`MySQL does not support array literals`);
|
|
1596
1560
|
else switch (type) {
|
|
1597
1561
|
case "Boolean": return value ? 1 : 0;
|
|
@@ -1606,6 +1570,7 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
|
|
|
1606
1570
|
}
|
|
1607
1571
|
transformOutput(value, type, array) {
|
|
1608
1572
|
if (value === null || value === void 0) return value;
|
|
1573
|
+
if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
|
|
1609
1574
|
switch (type) {
|
|
1610
1575
|
case "Boolean": return this.transformOutputBoolean(value);
|
|
1611
1576
|
case "DateTime": return this.transformOutputDate(value);
|
|
@@ -1634,7 +1599,12 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
|
|
|
1634
1599
|
return new Date(!anchored.endsWith("Z") ? anchored + "Z" : anchored);
|
|
1635
1600
|
}
|
|
1636
1601
|
transformOutputBytes(value) {
|
|
1637
|
-
|
|
1602
|
+
if (Buffer.isBuffer(value)) return Uint8Array.from(value);
|
|
1603
|
+
if (typeof value === "string") {
|
|
1604
|
+
const match = /^base64:type\d+:(.*)$/s.exec(value);
|
|
1605
|
+
if (match) return Uint8Array.from(Buffer.from(match[1], "base64"));
|
|
1606
|
+
}
|
|
1607
|
+
return value;
|
|
1638
1608
|
}
|
|
1639
1609
|
buildExistsExpression(innerQuery) {
|
|
1640
1610
|
return this.eb.exists(this.eb.selectFrom(innerQuery.as("$exists_sub")).select(this.eb.lit(1).as("_")));
|
|
@@ -1846,9 +1816,10 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
|
|
|
1846
1816
|
if (value instanceof JsonNullClass) return "null";
|
|
1847
1817
|
else if (value instanceof DbNullClass) return null;
|
|
1848
1818
|
else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
|
|
1849
|
-
if (isTypeDef(this.schema, type)) if (
|
|
1819
|
+
if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
|
|
1820
|
+
else if (typeof value !== "string") return JSON.stringify(value);
|
|
1850
1821
|
else return value;
|
|
1851
|
-
|
|
1822
|
+
if (Array.isArray(value)) if (type === "Json" && !forArrayField) return JSON.stringify(value);
|
|
1852
1823
|
else return value.map((v) => this.transformInput(v, type, false, fieldDef));
|
|
1853
1824
|
else switch (type) {
|
|
1854
1825
|
case "DateTime": {
|
|
@@ -1866,6 +1837,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
|
|
|
1866
1837
|
}
|
|
1867
1838
|
transformOutput(value, type, array) {
|
|
1868
1839
|
if (value === null || value === void 0) return value;
|
|
1840
|
+
if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
|
|
1869
1841
|
switch (type) {
|
|
1870
1842
|
case "DateTime": return this.transformOutputDate(value);
|
|
1871
1843
|
case "Bytes": return this.transformOutputBytes(value);
|
|
@@ -1978,6 +1950,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
|
|
|
1978
1950
|
const mapped = PostgresCrudDialect.dbAttributeToSqlTypeMap[attr.name];
|
|
1979
1951
|
if (mapped) return mapped;
|
|
1980
1952
|
}
|
|
1953
|
+
if (isPrimitiveTypeDef(this.schema, zmodelType)) zmodelType = this.schema.typeDefs[zmodelType].base;
|
|
1981
1954
|
if (isEnum(this.schema, zmodelType)) return "text";
|
|
1982
1955
|
else return this.zmodelToSqlTypeMap[zmodelType] ?? "text";
|
|
1983
1956
|
}
|
|
@@ -2161,7 +2134,9 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
|
|
|
2161
2134
|
if (value instanceof JsonNullClass) return "null";
|
|
2162
2135
|
else if (value instanceof DbNullClass) return null;
|
|
2163
2136
|
else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
|
|
2164
|
-
if (type
|
|
2137
|
+
if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema.typeDefs[type].base;
|
|
2138
|
+
else return JSON.stringify(value);
|
|
2139
|
+
if (type === "Json") return JSON.stringify(value);
|
|
2165
2140
|
if (Array.isArray(value)) return value.map((v) => this.transformInput(v, type, false));
|
|
2166
2141
|
else switch (type) {
|
|
2167
2142
|
case "Boolean": return value ? 1 : 0;
|
|
@@ -2173,8 +2148,10 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
|
|
|
2173
2148
|
}
|
|
2174
2149
|
transformOutput(value, type, array) {
|
|
2175
2150
|
if (value === null || value === void 0) return value;
|
|
2176
|
-
else if (this.schema.typeDefs && type in this.schema.typeDefs)
|
|
2177
|
-
|
|
2151
|
+
else if (this.schema.typeDefs && type in this.schema.typeDefs) {
|
|
2152
|
+
if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
|
|
2153
|
+
return this.transformOutputJson(value);
|
|
2154
|
+
} else switch (type) {
|
|
2178
2155
|
case "Boolean": return this.transformOutputBoolean(value);
|
|
2179
2156
|
case "DateTime": return this.transformOutputDate(value);
|
|
2180
2157
|
case "Bytes": return this.transformOutputBytes(value);
|
|
@@ -2433,7 +2410,7 @@ function createQuerySchemaFactory(clientOrSchema, options) {
|
|
|
2433
2410
|
* @see https://github.com/zenstackhq/zenstack/issues/2631
|
|
2434
2411
|
*/
|
|
2435
2412
|
function coercedDateTimeSchema() {
|
|
2436
|
-
return z
|
|
2413
|
+
return z.preprocess((val) => {
|
|
2437
2414
|
if (typeof val !== "string") return val;
|
|
2438
2415
|
if (/^\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d\d(?::\d\d)?)?$/.test(val)) {
|
|
2439
2416
|
const hasTz = val.endsWith("Z") || /[+-]\d\d(?::\d\d)?$/.test(val);
|
|
@@ -2442,10 +2419,10 @@ function coercedDateTimeSchema() {
|
|
|
2442
2419
|
}
|
|
2443
2420
|
const d = new Date(val);
|
|
2444
2421
|
return isNaN(d.getTime()) ? val : d;
|
|
2445
|
-
}, z
|
|
2446
|
-
z
|
|
2447
|
-
z
|
|
2448
|
-
z
|
|
2422
|
+
}, z.union([
|
|
2423
|
+
z.iso.datetime(),
|
|
2424
|
+
z.iso.date(),
|
|
2425
|
+
z.date()
|
|
2449
2426
|
]));
|
|
2450
2427
|
}
|
|
2451
2428
|
/**
|
|
@@ -2453,7 +2430,7 @@ function coercedDateTimeSchema() {
|
|
|
2453
2430
|
*/
|
|
2454
2431
|
var ZodSchemaFactory = class {
|
|
2455
2432
|
schemaCache = /* @__PURE__ */ new Map();
|
|
2456
|
-
schemaRegistry = z
|
|
2433
|
+
schemaRegistry = z.registry();
|
|
2457
2434
|
allFilterKinds = [...new Set(Object.values(FILTER_PROPERTY_TO_KIND))];
|
|
2458
2435
|
schema;
|
|
2459
2436
|
options;
|
|
@@ -2545,7 +2522,7 @@ var ZodSchemaFactory = class {
|
|
|
2545
2522
|
this.makeGroupBySchema(m);
|
|
2546
2523
|
}
|
|
2547
2524
|
for (const procName of Object.keys(this.schema.procedures ?? {})) if (this.isProcedureAllowed(procName)) this.makeProcedureArgsSchema(procName);
|
|
2548
|
-
return z
|
|
2525
|
+
return z.toJSONSchema(this.schemaRegistry, { unrepresentable: "any" });
|
|
2549
2526
|
}
|
|
2550
2527
|
get cacheStats() {
|
|
2551
2528
|
return {
|
|
@@ -2574,13 +2551,13 @@ var ZodSchemaFactory = class {
|
|
|
2574
2551
|
fields["omit"] = this.makeOmitSchema(model).optional().nullable();
|
|
2575
2552
|
if (!unique) {
|
|
2576
2553
|
fields["skip"] = this.makeSkipSchema().optional();
|
|
2577
|
-
if (findOne) fields["take"] = z
|
|
2554
|
+
if (findOne) fields["take"] = z.literal(1).optional();
|
|
2578
2555
|
else fields["take"] = this.makeTakeSchema().optional();
|
|
2579
2556
|
fields["orderBy"] = this.orArray(this.makeOrderBySchema(model, true, false, options), true).optional();
|
|
2580
2557
|
fields["cursor"] = this.makeCursorSchema(model, options).optional();
|
|
2581
2558
|
fields["distinct"] = this.makeDistinctSchema(model).optional();
|
|
2582
2559
|
}
|
|
2583
|
-
const baseSchema = z
|
|
2560
|
+
const baseSchema = z.strictObject(fields);
|
|
2584
2561
|
let result = this.mergePluginArgsSchema(baseSchema, operation);
|
|
2585
2562
|
result = this.refineForSelectIncludeMutuallyExclusive(result);
|
|
2586
2563
|
result = this.refineForSelectOmitMutuallyExclusive(result);
|
|
@@ -2590,27 +2567,27 @@ var ZodSchemaFactory = class {
|
|
|
2590
2567
|
return result;
|
|
2591
2568
|
}
|
|
2592
2569
|
makeExistsSchema(model, options) {
|
|
2593
|
-
const baseSchema = z
|
|
2570
|
+
const baseSchema = z.strictObject({ where: this.makeWhereSchema(model, false, false, false, options).optional() });
|
|
2594
2571
|
const result = this.mergePluginArgsSchema(baseSchema, "exists").optional();
|
|
2595
2572
|
this.registerSchema(`${model}ExistsArgs`, result);
|
|
2596
2573
|
return result;
|
|
2597
2574
|
}
|
|
2598
2575
|
makeScalarSchema(type, attributes) {
|
|
2599
|
-
if (this.schema.typeDefs && type in this.schema.typeDefs) return this.makeTypeDefSchema(type);
|
|
2576
|
+
if (this.schema.typeDefs && type in this.schema.typeDefs) return this.schema.typeDefs[type].base ? this.makeTypeDefSchema(type, attributes) : this.makeTypeDefSchema(type);
|
|
2600
2577
|
else if (this.schema.enums && type in this.schema.enums) return this.makeEnumSchema(type);
|
|
2601
|
-
else return match(type).with("String", () => this.extraValidationsEnabled ? ZodUtils.addStringValidation(z
|
|
2602
|
-
return z
|
|
2603
|
-
this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z
|
|
2604
|
-
ZodUtils.addDecimalValidation(z
|
|
2605
|
-
ZodUtils.addDecimalValidation(z
|
|
2578
|
+
else return match(type).with("String", () => this.extraValidationsEnabled ? ZodUtils.addStringValidation(z.string(), attributes) : z.string()).with("Int", () => this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number().int(), attributes) : z.number().int()).with("Float", () => this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number(), attributes) : z.number()).with("Boolean", () => z.boolean()).with("BigInt", () => z.union([this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number().int(), attributes) : z.number().int(), this.extraValidationsEnabled ? ZodUtils.addBigIntValidation(z.bigint(), attributes) : z.bigint()])).with("Decimal", () => {
|
|
2579
|
+
return z.union([
|
|
2580
|
+
this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number(), attributes) : z.number(),
|
|
2581
|
+
ZodUtils.addDecimalValidation(z.instanceof(Decimal), attributes, this.extraValidationsEnabled),
|
|
2582
|
+
ZodUtils.addDecimalValidation(z.string(), attributes, this.extraValidationsEnabled)
|
|
2606
2583
|
]);
|
|
2607
|
-
}).with("DateTime", () => this.makeDateTimeValueSchema()).with("Bytes", () => z
|
|
2584
|
+
}).with("DateTime", () => this.makeDateTimeValueSchema()).with("Bytes", () => z.instanceof(Uint8Array)).with("Json", () => this.makeJsonValueSchema()).otherwise(() => z.unknown());
|
|
2608
2585
|
}
|
|
2609
2586
|
isParameterizedComputedField(fieldDef) {
|
|
2610
2587
|
return !!(fieldDef.computed && fieldDef.params);
|
|
2611
2588
|
}
|
|
2612
2589
|
makeFieldArgsSchema(params) {
|
|
2613
|
-
return z
|
|
2590
|
+
return z.strictObject(Object.fromEntries(Object.entries(params).map(([name, param]) => {
|
|
2614
2591
|
let paramSchema = this.makeScalarSchema(param.type);
|
|
2615
2592
|
if (param.array) paramSchema = paramSchema.array();
|
|
2616
2593
|
if (param.optional) paramSchema = paramSchema.optional();
|
|
@@ -2618,9 +2595,9 @@ var ZodSchemaFactory = class {
|
|
|
2618
2595
|
})));
|
|
2619
2596
|
}
|
|
2620
2597
|
addComputedArgsToFilter(filterSchema, params) {
|
|
2621
|
-
const objectMembers = (filterSchema instanceof z
|
|
2598
|
+
const objectMembers = (filterSchema instanceof z.ZodUnion ? filterSchema.options : [filterSchema]).filter((m) => m instanceof z.ZodObject);
|
|
2622
2599
|
const components = Object.assign({}, ...objectMembers.map((o) => o.shape));
|
|
2623
|
-
return z
|
|
2600
|
+
return z.strictObject({
|
|
2624
2601
|
args: this.makeFieldArgsSchema(params),
|
|
2625
2602
|
...components
|
|
2626
2603
|
});
|
|
@@ -2628,20 +2605,31 @@ var ZodSchemaFactory = class {
|
|
|
2628
2605
|
makeEnumSchema(_enum) {
|
|
2629
2606
|
const enumDef = getEnum(this.schema, _enum);
|
|
2630
2607
|
invariant(enumDef, `Enum "${_enum}" not found in schema`);
|
|
2631
|
-
const schema = z
|
|
2608
|
+
const schema = z.enum(Object.keys(enumDef.values));
|
|
2632
2609
|
this.registerSchema(_enum, schema);
|
|
2633
2610
|
return schema;
|
|
2634
2611
|
}
|
|
2635
|
-
|
|
2612
|
+
/**
|
|
2613
|
+
* Attributes to validate each value of a scalar field against. For typedef list fields, the
|
|
2614
|
+
* field's own attributes (e.g. `@length`) validate the list rather than its items.
|
|
2615
|
+
*/
|
|
2616
|
+
getItemAttributes(fieldDef) {
|
|
2617
|
+
return fieldDef.array && isTypeDef(this.schema, fieldDef.type) ? void 0 : fieldDef.attributes;
|
|
2618
|
+
}
|
|
2619
|
+
makeTypeDefSchema(type, fieldAttributes) {
|
|
2636
2620
|
const typeDef = getTypeDef(this.schema, type);
|
|
2637
2621
|
invariant(typeDef, `Type definition "${type}" not found in schema`);
|
|
2638
|
-
|
|
2639
|
-
|
|
2622
|
+
if (typeDef.base) {
|
|
2623
|
+
const schema = this.makeScalarSchema(typeDef.base, [...typeDef.fields["this"]?.attributes ?? [], ...fieldAttributes ?? []]);
|
|
2624
|
+
return this.extraValidationsEnabled ? ZodUtils.addCustomValidation(schema, typeDef.attributes) : schema;
|
|
2625
|
+
}
|
|
2626
|
+
const schema = (typeDef.strict ? z.strictObject : z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
|
|
2627
|
+
let fieldSchema = isTypeDef(this.schema, def.type) ? z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
|
|
2640
2628
|
if (def.array) fieldSchema = fieldSchema.array();
|
|
2641
2629
|
if (def.optional) fieldSchema = fieldSchema.nullish();
|
|
2642
2630
|
return [field, fieldSchema];
|
|
2643
2631
|
})));
|
|
2644
|
-
const finalSchema = z
|
|
2632
|
+
const finalSchema = z.any().superRefine((value, ctx) => {
|
|
2645
2633
|
const parseResult = schema.safeParse(value);
|
|
2646
2634
|
if (!parseResult.success) parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
|
|
2647
2635
|
});
|
|
@@ -2657,17 +2645,17 @@ var ZodSchemaFactory = class {
|
|
|
2657
2645
|
if (fieldDef.relation) {
|
|
2658
2646
|
if (withoutRelationFields || !this.shouldIncludeRelations(options)) continue;
|
|
2659
2647
|
const allowedFilterKinds = this.getEffectiveFilterKinds(model, field);
|
|
2660
|
-
if (allowedFilterKinds && !allowedFilterKinds.includes("Relation")) fieldSchema = z
|
|
2648
|
+
if (allowedFilterKinds && !allowedFilterKinds.includes("Relation")) fieldSchema = z.never();
|
|
2661
2649
|
else {
|
|
2662
|
-
fieldSchema = z
|
|
2663
|
-
if (fieldDef.array) fieldSchema = z
|
|
2650
|
+
fieldSchema = z.lazy(() => this.makeWhereSchema(fieldDef.type, false, false, false, nextOpts).optional());
|
|
2651
|
+
if (fieldDef.array) fieldSchema = z.strictObject({
|
|
2664
2652
|
some: fieldSchema.optional(),
|
|
2665
2653
|
every: fieldSchema.optional(),
|
|
2666
2654
|
none: fieldSchema.optional()
|
|
2667
2655
|
});
|
|
2668
2656
|
else {
|
|
2669
2657
|
fieldSchema = this.nullableIf(fieldSchema, !fieldDef.array && !!fieldDef.optional);
|
|
2670
|
-
fieldSchema = z
|
|
2658
|
+
fieldSchema = z.union([fieldSchema, z.strictObject({
|
|
2671
2659
|
is: fieldSchema.optional(),
|
|
2672
2660
|
isNot: fieldSchema.optional()
|
|
2673
2661
|
})]);
|
|
@@ -2679,29 +2667,29 @@ var ZodSchemaFactory = class {
|
|
|
2679
2667
|
if (enumDef) {
|
|
2680
2668
|
if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, withAggregations, allowedFilterKinds);
|
|
2681
2669
|
} else if (fieldDef.array) fieldSchema = this.makeArrayFilterSchema(fieldDef.type, allowedFilterKinds);
|
|
2682
|
-
else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
|
|
2683
|
-
else fieldSchema = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
|
|
2670
|
+
else if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
|
|
2671
|
+
else fieldSchema = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
|
|
2684
2672
|
}
|
|
2685
2673
|
if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
|
|
2686
2674
|
if (fieldSchema) fields[field] = fieldSchema.optional();
|
|
2687
2675
|
}
|
|
2688
2676
|
if (unique) {
|
|
2689
2677
|
const uniqueFields = getUniqueFields(this.schema, model);
|
|
2690
|
-
for (const uniqueField of uniqueFields) if ("defs" in uniqueField) fields[uniqueField.name] = z
|
|
2678
|
+
for (const uniqueField of uniqueFields) if ("defs" in uniqueField) fields[uniqueField.name] = z.object(Object.fromEntries(Object.entries(uniqueField.defs).map(([key, def]) => {
|
|
2691
2679
|
invariant(!def.relation, "unique field cannot be a relation");
|
|
2692
2680
|
let fieldSchema;
|
|
2693
2681
|
const enumDef = getEnum(this.schema, def.type);
|
|
2694
2682
|
if (enumDef) if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(def.type, !!def.optional, !!def.array, false, void 0);
|
|
2695
|
-
else fieldSchema = z
|
|
2683
|
+
else fieldSchema = z.never();
|
|
2696
2684
|
else fieldSchema = this.makePrimitiveFilterSchema(def.type, !!def.optional, false, void 0);
|
|
2697
2685
|
return [key, fieldSchema];
|
|
2698
2686
|
}))).optional();
|
|
2699
2687
|
}
|
|
2700
|
-
fields["$expr"] = z
|
|
2701
|
-
fields["AND"] = this.orArray(z
|
|
2702
|
-
fields["OR"] = z
|
|
2703
|
-
fields["NOT"] = this.orArray(z
|
|
2704
|
-
const baseWhere = z
|
|
2688
|
+
fields["$expr"] = z.custom((v) => typeof v === "function", { error: "\"$expr\" must be a function" }).optional();
|
|
2689
|
+
fields["AND"] = this.orArray(z.lazy(() => this.makeWhereSchema(model, false, withoutRelationFields, false, options)), true).optional();
|
|
2690
|
+
fields["OR"] = z.lazy(() => this.makeWhereSchema(model, false, withoutRelationFields, false, options)).array().optional();
|
|
2691
|
+
fields["NOT"] = this.orArray(z.lazy(() => this.makeWhereSchema(model, false, withoutRelationFields, false, options)), true).optional();
|
|
2692
|
+
const baseWhere = z.strictObject(fields);
|
|
2705
2693
|
let result = baseWhere;
|
|
2706
2694
|
if (unique) {
|
|
2707
2695
|
const uniqueFields = getUniqueFields(this.schema, model);
|
|
@@ -2723,30 +2711,30 @@ var ZodSchemaFactory = class {
|
|
|
2723
2711
|
const candidates = [];
|
|
2724
2712
|
if (!array) {
|
|
2725
2713
|
const fieldSchemas = {};
|
|
2726
|
-
for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
|
|
2714
|
+
for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
|
|
2727
2715
|
else if (getEnum(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, false, void 0).optional();
|
|
2728
2716
|
else if (fieldDef.array) fieldSchemas[fieldName] = this.makeArrayFilterSchema(fieldDef.type, void 0).optional();
|
|
2729
|
-
else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, false, void 0).optional();
|
|
2730
|
-
candidates.push(z
|
|
2717
|
+
else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, false, void 0).optional();
|
|
2718
|
+
candidates.push(z.strictObject(fieldSchemas));
|
|
2731
2719
|
}
|
|
2732
|
-
const recursiveSchema = z
|
|
2733
|
-
if (array) candidates.push(z
|
|
2720
|
+
const recursiveSchema = z.lazy(() => this.makeTypedJsonFilterSchema(type, optional, false, allowedFilterKinds)).optional();
|
|
2721
|
+
if (array) candidates.push(z.strictObject({
|
|
2734
2722
|
some: recursiveSchema,
|
|
2735
2723
|
every: recursiveSchema,
|
|
2736
2724
|
none: recursiveSchema
|
|
2737
2725
|
}));
|
|
2738
|
-
else candidates.push(z
|
|
2726
|
+
else candidates.push(z.strictObject({
|
|
2739
2727
|
is: recursiveSchema,
|
|
2740
2728
|
isNot: recursiveSchema
|
|
2741
2729
|
}));
|
|
2742
2730
|
candidates.push(this.makeJsonFilterSchema(optional, allowedFilterKinds));
|
|
2743
2731
|
if (optional) {
|
|
2744
|
-
candidates.push(z
|
|
2745
|
-
candidates.push(z
|
|
2746
|
-
candidates.push(z
|
|
2747
|
-
candidates.push(z
|
|
2732
|
+
candidates.push(z.null());
|
|
2733
|
+
candidates.push(z.instanceof(DbNullClass));
|
|
2734
|
+
candidates.push(z.instanceof(JsonNullClass));
|
|
2735
|
+
candidates.push(z.instanceof(AnyNullClass));
|
|
2748
2736
|
}
|
|
2749
|
-
const result = z
|
|
2737
|
+
const result = z.union(candidates);
|
|
2750
2738
|
this.registerSchema(`${type}Filter${this.filterSchemaSuffix({
|
|
2751
2739
|
optional,
|
|
2752
2740
|
array,
|
|
@@ -2755,7 +2743,7 @@ var ZodSchemaFactory = class {
|
|
|
2755
2743
|
return result;
|
|
2756
2744
|
}
|
|
2757
2745
|
makeNullableTypedJsonMutationSchema(fieldSchema) {
|
|
2758
|
-
return z
|
|
2746
|
+
return z.any().superRefine((value, ctx) => {
|
|
2759
2747
|
if (value instanceof DbNullClass || value instanceof JsonNullClass || value === null || value === void 0) return;
|
|
2760
2748
|
const parseResult = fieldSchema.safeParse(value);
|
|
2761
2749
|
if (!parseResult.success) parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
|
|
@@ -2764,14 +2752,18 @@ var ZodSchemaFactory = class {
|
|
|
2764
2752
|
isTypeDefType(type) {
|
|
2765
2753
|
return this.schema.typeDefs && type in this.schema.typeDefs;
|
|
2766
2754
|
}
|
|
2755
|
+
getEffectiveFieldType(type) {
|
|
2756
|
+
if (isPrimitiveTypeDef(this.schema, type)) return this.schema.typeDefs[type].base;
|
|
2757
|
+
return type;
|
|
2758
|
+
}
|
|
2767
2759
|
makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds) {
|
|
2768
2760
|
const enumDef = getEnum(this.schema, enumName);
|
|
2769
2761
|
invariant(enumDef, `Enum "${enumName}" not found in schema`);
|
|
2770
|
-
const baseSchema = z
|
|
2762
|
+
const baseSchema = z.enum(Object.keys(enumDef.values));
|
|
2771
2763
|
let schema;
|
|
2772
2764
|
if (array) schema = this.internalMakeArrayFilterSchema(baseSchema, allowedFilterKinds);
|
|
2773
2765
|
else {
|
|
2774
|
-
const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => z
|
|
2766
|
+
const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => z.lazy(() => this.makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds)), [
|
|
2775
2767
|
"equals",
|
|
2776
2768
|
"in",
|
|
2777
2769
|
"notIn",
|
|
@@ -2805,42 +2797,42 @@ var ZodSchemaFactory = class {
|
|
|
2805
2797
|
has: elementSchema.optional(),
|
|
2806
2798
|
hasEvery: elementSchema.array().optional(),
|
|
2807
2799
|
hasSome: elementSchema.array().optional(),
|
|
2808
|
-
isEmpty: z
|
|
2800
|
+
isEmpty: z.boolean().optional()
|
|
2809
2801
|
};
|
|
2810
2802
|
const filteredOperators = this.trimFilterOperators(operators, allowedFilterKinds);
|
|
2811
|
-
return z
|
|
2803
|
+
return z.strictObject(filteredOperators);
|
|
2812
2804
|
}
|
|
2813
2805
|
makePrimitiveFilterSchema(type, optional, withAggregations, allowedFilterKinds, withFuzzy = false, withFullText = false) {
|
|
2814
|
-
return match(type).with("String", () => this.makeStringFilterSchema(optional, withAggregations, allowedFilterKinds, withFuzzy, withFullText)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.makeNumberFilterSchema(type, optional, withAggregations, allowedFilterKinds)).with("Boolean", () => this.makeBooleanFilterSchema(optional, withAggregations, allowedFilterKinds)).with("DateTime", () => this.makeDateTimeFilterSchema(optional, withAggregations, allowedFilterKinds)).with("Bytes", () => this.makeBytesFilterSchema(optional, withAggregations, allowedFilterKinds)).with("Json", () => this.makeJsonFilterSchema(optional, allowedFilterKinds)).with("Unsupported", () => z
|
|
2806
|
+
return match(type).with("String", () => this.makeStringFilterSchema(optional, withAggregations, allowedFilterKinds, withFuzzy, withFullText)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.makeNumberFilterSchema(type, optional, withAggregations, allowedFilterKinds)).with("Boolean", () => this.makeBooleanFilterSchema(optional, withAggregations, allowedFilterKinds)).with("DateTime", () => this.makeDateTimeFilterSchema(optional, withAggregations, allowedFilterKinds)).with("Bytes", () => this.makeBytesFilterSchema(optional, withAggregations, allowedFilterKinds)).with("Json", () => this.makeJsonFilterSchema(optional, allowedFilterKinds)).with("Unsupported", () => z.never()).exhaustive();
|
|
2815
2807
|
}
|
|
2816
2808
|
makeJsonValueSchema() {
|
|
2817
|
-
const schema = z
|
|
2818
|
-
z
|
|
2819
|
-
z
|
|
2820
|
-
z
|
|
2821
|
-
z
|
|
2822
|
-
z
|
|
2823
|
-
z
|
|
2809
|
+
const schema = z.union([
|
|
2810
|
+
z.string(),
|
|
2811
|
+
z.number(),
|
|
2812
|
+
z.boolean(),
|
|
2813
|
+
z.instanceof(JsonNullClass),
|
|
2814
|
+
z.lazy(() => z.union([this.makeJsonValueSchema(), z.null()]).array()),
|
|
2815
|
+
z.record(z.string(), z.lazy(() => z.union([this.makeJsonValueSchema(), z.null()])))
|
|
2824
2816
|
]);
|
|
2825
2817
|
this.registerSchema("JsonValue", schema);
|
|
2826
2818
|
return schema;
|
|
2827
2819
|
}
|
|
2828
2820
|
makeJsonFilterSchema(optional, allowedFilterKinds) {
|
|
2829
|
-
if (allowedFilterKinds && !allowedFilterKinds.includes("Json")) return z
|
|
2821
|
+
if (allowedFilterKinds && !allowedFilterKinds.includes("Json")) return z.never();
|
|
2830
2822
|
const filterMembers = [
|
|
2831
2823
|
this.makeJsonValueSchema(),
|
|
2832
|
-
z
|
|
2833
|
-
z
|
|
2824
|
+
z.instanceof(DbNullClass),
|
|
2825
|
+
z.instanceof(AnyNullClass)
|
|
2834
2826
|
];
|
|
2835
|
-
if (optional) filterMembers.push(z
|
|
2836
|
-
const filterValueSchema = z
|
|
2837
|
-
const schema = z
|
|
2838
|
-
path: z
|
|
2827
|
+
if (optional) filterMembers.push(z.null());
|
|
2828
|
+
const filterValueSchema = z.union(filterMembers);
|
|
2829
|
+
const schema = z.strictObject({
|
|
2830
|
+
path: z.string().optional(),
|
|
2839
2831
|
equals: filterValueSchema.optional(),
|
|
2840
2832
|
not: filterValueSchema.optional(),
|
|
2841
|
-
string_contains: z
|
|
2842
|
-
string_starts_with: z
|
|
2843
|
-
string_ends_with: z
|
|
2833
|
+
string_contains: z.string().optional(),
|
|
2834
|
+
string_starts_with: z.string().optional(),
|
|
2835
|
+
string_ends_with: z.string().optional(),
|
|
2844
2836
|
mode: this.makeStringModeSchema().optional(),
|
|
2845
2837
|
array_contains: filterValueSchema.optional(),
|
|
2846
2838
|
array_starts_with: filterValueSchema.optional(),
|
|
@@ -2859,7 +2851,7 @@ var ZodSchemaFactory = class {
|
|
|
2859
2851
|
}
|
|
2860
2852
|
makeDateTimeFilterSchema(optional, withAggregations, allowedFilterKinds) {
|
|
2861
2853
|
const filterValueSchema = this.makeDateTimeValueSchema();
|
|
2862
|
-
const schema = this.makeCommonPrimitiveFilterSchema(filterValueSchema, optional, () => z
|
|
2854
|
+
const schema = this.makeCommonPrimitiveFilterSchema(filterValueSchema, optional, () => z.lazy(() => this.makeDateTimeFilterSchema(optional, withAggregations, allowedFilterKinds)), withAggregations ? [
|
|
2863
2855
|
"_count",
|
|
2864
2856
|
"_min",
|
|
2865
2857
|
"_max"
|
|
@@ -2872,12 +2864,12 @@ var ZodSchemaFactory = class {
|
|
|
2872
2864
|
return schema;
|
|
2873
2865
|
}
|
|
2874
2866
|
makeBooleanFilterSchema(optional, withAggregations, allowedFilterKinds) {
|
|
2875
|
-
const components = this.makeCommonPrimitiveFilterComponents(z
|
|
2867
|
+
const components = this.makeCommonPrimitiveFilterComponents(z.boolean(), optional, () => z.lazy(() => this.makeBooleanFilterSchema(optional, withAggregations, allowedFilterKinds)), ["equals", "not"], withAggregations ? [
|
|
2876
2868
|
"_count",
|
|
2877
2869
|
"_min",
|
|
2878
2870
|
"_max"
|
|
2879
2871
|
] : void 0, allowedFilterKinds);
|
|
2880
|
-
const schema = this.createUnionFilterSchema(z
|
|
2872
|
+
const schema = this.createUnionFilterSchema(z.boolean(), optional, components, allowedFilterKinds);
|
|
2881
2873
|
this.registerSchema(`BooleanFilter${this.filterSchemaSuffix({
|
|
2882
2874
|
optional,
|
|
2883
2875
|
allowedFilterKinds,
|
|
@@ -2886,8 +2878,8 @@ var ZodSchemaFactory = class {
|
|
|
2886
2878
|
return schema;
|
|
2887
2879
|
}
|
|
2888
2880
|
makeBytesFilterSchema(optional, withAggregations, allowedFilterKinds) {
|
|
2889
|
-
const baseSchema = z
|
|
2890
|
-
const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => z
|
|
2881
|
+
const baseSchema = z.instanceof(Uint8Array);
|
|
2882
|
+
const components = this.makeCommonPrimitiveFilterComponents(baseSchema, optional, () => z.instanceof(Uint8Array), [
|
|
2891
2883
|
"equals",
|
|
2892
2884
|
"in",
|
|
2893
2885
|
"notIn",
|
|
@@ -2935,7 +2927,7 @@ var ZodSchemaFactory = class {
|
|
|
2935
2927
|
return this.createUnionFilterSchema(baseSchema, optional, components, allowedFilterKinds);
|
|
2936
2928
|
}
|
|
2937
2929
|
makeNumberFilterSchema(type, optional, withAggregations, allowedFilterKinds) {
|
|
2938
|
-
const schema = this.makeCommonPrimitiveFilterSchema(this.makeScalarSchema(type), optional, () => z
|
|
2930
|
+
const schema = this.makeCommonPrimitiveFilterSchema(this.makeScalarSchema(type), optional, () => z.lazy(() => this.makeNumberFilterSchema(type, optional, withAggregations, allowedFilterKinds)), withAggregations ? [
|
|
2939
2931
|
"_count",
|
|
2940
2932
|
"_avg",
|
|
2941
2933
|
"_sum",
|
|
@@ -2950,15 +2942,15 @@ var ZodSchemaFactory = class {
|
|
|
2950
2942
|
return schema;
|
|
2951
2943
|
}
|
|
2952
2944
|
makeStringFilterSchema(optional, withAggregations, allowedFilterKinds, withFuzzy = false, withFullText = false) {
|
|
2953
|
-
const baseComponents = this.makeCommonPrimitiveFilterComponents(z
|
|
2945
|
+
const baseComponents = this.makeCommonPrimitiveFilterComponents(z.string(), optional, () => z.lazy(() => this.makeStringFilterSchema(optional, withAggregations, allowedFilterKinds, withFuzzy, withFullText)), void 0, withAggregations ? [
|
|
2954
2946
|
"_count",
|
|
2955
2947
|
"_min",
|
|
2956
2948
|
"_max"
|
|
2957
2949
|
] : void 0, allowedFilterKinds);
|
|
2958
2950
|
const stringSpecificOperators = {
|
|
2959
|
-
startsWith: z
|
|
2960
|
-
endsWith: z
|
|
2961
|
-
contains: z
|
|
2951
|
+
startsWith: z.string().optional(),
|
|
2952
|
+
endsWith: z.string().optional(),
|
|
2953
|
+
contains: z.string().optional(),
|
|
2962
2954
|
...withFuzzy && this.providerSupportsFuzzySearch ? { fuzzy: this.makeFuzzyFilterSchema().optional() } : {},
|
|
2963
2955
|
...withFullText && this.providerSupportsFullTextSearch ? { fts: this.makeFullTextFilterSchema().optional() } : {},
|
|
2964
2956
|
...this.providerSupportsCaseSensitivity ? { mode: this.makeStringModeSchema().optional() } : {}
|
|
@@ -2968,7 +2960,7 @@ var ZodSchemaFactory = class {
|
|
|
2968
2960
|
...baseComponents,
|
|
2969
2961
|
...filteredStringOperators
|
|
2970
2962
|
};
|
|
2971
|
-
const schema = this.createUnionFilterSchema(z
|
|
2963
|
+
const schema = this.createUnionFilterSchema(z.string(), optional, allComponents, allowedFilterKinds);
|
|
2972
2964
|
const featureSuffix = `${withFuzzy ? "Fuzzy" : ""}${withFullText ? "FullText" : ""}`;
|
|
2973
2965
|
this.registerSchema(`StringFilter${this.filterSchemaSuffix({
|
|
2974
2966
|
optional,
|
|
@@ -2978,45 +2970,45 @@ var ZodSchemaFactory = class {
|
|
|
2978
2970
|
return schema;
|
|
2979
2971
|
}
|
|
2980
2972
|
makeStringModeSchema() {
|
|
2981
|
-
return z
|
|
2973
|
+
return z.union([z.literal("default"), z.literal("insensitive")]);
|
|
2982
2974
|
}
|
|
2983
2975
|
makeFuzzyFilterSchema() {
|
|
2984
|
-
return z
|
|
2985
|
-
search: z
|
|
2986
|
-
mode: z
|
|
2987
|
-
z
|
|
2988
|
-
z
|
|
2989
|
-
z
|
|
2976
|
+
return z.strictObject({
|
|
2977
|
+
search: z.string().min(1),
|
|
2978
|
+
mode: z.union([
|
|
2979
|
+
z.literal("simple"),
|
|
2980
|
+
z.literal("word"),
|
|
2981
|
+
z.literal("strictWord")
|
|
2990
2982
|
]).default("simple"),
|
|
2991
|
-
threshold: z
|
|
2992
|
-
unaccent: z
|
|
2983
|
+
threshold: z.number().min(0).max(1).optional(),
|
|
2984
|
+
unaccent: z.boolean().default(false)
|
|
2993
2985
|
});
|
|
2994
2986
|
}
|
|
2995
2987
|
makeFullTextFilterSchema() {
|
|
2996
|
-
return z
|
|
2997
|
-
search: z
|
|
2998
|
-
config: z
|
|
2988
|
+
return z.strictObject({
|
|
2989
|
+
search: z.string().min(1),
|
|
2990
|
+
config: z.string().min(1).optional()
|
|
2999
2991
|
});
|
|
3000
2992
|
}
|
|
3001
2993
|
makeSelectSchema(model, options) {
|
|
3002
2994
|
const fields = {};
|
|
3003
2995
|
for (const [field, fieldDef] of this.getModelFields(model)) {
|
|
3004
2996
|
if (this.isParameterizedComputedField(fieldDef)) {
|
|
3005
|
-
fields[field] = z
|
|
2997
|
+
fields[field] = z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
|
|
3006
2998
|
continue;
|
|
3007
2999
|
}
|
|
3008
3000
|
if (fieldDef.relation) {
|
|
3009
3001
|
if (!this.shouldIncludeRelations(options)) continue;
|
|
3010
3002
|
if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
|
|
3011
|
-
} else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = z
|
|
3012
|
-
else fields[field] = z
|
|
3003
|
+
} else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = z.literal(false).optional();
|
|
3004
|
+
else fields[field] = z.boolean().optional();
|
|
3013
3005
|
}
|
|
3014
3006
|
if (this.shouldIncludeRelations(options)) {
|
|
3015
3007
|
const _countSchema = this.makeCountSelectionSchema(model, options);
|
|
3016
|
-
if (!(_countSchema instanceof z
|
|
3008
|
+
if (!(_countSchema instanceof z.ZodNever)) fields["_count"] = _countSchema;
|
|
3017
3009
|
}
|
|
3018
3010
|
this.addExtResultFields(model, fields);
|
|
3019
|
-
const result = z
|
|
3011
|
+
const result = z.strictObject(fields);
|
|
3020
3012
|
this.registerSchema(`${model}Select`, result);
|
|
3021
3013
|
return result;
|
|
3022
3014
|
}
|
|
@@ -3025,24 +3017,24 @@ var ZodSchemaFactory = class {
|
|
|
3025
3017
|
const toManyRelations = Object.values(modelDef.fields).filter((def) => def.relation && def.array);
|
|
3026
3018
|
if (toManyRelations.length > 0) {
|
|
3027
3019
|
const nextOpts = this.nextOptions(options);
|
|
3028
|
-
const schema = z
|
|
3020
|
+
const schema = z.union([z.literal(true), z.strictObject({ select: z.strictObject(toManyRelations.reduce((acc, fieldDef) => ({
|
|
3029
3021
|
...acc,
|
|
3030
|
-
[fieldDef.name]: z
|
|
3022
|
+
[fieldDef.name]: z.union([z.boolean(), z.strictObject({ where: this.makeWhereSchema(fieldDef.type, false, false, false, nextOpts) })]).optional()
|
|
3031
3023
|
}), {})) })]).optional();
|
|
3032
3024
|
this.registerSchema(`${model}CountSelection`, schema);
|
|
3033
3025
|
return schema;
|
|
3034
|
-
} else return z
|
|
3026
|
+
} else return z.never();
|
|
3035
3027
|
}
|
|
3036
3028
|
makeRelationSelectIncludeSchema(model, field, options) {
|
|
3037
3029
|
const fieldDef = requireField(this.schema, model, field);
|
|
3038
3030
|
const nextOpts = this.nextOptions(options);
|
|
3039
|
-
let objSchema = z
|
|
3040
|
-
...fieldDef.array || fieldDef.optional ? { where: z
|
|
3041
|
-
select: z
|
|
3042
|
-
include: z
|
|
3043
|
-
omit: z
|
|
3031
|
+
let objSchema = z.strictObject({
|
|
3032
|
+
...fieldDef.array || fieldDef.optional ? { where: z.lazy(() => this.makeWhereSchema(fieldDef.type, false, false, false, nextOpts)).optional() } : {},
|
|
3033
|
+
select: z.lazy(() => this.makeSelectSchema(fieldDef.type, nextOpts)).optional().nullable(),
|
|
3034
|
+
include: z.lazy(() => this.makeIncludeSchema(fieldDef.type, nextOpts)).optional().nullable(),
|
|
3035
|
+
omit: z.lazy(() => this.makeOmitSchema(fieldDef.type)).optional().nullable(),
|
|
3044
3036
|
...fieldDef.array ? {
|
|
3045
|
-
orderBy: z
|
|
3037
|
+
orderBy: z.lazy(() => this.orArray(this.makeOrderBySchema(fieldDef.type, true, false, nextOpts), true)).optional(),
|
|
3046
3038
|
skip: this.makeSkipSchema().optional(),
|
|
3047
3039
|
take: this.makeTakeSchema().optional(),
|
|
3048
3040
|
cursor: this.makeCursorSchema(fieldDef.type, nextOpts).optional(),
|
|
@@ -3052,7 +3044,7 @@ var ZodSchemaFactory = class {
|
|
|
3052
3044
|
objSchema = this.refineForSelectIncludeMutuallyExclusive(objSchema);
|
|
3053
3045
|
objSchema = this.refineForSelectOmitMutuallyExclusive(objSchema);
|
|
3054
3046
|
objSchema = this.refineForSelectHasTruthyField(objSchema);
|
|
3055
|
-
const result = z
|
|
3047
|
+
const result = z.union([z.boolean(), objSchema]);
|
|
3056
3048
|
this.registerSchema(`${model}${upperCaseFirst(field)}RelationInput`, result);
|
|
3057
3049
|
return result;
|
|
3058
3050
|
}
|
|
@@ -3069,11 +3061,11 @@ var ZodSchemaFactory = class {
|
|
|
3069
3061
|
const fields = {};
|
|
3070
3062
|
for (const [field, fieldDef] of this.getModelFields(model)) {
|
|
3071
3063
|
if (this.isParameterizedComputedField(fieldDef)) continue;
|
|
3072
|
-
if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = z
|
|
3073
|
-
else fields[field] = z
|
|
3064
|
+
if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = z.boolean().optional();
|
|
3065
|
+
else fields[field] = z.literal(true).optional();
|
|
3074
3066
|
}
|
|
3075
3067
|
this.addExtResultFields(model, fields);
|
|
3076
|
-
const result = z
|
|
3068
|
+
const result = z.strictObject(fields);
|
|
3077
3069
|
this.registerSchema(`${model}OmitInput`, result);
|
|
3078
3070
|
return result;
|
|
3079
3071
|
}
|
|
@@ -3082,7 +3074,7 @@ var ZodSchemaFactory = class {
|
|
|
3082
3074
|
const resultConfig = plugin.result;
|
|
3083
3075
|
if (resultConfig) {
|
|
3084
3076
|
const modelConfig = resultConfig[lowerCaseFirst(model)];
|
|
3085
|
-
if (modelConfig) for (const field of Object.keys(modelConfig)) fields[field] = z
|
|
3077
|
+
if (modelConfig) for (const field of Object.keys(modelConfig)) fields[field] = z.boolean().optional();
|
|
3086
3078
|
}
|
|
3087
3079
|
}
|
|
3088
3080
|
}
|
|
@@ -3094,35 +3086,35 @@ var ZodSchemaFactory = class {
|
|
|
3094
3086
|
if (fieldDef.relation) {
|
|
3095
3087
|
if (!this.shouldIncludeRelations(options)) continue;
|
|
3096
3088
|
if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
|
|
3097
|
-
} else if (this.isParameterizedComputedField(fieldDef)) fields[field] = z
|
|
3089
|
+
} else if (this.isParameterizedComputedField(fieldDef)) fields[field] = z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
|
|
3098
3090
|
}
|
|
3099
3091
|
if (this.shouldIncludeRelations(options)) {
|
|
3100
3092
|
const _countSchema = this.makeCountSelectionSchema(model, options);
|
|
3101
|
-
if (!(_countSchema instanceof z
|
|
3093
|
+
if (!(_countSchema instanceof z.ZodNever)) fields["_count"] = _countSchema;
|
|
3102
3094
|
}
|
|
3103
|
-
const result = z
|
|
3095
|
+
const result = z.strictObject(fields);
|
|
3104
3096
|
this.registerSchema(`${model}Include`, result);
|
|
3105
3097
|
return result;
|
|
3106
3098
|
}
|
|
3107
3099
|
makeOrderBySchema(model, withRelation, WithAggregation, options) {
|
|
3108
3100
|
const fields = {};
|
|
3109
|
-
const sort = z
|
|
3101
|
+
const sort = z.union([z.literal("asc"), z.literal("desc")]);
|
|
3110
3102
|
const refineAtMostOneKey = (s) => s.refine((v) => Object.keys(v).length <= 1, { message: "Each orderBy element must have at most one key" });
|
|
3111
3103
|
const nextOpts = this.nextOptions(options);
|
|
3112
3104
|
for (const [field, fieldDef] of this.getModelFields(model)) if (fieldDef.relation) {
|
|
3113
|
-
if (withRelation && this.shouldIncludeRelations(options)) fields[field] = z
|
|
3105
|
+
if (withRelation && this.shouldIncludeRelations(options)) fields[field] = z.lazy(() => {
|
|
3114
3106
|
let relationOrderBy = this.makeOrderBySchema(fieldDef.type, withRelation, WithAggregation, nextOpts);
|
|
3115
3107
|
if (fieldDef.array) relationOrderBy = refineAtMostOneKey(relationOrderBy.safeExtend({ _count: sort }));
|
|
3116
3108
|
return relationOrderBy;
|
|
3117
3109
|
}).optional();
|
|
3118
|
-
} else if (fieldDef.computed && fieldDef.params) fields[field] = z
|
|
3110
|
+
} else if (fieldDef.computed && fieldDef.params) fields[field] = z.strictObject({
|
|
3119
3111
|
args: this.makeFieldArgsSchema(fieldDef.params),
|
|
3120
3112
|
sort,
|
|
3121
|
-
nulls: z
|
|
3113
|
+
nulls: z.union([z.literal("first"), z.literal("last")]).optional()
|
|
3122
3114
|
}).optional();
|
|
3123
|
-
else if (fieldDef.optional) fields[field] = z
|
|
3115
|
+
else if (fieldDef.optional) fields[field] = z.union([sort, z.strictObject({
|
|
3124
3116
|
sort,
|
|
3125
|
-
nulls: z
|
|
3117
|
+
nulls: z.union([z.literal("first"), z.literal("last")]).optional()
|
|
3126
3118
|
})]).optional();
|
|
3127
3119
|
else fields[field] = sort.optional();
|
|
3128
3120
|
if (WithAggregation) for (const agg of [
|
|
@@ -3131,31 +3123,31 @@ var ZodSchemaFactory = class {
|
|
|
3131
3123
|
"_sum",
|
|
3132
3124
|
"_min",
|
|
3133
3125
|
"_max"
|
|
3134
|
-
]) fields[agg] = z
|
|
3126
|
+
]) fields[agg] = z.lazy(() => this.makeOrderBySchema(model, true, false, options).optional());
|
|
3135
3127
|
if (this.providerSupportsFuzzySearch) {
|
|
3136
3128
|
const fuzzyFieldNames = this.getModelFields(model).filter(([, def]) => !def.relation && def.type === "String" && def.fuzzy === true).map(([name]) => name);
|
|
3137
|
-
if (fuzzyFieldNames.length > 0) fields["_fuzzyRelevance"] = z
|
|
3138
|
-
fields: z
|
|
3139
|
-
search: z
|
|
3140
|
-
mode: z
|
|
3141
|
-
z
|
|
3142
|
-
z
|
|
3143
|
-
z
|
|
3129
|
+
if (fuzzyFieldNames.length > 0) fields["_fuzzyRelevance"] = z.strictObject({
|
|
3130
|
+
fields: z.array(z.enum(fuzzyFieldNames)).min(1),
|
|
3131
|
+
search: z.string(),
|
|
3132
|
+
mode: z.union([
|
|
3133
|
+
z.literal("simple"),
|
|
3134
|
+
z.literal("word"),
|
|
3135
|
+
z.literal("strictWord")
|
|
3144
3136
|
]).default("simple"),
|
|
3145
|
-
unaccent: z
|
|
3137
|
+
unaccent: z.boolean().default(false),
|
|
3146
3138
|
sort
|
|
3147
3139
|
}).optional();
|
|
3148
3140
|
}
|
|
3149
3141
|
if (this.providerSupportsFullTextSearch) {
|
|
3150
3142
|
const fullTextFieldNames = this.getModelFields(model).filter(([, def]) => !def.relation && def.type === "String" && def.fullText === true).map(([name]) => name);
|
|
3151
|
-
if (fullTextFieldNames.length > 0) fields["_ftsRelevance"] = z
|
|
3152
|
-
fields: z
|
|
3153
|
-
search: z
|
|
3154
|
-
config: z
|
|
3143
|
+
if (fullTextFieldNames.length > 0) fields["_ftsRelevance"] = z.strictObject({
|
|
3144
|
+
fields: z.array(z.enum(fullTextFieldNames)).min(1),
|
|
3145
|
+
search: z.string().min(1),
|
|
3146
|
+
config: z.string().min(1).optional(),
|
|
3155
3147
|
sort
|
|
3156
3148
|
}).optional();
|
|
3157
3149
|
}
|
|
3158
|
-
const schema = refineAtMostOneKey(z
|
|
3150
|
+
const schema = refineAtMostOneKey(z.strictObject(fields));
|
|
3159
3151
|
let schemaId = `${model}OrderBy`;
|
|
3160
3152
|
if (withRelation) schemaId += "WithRelation";
|
|
3161
3153
|
if (WithAggregation) schemaId += "WithAggregation";
|
|
@@ -3165,7 +3157,7 @@ var ZodSchemaFactory = class {
|
|
|
3165
3157
|
}
|
|
3166
3158
|
makeDistinctSchema(model) {
|
|
3167
3159
|
const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
|
|
3168
|
-
const schema = nonRelationFields.length > 0 ? this.orArray(z
|
|
3160
|
+
const schema = nonRelationFields.length > 0 ? this.orArray(z.enum(nonRelationFields), true) : z.never();
|
|
3169
3161
|
this.registerSchema(`${model}DistinctInput`, schema);
|
|
3170
3162
|
return schema;
|
|
3171
3163
|
}
|
|
@@ -3176,7 +3168,7 @@ var ZodSchemaFactory = class {
|
|
|
3176
3168
|
}
|
|
3177
3169
|
makeCreateSchema(model, options) {
|
|
3178
3170
|
const dataSchema = this.makeCreateDataSchema(model, false, [], false, options);
|
|
3179
|
-
const baseSchema = z
|
|
3171
|
+
const baseSchema = z.strictObject({
|
|
3180
3172
|
data: dataSchema,
|
|
3181
3173
|
select: this.makeSelectSchema(model, options).optional().nullable(),
|
|
3182
3174
|
include: this.makeIncludeSchema(model, options).optional().nullable(),
|
|
@@ -3225,7 +3217,7 @@ var ZodSchemaFactory = class {
|
|
|
3225
3217
|
const oppositeFieldDef = requireField(this.schema, fieldDef.type, oppositeField);
|
|
3226
3218
|
if (oppositeFieldDef.relation?.fields) excludeFields.push(...oppositeFieldDef.relation.fields);
|
|
3227
3219
|
}
|
|
3228
|
-
let fieldSchema = z
|
|
3220
|
+
let fieldSchema = z.lazy(() => this.makeRelationManipulationSchema(model, field, excludeFields, "create", nextOpts));
|
|
3229
3221
|
if (fieldDef.optional || fieldDef.array) fieldSchema = fieldSchema.optional();
|
|
3230
3222
|
else {
|
|
3231
3223
|
let allFksOptional = false;
|
|
@@ -3239,26 +3231,26 @@ var ZodSchemaFactory = class {
|
|
|
3239
3231
|
checkedVariantFields[field] = fieldSchema;
|
|
3240
3232
|
if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
|
|
3241
3233
|
} else {
|
|
3242
|
-
let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef
|
|
3234
|
+
let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
|
|
3243
3235
|
if (fieldDef.array) {
|
|
3244
3236
|
fieldSchema = ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
|
|
3245
|
-
fieldSchema = z
|
|
3237
|
+
fieldSchema = z.union([fieldSchema, z.strictObject({ set: fieldSchema })]).optional();
|
|
3246
3238
|
}
|
|
3247
3239
|
if (fieldDef.optional || fieldHasDefaultValue(fieldDef)) fieldSchema = fieldSchema.optional();
|
|
3248
|
-
if (fieldDef.optional) if (fieldDef.type === "Json") fieldSchema = z
|
|
3240
|
+
if (fieldDef.optional) if (fieldDef.type === "Json") fieldSchema = z.union([fieldSchema, z.instanceof(DbNullClass)]);
|
|
3249
3241
|
else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeNullableTypedJsonMutationSchema(fieldSchema);
|
|
3250
3242
|
else fieldSchema = fieldSchema.nullable();
|
|
3251
3243
|
uncheckedVariantFields[field] = fieldSchema;
|
|
3252
3244
|
if (!fieldDef.foreignKeyFor) checkedVariantFields[field] = fieldSchema;
|
|
3253
3245
|
}
|
|
3254
3246
|
});
|
|
3255
|
-
const uncheckedCreateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z
|
|
3256
|
-
const checkedCreateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z
|
|
3257
|
-
const result = !hasRelation ? this.orArray(uncheckedCreateSchema, canBeArray) : z
|
|
3247
|
+
const uncheckedCreateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes) : z.strictObject(uncheckedVariantFields);
|
|
3248
|
+
const checkedCreateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes) : z.strictObject(checkedVariantFields);
|
|
3249
|
+
const result = !hasRelation ? this.orArray(uncheckedCreateSchema, canBeArray) : z.union([
|
|
3258
3250
|
uncheckedCreateSchema,
|
|
3259
3251
|
checkedCreateSchema,
|
|
3260
|
-
...canBeArray ? [z
|
|
3261
|
-
...canBeArray ? [z
|
|
3252
|
+
...canBeArray ? [z.array(uncheckedCreateSchema)] : [],
|
|
3253
|
+
...canBeArray ? [z.array(checkedCreateSchema)] : []
|
|
3262
3254
|
]);
|
|
3263
3255
|
const idParts = [`${model}CreateData`];
|
|
3264
3256
|
if (canBeArray) idParts.push("Array");
|
|
@@ -3283,17 +3275,17 @@ var ZodSchemaFactory = class {
|
|
|
3283
3275
|
fields["disconnect"] = this.makeDisconnectDataSchema(fieldType, array, options).optional();
|
|
3284
3276
|
fields["delete"] = this.makeDeleteRelationDataSchema(fieldType, array, true, options).optional();
|
|
3285
3277
|
}
|
|
3286
|
-
fields["update"] = array ? this.orArray(z
|
|
3278
|
+
fields["update"] = array ? this.orArray(z.strictObject({
|
|
3287
3279
|
where: this.makeWhereSchema(fieldType, true, false, false, options),
|
|
3288
3280
|
data: this.makeUpdateDataSchema(fieldType, withoutFields, false, options)
|
|
3289
|
-
}), true).optional() : z
|
|
3281
|
+
}), true).optional() : z.union([z.strictObject({
|
|
3290
3282
|
where: this.makeWhereSchema(fieldType, false, false, false, options).optional(),
|
|
3291
3283
|
data: this.makeUpdateDataSchema(fieldType, withoutFields, false, options)
|
|
3292
3284
|
}), this.makeUpdateDataSchema(fieldType, withoutFields, false, options)]).optional();
|
|
3293
3285
|
if (canCreateModel) {
|
|
3294
3286
|
let upsertWhere = this.makeWhereSchema(fieldType, true, false, false, options);
|
|
3295
3287
|
if (!fieldDef.array) upsertWhere = upsertWhere.optional();
|
|
3296
|
-
fields["upsert"] = this.orArray(z
|
|
3288
|
+
fields["upsert"] = this.orArray(z.strictObject({
|
|
3297
3289
|
where: upsertWhere,
|
|
3298
3290
|
create: this.makeCreateDataSchema(fieldType, false, withoutFields, false, options),
|
|
3299
3291
|
update: this.makeUpdateDataSchema(fieldType, withoutFields, false, options)
|
|
@@ -3301,14 +3293,14 @@ var ZodSchemaFactory = class {
|
|
|
3301
3293
|
}
|
|
3302
3294
|
if (array) {
|
|
3303
3295
|
fields["set"] = this.makeSetDataSchema(fieldType, true, options).optional();
|
|
3304
|
-
fields["updateMany"] = this.orArray(z
|
|
3296
|
+
fields["updateMany"] = this.orArray(z.strictObject({
|
|
3305
3297
|
where: this.makeWhereSchema(fieldType, false, true, false, options),
|
|
3306
3298
|
data: this.makeUpdateDataSchema(fieldType, withoutFields, false, options)
|
|
3307
3299
|
}), true).optional();
|
|
3308
3300
|
fields["deleteMany"] = this.makeDeleteRelationDataSchema(fieldType, true, false, options).optional();
|
|
3309
3301
|
}
|
|
3310
3302
|
}
|
|
3311
|
-
return z
|
|
3303
|
+
return z.strictObject(fields);
|
|
3312
3304
|
}
|
|
3313
3305
|
makeSetDataSchema(model, canBeArray, options) {
|
|
3314
3306
|
return this.orArray(this.makeWhereSchema(model, true, false, false, options), canBeArray);
|
|
@@ -3318,23 +3310,23 @@ var ZodSchemaFactory = class {
|
|
|
3318
3310
|
}
|
|
3319
3311
|
makeDisconnectDataSchema(model, canBeArray, options) {
|
|
3320
3312
|
if (canBeArray) return this.orArray(this.makeWhereSchema(model, true, false, false, options), canBeArray);
|
|
3321
|
-
else return z
|
|
3313
|
+
else return z.union([z.boolean(), this.makeWhereSchema(model, false, false, false, options)]);
|
|
3322
3314
|
}
|
|
3323
3315
|
makeDeleteRelationDataSchema(model, toManyRelation, uniqueFilter, options) {
|
|
3324
|
-
return toManyRelation ? this.orArray(this.makeWhereSchema(model, uniqueFilter, false, false, options), true) : z
|
|
3316
|
+
return toManyRelation ? this.orArray(this.makeWhereSchema(model, uniqueFilter, false, false, options), true) : z.union([z.boolean(), this.makeWhereSchema(model, uniqueFilter, false, false, options)]);
|
|
3325
3317
|
}
|
|
3326
3318
|
makeConnectOrCreateDataSchema(model, canBeArray, withoutFields, options) {
|
|
3327
3319
|
const whereSchema = this.makeWhereSchema(model, true, false, false, options);
|
|
3328
3320
|
const createSchema = this.makeCreateDataSchema(model, false, withoutFields, false, options);
|
|
3329
|
-
return this.orArray(z
|
|
3321
|
+
return this.orArray(z.strictObject({
|
|
3330
3322
|
where: whereSchema,
|
|
3331
3323
|
create: createSchema
|
|
3332
3324
|
}), canBeArray);
|
|
3333
3325
|
}
|
|
3334
3326
|
makeCreateManyPayloadSchema(model, withoutFields, options) {
|
|
3335
|
-
const schema = z
|
|
3327
|
+
const schema = z.strictObject({
|
|
3336
3328
|
data: this.makeCreateDataSchema(model, true, withoutFields, true, options),
|
|
3337
|
-
skipDuplicates: z
|
|
3329
|
+
skipDuplicates: z.boolean().optional()
|
|
3338
3330
|
});
|
|
3339
3331
|
const idParts = [`${model}CreateManyPayload`];
|
|
3340
3332
|
if (withoutFields.length) idParts.push(`Without${withoutFields.slice().sort().join("")}`);
|
|
@@ -3342,7 +3334,7 @@ var ZodSchemaFactory = class {
|
|
|
3342
3334
|
return schema;
|
|
3343
3335
|
}
|
|
3344
3336
|
makeUpdateSchema(model, options) {
|
|
3345
|
-
const baseSchema = z
|
|
3337
|
+
const baseSchema = z.strictObject({
|
|
3346
3338
|
where: this.makeWhereSchema(model, true, false, false, options),
|
|
3347
3339
|
data: this.makeUpdateDataSchema(model, [], false, options),
|
|
3348
3340
|
select: this.makeSelectSchema(model, options).optional().nullable(),
|
|
@@ -3357,10 +3349,10 @@ var ZodSchemaFactory = class {
|
|
|
3357
3349
|
return schema;
|
|
3358
3350
|
}
|
|
3359
3351
|
makeUpdateManySchema(model, options) {
|
|
3360
|
-
const result = this.mergePluginArgsSchema(z
|
|
3352
|
+
const result = this.mergePluginArgsSchema(z.strictObject({
|
|
3361
3353
|
where: this.makeWhereSchema(model, false, false, false, options).optional(),
|
|
3362
3354
|
data: this.makeUpdateDataSchema(model, [], true, options),
|
|
3363
|
-
limit: z
|
|
3355
|
+
limit: z.number().int().nonnegative().optional()
|
|
3364
3356
|
}), "updateMany");
|
|
3365
3357
|
this.registerSchema(`${model}UpdateManyArgs`, result);
|
|
3366
3358
|
return result;
|
|
@@ -3376,7 +3368,7 @@ var ZodSchemaFactory = class {
|
|
|
3376
3368
|
return schema;
|
|
3377
3369
|
}
|
|
3378
3370
|
makeUpsertSchema(model, options) {
|
|
3379
|
-
const baseSchema = z
|
|
3371
|
+
const baseSchema = z.strictObject({
|
|
3380
3372
|
where: this.makeWhereSchema(model, true, false, false, options),
|
|
3381
3373
|
create: this.makeCreateDataSchema(model, false, [], false, options),
|
|
3382
3374
|
update: this.makeUpdateDataSchema(model, [], false, options),
|
|
@@ -3412,27 +3404,27 @@ var ZodSchemaFactory = class {
|
|
|
3412
3404
|
const oppositeFieldDef = requireField(this.schema, fieldDef.type, oppositeField);
|
|
3413
3405
|
if (oppositeFieldDef.relation?.fields) excludeFields.push(...oppositeFieldDef.relation.fields);
|
|
3414
3406
|
}
|
|
3415
|
-
let fieldSchema = z
|
|
3407
|
+
let fieldSchema = z.lazy(() => this.makeRelationManipulationSchema(model, field, excludeFields, "update", nextOpts)).optional();
|
|
3416
3408
|
if (fieldDef.optional && !fieldDef.array) fieldSchema = fieldSchema.nullable();
|
|
3417
3409
|
checkedVariantFields[field] = fieldSchema;
|
|
3418
3410
|
if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
|
|
3419
3411
|
} else {
|
|
3420
|
-
let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef
|
|
3421
|
-
if (this.isNumericField(fieldDef)) fieldSchema = z
|
|
3422
|
-
set: this.nullableIf(z
|
|
3423
|
-
increment: z
|
|
3424
|
-
decrement: z
|
|
3425
|
-
multiply: z
|
|
3426
|
-
divide: z
|
|
3412
|
+
let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
|
|
3413
|
+
if (this.isNumericField(fieldDef)) fieldSchema = z.union([fieldSchema, z.object({
|
|
3414
|
+
set: this.nullableIf(z.number().optional(), !!fieldDef.optional).optional(),
|
|
3415
|
+
increment: z.number().optional(),
|
|
3416
|
+
decrement: z.number().optional(),
|
|
3417
|
+
multiply: z.number().optional(),
|
|
3418
|
+
divide: z.number().optional()
|
|
3427
3419
|
}).refine((v) => Object.keys(v).length === 1, "Only one of \"set\", \"increment\", \"decrement\", \"multiply\", or \"divide\" can be provided")]);
|
|
3428
3420
|
if (fieldDef.array) {
|
|
3429
3421
|
const arraySchema = ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
|
|
3430
|
-
fieldSchema = z
|
|
3422
|
+
fieldSchema = z.union([arraySchema, z.object({
|
|
3431
3423
|
set: arraySchema.optional(),
|
|
3432
|
-
push: z
|
|
3424
|
+
push: z.union([fieldSchema, fieldSchema.array()]).optional()
|
|
3433
3425
|
}).refine((v) => Object.keys(v).length === 1, "Only one of \"set\", \"push\" can be provided")]);
|
|
3434
3426
|
}
|
|
3435
|
-
if (fieldDef.optional) if (fieldDef.type === "Json") fieldSchema = z
|
|
3427
|
+
if (fieldDef.optional) if (fieldDef.type === "Json") fieldSchema = z.union([fieldSchema, z.instanceof(DbNullClass)]);
|
|
3436
3428
|
else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeNullableTypedJsonMutationSchema(fieldSchema);
|
|
3437
3429
|
else fieldSchema = fieldSchema.nullable();
|
|
3438
3430
|
fieldSchema = fieldSchema.optional();
|
|
@@ -3440,9 +3432,9 @@ var ZodSchemaFactory = class {
|
|
|
3440
3432
|
if (!fieldDef.foreignKeyFor) checkedVariantFields[field] = fieldSchema;
|
|
3441
3433
|
}
|
|
3442
3434
|
});
|
|
3443
|
-
const uncheckedUpdateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z
|
|
3444
|
-
const checkedUpdateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z
|
|
3445
|
-
const result = !hasRelation ? uncheckedUpdateSchema : z
|
|
3435
|
+
const uncheckedUpdateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes) : z.strictObject(uncheckedVariantFields);
|
|
3436
|
+
const checkedUpdateSchema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes) : z.strictObject(checkedVariantFields);
|
|
3437
|
+
const result = !hasRelation ? uncheckedUpdateSchema : z.union([uncheckedUpdateSchema, checkedUpdateSchema]);
|
|
3446
3438
|
const idParts = [`${model}UpdateData`];
|
|
3447
3439
|
if (withoutRelationFields) idParts.push("WithoutRelation");
|
|
3448
3440
|
if (withoutFields.length) idParts.push(`Without${withoutFields.slice().sort().join("")}`);
|
|
@@ -3450,7 +3442,7 @@ var ZodSchemaFactory = class {
|
|
|
3450
3442
|
return result;
|
|
3451
3443
|
}
|
|
3452
3444
|
makeDeleteSchema(model, options) {
|
|
3453
|
-
const baseSchema = z
|
|
3445
|
+
const baseSchema = z.strictObject({
|
|
3454
3446
|
where: this.makeWhereSchema(model, true, false, false, options),
|
|
3455
3447
|
select: this.makeSelectSchema(model, options).optional().nullable(),
|
|
3456
3448
|
include: this.makeIncludeSchema(model, options).optional().nullable(),
|
|
@@ -3464,15 +3456,15 @@ var ZodSchemaFactory = class {
|
|
|
3464
3456
|
return schema;
|
|
3465
3457
|
}
|
|
3466
3458
|
makeDeleteManySchema(model, options) {
|
|
3467
|
-
const result = this.mergePluginArgsSchema(z
|
|
3459
|
+
const result = this.mergePluginArgsSchema(z.strictObject({
|
|
3468
3460
|
where: this.makeWhereSchema(model, false, false, false, options).optional(),
|
|
3469
|
-
limit: z
|
|
3461
|
+
limit: z.number().int().nonnegative().optional()
|
|
3470
3462
|
}), "deleteMany").optional();
|
|
3471
3463
|
this.registerSchema(`${model}DeleteManyArgs`, result);
|
|
3472
3464
|
return result;
|
|
3473
3465
|
}
|
|
3474
3466
|
makeCountSchema(model, options) {
|
|
3475
|
-
const result = this.mergePluginArgsSchema(z
|
|
3467
|
+
const result = this.mergePluginArgsSchema(z.strictObject({
|
|
3476
3468
|
where: this.makeWhereSchema(model, false, false, false, options).optional(),
|
|
3477
3469
|
skip: this.makeSkipSchema().optional(),
|
|
3478
3470
|
take: this.makeTakeSchema().optional(),
|
|
@@ -3483,10 +3475,10 @@ var ZodSchemaFactory = class {
|
|
|
3483
3475
|
return result;
|
|
3484
3476
|
}
|
|
3485
3477
|
makeCountAggregateInputSchema(model) {
|
|
3486
|
-
const schema = z
|
|
3487
|
-
_all: z
|
|
3478
|
+
const schema = z.union([z.literal(true), z.strictObject({
|
|
3479
|
+
_all: z.literal(true).optional(),
|
|
3488
3480
|
...this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
|
|
3489
|
-
acc[field] = this.isParameterizedComputedField(fieldDef) ? z
|
|
3481
|
+
acc[field] = this.isParameterizedComputedField(fieldDef) ? z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z.literal(true).optional();
|
|
3490
3482
|
return acc;
|
|
3491
3483
|
}, {})
|
|
3492
3484
|
})]);
|
|
@@ -3494,7 +3486,7 @@ var ZodSchemaFactory = class {
|
|
|
3494
3486
|
return schema;
|
|
3495
3487
|
}
|
|
3496
3488
|
makeAggregateSchema(model, options) {
|
|
3497
|
-
const result = this.mergePluginArgsSchema(z
|
|
3489
|
+
const result = this.mergePluginArgsSchema(z.strictObject({
|
|
3498
3490
|
where: this.makeWhereSchema(model, false, false, false, options).optional(),
|
|
3499
3491
|
skip: this.makeSkipSchema().optional(),
|
|
3500
3492
|
take: this.makeTakeSchema().optional(),
|
|
@@ -3509,16 +3501,16 @@ var ZodSchemaFactory = class {
|
|
|
3509
3501
|
return result;
|
|
3510
3502
|
}
|
|
3511
3503
|
makeSumAvgInputSchema(model) {
|
|
3512
|
-
const schema = z
|
|
3513
|
-
if (this.isNumericField(fieldDef)) acc[field] = this.isParameterizedComputedField(fieldDef) ? z
|
|
3504
|
+
const schema = z.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
|
|
3505
|
+
if (this.isNumericField(fieldDef)) acc[field] = this.isParameterizedComputedField(fieldDef) ? z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z.literal(true).optional();
|
|
3514
3506
|
return acc;
|
|
3515
3507
|
}, {}));
|
|
3516
3508
|
this.registerSchema(`${model}SumAvgAggregateInput`, schema);
|
|
3517
3509
|
return schema;
|
|
3518
3510
|
}
|
|
3519
3511
|
makeMinMaxInputSchema(model) {
|
|
3520
|
-
const schema = z
|
|
3521
|
-
if (!fieldDef.relation && !fieldDef.array) acc[field] = this.isParameterizedComputedField(fieldDef) ? z
|
|
3512
|
+
const schema = z.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
|
|
3513
|
+
if (!fieldDef.relation && !fieldDef.array) acc[field] = this.isParameterizedComputedField(fieldDef) ? z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : z.literal(true).optional();
|
|
3522
3514
|
return acc;
|
|
3523
3515
|
}, {}));
|
|
3524
3516
|
this.registerSchema(`${model}MinMaxAggregateInput`, schema);
|
|
@@ -3527,14 +3519,14 @@ var ZodSchemaFactory = class {
|
|
|
3527
3519
|
makeGroupBySchema(model, options) {
|
|
3528
3520
|
const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
|
|
3529
3521
|
const byMembers = [];
|
|
3530
|
-
if (nonRelationFields.length > 0) byMembers.push(z
|
|
3531
|
-
for (const [field, fieldDef] of this.getModelFields(model)) if (this.isParameterizedComputedField(fieldDef)) byMembers.push(z
|
|
3532
|
-
field: z
|
|
3522
|
+
if (nonRelationFields.length > 0) byMembers.push(z.enum(nonRelationFields));
|
|
3523
|
+
for (const [field, fieldDef] of this.getModelFields(model)) if (this.isParameterizedComputedField(fieldDef)) byMembers.push(z.strictObject({
|
|
3524
|
+
field: z.literal(field),
|
|
3533
3525
|
args: this.makeFieldArgsSchema(fieldDef.params)
|
|
3534
3526
|
}));
|
|
3535
|
-
const byElement = byMembers.length === 0 ? void 0 : byMembers.length === 1 ? byMembers[0] : z
|
|
3536
|
-
const bySchema = byElement ? this.orArray(byElement, true) : z
|
|
3537
|
-
const baseSchema = z
|
|
3527
|
+
const byElement = byMembers.length === 0 ? void 0 : byMembers.length === 1 ? byMembers[0] : z.union(byMembers);
|
|
3528
|
+
const bySchema = byElement ? this.orArray(byElement, true) : z.never();
|
|
3529
|
+
const baseSchema = z.strictObject({
|
|
3538
3530
|
where: this.makeWhereSchema(model, false, false, false, options).optional(),
|
|
3539
3531
|
orderBy: this.orArray(this.makeOrderBySchema(model, false, true, options), true).optional(),
|
|
3540
3532
|
by: bySchema,
|
|
@@ -3586,7 +3578,7 @@ var ZodSchemaFactory = class {
|
|
|
3586
3578
|
if (!procDef) throw createInternalError(`Procedure not found: ${procName}`);
|
|
3587
3579
|
const shape = {};
|
|
3588
3580
|
for (const param of Object.values(procDef.params ?? {})) shape[param.name] = this.makeProcedureParamSchema(param);
|
|
3589
|
-
const schema = z
|
|
3581
|
+
const schema = z.object(shape);
|
|
3590
3582
|
this.registerSchema(`${procName}ProcArgs`, schema);
|
|
3591
3583
|
return schema;
|
|
3592
3584
|
}
|
|
@@ -3594,10 +3586,10 @@ var ZodSchemaFactory = class {
|
|
|
3594
3586
|
let schema;
|
|
3595
3587
|
if (isTypeDef(this.schema, param.type)) schema = this.makeTypeDefSchema(param.type);
|
|
3596
3588
|
else if (isEnum(this.schema, param.type)) schema = this.makeEnumSchema(param.type);
|
|
3597
|
-
else if (param.type in (this.schema.models ?? {})) schema = z
|
|
3589
|
+
else if (param.type in (this.schema.models ?? {})) schema = z.record(z.string(), z.unknown());
|
|
3598
3590
|
else {
|
|
3599
3591
|
schema = this.makeScalarSchema(param.type);
|
|
3600
|
-
if (schema instanceof z
|
|
3592
|
+
if (schema instanceof z.ZodUnknown) throw createInternalError(`Unsupported procedure parameter type: ${param.type}`);
|
|
3601
3593
|
}
|
|
3602
3594
|
if (param.array) schema = schema.array();
|
|
3603
3595
|
if (param.optional) schema = schema.optional();
|
|
@@ -3633,10 +3625,10 @@ var ZodSchemaFactory = class {
|
|
|
3633
3625
|
return result;
|
|
3634
3626
|
}
|
|
3635
3627
|
makeSkipSchema() {
|
|
3636
|
-
return z
|
|
3628
|
+
return z.number().int().nonnegative();
|
|
3637
3629
|
}
|
|
3638
3630
|
makeTakeSchema() {
|
|
3639
|
-
return z
|
|
3631
|
+
return z.number().int();
|
|
3640
3632
|
}
|
|
3641
3633
|
refineForSelectIncludeMutuallyExclusive(schema) {
|
|
3642
3634
|
return schema.refine((value) => !(value["select"] && value["include"]), "\"select\" and \"include\" cannot be used together");
|
|
@@ -3655,10 +3647,10 @@ var ZodSchemaFactory = class {
|
|
|
3655
3647
|
return nullable ? schema.nullable() : schema;
|
|
3656
3648
|
}
|
|
3657
3649
|
orArray(schema, canBeArray) {
|
|
3658
|
-
return canBeArray ? z
|
|
3650
|
+
return canBeArray ? z.union([schema, z.array(schema)]) : schema;
|
|
3659
3651
|
}
|
|
3660
3652
|
isNumericField(fieldDef) {
|
|
3661
|
-
return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
|
|
3653
|
+
return NUMERIC_FIELD_TYPES.includes(this.getEffectiveFieldType(fieldDef.type)) && !fieldDef.array;
|
|
3662
3654
|
}
|
|
3663
3655
|
get providerSupportsCaseSensitivity() {
|
|
3664
3656
|
return this.schema.provider.type === "postgresql";
|
|
@@ -3717,10 +3709,10 @@ var ZodSchemaFactory = class {
|
|
|
3717
3709
|
createUnionFilterSchema(valueSchema, optional, components, allowedFilterKinds) {
|
|
3718
3710
|
if (Object.keys(components).length === 0) {
|
|
3719
3711
|
if (!allowedFilterKinds || allowedFilterKinds.includes("Equality")) return this.nullableIf(valueSchema, optional);
|
|
3720
|
-
return z
|
|
3712
|
+
return z.never();
|
|
3721
3713
|
}
|
|
3722
|
-
if (!allowedFilterKinds || allowedFilterKinds.includes("Equality")) return z
|
|
3723
|
-
else return z
|
|
3714
|
+
if (!allowedFilterKinds || allowedFilterKinds.includes("Equality")) return z.union([this.nullableIf(valueSchema, optional), z.strictObject(components)]);
|
|
3715
|
+
else return z.strictObject(components);
|
|
3724
3716
|
}
|
|
3725
3717
|
canCreateModel(model) {
|
|
3726
3718
|
const modelDef = requireModel(this.schema, model);
|
|
@@ -3778,7 +3770,7 @@ __decorate([
|
|
|
3778
3770
|
__decorate([
|
|
3779
3771
|
cache(),
|
|
3780
3772
|
__decorateMetadata("design:type", Function),
|
|
3781
|
-
__decorateMetadata("design:paramtypes", [String]),
|
|
3773
|
+
__decorateMetadata("design:paramtypes", [String, Array]),
|
|
3782
3774
|
__decorateMetadata("design:returntype", typeof (_ref2 = typeof ZodType !== "undefined" && ZodType) === "function" ? _ref2 : Object)
|
|
3783
3775
|
], ZodSchemaFactory.prototype, "makeTypeDefSchema", null);
|
|
3784
3776
|
__decorate([
|
|
@@ -4283,94 +4275,13 @@ var InputValidator = class {
|
|
|
4283
4275
|
//#endregion
|
|
4284
4276
|
//#region src/client/crud/operations/base.ts
|
|
4285
4277
|
/**
|
|
4286
|
-
*
|
|
4278
|
+
* Maximum number of rows identified by id in a single statement during cascade delete simulation.
|
|
4287
4279
|
*/
|
|
4288
|
-
const
|
|
4289
|
-
"findMany",
|
|
4290
|
-
"findUnique",
|
|
4291
|
-
"findFirst",
|
|
4292
|
-
"create",
|
|
4293
|
-
"createMany",
|
|
4294
|
-
"createManyAndReturn",
|
|
4295
|
-
"update",
|
|
4296
|
-
"updateMany",
|
|
4297
|
-
"updateManyAndReturn",
|
|
4298
|
-
"upsert",
|
|
4299
|
-
"delete",
|
|
4300
|
-
"deleteMany",
|
|
4301
|
-
"count",
|
|
4302
|
-
"aggregate",
|
|
4303
|
-
"groupBy",
|
|
4304
|
-
"exists"
|
|
4305
|
-
];
|
|
4280
|
+
const DELETE_ID_BATCH_SIZE = 1e3;
|
|
4306
4281
|
/**
|
|
4307
|
-
*
|
|
4282
|
+
* Same as `DELETE_ID_BATCH_SIZE`, for compound ids, which are matched with one `OR` branch per row.
|
|
4308
4283
|
*/
|
|
4309
|
-
const
|
|
4310
|
-
"findMany",
|
|
4311
|
-
"findUnique",
|
|
4312
|
-
"findFirst",
|
|
4313
|
-
"count",
|
|
4314
|
-
"aggregate",
|
|
4315
|
-
"groupBy",
|
|
4316
|
-
"exists"
|
|
4317
|
-
];
|
|
4318
|
-
/**
|
|
4319
|
-
* List of core write operations.
|
|
4320
|
-
*/
|
|
4321
|
-
const CoreWriteOperations = [
|
|
4322
|
-
"create",
|
|
4323
|
-
"createMany",
|
|
4324
|
-
"createManyAndReturn",
|
|
4325
|
-
"update",
|
|
4326
|
-
"updateMany",
|
|
4327
|
-
"updateManyAndReturn",
|
|
4328
|
-
"upsert",
|
|
4329
|
-
"delete",
|
|
4330
|
-
"deleteMany"
|
|
4331
|
-
];
|
|
4332
|
-
/**
|
|
4333
|
-
* List of core create operations.
|
|
4334
|
-
*/
|
|
4335
|
-
const CoreCreateOperations = [
|
|
4336
|
-
"create",
|
|
4337
|
-
"createMany",
|
|
4338
|
-
"createManyAndReturn",
|
|
4339
|
-
"upsert"
|
|
4340
|
-
];
|
|
4341
|
-
/**
|
|
4342
|
-
* List of core update operations.
|
|
4343
|
-
*/
|
|
4344
|
-
const CoreUpdateOperations = [
|
|
4345
|
-
"update",
|
|
4346
|
-
"updateMany",
|
|
4347
|
-
"updateManyAndReturn",
|
|
4348
|
-
"upsert"
|
|
4349
|
-
];
|
|
4350
|
-
/**
|
|
4351
|
-
* List of core delete operations.
|
|
4352
|
-
*/
|
|
4353
|
-
const CoreDeleteOperations = ["delete", "deleteMany"];
|
|
4354
|
-
/**
|
|
4355
|
-
* List of all CRUD operations, including 'orThrow' variants.
|
|
4356
|
-
*/
|
|
4357
|
-
const AllCrudOperations = [
|
|
4358
|
-
...CoreCrudOperations,
|
|
4359
|
-
"findUniqueOrThrow",
|
|
4360
|
-
"findFirstOrThrow"
|
|
4361
|
-
];
|
|
4362
|
-
/**
|
|
4363
|
-
* List of all read operations, including 'orThrow' variants.
|
|
4364
|
-
*/
|
|
4365
|
-
const AllReadOperations = [
|
|
4366
|
-
...CoreReadOperations,
|
|
4367
|
-
"findUniqueOrThrow",
|
|
4368
|
-
"findFirstOrThrow"
|
|
4369
|
-
];
|
|
4370
|
-
/**
|
|
4371
|
-
* List of all write operations - simply an alias of CoreWriteOperations.
|
|
4372
|
-
*/
|
|
4373
|
-
const AllWriteOperations = CoreWriteOperations;
|
|
4284
|
+
const DELETE_COMPOUND_ID_BATCH_SIZE = 100;
|
|
4374
4285
|
var BaseOperationHandler = class {
|
|
4375
4286
|
dialect;
|
|
4376
4287
|
constructor(client, model, inputValidator) {
|
|
@@ -4465,7 +4376,7 @@ var BaseOperationHandler = class {
|
|
|
4465
4376
|
result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
|
|
4466
4377
|
} else {
|
|
4467
4378
|
if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
|
|
4468
|
-
if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, fieldDef.originModel, payload);
|
|
4379
|
+
if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, this.dialect.delegateJoinAlias(model, parentAlias, fieldDef.originModel), payload);
|
|
4469
4380
|
else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
|
|
4470
4381
|
}
|
|
4471
4382
|
}
|
|
@@ -4827,16 +4738,9 @@ var BaseOperationHandler = class {
|
|
|
4827
4738
|
if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
|
|
4828
4739
|
const origWhere = combinedWhere;
|
|
4829
4740
|
const modelDef = this.requireModel(model);
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
|
|
4834
|
-
if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
|
|
4835
|
-
if (finalData === data) finalData = clone(data);
|
|
4836
|
-
finalData[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
|
|
4837
|
-
autoUpdatedFields.push(fieldName);
|
|
4838
|
-
}
|
|
4839
|
-
}
|
|
4741
|
+
const filled = this.fillUpdatedAtFields(modelDef, data);
|
|
4742
|
+
let finalData = filled.data;
|
|
4743
|
+
const autoUpdatedFields = filled.autoUpdatedFields;
|
|
4840
4744
|
let thisEntity;
|
|
4841
4745
|
const loadThisEntity = async () => {
|
|
4842
4746
|
if (thisEntity === void 0) {
|
|
@@ -4985,7 +4889,8 @@ var BaseOperationHandler = class {
|
|
|
4985
4889
|
});
|
|
4986
4890
|
}
|
|
4987
4891
|
isNumericField(fieldDef) {
|
|
4988
|
-
|
|
4892
|
+
const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
|
|
4893
|
+
return NUMERIC_FIELD_TYPES.includes(type) && !fieldDef.array;
|
|
4989
4894
|
}
|
|
4990
4895
|
makeContextComment(_context) {
|
|
4991
4896
|
return sql``;
|
|
@@ -4998,11 +4903,13 @@ var BaseOperationHandler = class {
|
|
|
4998
4903
|
const parentWhere = await this.buildUpdateParentRelationFilter(kysely, fromRelation);
|
|
4999
4904
|
let combinedWhere = where ?? true;
|
|
5000
4905
|
if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
|
|
4906
|
+
const { data: finalData } = this.fillUpdatedAtFields(modelDef, data);
|
|
4907
|
+
if (modelDef.baseModel && filterModel === void 0) return this.updateManyByIds(kysely, model, combinedWhere, finalData, returnData, fieldsToReturn);
|
|
5001
4908
|
filterModel ??= model;
|
|
5002
4909
|
let updateFields = {};
|
|
5003
|
-
for (const field in
|
|
4910
|
+
for (const field in finalData) {
|
|
5004
4911
|
if (isRelationField(this.schema, model, field)) continue;
|
|
5005
|
-
updateFields[field] = this.processScalarFieldUpdateData(model, field,
|
|
4912
|
+
updateFields[field] = this.processScalarFieldUpdateData(model, field, finalData);
|
|
5006
4913
|
}
|
|
5007
4914
|
let resultFromBaseModel = void 0;
|
|
5008
4915
|
if (modelDef.baseModel) {
|
|
@@ -5053,6 +4960,50 @@ var BaseOperationHandler = class {
|
|
|
5053
4960
|
}
|
|
5054
4961
|
}
|
|
5055
4962
|
}
|
|
4963
|
+
/**
|
|
4964
|
+
* Runs `updateMany` on a delegate sub model by id. Reads the ids of the rows that match
|
|
4965
|
+
* `where`, then updates them in batches with an id filter. Callers run this inside a
|
|
4966
|
+
* transaction (`needsNestedUpdate` is true for every model with a base model).
|
|
4967
|
+
*/
|
|
4968
|
+
async updateManyByIds(kysely, model, where, data, returnData, fieldsToReturn) {
|
|
4969
|
+
const idFields = requireIdFields(this.schema, model);
|
|
4970
|
+
const rows = await this.read(kysely, model, {
|
|
4971
|
+
where,
|
|
4972
|
+
select: Object.fromEntries(idFields.map((f) => [f, true]))
|
|
4973
|
+
});
|
|
4974
|
+
const batchSize = idFields.length === 1 ? 1e3 : 100;
|
|
4975
|
+
let count = 0;
|
|
4976
|
+
const returned = [];
|
|
4977
|
+
for (let i = 0; i < rows.length; i += batchSize) {
|
|
4978
|
+
const batch = rows.slice(i, i + batchSize);
|
|
4979
|
+
const idWhere = idFields.length === 1 ? { [idFields[0]]: { in: batch.map((row) => row[idFields[0]]) } } : { OR: batch.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
|
|
4980
|
+
const result = await this.updateMany(kysely, model, idWhere, data, void 0, returnData, model, void 0, fieldsToReturn);
|
|
4981
|
+
if (returnData) returned.push(...result);
|
|
4982
|
+
else count += result.count;
|
|
4983
|
+
}
|
|
4984
|
+
return returnData ? returned : { count };
|
|
4985
|
+
}
|
|
4986
|
+
/**
|
|
4987
|
+
* Sets `@updatedAt` fields to the current time when `data` changes a scalar or foreign key
|
|
4988
|
+
* field that is not in the field's `ignore` list. A value given explicitly in `data` is kept.
|
|
4989
|
+
* Returns the original `data` object when nothing is filled in, otherwise a clone.
|
|
4990
|
+
*/
|
|
4991
|
+
fillUpdatedAtFields(modelDef, data) {
|
|
4992
|
+
let result = data;
|
|
4993
|
+
const autoUpdatedFields = [];
|
|
4994
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && result[fieldName] === void 0) {
|
|
4995
|
+
const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
|
|
4996
|
+
if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
|
|
4997
|
+
if (result === data) result = clone(data);
|
|
4998
|
+
result[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
|
|
4999
|
+
autoUpdatedFields.push(fieldName);
|
|
5000
|
+
}
|
|
5001
|
+
}
|
|
5002
|
+
return {
|
|
5003
|
+
data: result,
|
|
5004
|
+
autoUpdatedFields
|
|
5005
|
+
};
|
|
5006
|
+
}
|
|
5056
5007
|
async processBaseModelUpdateMany(kysely, model, where, updateFields, filterModel) {
|
|
5057
5008
|
const thisUpdateFields = {};
|
|
5058
5009
|
const remainingFields = {};
|
|
@@ -5123,7 +5074,7 @@ var BaseOperationHandler = class {
|
|
|
5123
5074
|
case "updateMany":
|
|
5124
5075
|
for (const _item of enumerate(value)) {
|
|
5125
5076
|
const item = _item;
|
|
5126
|
-
await this.updateMany(kysely, fieldModel, item.where, item.data, item.limit, false,
|
|
5077
|
+
await this.updateMany(kysely, fieldModel, item.where, item.data, item.limit, false, void 0, fromRelationContext);
|
|
5127
5078
|
}
|
|
5128
5079
|
break;
|
|
5129
5080
|
case "delete":
|
|
@@ -5305,37 +5256,125 @@ var BaseOperationHandler = class {
|
|
|
5305
5256
|
normalizeRelationManipulationInput(model, data) {
|
|
5306
5257
|
return enumerate(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
|
|
5307
5258
|
}
|
|
5308
|
-
async delete(kysely, model, where, limit, filterModel, fieldsToReturn) {
|
|
5259
|
+
async delete(kysely, model, where, limit, filterModel, fieldsToReturn, visited) {
|
|
5309
5260
|
filterModel ??= model;
|
|
5261
|
+
visited ??= /* @__PURE__ */ new Set();
|
|
5310
5262
|
const modelDef = this.requireModel(model);
|
|
5311
5263
|
if (modelDef.baseModel) {
|
|
5312
5264
|
if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
|
|
5313
|
-
return this.processBaseModelDelete(kysely, modelDef.baseModel, where, limit, filterModel);
|
|
5265
|
+
return this.processBaseModelDelete(kysely, modelDef.baseModel, where, limit, filterModel, visited);
|
|
5266
|
+
}
|
|
5267
|
+
const cascadeRelations = this.getDelegateCascadeRelations(model, filterModel);
|
|
5268
|
+
if (cascadeRelations.length === 0) return this.executeDelete(kysely, model, where, limit, filterModel, fieldsToReturn);
|
|
5269
|
+
const discriminator = getDiscriminatorField(this.schema, model);
|
|
5270
|
+
const deletedRows = await this.read(kysely, filterModel, {
|
|
5271
|
+
where,
|
|
5272
|
+
select: {
|
|
5273
|
+
...this.makeIdSelect(filterModel),
|
|
5274
|
+
...discriminator ? { [discriminator]: true } : {}
|
|
5275
|
+
},
|
|
5276
|
+
...limit !== void 0 ? { take: limit } : {}
|
|
5277
|
+
});
|
|
5278
|
+
deletedRows.forEach((row) => visited.add(this.makeVisitedKey(model, row)));
|
|
5279
|
+
for (const { fieldDef, discriminatorValue } of cascadeRelations) {
|
|
5280
|
+
const parentRows = discriminatorValue === void 0 ? deletedRows : deletedRows.filter((row) => row[discriminator] === discriminatorValue);
|
|
5281
|
+
for (const batch of this.batchRows(model, parentRows)) {
|
|
5282
|
+
const childModel = fieldDef.type;
|
|
5283
|
+
const pendingRows = (await this.read(kysely, childModel, {
|
|
5284
|
+
where: this.makeChildFilter(model, fieldDef, batch),
|
|
5285
|
+
select: this.makeIdSelect(childModel)
|
|
5286
|
+
})).filter((row) => {
|
|
5287
|
+
const key = this.makeVisitedKey(childModel, row);
|
|
5288
|
+
if (visited.has(key)) return false;
|
|
5289
|
+
visited.add(key);
|
|
5290
|
+
return true;
|
|
5291
|
+
});
|
|
5292
|
+
for (const childBatch of this.batchRows(childModel, pendingRows)) await this.delete(kysely, childModel, this.makeIdsFilter(childModel, childBatch), void 0, void 0, void 0, visited);
|
|
5293
|
+
}
|
|
5314
5294
|
}
|
|
5295
|
+
let numAffectedRows = 0n;
|
|
5296
|
+
const rows = [];
|
|
5297
|
+
for (const batch of this.batchRows(model, deletedRows)) {
|
|
5298
|
+
const result = await this.executeDelete(kysely, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
|
|
5299
|
+
numAffectedRows += result.numAffectedRows ?? 0n;
|
|
5300
|
+
rows.push(...result.rows);
|
|
5301
|
+
}
|
|
5302
|
+
return {
|
|
5303
|
+
numAffectedRows,
|
|
5304
|
+
rows
|
|
5305
|
+
};
|
|
5306
|
+
}
|
|
5307
|
+
async executeDelete(kysely, model, where, limit, filterModel, fieldsToReturn) {
|
|
5308
|
+
const modelDef = this.requireModel(model);
|
|
5315
5309
|
fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
|
|
5316
5310
|
let needIdFilter = false;
|
|
5317
5311
|
if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
|
|
5318
5312
|
if (modelDef.isDelegate || modelDef.baseModel) needIdFilter = true;
|
|
5319
5313
|
const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely, model)), "in", 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()) : () => this.dialect.buildFilter(model, model, where);
|
|
5320
|
-
await this.processDelegateRelationDelete(kysely, modelDef, where, limit);
|
|
5321
5314
|
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({
|
|
5322
5315
|
model,
|
|
5323
5316
|
operation: "delete"
|
|
5324
5317
|
}));
|
|
5325
5318
|
return this.executeQuery(kysely, query, "delete");
|
|
5326
5319
|
}
|
|
5327
|
-
|
|
5328
|
-
|
|
5320
|
+
/**
|
|
5321
|
+
* Gets the relations whose deletion must be simulated when deleting from the given model: relations
|
|
5322
|
+
* pointing to a model that extends a delegate model, with cascade delete on the opposite side. For a
|
|
5323
|
+
* delegate model, this includes relations declared on its sub models, because deleting a base row
|
|
5324
|
+
* cascades to the sub model rows in the database. `discriminatorValue` is set for a sub model relation:
|
|
5325
|
+
* it is the base model's discriminator value of the rows the relation can belong to.
|
|
5326
|
+
*/
|
|
5327
|
+
getDelegateCascadeRelations(model, filterModel = model) {
|
|
5328
|
+
const modelDef = this.requireModel(model);
|
|
5329
|
+
const filterDiscriminatorValue = filterModel === model ? void 0 : this.getDiscriminatorValueBelow(model, filterModel);
|
|
5330
|
+
const candidates = Object.values(modelDef.fields).map((fieldDef) => ({
|
|
5331
|
+
fieldDef,
|
|
5332
|
+
discriminatorValue: void 0
|
|
5333
|
+
}));
|
|
5334
|
+
if (modelDef.isDelegate) for (const subModel of getDelegateDescendantModels(this.schema, model)) {
|
|
5335
|
+
const discriminatorValue = this.getDiscriminatorValueBelow(model, subModel.name);
|
|
5336
|
+
if (filterDiscriminatorValue !== void 0 && discriminatorValue !== filterDiscriminatorValue) continue;
|
|
5337
|
+
for (const fieldDef of Object.values(subModel.fields)) if (!fieldDef.originModel) candidates.push({
|
|
5338
|
+
fieldDef,
|
|
5339
|
+
discriminatorValue
|
|
5340
|
+
});
|
|
5341
|
+
}
|
|
5342
|
+
return candidates.filter(({ fieldDef }) => {
|
|
5343
|
+
if (!fieldDef.relation?.opposite) return false;
|
|
5329
5344
|
const oppositeModelDef = this.requireModel(fieldDef.type);
|
|
5330
5345
|
const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
|
|
5331
|
-
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
|
|
5335
|
-
|
|
5346
|
+
return !!oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade";
|
|
5347
|
+
});
|
|
5348
|
+
}
|
|
5349
|
+
getDiscriminatorValueBelow(model, subModel) {
|
|
5350
|
+
let ancestor = this.requireModel(subModel);
|
|
5351
|
+
while (ancestor.baseModel !== model) ancestor = this.requireModel(ancestor.baseModel);
|
|
5352
|
+
return getDelegateDiscriminatorValue(this.schema, ancestor.name);
|
|
5353
|
+
}
|
|
5354
|
+
makeVisitedKey(model, row) {
|
|
5355
|
+
let root = model;
|
|
5356
|
+
for (let base = this.requireModel(root).baseModel; base; base = this.requireModel(root).baseModel) root = base;
|
|
5357
|
+
return JSON.stringify([root, ...this.requireModel(model).idFields.map((f) => row[f])]);
|
|
5358
|
+
}
|
|
5359
|
+
makeChildFilter(model, fieldDef, parentRows) {
|
|
5360
|
+
const opposite = fieldDef.relation.opposite;
|
|
5361
|
+
const { fields, references } = this.requireField(fieldDef.type, opposite).relation ?? {};
|
|
5362
|
+
const idFields = this.requireModel(model).idFields;
|
|
5363
|
+
if (!fields || !references || !references.every((f) => idFields.includes(f))) return { [opposite]: this.makeIdsFilter(model, parentRows) };
|
|
5364
|
+
if (fields.length === 1) return { [fields[0]]: { in: parentRows.map((row) => row[references[0]]) } };
|
|
5365
|
+
return { OR: parentRows.map((row) => Object.fromEntries(fields.map((f, i) => [f, row[references[i]]]))) };
|
|
5366
|
+
}
|
|
5367
|
+
makeIdsFilter(model, rows) {
|
|
5368
|
+
const idFields = this.requireModel(model).idFields;
|
|
5369
|
+
if (idFields.length === 1) return { [idFields[0]]: { in: rows.map((row) => row[idFields[0]]) } };
|
|
5370
|
+
return { OR: rows.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
|
|
5371
|
+
}
|
|
5372
|
+
*batchRows(model, rows) {
|
|
5373
|
+
const size = this.requireModel(model).idFields.length === 1 ? DELETE_ID_BATCH_SIZE : DELETE_COMPOUND_ID_BATCH_SIZE;
|
|
5374
|
+
for (let i = 0; i < rows.length; i += size) yield rows.slice(i, i + size);
|
|
5336
5375
|
}
|
|
5337
|
-
async processBaseModelDelete(kysely, model, where, limit, filterModel) {
|
|
5338
|
-
return this.delete(kysely, model, where, limit, filterModel);
|
|
5376
|
+
async processBaseModelDelete(kysely, model, where, limit, filterModel, visited) {
|
|
5377
|
+
return this.delete(kysely, model, where, limit, filterModel, void 0, visited);
|
|
5339
5378
|
}
|
|
5340
5379
|
makeIdSelect(model) {
|
|
5341
5380
|
return this.requireModel(model).idFields.reduce((acc, f) => {
|
|
@@ -5511,7 +5550,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
|
|
|
5511
5550
|
if (typeof value === "string") {
|
|
5512
5551
|
const fieldDef = getField(this.schema, this.model, field);
|
|
5513
5552
|
if (fieldDef) {
|
|
5514
|
-
const type = fieldDef.type;
|
|
5553
|
+
const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
|
|
5515
5554
|
if (op === "_avg") val = parseFloat(val);
|
|
5516
5555
|
else if (op === "_sum" || op === "_min" || op === "_max") val = match(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
|
|
5517
5556
|
}
|
|
@@ -5638,14 +5677,8 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
|
|
|
5638
5677
|
});
|
|
5639
5678
|
}
|
|
5640
5679
|
needsNestedDelete() {
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation?.opposite) {
|
|
5644
|
-
const oppositeModelDef = this.requireModel(fieldDef.type);
|
|
5645
|
-
const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
|
|
5646
|
-
if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") return true;
|
|
5647
|
-
}
|
|
5648
|
-
return false;
|
|
5680
|
+
if (this.requireModel(this.model).baseModel) return true;
|
|
5681
|
+
return this.getDelegateCascadeRelations(this.model).length > 0;
|
|
5649
5682
|
}
|
|
5650
5683
|
};
|
|
5651
5684
|
//#endregion
|
|
@@ -5740,7 +5773,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
|
|
|
5740
5773
|
if (typeof value === "string") {
|
|
5741
5774
|
const fieldDef = getField(this.schema, this.model, field);
|
|
5742
5775
|
if (fieldDef) {
|
|
5743
|
-
const type = fieldDef.type;
|
|
5776
|
+
const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
|
|
5744
5777
|
if (op === "_avg") val = parseFloat(val);
|
|
5745
5778
|
else if (op === "_sum" || op === "_min" || op === "_max") val = match(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
|
|
5746
5779
|
}
|
|
@@ -6160,7 +6193,7 @@ var QueryNameMapper = class extends OperationNodeTransformer {
|
|
|
6160
6193
|
return ColumnNode.create(mappedName);
|
|
6161
6194
|
}
|
|
6162
6195
|
transformBinaryOperation(node, queryId) {
|
|
6163
|
-
if (ReferenceNode.is(node.leftOperand) && ColumnNode.is(node.leftOperand.column) && (ValueNode.is(node.rightOperand) || PrimitiveValueListNode.is(node.rightOperand))) {
|
|
6196
|
+
if (ReferenceNode.is(node.leftOperand) && ColumnNode.is(node.leftOperand.column) && (ValueNode.is(node.rightOperand) || PrimitiveValueListNode.is(node.rightOperand) || ValueListNode.is(node.rightOperand))) {
|
|
6164
6197
|
const columnNode = node.leftOperand.column;
|
|
6165
6198
|
const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
|
|
6166
6199
|
if (resolvedScope?.model) {
|
|
@@ -6168,6 +6201,7 @@ var QueryNameMapper = class extends OperationNodeTransformer {
|
|
|
6168
6201
|
let resultValue = valueNode;
|
|
6169
6202
|
if (ValueNode.is(valueNode)) resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
|
|
6170
6203
|
else if (PrimitiveValueListNode.is(valueNode)) resultValue = PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
|
|
6204
|
+
else if (ValueListNode.is(valueNode)) resultValue = ValueListNode.create(valueNode.values.map((v) => ValueNode.is(v) ? this.processEnumMappingForValue(resolvedScope.model, columnNode, v) : v));
|
|
6171
6205
|
return super.transformBinaryOperation({
|
|
6172
6206
|
...node,
|
|
6173
6207
|
rightOperand: resultValue
|
|
@@ -6568,7 +6602,11 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
|
|
|
6568
6602
|
return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
|
|
6569
6603
|
}
|
|
6570
6604
|
get hasEntityMutationPluginsWithAfterMutationHooks() {
|
|
6571
|
-
return (this.client.$options.plugins ?? []).some((plugin) =>
|
|
6605
|
+
return (this.client.$options.plugins ?? []).some((plugin) => {
|
|
6606
|
+
if (!plugin.onEntityMutation) return false;
|
|
6607
|
+
if (plugin.onEntityMutation["$all"]?.afterEntityMutation) return true;
|
|
6608
|
+
return Object.keys(this.client.$schema.models).some((model) => plugin.onEntityMutation?.[model]?.afterEntityMutation);
|
|
6609
|
+
});
|
|
6572
6610
|
}
|
|
6573
6611
|
get hasOnKyselyHooks() {
|
|
6574
6612
|
return (this.client.$options.plugins ?? []).some((plugin) => plugin.onKyselyQuery);
|
|
@@ -6673,8 +6711,17 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
|
|
|
6673
6711
|
const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
|
|
6674
6712
|
if (this.options.plugins) for (const plugin of this.options.plugins) {
|
|
6675
6713
|
const onEntityMutation = plugin.onEntityMutation;
|
|
6676
|
-
if (!onEntityMutation
|
|
6677
|
-
await onEntityMutation.beforeEntityMutation({
|
|
6714
|
+
if (!onEntityMutation) continue;
|
|
6715
|
+
if (onEntityMutation["$all"]?.beforeEntityMutation) await onEntityMutation["$all"].beforeEntityMutation({
|
|
6716
|
+
model: mutationInfo.model,
|
|
6717
|
+
action: mutationInfo.action,
|
|
6718
|
+
queryNode,
|
|
6719
|
+
loadBeforeMutationEntities,
|
|
6720
|
+
client,
|
|
6721
|
+
queryId
|
|
6722
|
+
});
|
|
6723
|
+
const modelHooks = onEntityMutation[mutationInfo.model];
|
|
6724
|
+
if (modelHooks?.beforeEntityMutation) await modelHooks.beforeEntityMutation({
|
|
6678
6725
|
model: mutationInfo.model,
|
|
6679
6726
|
action: mutationInfo.action,
|
|
6680
6727
|
queryNode,
|
|
@@ -6689,10 +6736,16 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
|
|
|
6689
6736
|
const hooks = [];
|
|
6690
6737
|
for (const plugin of this.options.plugins ?? []) {
|
|
6691
6738
|
const onEntityMutation = plugin.onEntityMutation;
|
|
6692
|
-
if (!onEntityMutation
|
|
6693
|
-
if (
|
|
6694
|
-
|
|
6695
|
-
|
|
6739
|
+
if (!onEntityMutation) continue;
|
|
6740
|
+
if (onEntityMutation["$all"]?.afterEntityMutation) {
|
|
6741
|
+
const runInTx = onEntityMutation["$all"].runAfterMutationWithinTransaction ?? false;
|
|
6742
|
+
if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(onEntityMutation["$all"].afterEntityMutation.bind(plugin));
|
|
6743
|
+
}
|
|
6744
|
+
const modelHooks = onEntityMutation[mutationInfo.model];
|
|
6745
|
+
if (modelHooks?.afterEntityMutation) {
|
|
6746
|
+
const runInTx = modelHooks.runAfterMutationWithinTransaction ?? false;
|
|
6747
|
+
if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(modelHooks.afterEntityMutation.bind(plugin));
|
|
6748
|
+
}
|
|
6696
6749
|
}
|
|
6697
6750
|
if (hooks.length === 0) return;
|
|
6698
6751
|
for (const hook of hooks) await hook({
|
|
@@ -6707,7 +6760,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
|
|
|
6707
6760
|
}
|
|
6708
6761
|
async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
|
|
6709
6762
|
if (mutationInfo.action === "delete") return;
|
|
6710
|
-
if (this.dialect.supportsReturning) return queryResult.rows;
|
|
6763
|
+
if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
|
|
6711
6764
|
else {
|
|
6712
6765
|
const mutatedIds = InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
|
|
6713
6766
|
if (mutatedIds) {
|
|
@@ -7167,8 +7220,12 @@ var SchemaDbPusher = class {
|
|
|
7167
7220
|
return sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
|
|
7168
7221
|
} else return "text";
|
|
7169
7222
|
if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") return "serial";
|
|
7170
|
-
|
|
7171
|
-
|
|
7223
|
+
let type = fieldDef.type;
|
|
7224
|
+
if (this.isCustomType(type)) {
|
|
7225
|
+
const typeDef = Object.values(this.schema.typeDefs).find((def) => def.name === type);
|
|
7226
|
+
if (typeDef.base) type = typeDef.base;
|
|
7227
|
+
else return this.jsonType;
|
|
7228
|
+
}
|
|
7172
7229
|
const result = 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(() => {
|
|
7173
7230
|
throw new Error(`Unsupported field type: ${type}`);
|
|
7174
7231
|
});
|
|
@@ -7304,7 +7361,7 @@ var ResultProcessor = class {
|
|
|
7304
7361
|
else if (key.startsWith("$delegate$")) {
|
|
7305
7362
|
if (value) {
|
|
7306
7363
|
const subRow = this.dialect.transformOutput(value, "Json", false);
|
|
7307
|
-
const subModel = key.slice(
|
|
7364
|
+
const subModel = key.slice(DELEGATE_JOINED_FIELD_PREFIX.length);
|
|
7308
7365
|
const idValues = getIdValues(this.schema, subModel, subRow);
|
|
7309
7366
|
if (Object.values(idValues).some((v) => v === null || v === void 0)) {
|
|
7310
7367
|
delete data[key];
|
|
@@ -7360,6 +7417,7 @@ var ResultProcessor = class {
|
|
|
7360
7417
|
};
|
|
7361
7418
|
//#endregion
|
|
7362
7419
|
//#region src/client/client-impl.ts
|
|
7420
|
+
const warnedPlugins = /* @__PURE__ */ new WeakSet();
|
|
7363
7421
|
/**
|
|
7364
7422
|
* Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
|
|
7365
7423
|
*/
|
|
@@ -7390,6 +7448,7 @@ var ClientImpl = class ClientImpl {
|
|
|
7390
7448
|
...functions_exports,
|
|
7391
7449
|
...this.$options.functions
|
|
7392
7450
|
};
|
|
7451
|
+
if (this.$options.plugins) this.$options.plugins = this.normalizePlugins(this.$options.plugins);
|
|
7393
7452
|
this.validateOptions(baseClient, options);
|
|
7394
7453
|
if (baseClient) {
|
|
7395
7454
|
this.kyselyProps = {
|
|
@@ -7423,12 +7482,69 @@ var ClientImpl = class ClientImpl {
|
|
|
7423
7482
|
this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this, { enabled: this.$options.validateInput !== false });
|
|
7424
7483
|
return createClientProxy(this);
|
|
7425
7484
|
}
|
|
7485
|
+
/**
|
|
7486
|
+
* Normalizes plugin definitions for backward compatibility and validates
|
|
7487
|
+
* `onEntityMutation` keys. Legacy plugins that define hooks directly under
|
|
7488
|
+
* `onEntityMutation` (instead of under `$all`) are converted to the new shape
|
|
7489
|
+
* with a one-time warning.
|
|
7490
|
+
*/
|
|
7491
|
+
normalizePlugins(plugins) {
|
|
7492
|
+
let changed = false;
|
|
7493
|
+
const result = plugins.map((plugin) => {
|
|
7494
|
+
const normalized = this.normalizeEntityMutationHooks(plugin);
|
|
7495
|
+
if (normalized !== plugin) changed = true;
|
|
7496
|
+
return normalized;
|
|
7497
|
+
});
|
|
7498
|
+
return changed ? result : plugins;
|
|
7499
|
+
}
|
|
7500
|
+
normalizeEntityMutationHooks(plugin) {
|
|
7501
|
+
const hooks = plugin.onEntityMutation;
|
|
7502
|
+
if (!hooks || typeof hooks !== "object") return plugin;
|
|
7503
|
+
const legacyKeys = [
|
|
7504
|
+
"beforeEntityMutation",
|
|
7505
|
+
"afterEntityMutation",
|
|
7506
|
+
"runAfterMutationWithinTransaction"
|
|
7507
|
+
];
|
|
7508
|
+
const presentLegacyKeys = legacyKeys.filter((key) => key in hooks);
|
|
7509
|
+
const unknownKeys = Object.keys(hooks).filter((key) => key !== "$all" && !legacyKeys.includes(key) && !(key in this.$schema.models));
|
|
7510
|
+
const warnOnce = (message) => {
|
|
7511
|
+
if (!warnedPlugins.has(hooks)) console.warn(message);
|
|
7512
|
+
};
|
|
7513
|
+
if (unknownKeys.length > 0) warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks for unknown keys: ${unknownKeys.map((k) => `"${k}"`).join(", ")}. Valid keys are "$all" and model names. These hooks will never be invoked.`);
|
|
7514
|
+
if (presentLegacyKeys.length === 0) {
|
|
7515
|
+
warnedPlugins.add(hooks);
|
|
7516
|
+
return plugin;
|
|
7517
|
+
}
|
|
7518
|
+
warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks in a deprecated shape. Hooks that apply to all models should be nested under "$all": { onEntityMutation: { $all: { beforeEntityMutation, afterEntityMutation, runAfterMutationWithinTransaction } } }. The legacy shape is still supported but will be removed in a future release.`);
|
|
7519
|
+
warnedPlugins.add(hooks);
|
|
7520
|
+
const legacy = {};
|
|
7521
|
+
const rest = {};
|
|
7522
|
+
for (const [key, value] of Object.entries(hooks)) if (legacyKeys.includes(key)) legacy[key] = value;
|
|
7523
|
+
else rest[key] = value;
|
|
7524
|
+
for (const key of ["beforeEntityMutation", "afterEntityMutation"]) if (typeof legacy[key] === "function") legacy[key] = legacy[key].bind(plugin);
|
|
7525
|
+
const normalizedHooks = {
|
|
7526
|
+
...rest,
|
|
7527
|
+
$all: {
|
|
7528
|
+
...legacy,
|
|
7529
|
+
...rest["$all"]
|
|
7530
|
+
}
|
|
7531
|
+
};
|
|
7532
|
+
warnedPlugins.add(normalizedHooks);
|
|
7533
|
+
const copy = Object.create(Object.getPrototypeOf(plugin), Object.getOwnPropertyDescriptors(plugin));
|
|
7534
|
+
Object.defineProperty(copy, "onEntityMutation", {
|
|
7535
|
+
value: normalizedHooks,
|
|
7536
|
+
enumerable: true,
|
|
7537
|
+
configurable: true,
|
|
7538
|
+
writable: true
|
|
7539
|
+
});
|
|
7540
|
+
return copy;
|
|
7541
|
+
}
|
|
7426
7542
|
validateOptions(baseClient, options) {
|
|
7427
7543
|
if (!baseClient && !options.skipValidationForComputedFields) this.validateComputedFieldsConfig(options);
|
|
7428
7544
|
if (options.diagnostics) {
|
|
7429
|
-
const parseResult = z.object({
|
|
7430
|
-
slowQueryThresholdMs: z.number().nonnegative().optional(),
|
|
7431
|
-
slowQueryMaxRecords: z.int().nonnegative().or(z.literal(Infinity)).optional()
|
|
7545
|
+
const parseResult = z$1.object({
|
|
7546
|
+
slowQueryThresholdMs: z$1.number().nonnegative().optional(),
|
|
7547
|
+
slowQueryMaxRecords: z$1.int().nonnegative().or(z$1.literal(Infinity)).optional()
|
|
7432
7548
|
}).safeParse(options.diagnostics);
|
|
7433
7549
|
if (!parseResult.success) throw createConfigError(`Invalid diagnostics configuration: ${formatError(parseResult.error)}`);
|
|
7434
7550
|
}
|