@zenstackhq/orm 3.9.7 → 3.9.8

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.
@@ -0,0 +1,129 @@
1
+ //#region src/client/constants.d.ts
2
+ /**
3
+ * Client API methods that are not supported in transactions.
4
+ */
5
+ declare const TRANSACTION_UNSUPPORTED_METHODS: readonly ["$transaction", "$connect", "$disconnect", "$use"];
6
+ /**
7
+ * Logical combinators used in filters.
8
+ */
9
+ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"];
10
+ /**
11
+ * Aggregation operators.
12
+ */
13
+ declare const AggregateOperators: readonly ["_count", "_sum", "_avg", "_min", "_max"];
14
+ type AggregateOperators = (typeof AggregateOperators)[number];
15
+ /**
16
+ * Mapping of filter operators to their corresponding filter kind categories.
17
+ */
18
+ declare const FILTER_PROPERTY_TO_KIND: {
19
+ readonly equals: "Equality";
20
+ readonly not: "Equality";
21
+ readonly in: "Equality";
22
+ readonly notIn: "Equality";
23
+ readonly lt: "Range";
24
+ readonly lte: "Range";
25
+ readonly gt: "Range";
26
+ readonly gte: "Range";
27
+ readonly between: "Range";
28
+ readonly contains: "Like";
29
+ readonly startsWith: "Like";
30
+ readonly endsWith: "Like";
31
+ readonly mode: "Like";
32
+ readonly is: "Relation";
33
+ readonly isNot: "Relation";
34
+ readonly some: "Relation";
35
+ readonly every: "Relation";
36
+ readonly none: "Relation";
37
+ readonly path: "Json";
38
+ readonly string_contains: "Json";
39
+ readonly string_starts_with: "Json";
40
+ readonly string_ends_with: "Json";
41
+ readonly array_contains: "Json";
42
+ readonly array_starts_with: "Json";
43
+ readonly array_ends_with: "Json";
44
+ readonly fuzzy: "Fuzzy";
45
+ readonly fts: "FullText";
46
+ readonly has: "List";
47
+ readonly hasEvery: "List";
48
+ readonly hasSome: "List";
49
+ readonly isEmpty: "List";
50
+ };
51
+ /**
52
+ * Mapping of filter operators to their corresponding filter kind categories.
53
+ */
54
+ type FilterPropertyToKind = typeof FILTER_PROPERTY_TO_KIND;
55
+ /**
56
+ * List of core CRUD operations. It excludes the 'orThrow' variants.
57
+ */
58
+ declare const CoreCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists"];
59
+ /**
60
+ * List of core CRUD operations. It excludes the 'orThrow' variants.
61
+ */
62
+ type CoreCrudOperations = (typeof CoreCrudOperations)[number];
63
+ /**
64
+ * List of core read operations. It excludes the 'orThrow' variants.
65
+ */
66
+ declare const CoreReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists"];
67
+ /**
68
+ * List of core read operations. It excludes the 'orThrow' variants.
69
+ */
70
+ type CoreReadOperations = (typeof CoreReadOperations)[number];
71
+ /**
72
+ * List of core write operations.
73
+ */
74
+ declare const CoreWriteOperations: readonly ["create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"];
75
+ /**
76
+ * List of core write operations.
77
+ */
78
+ type CoreWriteOperations = (typeof CoreWriteOperations)[number];
79
+ /**
80
+ * List of core create operations.
81
+ */
82
+ declare const CoreCreateOperations: readonly ["create", "createMany", "createManyAndReturn", "upsert"];
83
+ /**
84
+ * List of core create operations.
85
+ */
86
+ type CoreCreateOperations = (typeof CoreCreateOperations)[number];
87
+ /**
88
+ * List of core update operations.
89
+ */
90
+ declare const CoreUpdateOperations: readonly ["update", "updateMany", "updateManyAndReturn", "upsert"];
91
+ /**
92
+ * List of core update operations.
93
+ */
94
+ type CoreUpdateOperations = (typeof CoreUpdateOperations)[number];
95
+ /**
96
+ * List of core delete operations.
97
+ */
98
+ declare const CoreDeleteOperations: readonly ["delete", "deleteMany"];
99
+ /**
100
+ * List of core delete operations.
101
+ */
102
+ type CoreDeleteOperations = (typeof CoreDeleteOperations)[number];
103
+ /**
104
+ * List of all CRUD operations, including 'orThrow' variants.
105
+ */
106
+ declare const AllCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"];
107
+ /**
108
+ * List of all CRUD operations, including 'orThrow' variants.
109
+ */
110
+ type AllCrudOperations = (typeof AllCrudOperations)[number];
111
+ /**
112
+ * List of all read operations, including 'orThrow' variants.
113
+ */
114
+ declare const AllReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"];
115
+ /**
116
+ * List of all read operations, including 'orThrow' variants.
117
+ */
118
+ type AllReadOperations = (typeof AllReadOperations)[number];
119
+ /**
120
+ * List of all write operations - simply an alias of CoreWriteOperations.
121
+ */
122
+ declare const AllWriteOperations: readonly ["create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"];
123
+ /**
124
+ * List of all write operations - simply an alias of CoreWriteOperations.
125
+ */
126
+ type AllWriteOperations = CoreWriteOperations;
127
+ //#endregion
128
+ export { CoreCreateOperations as a, CoreReadOperations as c, FilterPropertyToKind as d, LOGICAL_COMBINATORS as f, AllWriteOperations as i, CoreUpdateOperations as l, AllCrudOperations as n, CoreCrudOperations as o, TRANSACTION_UNSUPPORTED_METHODS as p, AllReadOperations as r, CoreDeleteOperations as s, AggregateOperators as t, CoreWriteOperations as u };
129
+ //# sourceMappingURL=constants-lRwcp6Hv.d.cts.map
@@ -0,0 +1,11 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_constants = require("./constants-CcJSpq4B.cjs");
3
+ exports.AllCrudOperations = require_constants.AllCrudOperations;
4
+ exports.AllReadOperations = require_constants.AllReadOperations;
5
+ exports.AllWriteOperations = require_constants.AllWriteOperations;
6
+ exports.CoreCreateOperations = require_constants.CoreCreateOperations;
7
+ exports.CoreCrudOperations = require_constants.CoreCrudOperations;
8
+ exports.CoreDeleteOperations = require_constants.CoreDeleteOperations;
9
+ exports.CoreReadOperations = require_constants.CoreReadOperations;
10
+ exports.CoreUpdateOperations = require_constants.CoreUpdateOperations;
11
+ exports.CoreWriteOperations = require_constants.CoreWriteOperations;
@@ -0,0 +1,2 @@
1
+ import { a as CoreCreateOperations, c as CoreReadOperations, i as AllWriteOperations, l as CoreUpdateOperations, n as AllCrudOperations, o as CoreCrudOperations, r as AllReadOperations, s as CoreDeleteOperations, u as CoreWriteOperations } from "./constants-lRwcp6Hv.cjs";
2
+ export { AllCrudOperations, AllReadOperations, AllWriteOperations, CoreCreateOperations, CoreCrudOperations, CoreDeleteOperations, CoreReadOperations, CoreUpdateOperations, CoreWriteOperations };
@@ -0,0 +1,2 @@
1
+ import { a as CoreCreateOperations, c as CoreReadOperations, i as AllWriteOperations, l as CoreUpdateOperations, n as AllCrudOperations, o as CoreCrudOperations, r as AllReadOperations, s as CoreDeleteOperations, u as CoreWriteOperations } from "./constants-RUWhnVl4.mjs";
2
+ export { AllCrudOperations, AllReadOperations, AllWriteOperations, CoreCreateOperations, CoreCrudOperations, CoreDeleteOperations, CoreReadOperations, CoreUpdateOperations, CoreWriteOperations };
@@ -0,0 +1,2 @@
1
+ import { a as CoreCreateOperations, c as CoreReadOperations, i as AllWriteOperations, l as CoreUpdateOperations, n as AllCrudOperations, o as CoreCrudOperations, r as AllReadOperations, s as CoreDeleteOperations, u as CoreWriteOperations } from "./constants-BQEq4CBi.mjs";
2
+ export { AllCrudOperations, AllReadOperations, AllWriteOperations, CoreCreateOperations, CoreCrudOperations, CoreDeleteOperations, CoreReadOperations, CoreUpdateOperations, CoreWriteOperations };
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  enumerable: true
31
31
  }) : target, mod));
32
32
  //#endregion
33
+ const require_constants = require("./constants-CcJSpq4B.cjs");
33
34
  const require_common_types = require("./common-types.cjs");
34
35
  let _zenstackhq_common_helpers = require("@zenstackhq/common-helpers");
35
36
  let kysely = require("kysely");
@@ -578,75 +579,6 @@ function tmpAlias(name) {
578
579
  else return name;
579
580
  }
580
581
  //#endregion
581
- //#region src/client/constants.ts
582
- /**
583
- * The types of fields that are numeric.
584
- */
585
- const NUMERIC_FIELD_TYPES = [
586
- "Int",
587
- "Float",
588
- "BigInt",
589
- "Decimal"
590
- ];
591
- /**
592
- * Prefix for JSON field used to store joined delegate rows.
593
- */
594
- const DELEGATE_JOINED_FIELD_PREFIX = "$delegate$";
595
- /**
596
- * Logical combinators used in filters.
597
- */
598
- const LOGICAL_COMBINATORS = [
599
- "AND",
600
- "OR",
601
- "NOT"
602
- ];
603
- /**
604
- * Aggregation operators.
605
- */
606
- const AggregateOperators = [
607
- "_count",
608
- "_sum",
609
- "_avg",
610
- "_min",
611
- "_max"
612
- ];
613
- /**
614
- * Mapping of filter operators to their corresponding filter kind categories.
615
- */
616
- const FILTER_PROPERTY_TO_KIND = {
617
- equals: "Equality",
618
- not: "Equality",
619
- in: "Equality",
620
- notIn: "Equality",
621
- lt: "Range",
622
- lte: "Range",
623
- gt: "Range",
624
- gte: "Range",
625
- between: "Range",
626
- contains: "Like",
627
- startsWith: "Like",
628
- endsWith: "Like",
629
- mode: "Like",
630
- is: "Relation",
631
- isNot: "Relation",
632
- some: "Relation",
633
- every: "Relation",
634
- none: "Relation",
635
- path: "Json",
636
- string_contains: "Json",
637
- string_starts_with: "Json",
638
- string_ends_with: "Json",
639
- array_contains: "Json",
640
- array_starts_with: "Json",
641
- array_ends_with: "Json",
642
- fuzzy: "Fuzzy",
643
- fts: "FullText",
644
- has: "List",
645
- hasEvery: "List",
646
- hasSome: "List",
647
- isEmpty: "List"
648
- };
649
- //#endregion
650
582
  //#region src/client/contract.ts
651
583
  /**
652
584
  * Transaction isolation levels.
@@ -825,7 +757,7 @@ var BaseCrudDialect = class {
825
757
  return result;
826
758
  }
827
759
  isLogicalCombinator(key) {
828
- return LOGICAL_COMBINATORS.includes(key);
760
+ return require_constants.LOGICAL_COMBINATORS.includes(key);
829
761
  }
830
762
  buildCompositeFilter(model, modelAlias, key, payload) {
831
763
  const normalizedFilters = (0, _zenstackhq_common_helpers.enumerate)(payload).filter((el) => {
@@ -1102,7 +1034,7 @@ var BaseCrudDialect = class {
1102
1034
  (0, _zenstackhq_common_helpers.invariant)(rhs.length === 2, "right hand side must have a length of 2");
1103
1035
  const [start, end] = rhs;
1104
1036
  return this.eb.and([this.eb(lhs, ">=", start), this.eb(lhs, "<=", end)]);
1105
- }).with("not", () => this.eb.not(recurse(value))).with(ts_pattern.P.union(...AggregateOperators), (op) => {
1037
+ }).with("not", () => this.eb.not(recurse(value))).with(ts_pattern.P.union(...require_constants.AggregateOperators), (op) => {
1106
1038
  const innerResult = this.buildStandardFilter(type, value, aggregate(this.eb, lhs, op), getRhs, recurse, throwIfInvalid);
1107
1039
  consumedKeys.push(...innerResult.consumedKeys);
1108
1040
  return this.and(...innerResult.conditions);
@@ -1323,7 +1255,7 @@ var BaseCrudDialect = class {
1323
1255
  if (fieldDef.computed && fieldDef.params) continue;
1324
1256
  jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1325
1257
  }
1326
- return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1258
+ return this.buildJsonObject(jsonObject).as(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1327
1259
  });
1328
1260
  }
1329
1261
  return result;
@@ -1561,7 +1493,7 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1561
1493
  const relationModelDef = requireModel(this.schema, relationModel);
1562
1494
  const objArgs = {};
1563
1495
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1564
- if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1496
+ if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1565
1497
  if (payload === true || !payload.select) {
1566
1498
  const omit = typeof payload === "object" ? payload.omit : void 0;
1567
1499
  Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
@@ -2271,7 +2203,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2271
2203
  tbl = tbl.select(() => {
2272
2204
  const objArgs = [];
2273
2205
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
2274
- if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [kysely.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2206
+ if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [kysely.sql.lit(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${require_constants.DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2275
2207
  if (payload === true || !payload.select) {
2276
2208
  const omit = typeof payload === "object" ? payload.omit : void 0;
2277
2209
  objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
@@ -2491,7 +2423,7 @@ function coercedDateTimeSchema() {
2491
2423
  var ZodSchemaFactory = class {
2492
2424
  schemaCache = /* @__PURE__ */ new Map();
2493
2425
  schemaRegistry = zod.z.registry();
2494
- allFilterKinds = [...new Set(Object.values(FILTER_PROPERTY_TO_KIND))];
2426
+ allFilterKinds = [...new Set(Object.values(require_constants.FILTER_PROPERTY_TO_KIND))];
2495
2427
  schema;
2496
2428
  options;
2497
2429
  extraValidationsEnabled = true;
@@ -3588,7 +3520,7 @@ var ZodSchemaFactory = class {
3588
3520
  schema = schema.refine((value) => {
3589
3521
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3590
3522
  if (value.having && typeof value.having === "object") for (const [key, val] of Object.entries(value.having)) {
3591
- if (AggregateOperators.includes(key)) continue;
3523
+ if (require_constants.AggregateOperators.includes(key)) continue;
3592
3524
  if (bys.includes(key)) continue;
3593
3525
  if (!val || typeof val !== "object") return false;
3594
3526
  if (!this.onlyAggregationFields(val)) return false;
@@ -3597,7 +3529,7 @@ var ZodSchemaFactory = class {
3597
3529
  }, "fields in \"having\" must be in \"by\"");
3598
3530
  schema = schema.refine((value) => {
3599
3531
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3600
- for (const orderBy of (0, _zenstackhq_common_helpers.enumerate)(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3532
+ for (const orderBy of (0, _zenstackhq_common_helpers.enumerate)(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !require_constants.AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3601
3533
  return true;
3602
3534
  }, "fields in \"orderBy\" must be in \"by\"");
3603
3535
  this.registerSchema(`${model}GroupByArgs`, schema);
@@ -3605,8 +3537,8 @@ var ZodSchemaFactory = class {
3605
3537
  }
3606
3538
  onlyAggregationFields(val) {
3607
3539
  for (const [key, value] of Object.entries(val)) {
3608
- if (AggregateOperators.includes(key)) continue;
3609
- if (LOGICAL_COMBINATORS.includes(key)) {
3540
+ if (require_constants.AggregateOperators.includes(key)) continue;
3541
+ if (require_constants.LOGICAL_COMBINATORS.includes(key)) {
3610
3542
  if ((0, _zenstackhq_common_helpers.enumerate)(value).every((v) => this.onlyAggregationFields(v))) continue;
3611
3543
  }
3612
3544
  return false;
@@ -3661,10 +3593,10 @@ var ZodSchemaFactory = class {
3661
3593
  result = createSchema.extend(updateSchema.shape);
3662
3594
  } else if (createSchema) result = createSchema;
3663
3595
  else if (updateSchema) result = updateSchema;
3664
- } else if (CoreCreateOperations.includes(operation) && "$create" in plugin.queryArgs && plugin.queryArgs["$create"]) result = plugin.queryArgs["$create"];
3665
- else if (CoreReadOperations.includes(operation) && "$read" in plugin.queryArgs && plugin.queryArgs["$read"]) result = plugin.queryArgs["$read"];
3666
- else if (CoreUpdateOperations.includes(operation) && "$update" in plugin.queryArgs && plugin.queryArgs["$update"]) result = plugin.queryArgs["$update"];
3667
- else if (CoreDeleteOperations.includes(operation) && "$delete" in plugin.queryArgs && plugin.queryArgs["$delete"]) result = plugin.queryArgs["$delete"];
3596
+ } else if (require_constants.CoreCreateOperations.includes(operation) && "$create" in plugin.queryArgs && plugin.queryArgs["$create"]) result = plugin.queryArgs["$create"];
3597
+ else if (require_constants.CoreReadOperations.includes(operation) && "$read" in plugin.queryArgs && plugin.queryArgs["$read"]) result = plugin.queryArgs["$read"];
3598
+ else if (require_constants.CoreUpdateOperations.includes(operation) && "$update" in plugin.queryArgs && plugin.queryArgs["$update"]) result = plugin.queryArgs["$update"];
3599
+ else if (require_constants.CoreDeleteOperations.includes(operation) && "$delete" in plugin.queryArgs && plugin.queryArgs["$delete"]) result = plugin.queryArgs["$delete"];
3668
3600
  else if ("$all" in plugin.queryArgs && plugin.queryArgs["$all"]) result = plugin.queryArgs["$all"];
3669
3601
  (0, _zenstackhq_common_helpers.invariant)(result === void 0 || result instanceof zod.ZodObject, "Plugin extended query args schema must be a Zod object");
3670
3602
  return result;
@@ -3695,7 +3627,7 @@ var ZodSchemaFactory = class {
3695
3627
  return canBeArray ? zod.z.union([schema, zod.z.array(schema)]) : schema;
3696
3628
  }
3697
3629
  isNumericField(fieldDef) {
3698
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3630
+ return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3699
3631
  }
3700
3632
  get providerSupportsCaseSensitivity() {
3701
3633
  return this.schema.provider.type === "postgresql";
@@ -3748,7 +3680,7 @@ var ZodSchemaFactory = class {
3748
3680
  trimFilterOperators(operators, allowedKinds) {
3749
3681
  if (!allowedKinds) return operators;
3750
3682
  return Object.fromEntries(Object.entries(operators).filter(([key, _]) => {
3751
- return !(key in FILTER_PROPERTY_TO_KIND) || allowedKinds.includes(FILTER_PROPERTY_TO_KIND[key]);
3683
+ return !(key in require_constants.FILTER_PROPERTY_TO_KIND) || allowedKinds.includes(require_constants.FILTER_PROPERTY_TO_KIND[key]);
3752
3684
  }));
3753
3685
  }
3754
3686
  createUnionFilterSchema(valueSchema, optional, components, allowedFilterKinds) {
@@ -4320,94 +4252,13 @@ var InputValidator = class {
4320
4252
  //#endregion
4321
4253
  //#region src/client/crud/operations/base.ts
4322
4254
  /**
4323
- * List of core CRUD operations. It excludes the 'orThrow' variants.
4324
- */
4325
- const CoreCrudOperations = [
4326
- "findMany",
4327
- "findUnique",
4328
- "findFirst",
4329
- "create",
4330
- "createMany",
4331
- "createManyAndReturn",
4332
- "update",
4333
- "updateMany",
4334
- "updateManyAndReturn",
4335
- "upsert",
4336
- "delete",
4337
- "deleteMany",
4338
- "count",
4339
- "aggregate",
4340
- "groupBy",
4341
- "exists"
4342
- ];
4343
- /**
4344
- * List of core read operations. It excludes the 'orThrow' variants.
4345
- */
4346
- const CoreReadOperations = [
4347
- "findMany",
4348
- "findUnique",
4349
- "findFirst",
4350
- "count",
4351
- "aggregate",
4352
- "groupBy",
4353
- "exists"
4354
- ];
4355
- /**
4356
- * List of core write operations.
4357
- */
4358
- const CoreWriteOperations = [
4359
- "create",
4360
- "createMany",
4361
- "createManyAndReturn",
4362
- "update",
4363
- "updateMany",
4364
- "updateManyAndReturn",
4365
- "upsert",
4366
- "delete",
4367
- "deleteMany"
4368
- ];
4369
- /**
4370
- * List of core create operations.
4371
- */
4372
- const CoreCreateOperations = [
4373
- "create",
4374
- "createMany",
4375
- "createManyAndReturn",
4376
- "upsert"
4377
- ];
4378
- /**
4379
- * List of core update operations.
4380
- */
4381
- const CoreUpdateOperations = [
4382
- "update",
4383
- "updateMany",
4384
- "updateManyAndReturn",
4385
- "upsert"
4386
- ];
4387
- /**
4388
- * List of core delete operations.
4389
- */
4390
- const CoreDeleteOperations = ["delete", "deleteMany"];
4391
- /**
4392
- * List of all CRUD operations, including 'orThrow' variants.
4393
- */
4394
- const AllCrudOperations = [
4395
- ...CoreCrudOperations,
4396
- "findUniqueOrThrow",
4397
- "findFirstOrThrow"
4398
- ];
4399
- /**
4400
- * List of all read operations, including 'orThrow' variants.
4255
+ * Maximum number of rows identified by id in a single statement during cascade delete simulation.
4401
4256
  */
4402
- const AllReadOperations = [
4403
- ...CoreReadOperations,
4404
- "findUniqueOrThrow",
4405
- "findFirstOrThrow"
4406
- ];
4257
+ const DELETE_ID_BATCH_SIZE = 1e3;
4407
4258
  /**
4408
- * List of all write operations - simply an alias of CoreWriteOperations.
4259
+ * Same as `DELETE_ID_BATCH_SIZE`, for compound ids, which are matched with one `OR` branch per row.
4409
4260
  */
4410
- const AllWriteOperations = CoreWriteOperations;
4261
+ const DELETE_COMPOUND_ID_BATCH_SIZE = 100;
4411
4262
  var BaseOperationHandler = class {
4412
4263
  dialect;
4413
4264
  constructor(client, model, inputValidator) {
@@ -5022,7 +4873,7 @@ var BaseOperationHandler = class {
5022
4873
  });
5023
4874
  }
5024
4875
  isNumericField(fieldDef) {
5025
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
4876
+ return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
5026
4877
  }
5027
4878
  makeContextComment(_context) {
5028
4879
  return kysely.sql``;
@@ -5342,37 +5193,130 @@ var BaseOperationHandler = class {
5342
5193
  normalizeRelationManipulationInput(model, data) {
5343
5194
  return (0, _zenstackhq_common_helpers.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
5344
5195
  }
5345
- async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn) {
5196
+ async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn, visited) {
5346
5197
  filterModel ??= model;
5198
+ visited ??= /* @__PURE__ */ new Set();
5347
5199
  const modelDef = this.requireModel(model);
5348
5200
  if (modelDef.baseModel) {
5349
5201
  if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5350
- return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel);
5202
+ return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel, visited);
5351
5203
  }
5204
+ const cascadeRelations = this.getDelegateCascadeRelations(model, filterModel);
5205
+ if (cascadeRelations.length === 0) return this.executeDelete(kysely$28, model, where, limit, filterModel, fieldsToReturn);
5206
+ if (!modelDef.isDelegate) {
5207
+ if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5208
+ for (const { fieldDef } of cascadeRelations) await this.delete(kysely$28, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0, void 0, void 0, visited);
5209
+ return this.executeDelete(kysely$28, model, where, limit, filterModel, fieldsToReturn);
5210
+ }
5211
+ const discriminator = getDiscriminatorField(this.schema, model);
5212
+ const deletedRows = await this.read(kysely$28, filterModel, {
5213
+ where,
5214
+ select: {
5215
+ ...this.makeIdSelect(filterModel),
5216
+ [discriminator]: true
5217
+ },
5218
+ ...limit !== void 0 ? { take: limit } : {}
5219
+ });
5220
+ deletedRows.forEach((row) => visited.add(this.makeVisitedKey(model, row)));
5221
+ for (const { fieldDef, discriminatorValue } of cascadeRelations) {
5222
+ const parentRows = discriminatorValue === void 0 ? deletedRows : deletedRows.filter((row) => row[discriminator] === discriminatorValue);
5223
+ for (const batch of this.batchRows(model, parentRows)) {
5224
+ const childModel = fieldDef.type;
5225
+ const pendingRows = (await this.read(kysely$28, childModel, {
5226
+ where: this.makeChildFilter(model, fieldDef, batch),
5227
+ select: this.makeIdSelect(childModel)
5228
+ })).filter((row) => {
5229
+ const key = this.makeVisitedKey(childModel, row);
5230
+ if (visited.has(key)) return false;
5231
+ visited.add(key);
5232
+ return true;
5233
+ });
5234
+ for (const childBatch of this.batchRows(childModel, pendingRows)) await this.delete(kysely$28, childModel, this.makeIdsFilter(childModel, childBatch), void 0, void 0, void 0, visited);
5235
+ }
5236
+ }
5237
+ let numAffectedRows = 0n;
5238
+ const rows = [];
5239
+ for (const batch of this.batchRows(model, deletedRows)) {
5240
+ const result = await this.executeDelete(kysely$28, model, this.makeIdsFilter(model, batch), void 0, model, fieldsToReturn);
5241
+ numAffectedRows += result.numAffectedRows ?? 0n;
5242
+ rows.push(...result.rows);
5243
+ }
5244
+ return {
5245
+ numAffectedRows,
5246
+ rows
5247
+ };
5248
+ }
5249
+ async executeDelete(kysely$29, model, where, limit, filterModel, fieldsToReturn) {
5250
+ const modelDef = this.requireModel(model);
5352
5251
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
5353
5252
  let needIdFilter = false;
5354
5253
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
5355
5254
  if (modelDef.isDelegate || modelDef.baseModel) needIdFilter = true;
5356
- const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely$28, model)), "in", eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely$28, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()) : () => this.dialect.buildFilter(model, model, where);
5357
- await this.processDelegateRelationDelete(kysely$28, modelDef, where, limit);
5358
- const query = kysely$28.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({
5255
+ const deleteFilter = needIdFilter ? (eb) => eb(eb.refTuple(...this.buildIdFieldRefs(kysely$29, model)), "in", eb.selectFrom(this.dialect.buildSelectModel(filterModel, filterModel).where(() => this.dialect.buildFilter(filterModel, filterModel, where)).select(this.buildIdFieldRefs(kysely$29, filterModel)).$if(limit !== void 0, (qb) => qb.limit(limit)).as("$sub")).selectAll()) : () => this.dialect.buildFilter(model, model, where);
5256
+ const query = kysely$29.deleteFrom(model).where(deleteFilter).$if(this.dialect.supportsReturning, (qb) => qb.returning(fieldsToReturn)).$if(limit !== void 0 && this.dialect.supportsDeleteWithLimit, (qb) => qb.limit(limit)).modifyEnd(this.makeContextComment({
5359
5257
  model,
5360
5258
  operation: "delete"
5361
5259
  }));
5362
- return this.executeQuery(kysely$28, query, "delete");
5260
+ return this.executeQuery(kysely$29, query, "delete");
5363
5261
  }
5364
- async processDelegateRelationDelete(kysely$29, modelDef, where, limit) {
5365
- for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation && fieldDef.relation.opposite) {
5262
+ /**
5263
+ * Gets the relations whose deletion must be simulated when deleting from the given model: relations
5264
+ * pointing to a model that extends a delegate model, with cascade delete on the opposite side. For a
5265
+ * delegate model, this includes relations declared on its sub models, because deleting a base row
5266
+ * cascades to the sub model rows in the database. `discriminatorValue` is set for a sub model relation:
5267
+ * it is the base model's discriminator value of the rows the relation can belong to.
5268
+ */
5269
+ getDelegateCascadeRelations(model, filterModel = model) {
5270
+ const modelDef = this.requireModel(model);
5271
+ const filterDiscriminatorValue = filterModel === model ? void 0 : this.getDiscriminatorValueBelow(model, filterModel);
5272
+ const candidates = Object.values(modelDef.fields).map((fieldDef) => ({
5273
+ fieldDef,
5274
+ discriminatorValue: void 0
5275
+ }));
5276
+ if (modelDef.isDelegate) for (const subModel of getDelegateDescendantModels(this.schema, model)) {
5277
+ const discriminatorValue = this.getDiscriminatorValueBelow(model, subModel.name);
5278
+ if (filterDiscriminatorValue !== void 0 && discriminatorValue !== filterDiscriminatorValue) continue;
5279
+ for (const fieldDef of Object.values(subModel.fields)) if (!fieldDef.originModel) candidates.push({
5280
+ fieldDef,
5281
+ discriminatorValue
5282
+ });
5283
+ }
5284
+ return candidates.filter(({ fieldDef }) => {
5285
+ if (!fieldDef.relation?.opposite) return false;
5366
5286
  const oppositeModelDef = this.requireModel(fieldDef.type);
5367
5287
  const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5368
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") {
5369
- if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5370
- await this.delete(kysely$29, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0);
5371
- }
5372
- }
5288
+ return !!oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade";
5289
+ });
5290
+ }
5291
+ getDiscriminatorValueBelow(model, subModel) {
5292
+ let ancestor = this.requireModel(subModel);
5293
+ while (ancestor.baseModel !== model) ancestor = this.requireModel(ancestor.baseModel);
5294
+ return getDelegateDiscriminatorValue(this.schema, ancestor.name);
5373
5295
  }
5374
- async processBaseModelDelete(kysely$30, model, where, limit, filterModel) {
5375
- return this.delete(kysely$30, model, where, limit, filterModel);
5296
+ makeVisitedKey(model, row) {
5297
+ let root = model;
5298
+ for (let base = this.requireModel(root).baseModel; base; base = this.requireModel(root).baseModel) root = base;
5299
+ return JSON.stringify([root, ...this.requireModel(model).idFields.map((f) => row[f])]);
5300
+ }
5301
+ makeChildFilter(model, fieldDef, parentRows) {
5302
+ const opposite = fieldDef.relation.opposite;
5303
+ const { fields, references } = this.requireField(fieldDef.type, opposite).relation ?? {};
5304
+ const idFields = this.requireModel(model).idFields;
5305
+ if (!fields || !references || !references.every((f) => idFields.includes(f))) return { [opposite]: this.makeIdsFilter(model, parentRows) };
5306
+ if (fields.length === 1) return { [fields[0]]: { in: parentRows.map((row) => row[references[0]]) } };
5307
+ return { OR: parentRows.map((row) => Object.fromEntries(fields.map((f, i) => [f, row[references[i]]]))) };
5308
+ }
5309
+ makeIdsFilter(model, rows) {
5310
+ const idFields = this.requireModel(model).idFields;
5311
+ if (idFields.length === 1) return { [idFields[0]]: { in: rows.map((row) => row[idFields[0]]) } };
5312
+ return { OR: rows.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
5313
+ }
5314
+ *batchRows(model, rows) {
5315
+ const size = this.requireModel(model).idFields.length === 1 ? DELETE_ID_BATCH_SIZE : DELETE_COMPOUND_ID_BATCH_SIZE;
5316
+ for (let i = 0; i < rows.length; i += size) yield rows.slice(i, i + size);
5317
+ }
5318
+ async processBaseModelDelete(kysely$30, model, where, limit, filterModel, visited) {
5319
+ return this.delete(kysely$30, model, where, limit, filterModel, void 0, visited);
5376
5320
  }
5377
5321
  makeIdSelect(model) {
5378
5322
  return this.requireModel(model).idFields.reduce((acc, f) => {
@@ -5675,14 +5619,8 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
5675
5619
  });
5676
5620
  }
5677
5621
  needsNestedDelete() {
5678
- const modelDef = this.requireModel(this.model);
5679
- if (modelDef.baseModel) return true;
5680
- for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation?.opposite) {
5681
- const oppositeModelDef = this.requireModel(fieldDef.type);
5682
- const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5683
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") return true;
5684
- }
5685
- return false;
5622
+ if (this.requireModel(this.model).baseModel) return true;
5623
+ return this.getDelegateCascadeRelations(this.model).length > 0;
5686
5624
  }
5687
5625
  };
5688
5626
  //#endregion
@@ -7341,7 +7279,7 @@ var ResultProcessor = class {
7341
7279
  else if (key.startsWith("$delegate$")) {
7342
7280
  if (value) {
7343
7281
  const subRow = this.dialect.transformOutput(value, "Json", false);
7344
- const subModel = key.slice(10);
7282
+ const subModel = key.slice(require_constants.DELEGATE_JOINED_FIELD_PREFIX.length);
7345
7283
  const idValues = getIdValues(this.schema, subModel, subRow);
7346
7284
  if (Object.values(idValues).some((v) => v === null || v === void 0)) {
7347
7285
  delete data[key];
@@ -8399,20 +8337,20 @@ var MatchingExpressionVisitor = class extends ExpressionVisitor {
8399
8337
  }
8400
8338
  };
8401
8339
  //#endregion
8402
- exports.AllCrudOperations = AllCrudOperations;
8403
- exports.AllReadOperations = AllReadOperations;
8404
- exports.AllWriteOperations = AllWriteOperations;
8340
+ exports.AllCrudOperations = require_constants.AllCrudOperations;
8341
+ exports.AllReadOperations = require_constants.AllReadOperations;
8342
+ exports.AllWriteOperations = require_constants.AllWriteOperations;
8405
8343
  exports.AnyNull = require_common_types.AnyNull;
8406
8344
  exports.AnyNullClass = require_common_types.AnyNullClass;
8407
8345
  exports.BaseCrudDialect = BaseCrudDialect;
8408
8346
  exports.CRUD = CRUD;
8409
8347
  exports.CRUD_EXT = CRUD_EXT;
8410
- exports.CoreCreateOperations = CoreCreateOperations;
8411
- exports.CoreCrudOperations = CoreCrudOperations;
8412
- exports.CoreDeleteOperations = CoreDeleteOperations;
8413
- exports.CoreReadOperations = CoreReadOperations;
8414
- exports.CoreUpdateOperations = CoreUpdateOperations;
8415
- exports.CoreWriteOperations = CoreWriteOperations;
8348
+ exports.CoreCreateOperations = require_constants.CoreCreateOperations;
8349
+ exports.CoreCrudOperations = require_constants.CoreCrudOperations;
8350
+ exports.CoreDeleteOperations = require_constants.CoreDeleteOperations;
8351
+ exports.CoreReadOperations = require_constants.CoreReadOperations;
8352
+ exports.CoreUpdateOperations = require_constants.CoreUpdateOperations;
8353
+ exports.CoreWriteOperations = require_constants.CoreWriteOperations;
8416
8354
  exports.DbNull = require_common_types.DbNull;
8417
8355
  exports.DbNullClass = require_common_types.DbNullClass;
8418
8356
  exports.ExtQueryArgsMarker = ExtQueryArgsMarker;