@zenstackhq/runtime 3.0.0-alpha.13 → 3.0.0-alpha.15

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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ClientConstructor } from './contract-CBOBlAuw.cjs';
2
- export { K as AggregateArgs, L as AggregateResult, B as BatchResult, i as BooleanFilter, h as BytesFilter, c as ClientContract, d as ClientOptions, G as CountArgs, H as CountResult, u as CreateArgs, w as CreateManyAndReturnArgs, v as CreateManyArgs, D as DateTimeFilter, A as DeleteArgs, E as DeleteManyArgs, F as FindArgs, s as FindFirstArgs, r as FindManyArgs, t as FindUniqueArgs, P as GroupByArgs, Q as GroupByResult, I as IncludeInput, J as JsonArray, a as JsonObject, b as JsonValue, M as ModelResult, k as NullsOrder, N as NumberFilter, m as OmitInput, O as OrderBy, n as SelectIncludeOmit, o as SelectInput, q as SelectSubset, S as SimplifiedModelResult, j as SortOrder, g as StringFilter, p as Subset, T as ToKysely, f as TypeDefResult, U as UpdateArgs, y as UpdateManyAndReturnArgs, x as UpdateManyArgs, z as UpsertArgs, W as WhereInput, l as WhereUniqueInput, e as definePlugin } from './contract-CBOBlAuw.cjs';
1
+ import { C as ClientConstructor } from './contract-BYc34jr_.cjs';
2
+ export { K as AggregateArgs, L as AggregateResult, B as BatchResult, i as BooleanFilter, h as BytesFilter, c as ClientContract, d as ClientOptions, G as CountArgs, H as CountResult, u as CreateArgs, w as CreateManyAndReturnArgs, v as CreateManyArgs, D as DateTimeFilter, A as DeleteArgs, E as DeleteManyArgs, F as FindArgs, s as FindFirstArgs, r as FindManyArgs, t as FindUniqueArgs, P as GroupByArgs, Q as GroupByResult, I as IncludeInput, J as JsonArray, a as JsonObject, b as JsonValue, M as ModelResult, k as NullsOrder, N as NumberFilter, m as OmitInput, O as OrderBy, n as SelectIncludeOmit, o as SelectInput, q as SelectSubset, S as SimplifiedModelResult, j as SortOrder, g as StringFilter, p as Subset, T as ToKysely, f as TypeDefResult, U as UpdateArgs, y as UpdateManyAndReturnArgs, x as UpdateManyArgs, z as UpsertArgs, W as WhereInput, l as WhereUniqueInput, e as definePlugin } from './contract-BYc34jr_.cjs';
3
3
  import 'decimal.js';
4
4
  import '@zenstackhq/sdk/schema';
5
5
  import 'kysely';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ClientConstructor } from './contract-CBOBlAuw.js';
2
- export { K as AggregateArgs, L as AggregateResult, B as BatchResult, i as BooleanFilter, h as BytesFilter, c as ClientContract, d as ClientOptions, G as CountArgs, H as CountResult, u as CreateArgs, w as CreateManyAndReturnArgs, v as CreateManyArgs, D as DateTimeFilter, A as DeleteArgs, E as DeleteManyArgs, F as FindArgs, s as FindFirstArgs, r as FindManyArgs, t as FindUniqueArgs, P as GroupByArgs, Q as GroupByResult, I as IncludeInput, J as JsonArray, a as JsonObject, b as JsonValue, M as ModelResult, k as NullsOrder, N as NumberFilter, m as OmitInput, O as OrderBy, n as SelectIncludeOmit, o as SelectInput, q as SelectSubset, S as SimplifiedModelResult, j as SortOrder, g as StringFilter, p as Subset, T as ToKysely, f as TypeDefResult, U as UpdateArgs, y as UpdateManyAndReturnArgs, x as UpdateManyArgs, z as UpsertArgs, W as WhereInput, l as WhereUniqueInput, e as definePlugin } from './contract-CBOBlAuw.js';
1
+ import { C as ClientConstructor } from './contract-BYc34jr_.js';
2
+ export { K as AggregateArgs, L as AggregateResult, B as BatchResult, i as BooleanFilter, h as BytesFilter, c as ClientContract, d as ClientOptions, G as CountArgs, H as CountResult, u as CreateArgs, w as CreateManyAndReturnArgs, v as CreateManyArgs, D as DateTimeFilter, A as DeleteArgs, E as DeleteManyArgs, F as FindArgs, s as FindFirstArgs, r as FindManyArgs, t as FindUniqueArgs, P as GroupByArgs, Q as GroupByResult, I as IncludeInput, J as JsonArray, a as JsonObject, b as JsonValue, M as ModelResult, k as NullsOrder, N as NumberFilter, m as OmitInput, O as OrderBy, n as SelectIncludeOmit, o as SelectInput, q as SelectSubset, S as SimplifiedModelResult, j as SortOrder, g as StringFilter, p as Subset, T as ToKysely, f as TypeDefResult, U as UpdateArgs, y as UpdateManyAndReturnArgs, x as UpdateManyArgs, z as UpsertArgs, W as WhereInput, l as WhereUniqueInput, e as definePlugin } from './contract-BYc34jr_.js';
3
3
  import 'decimal.js';
4
4
  import '@zenstackhq/sdk/schema';
5
5
  import 'kysely';
package/dist/index.js CHANGED
@@ -2631,14 +2631,14 @@ var BaseOperationHandler = class {
2631
2631
  getField(model, field) {
2632
2632
  return getField(this.schema, model, field);
2633
2633
  }
2634
- exists(kysely, model, filter) {
2634
+ async exists(kysely, model, filter) {
2635
2635
  const idFields = getIdFields(this.schema, model);
2636
2636
  const _filter = flattenCompoundUniqueFilters(this.schema, model, filter);
2637
2637
  const query = kysely.selectFrom(model).where((eb) => eb.and(_filter)).select(idFields.map((f) => kysely.dynamic.ref(f))).limit(1).modifyEnd(this.makeContextComment({
2638
2638
  model,
2639
2639
  operation: "read"
2640
2640
  }));
2641
- return query.executeTakeFirst();
2641
+ return this.executeQueryTakeFirst(kysely, query, "exists");
2642
2642
  }
2643
2643
  async read(kysely, model, args) {
2644
2644
  let query = this.dialect.buildSelectModel(expressionBuilder2(), model);
@@ -2815,7 +2815,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
2815
2815
  model: fromRelation.model,
2816
2816
  operation: "update"
2817
2817
  }));
2818
- return query2.execute();
2818
+ return this.executeQuery(kysely, query2, "update");
2819
2819
  }, "parentUpdateTask");
2820
2820
  }
2821
2821
  }
@@ -2854,7 +2854,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
2854
2854
  model,
2855
2855
  operation: "create"
2856
2856
  }));
2857
- const createdEntity = await query.executeTakeFirst();
2857
+ const createdEntity = await this.executeQueryTakeFirst(kysely, query, "create");
2858
2858
  if (Object.keys(postCreateRelations).length > 0) {
2859
2859
  const relationPromises = Object.entries(postCreateRelations).map(([field, subPayload]) => {
2860
2860
  return this.processNoneOwnedRelationForCreate(kysely, model, field, subPayload, createdEntity);
@@ -3086,9 +3086,9 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3086
3086
  operation: "create"
3087
3087
  }));
3088
3088
  if (!returnData) {
3089
- const result = await query.executeTakeFirstOrThrow();
3089
+ const result = await this.executeQuery(kysely, query, "createMany");
3090
3090
  return {
3091
- count: Number(result.numInsertedOrUpdatedRows)
3091
+ count: Number(result.numAffectedRows)
3092
3092
  };
3093
3093
  } else {
3094
3094
  const idFields = getIdFields(this.schema, model);
@@ -3267,7 +3267,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3267
3267
  model,
3268
3268
  operation: "update"
3269
3269
  }));
3270
- const updatedEntity = await query.executeTakeFirst();
3270
+ const updatedEntity = await this.executeQueryTakeFirst(kysely, query, "update");
3271
3271
  if (!updatedEntity) {
3272
3272
  if (throwIfNotFound) {
3273
3273
  throw new NotFoundError(model);
@@ -3407,9 +3407,9 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3407
3407
  operation: "update"
3408
3408
  }));
3409
3409
  if (!returnData) {
3410
- const result = await query.executeTakeFirstOrThrow();
3410
+ const result = await this.executeQuery(kysely, query, "update");
3411
3411
  return {
3412
- count: Number(result.numUpdatedRows)
3412
+ count: Number(result.numAffectedRows)
3413
3413
  };
3414
3414
  } else {
3415
3415
  const idFields = getIdFields(this.schema, model);
@@ -3554,7 +3554,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3554
3554
  model: fromRelation.model,
3555
3555
  operation: "update"
3556
3556
  }));
3557
- updateResult = await query.executeTakeFirstOrThrow();
3557
+ updateResult = await this.executeQuery(kysely, query, "connect");
3558
3558
  } else {
3559
3559
  const relationFieldDef = this.requireField(fromRelation.model, fromRelation.field);
3560
3560
  if (!relationFieldDef.array) {
@@ -3565,7 +3565,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3565
3565
  model: fromRelation.model,
3566
3566
  operation: "update"
3567
3567
  }));
3568
- await query2.execute();
3568
+ await this.executeQuery(kysely, query2, "disconnect");
3569
3569
  }
3570
3570
  const query = kysely.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
3571
3571
  ...acc,
@@ -3574,9 +3574,9 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3574
3574
  model,
3575
3575
  operation: "update"
3576
3576
  }));
3577
- updateResult = await query.executeTakeFirstOrThrow();
3577
+ updateResult = await this.executeQuery(kysely, query, "connect");
3578
3578
  }
3579
- if (_data.length > updateResult.numUpdatedRows) {
3579
+ if (_data.length > updateResult.numAffectedRows) {
3580
3580
  throw new NotFoundError(model);
3581
3581
  }
3582
3582
  }
@@ -3644,7 +3644,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3644
3644
  model: fromRelation.model,
3645
3645
  operation: "update"
3646
3646
  }));
3647
- await query.executeTakeFirstOrThrow();
3647
+ await this.executeQuery(kysely, query, "disconnect");
3648
3648
  } else {
3649
3649
  const query = kysely.updateTable(model).where(eb.and([
3650
3650
  // fk filter
@@ -3661,7 +3661,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3661
3661
  model,
3662
3662
  operation: "update"
3663
3663
  }));
3664
- await query.executeTakeFirstOrThrow();
3664
+ await this.executeQuery(kysely, query, "disconnect");
3665
3665
  }
3666
3666
  }
3667
3667
  }
@@ -3699,7 +3699,7 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3699
3699
  model,
3700
3700
  operation: "update"
3701
3701
  }));
3702
- await query.execute();
3702
+ await this.executeQuery(kysely, query, "disconnect");
3703
3703
  if (_data.length > 0) {
3704
3704
  const query2 = kysely.updateTable(model).where((eb) => eb.or(_data.map((d) => eb.and(d)))).set(keyPairs.reduce((acc, { fk, pk }) => ({
3705
3705
  ...acc,
@@ -3708,8 +3708,8 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3708
3708
  model,
3709
3709
  operation: "update"
3710
3710
  }));
3711
- const r = await query2.executeTakeFirstOrThrow();
3712
- if (_data.length > r.numUpdatedRows) {
3711
+ const r = await this.executeQuery(kysely, query2, "connect");
3712
+ if (_data.length > r.numAffectedRows) {
3713
3713
  throw new NotFoundError(model);
3714
3714
  }
3715
3715
  }
@@ -3825,9 +3825,9 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3825
3825
  model,
3826
3826
  operation: "delete"
3827
3827
  }));
3828
- const result = await query.executeTakeFirstOrThrow();
3828
+ const result = await this.executeQuery(kysely, query, "delete");
3829
3829
  return {
3830
- count: Number(result.numDeletedRows)
3830
+ count: Number(result.numAffectedRows)
3831
3831
  };
3832
3832
  }
3833
3833
  async processDelegateRelationDelete(kysely, modelDef, where, limit) {
@@ -3924,6 +3924,25 @@ ${compiled.parameters.map((p) => inspect(p)).join("\n")}`;
3924
3924
  }
3925
3925
  }
3926
3926
  }
3927
+ makeQueryId(operation) {
3928
+ return {
3929
+ queryId: `${operation}-${createId()}`
3930
+ };
3931
+ }
3932
+ executeQuery(kysely, query, operation) {
3933
+ return kysely.executeQuery(query.compile(), this.makeQueryId(operation));
3934
+ }
3935
+ async executeQueryTakeFirst(kysely, query, operation) {
3936
+ const result = await kysely.executeQuery(query.compile(), this.makeQueryId(operation));
3937
+ return result.rows[0];
3938
+ }
3939
+ async executeQueryTakeFirstOrThrow(kysely, query, operation) {
3940
+ const result = await kysely.executeQuery(query.compile(), this.makeQueryId(operation));
3941
+ if (result.rows.length === 0) {
3942
+ throw new QueryError("No rows found");
3943
+ }
3944
+ return result.rows[0];
3945
+ }
3927
3946
  };
3928
3947
 
3929
3948
  // src/client/crud/operations/aggregate.ts
@@ -3996,9 +4015,9 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
3996
4015
  }
3997
4016
  }
3998
4017
  }
3999
- const result = await query.executeTakeFirstOrThrow();
4018
+ const result = await this.executeQuery(this.kysely, query, "aggregate");
4000
4019
  const ret = {};
4001
- for (const [key, value] of Object.entries(result)) {
4020
+ for (const [key, value] of Object.entries(result.rows[0])) {
4002
4021
  if (key === "_count") {
4003
4022
  ret[key] = value;
4004
4023
  continue;
@@ -4060,11 +4079,12 @@ var CountOperationHandler = class extends BaseOperationHandler {
4060
4079
  });
4061
4080
  if (parsedArgs?.select && typeof parsedArgs.select === "object") {
4062
4081
  query = query.select((eb) => Object.keys(parsedArgs.select).map((key) => key === "_all" ? eb.cast(eb.fn.countAll(), "integer").as("_all") : eb.cast(eb.fn.count(sql6.ref(`${subQueryName}.${key}`)), "integer").as(key)));
4063
- return query.executeTakeFirstOrThrow();
4082
+ const result = await this.executeQuery(this.kysely, query, "count");
4083
+ return result.rows[0];
4064
4084
  } else {
4065
4085
  query = query.select((eb) => eb.cast(eb.fn.countAll(), "integer").as("count"));
4066
- const result = await query.executeTakeFirstOrThrow();
4067
- return result.count;
4086
+ const result = await this.executeQuery(this.kysely, query, "count");
4087
+ return result.rows[0].count;
4068
4088
  }
4069
4089
  }
4070
4090
  };
@@ -4144,7 +4164,7 @@ var DeleteOperationHandler = class extends BaseOperationHandler {
4144
4164
  throw new NotFoundError(this.model);
4145
4165
  }
4146
4166
  await this.safeTransaction(async (tx) => {
4147
- const result = await this.delete(tx, this.model, args.where, void 0);
4167
+ const result = await this.delete(tx, this.model, args.where);
4148
4168
  if (result.count === 0) {
4149
4169
  throw new NotFoundError(this.model);
4150
4170
  }
@@ -4243,8 +4263,8 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
4243
4263
  }
4244
4264
  }
4245
4265
  }
4246
- const result = await query.execute();
4247
- return result.map((row) => this.postProcessRow(row));
4266
+ const result = await this.executeQuery(this.kysely, query, "groupBy");
4267
+ return result.rows.map((row) => this.postProcessRow(row));
4248
4268
  }
4249
4269
  postProcessRow(row) {
4250
4270
  const ret = {};
@@ -5247,11 +5267,11 @@ var ZenStackDriver = class {
5247
5267
  }
5248
5268
  #driver;
5249
5269
  #log;
5250
- txConnection;
5251
5270
  #initPromise;
5252
5271
  #initDone;
5253
5272
  #destroyPromise;
5254
5273
  #connections = /* @__PURE__ */ new WeakSet();
5274
+ #txConnections = /* @__PURE__ */ new WeakMap();
5255
5275
  constructor(driver, log) {
5256
5276
  this.#initDone = false;
5257
5277
  this.#driver = driver;
@@ -5292,21 +5312,30 @@ var ZenStackDriver = class {
5292
5312
  }
5293
5313
  async beginTransaction(connection, settings) {
5294
5314
  const result = await this.#driver.beginTransaction(connection, settings);
5295
- this.txConnection = connection;
5315
+ this.#txConnections.set(connection, []);
5296
5316
  return result;
5297
5317
  }
5298
- commitTransaction(connection) {
5318
+ async commitTransaction(connection) {
5299
5319
  try {
5300
- return this.#driver.commitTransaction(connection);
5301
- } finally {
5302
- this.txConnection = void 0;
5320
+ const result = await this.#driver.commitTransaction(connection);
5321
+ const callbacks = this.#txConnections.get(connection);
5322
+ this.#txConnections.delete(connection);
5323
+ if (callbacks) {
5324
+ for (const callback of callbacks) {
5325
+ await callback();
5326
+ }
5327
+ }
5328
+ return result;
5329
+ } catch (err) {
5330
+ this.#txConnections.delete(connection);
5331
+ throw err;
5303
5332
  }
5304
5333
  }
5305
- rollbackTransaction(connection) {
5334
+ async rollbackTransaction(connection) {
5306
5335
  try {
5307
- return this.#driver.rollbackTransaction(connection);
5336
+ return await this.#driver.rollbackTransaction(connection);
5308
5337
  } finally {
5309
- this.txConnection = void 0;
5338
+ this.#txConnections.delete(connection);
5310
5339
  }
5311
5340
  }
5312
5341
  async destroy() {
@@ -5384,6 +5413,22 @@ var ZenStackDriver = class {
5384
5413
  #calculateDurationMillis(startTime) {
5385
5414
  return performanceNow() - startTime;
5386
5415
  }
5416
+ isTransactionConnection(connection) {
5417
+ return this.#txConnections.has(connection);
5418
+ }
5419
+ registerTransactionCommitCallback(connection, callback) {
5420
+ if (!this.#txConnections.has(connection)) {
5421
+ return;
5422
+ }
5423
+ const callbacks = this.#txConnections.get(connection);
5424
+ if (callbacks) {
5425
+ callbacks.push(callback);
5426
+ } else {
5427
+ this.#txConnections.set(connection, [
5428
+ callback
5429
+ ]);
5430
+ }
5431
+ }
5387
5432
  };
5388
5433
  function performanceNow() {
5389
5434
  if (typeof performance !== "undefined" && typeof performance.now === "function") {
@@ -5625,7 +5670,7 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends DefaultQueryExe
5625
5670
  get options() {
5626
5671
  return this.client.$options;
5627
5672
  }
5628
- async executeQuery(compiledQuery, queryId) {
5673
+ async executeQuery(compiledQuery, _queryId) {
5629
5674
  let queryNode = compiledQuery.query;
5630
5675
  let mutationInterceptionInfo;
5631
5676
  if (this.isMutationNode(queryNode) && this.hasMutationHooks) {
@@ -5636,7 +5681,7 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends DefaultQueryExe
5636
5681
  await this.callBeforeMutationHooks(queryNode, mutationInterceptionInfo);
5637
5682
  }
5638
5683
  const oldQueryNode = queryNode;
5639
- if ((InsertQueryNode2.is(queryNode) || DeleteQueryNode2.is(queryNode)) && mutationInterceptionInfo?.loadAfterMutationEntity) {
5684
+ if ((InsertQueryNode2.is(queryNode) || UpdateQueryNode2.is(queryNode)) && mutationInterceptionInfo?.loadAfterMutationEntity) {
5640
5685
  queryNode = {
5641
5686
  ...queryNode,
5642
5687
  returning: ReturningNode3.create([
@@ -5645,34 +5690,49 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends DefaultQueryExe
5645
5690
  };
5646
5691
  }
5647
5692
  const queryParams = compiledQuery.$raw ? compiledQuery.parameters : void 0;
5648
- const result = await this.proceedQueryWithKyselyInterceptors(queryNode, queryParams, queryId);
5693
+ const result = await this.proceedQueryWithKyselyInterceptors(queryNode, queryParams);
5649
5694
  if (this.isMutationNode(queryNode)) {
5650
- await this.callAfterQueryInterceptionFilters(result, queryNode, mutationInterceptionInfo);
5695
+ await this.callAfterMutationHooks(result.result, queryNode, mutationInterceptionInfo, result.connection);
5651
5696
  }
5652
5697
  if (oldQueryNode !== queryNode) {
5653
5698
  }
5654
- return result;
5699
+ return result.result;
5655
5700
  }, "task");
5656
5701
  return task();
5657
5702
  }
5658
- proceedQueryWithKyselyInterceptors(queryNode, parameters, queryId) {
5659
- let proceed = /* @__PURE__ */ __name((q) => this.proceedQuery(q, parameters, queryId), "proceed");
5660
- const hooks = this.options.plugins?.filter((plugin) => typeof plugin.onKyselyQuery === "function").map((plugin) => plugin.onKyselyQuery.bind(plugin)) ?? [];
5703
+ proceedQueryWithKyselyInterceptors(queryNode, parameters) {
5704
+ let proceed = /* @__PURE__ */ __name((q) => this.proceedQuery(q, parameters), "proceed");
5705
+ const hooks = [];
5706
+ for (const plugin of this.client.$options.plugins ?? []) {
5707
+ if (plugin.onKyselyQuery) {
5708
+ hooks.push(plugin.onKyselyQuery.bind(plugin));
5709
+ }
5710
+ }
5661
5711
  for (const hook of hooks) {
5662
5712
  const _proceed = proceed;
5663
- proceed = /* @__PURE__ */ __name((query) => {
5664
- return hook({
5713
+ proceed = /* @__PURE__ */ __name(async (query) => {
5714
+ let connection;
5715
+ const _p = /* @__PURE__ */ __name(async (q) => {
5716
+ const r = await _proceed(q);
5717
+ connection = r.connection;
5718
+ return r.result;
5719
+ }, "_p");
5720
+ const hookResult = await hook({
5665
5721
  client: this.client,
5666
5722
  schema: this.client.$schema,
5667
5723
  kysely: this.kysely,
5668
5724
  query,
5669
- proceed: _proceed
5725
+ proceed: _p
5670
5726
  });
5727
+ return {
5728
+ result: hookResult,
5729
+ connection
5730
+ };
5671
5731
  }, "proceed");
5672
5732
  }
5673
5733
  return proceed(queryNode);
5674
5734
  }
5675
- async proceedQuery(query, parameters, queryId) {
5735
+ async proceedQuery(query, parameters) {
5676
5736
  const finalQuery = this.nameMapper.transformNode(query);
5677
5737
  let compiled = this.compileQuery(finalQuery);
5678
5738
  if (parameters) {
@@ -5682,7 +5742,13 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends DefaultQueryExe
5682
5742
  };
5683
5743
  }
5684
5744
  try {
5685
- return await super.executeQuery(compiled, queryId);
5745
+ return await this.provideConnection(async (connection) => {
5746
+ const result = await connection.executeQuery(compiled);
5747
+ return {
5748
+ result,
5749
+ connection
5750
+ };
5751
+ });
5686
5752
  } catch (err) {
5687
5753
  let message = `Failed to execute query: ${err}, sql: ${compiled.sql}`;
5688
5754
  if (this.options.debug) {
@@ -5785,10 +5851,11 @@ ${compiled.parameters.map((p) => inspect2(p)).join("\n")}`;
5785
5851
  return;
5786
5852
  }
5787
5853
  if (this.options.plugins) {
5854
+ const mutationModel = this.getMutationModel(queryNode);
5788
5855
  for (const plugin of this.options.plugins) {
5789
5856
  if (plugin.beforeEntityMutation) {
5790
5857
  await plugin.beforeEntityMutation({
5791
- model: this.getMutationModel(queryNode),
5858
+ model: mutationModel,
5792
5859
  action: mutationInterceptionInfo.action,
5793
5860
  queryNode,
5794
5861
  entities: mutationInterceptionInfo.beforeMutationEntities
@@ -5797,30 +5864,45 @@ ${compiled.parameters.map((p) => inspect2(p)).join("\n")}`;
5797
5864
  }
5798
5865
  }
5799
5866
  }
5800
- async callAfterQueryInterceptionFilters(queryResult, queryNode, mutationInterceptionInfo) {
5867
+ async callAfterMutationHooks(queryResult, queryNode, mutationInterceptionInfo, connection) {
5801
5868
  if (!mutationInterceptionInfo?.intercept) {
5802
5869
  return;
5803
5870
  }
5804
- if (this.options.plugins) {
5805
- const mutationModel = this.getMutationModel(queryNode);
5806
- for (const plugin of this.options.plugins) {
5807
- if (plugin.afterEntityMutation) {
5808
- let afterMutationEntities = void 0;
5809
- if (mutationInterceptionInfo.loadAfterMutationEntity) {
5810
- if (UpdateQueryNode2.is(queryNode)) {
5811
- afterMutationEntities = await this.loadEntities(mutationModel, mutationInterceptionInfo.where);
5812
- } else {
5813
- afterMutationEntities = queryResult.rows;
5814
- }
5815
- }
5816
- await plugin.afterEntityMutation({
5817
- model: this.getMutationModel(queryNode),
5871
+ const hooks = [];
5872
+ for (const plugin of this.options.plugins ?? []) {
5873
+ if (plugin.afterEntityMutation) {
5874
+ hooks.push(plugin.afterEntityMutation.bind(plugin));
5875
+ }
5876
+ }
5877
+ if (hooks.length === 0) {
5878
+ return;
5879
+ }
5880
+ const mutationModel = this.getMutationModel(queryNode);
5881
+ const inTransaction = this.driver.isTransactionConnection(connection);
5882
+ for (const hook of hooks) {
5883
+ let afterMutationEntities = void 0;
5884
+ if (mutationInterceptionInfo.loadAfterMutationEntity) {
5885
+ if (InsertQueryNode2.is(queryNode) || UpdateQueryNode2.is(queryNode)) {
5886
+ afterMutationEntities = queryResult.rows;
5887
+ }
5888
+ }
5889
+ const action = /* @__PURE__ */ __name(async () => {
5890
+ try {
5891
+ await hook({
5892
+ model: mutationModel,
5818
5893
  action: mutationInterceptionInfo.action,
5819
5894
  queryNode,
5820
5895
  beforeMutationEntities: mutationInterceptionInfo.beforeMutationEntities,
5821
5896
  afterMutationEntities
5822
5897
  });
5898
+ } catch (err) {
5899
+ console.error(`Error in afterEntityMutation hook for model "${mutationModel}": ${err}`);
5823
5900
  }
5901
+ }, "action");
5902
+ if (inTransaction) {
5903
+ this.driver.registerTransactionCommitCallback(connection, action);
5904
+ } else {
5905
+ await action();
5824
5906
  }
5825
5907
  }
5826
5908
  }
@@ -6459,19 +6541,26 @@ var ClientImpl = class _ClientImpl {
6459
6541
  await new SchemaDbPusher(this.schema, this.kysely).push();
6460
6542
  }
6461
6543
  $use(plugin) {
6544
+ const newPlugins = [
6545
+ ...this.$options.plugins ?? [],
6546
+ plugin
6547
+ ];
6462
6548
  const newOptions = {
6463
6549
  ...this.options,
6464
- plugins: [
6465
- ...this.options.plugins ?? [],
6466
- plugin
6467
- ]
6550
+ plugins: newPlugins
6468
6551
  };
6469
6552
  return new _ClientImpl(this.schema, newOptions, this);
6470
6553
  }
6471
6554
  $unuse(pluginId) {
6555
+ const newPlugins = [];
6556
+ for (const plugin of this.options.plugins ?? []) {
6557
+ if (plugin.id !== pluginId) {
6558
+ newPlugins.push(plugin);
6559
+ }
6560
+ }
6472
6561
  const newOptions = {
6473
6562
  ...this.options,
6474
- plugins: this.options.plugins?.filter((p) => p.id !== pluginId)
6563
+ plugins: newPlugins
6475
6564
  };
6476
6565
  return new _ClientImpl(this.schema, newOptions, this);
6477
6566
  }