@zenstackhq/orm 3.9.7-beta.1 → 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.
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) })));
@@ -2068,7 +2000,11 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
2068
2000
  if (columnResolved.sqlType === "uuid" && (op === "=" || op === "!=")) {
2069
2001
  const value = valueNode.value;
2070
2002
  if (typeof value === "string" && PostgresCrudDialect.uuidFormatRegex.test(value)) return this.eb(left, op, right);
2071
- else return this.eb.lit(op === "!=");
2003
+ else if (op === "=") return this.eb.lit(false);
2004
+ else {
2005
+ const column = valueNode === rightNode ? left : right;
2006
+ return this.eb(column, "is not", null);
2007
+ }
2072
2008
  }
2073
2009
  }
2074
2010
  getStringCasingBehavior() {
@@ -2267,7 +2203,7 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2267
2203
  tbl = tbl.select(() => {
2268
2204
  const objArgs = [];
2269
2205
  const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
2270
- 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));
2271
2207
  if (payload === true || !payload.select) {
2272
2208
  const omit = typeof payload === "object" ? payload.omit : void 0;
2273
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));
@@ -2487,7 +2423,7 @@ function coercedDateTimeSchema() {
2487
2423
  var ZodSchemaFactory = class {
2488
2424
  schemaCache = /* @__PURE__ */ new Map();
2489
2425
  schemaRegistry = zod.z.registry();
2490
- allFilterKinds = [...new Set(Object.values(FILTER_PROPERTY_TO_KIND))];
2426
+ allFilterKinds = [...new Set(Object.values(require_constants.FILTER_PROPERTY_TO_KIND))];
2491
2427
  schema;
2492
2428
  options;
2493
2429
  extraValidationsEnabled = true;
@@ -3584,7 +3520,7 @@ var ZodSchemaFactory = class {
3584
3520
  schema = schema.refine((value) => {
3585
3521
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3586
3522
  if (value.having && typeof value.having === "object") for (const [key, val] of Object.entries(value.having)) {
3587
- if (AggregateOperators.includes(key)) continue;
3523
+ if (require_constants.AggregateOperators.includes(key)) continue;
3588
3524
  if (bys.includes(key)) continue;
3589
3525
  if (!val || typeof val !== "object") return false;
3590
3526
  if (!this.onlyAggregationFields(val)) return false;
@@ -3593,7 +3529,7 @@ var ZodSchemaFactory = class {
3593
3529
  }, "fields in \"having\" must be in \"by\"");
3594
3530
  schema = schema.refine((value) => {
3595
3531
  const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3596
- 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;
3597
3533
  return true;
3598
3534
  }, "fields in \"orderBy\" must be in \"by\"");
3599
3535
  this.registerSchema(`${model}GroupByArgs`, schema);
@@ -3601,8 +3537,8 @@ var ZodSchemaFactory = class {
3601
3537
  }
3602
3538
  onlyAggregationFields(val) {
3603
3539
  for (const [key, value] of Object.entries(val)) {
3604
- if (AggregateOperators.includes(key)) continue;
3605
- if (LOGICAL_COMBINATORS.includes(key)) {
3540
+ if (require_constants.AggregateOperators.includes(key)) continue;
3541
+ if (require_constants.LOGICAL_COMBINATORS.includes(key)) {
3606
3542
  if ((0, _zenstackhq_common_helpers.enumerate)(value).every((v) => this.onlyAggregationFields(v))) continue;
3607
3543
  }
3608
3544
  return false;
@@ -3657,10 +3593,10 @@ var ZodSchemaFactory = class {
3657
3593
  result = createSchema.extend(updateSchema.shape);
3658
3594
  } else if (createSchema) result = createSchema;
3659
3595
  else if (updateSchema) result = updateSchema;
3660
- } else if (CoreCreateOperations.includes(operation) && "$create" in plugin.queryArgs && plugin.queryArgs["$create"]) result = plugin.queryArgs["$create"];
3661
- else if (CoreReadOperations.includes(operation) && "$read" in plugin.queryArgs && plugin.queryArgs["$read"]) result = plugin.queryArgs["$read"];
3662
- else if (CoreUpdateOperations.includes(operation) && "$update" in plugin.queryArgs && plugin.queryArgs["$update"]) result = plugin.queryArgs["$update"];
3663
- 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"];
3664
3600
  else if ("$all" in plugin.queryArgs && plugin.queryArgs["$all"]) result = plugin.queryArgs["$all"];
3665
3601
  (0, _zenstackhq_common_helpers.invariant)(result === void 0 || result instanceof zod.ZodObject, "Plugin extended query args schema must be a Zod object");
3666
3602
  return result;
@@ -3691,7 +3627,7 @@ var ZodSchemaFactory = class {
3691
3627
  return canBeArray ? zod.z.union([schema, zod.z.array(schema)]) : schema;
3692
3628
  }
3693
3629
  isNumericField(fieldDef) {
3694
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3630
+ return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3695
3631
  }
3696
3632
  get providerSupportsCaseSensitivity() {
3697
3633
  return this.schema.provider.type === "postgresql";
@@ -3744,7 +3680,7 @@ var ZodSchemaFactory = class {
3744
3680
  trimFilterOperators(operators, allowedKinds) {
3745
3681
  if (!allowedKinds) return operators;
3746
3682
  return Object.fromEntries(Object.entries(operators).filter(([key, _]) => {
3747
- 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]);
3748
3684
  }));
3749
3685
  }
3750
3686
  createUnionFilterSchema(valueSchema, optional, components, allowedFilterKinds) {
@@ -4316,94 +4252,13 @@ var InputValidator = class {
4316
4252
  //#endregion
4317
4253
  //#region src/client/crud/operations/base.ts
4318
4254
  /**
4319
- * List of core CRUD operations. It excludes the 'orThrow' variants.
4320
- */
4321
- const CoreCrudOperations = [
4322
- "findMany",
4323
- "findUnique",
4324
- "findFirst",
4325
- "create",
4326
- "createMany",
4327
- "createManyAndReturn",
4328
- "update",
4329
- "updateMany",
4330
- "updateManyAndReturn",
4331
- "upsert",
4332
- "delete",
4333
- "deleteMany",
4334
- "count",
4335
- "aggregate",
4336
- "groupBy",
4337
- "exists"
4338
- ];
4339
- /**
4340
- * List of core read operations. It excludes the 'orThrow' variants.
4341
- */
4342
- const CoreReadOperations = [
4343
- "findMany",
4344
- "findUnique",
4345
- "findFirst",
4346
- "count",
4347
- "aggregate",
4348
- "groupBy",
4349
- "exists"
4350
- ];
4351
- /**
4352
- * List of core write operations.
4353
- */
4354
- const CoreWriteOperations = [
4355
- "create",
4356
- "createMany",
4357
- "createManyAndReturn",
4358
- "update",
4359
- "updateMany",
4360
- "updateManyAndReturn",
4361
- "upsert",
4362
- "delete",
4363
- "deleteMany"
4364
- ];
4365
- /**
4366
- * List of core create operations.
4367
- */
4368
- const CoreCreateOperations = [
4369
- "create",
4370
- "createMany",
4371
- "createManyAndReturn",
4372
- "upsert"
4373
- ];
4374
- /**
4375
- * List of core update operations.
4376
- */
4377
- const CoreUpdateOperations = [
4378
- "update",
4379
- "updateMany",
4380
- "updateManyAndReturn",
4381
- "upsert"
4382
- ];
4383
- /**
4384
- * List of core delete operations.
4385
- */
4386
- const CoreDeleteOperations = ["delete", "deleteMany"];
4387
- /**
4388
- * List of all CRUD operations, including 'orThrow' variants.
4389
- */
4390
- const AllCrudOperations = [
4391
- ...CoreCrudOperations,
4392
- "findUniqueOrThrow",
4393
- "findFirstOrThrow"
4394
- ];
4395
- /**
4396
- * List of all read operations, including 'orThrow' variants.
4255
+ * Maximum number of rows identified by id in a single statement during cascade delete simulation.
4397
4256
  */
4398
- const AllReadOperations = [
4399
- ...CoreReadOperations,
4400
- "findUniqueOrThrow",
4401
- "findFirstOrThrow"
4402
- ];
4257
+ const DELETE_ID_BATCH_SIZE = 1e3;
4403
4258
  /**
4404
- * 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.
4405
4260
  */
4406
- const AllWriteOperations = CoreWriteOperations;
4261
+ const DELETE_COMPOUND_ID_BATCH_SIZE = 100;
4407
4262
  var BaseOperationHandler = class {
4408
4263
  dialect;
4409
4264
  constructor(client, model, inputValidator) {
@@ -5018,7 +4873,7 @@ var BaseOperationHandler = class {
5018
4873
  });
5019
4874
  }
5020
4875
  isNumericField(fieldDef) {
5021
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
4876
+ return require_constants.NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
5022
4877
  }
5023
4878
  makeContextComment(_context) {
5024
4879
  return kysely.sql``;
@@ -5338,37 +5193,130 @@ var BaseOperationHandler = class {
5338
5193
  normalizeRelationManipulationInput(model, data) {
5339
5194
  return (0, _zenstackhq_common_helpers.enumerate)(data).map((item) => flattenCompoundUniqueFilters(this.schema, model, item));
5340
5195
  }
5341
- async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn) {
5196
+ async delete(kysely$28, model, where, limit, filterModel, fieldsToReturn, visited) {
5342
5197
  filterModel ??= model;
5198
+ visited ??= /* @__PURE__ */ new Set();
5343
5199
  const modelDef = this.requireModel(model);
5344
5200
  if (modelDef.baseModel) {
5345
5201
  if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5346
- return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel);
5202
+ return this.processBaseModelDelete(kysely$28, modelDef.baseModel, where, limit, filterModel, visited);
5347
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);
5348
5251
  fieldsToReturn = fieldsToReturn ?? requireIdFields(this.schema, model);
5349
5252
  let needIdFilter = false;
5350
5253
  if (limit !== void 0 && !this.dialect.supportsDeleteWithLimit) needIdFilter = true;
5351
5254
  if (modelDef.isDelegate || modelDef.baseModel) needIdFilter = true;
5352
- 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);
5353
- await this.processDelegateRelationDelete(kysely$28, modelDef, where, limit);
5354
- 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({
5355
5257
  model,
5356
5258
  operation: "delete"
5357
5259
  }));
5358
- return this.executeQuery(kysely$28, query, "delete");
5260
+ return this.executeQuery(kysely$29, query, "delete");
5359
5261
  }
5360
- async processDelegateRelationDelete(kysely$29, modelDef, where, limit) {
5361
- 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;
5362
5286
  const oppositeModelDef = this.requireModel(fieldDef.type);
5363
5287
  const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5364
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") {
5365
- if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5366
- await this.delete(kysely$29, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0);
5367
- }
5368
- }
5288
+ return !!oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade";
5289
+ });
5369
5290
  }
5370
- async processBaseModelDelete(kysely$30, model, where, limit, filterModel) {
5371
- return this.delete(kysely$30, model, where, limit, filterModel);
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);
5295
+ }
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);
5372
5320
  }
5373
5321
  makeIdSelect(model) {
5374
5322
  return this.requireModel(model).idFields.reduce((acc, f) => {
@@ -5671,14 +5619,8 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
5671
5619
  });
5672
5620
  }
5673
5621
  needsNestedDelete() {
5674
- const modelDef = this.requireModel(this.model);
5675
- if (modelDef.baseModel) return true;
5676
- for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation?.opposite) {
5677
- const oppositeModelDef = this.requireModel(fieldDef.type);
5678
- const oppositeRelation = this.requireField(fieldDef.type, fieldDef.relation.opposite);
5679
- if (oppositeModelDef.baseModel && oppositeRelation.relation?.onDelete === "Cascade") return true;
5680
- }
5681
- return false;
5622
+ if (this.requireModel(this.model).baseModel) return true;
5623
+ return this.getDelegateCascadeRelations(this.model).length > 0;
5682
5624
  }
5683
5625
  };
5684
5626
  //#endregion
@@ -7337,7 +7279,7 @@ var ResultProcessor = class {
7337
7279
  else if (key.startsWith("$delegate$")) {
7338
7280
  if (value) {
7339
7281
  const subRow = this.dialect.transformOutput(value, "Json", false);
7340
- const subModel = key.slice(10);
7282
+ const subModel = key.slice(require_constants.DELEGATE_JOINED_FIELD_PREFIX.length);
7341
7283
  const idValues = getIdValues(this.schema, subModel, subRow);
7342
7284
  if (Object.values(idValues).some((v) => v === null || v === void 0)) {
7343
7285
  delete data[key];
@@ -8395,20 +8337,20 @@ var MatchingExpressionVisitor = class extends ExpressionVisitor {
8395
8337
  }
8396
8338
  };
8397
8339
  //#endregion
8398
- exports.AllCrudOperations = AllCrudOperations;
8399
- exports.AllReadOperations = AllReadOperations;
8400
- exports.AllWriteOperations = AllWriteOperations;
8340
+ exports.AllCrudOperations = require_constants.AllCrudOperations;
8341
+ exports.AllReadOperations = require_constants.AllReadOperations;
8342
+ exports.AllWriteOperations = require_constants.AllWriteOperations;
8401
8343
  exports.AnyNull = require_common_types.AnyNull;
8402
8344
  exports.AnyNullClass = require_common_types.AnyNullClass;
8403
8345
  exports.BaseCrudDialect = BaseCrudDialect;
8404
8346
  exports.CRUD = CRUD;
8405
8347
  exports.CRUD_EXT = CRUD_EXT;
8406
- exports.CoreCreateOperations = CoreCreateOperations;
8407
- exports.CoreCrudOperations = CoreCrudOperations;
8408
- exports.CoreDeleteOperations = CoreDeleteOperations;
8409
- exports.CoreReadOperations = CoreReadOperations;
8410
- exports.CoreUpdateOperations = CoreUpdateOperations;
8411
- 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;
8412
8354
  exports.DbNull = require_common_types.DbNull;
8413
8355
  exports.DbNullClass = require_common_types.DbNullClass;
8414
8356
  exports.ExtQueryArgsMarker = ExtQueryArgsMarker;