@zenstackhq/runtime 3.0.0-alpha.31 → 3.0.0-alpha.32

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
@@ -37,13 +37,13 @@ __export(src_exports, {
37
37
  QueryError: () => QueryError,
38
38
  ZenStackClient: () => ZenStackClient,
39
39
  definePlugin: () => definePlugin,
40
- sql: () => import_kysely17.sql
40
+ sql: () => import_kysely18.sql
41
41
  });
42
42
  module.exports = __toCommonJS(src_exports);
43
43
 
44
44
  // src/client/client-impl.ts
45
- var import_common_helpers14 = require("@zenstackhq/common-helpers");
46
- var import_kysely16 = require("kysely");
45
+ var import_common_helpers16 = require("@zenstackhq/common-helpers");
46
+ var import_kysely17 = require("kysely");
47
47
 
48
48
  // src/client/crud/operations/aggregate.ts
49
49
  var import_kysely9 = require("kysely");
@@ -2740,6 +2740,16 @@ function clone(value) {
2740
2740
  }
2741
2741
  __name(clone, "clone");
2742
2742
 
2743
+ // src/client/contract.ts
2744
+ var TransactionIsolationLevel = /* @__PURE__ */ function(TransactionIsolationLevel2) {
2745
+ TransactionIsolationLevel2["ReadUncommitted"] = "read uncommitted";
2746
+ TransactionIsolationLevel2["ReadCommitted"] = "read committed";
2747
+ TransactionIsolationLevel2["RepeatableRead"] = "repeatable read";
2748
+ TransactionIsolationLevel2["Serializable"] = "serializable";
2749
+ TransactionIsolationLevel2["Snapshot"] = "snapshot";
2750
+ return TransactionIsolationLevel2;
2751
+ }({});
2752
+
2743
2753
  // src/client/crud/operations/base.ts
2744
2754
  var BaseOperationHandler = class {
2745
2755
  static {
@@ -3978,7 +3988,7 @@ var BaseOperationHandler = class {
3978
3988
  return callback(this.kysely);
3979
3989
  } else {
3980
3990
  let txBuilder = this.kysely.transaction();
3981
- txBuilder = txBuilder.setIsolationLevel(isolationLevel ?? "repeatable read");
3991
+ txBuilder = txBuilder.setIsolationLevel(isolationLevel ?? TransactionIsolationLevel.RepeatableRead);
3982
3992
  return txBuilder.execute(callback);
3983
3993
  }
3984
3994
  }
@@ -5544,7 +5554,11 @@ var ZenStackDriver = class {
5544
5554
  this.#txConnections.delete(connection);
5545
5555
  if (callbacks) {
5546
5556
  for (const callback of callbacks) {
5547
- await callback();
5557
+ try {
5558
+ await callback();
5559
+ } catch (err) {
5560
+ console.error(`Error executing transaction commit callback: ${err}`);
5561
+ }
5548
5562
  }
5549
5563
  }
5550
5564
  return result;
@@ -5662,14 +5676,33 @@ function performanceNow() {
5662
5676
  __name(performanceNow, "performanceNow");
5663
5677
 
5664
5678
  // src/client/executor/zenstack-query-executor.ts
5665
- var import_kysely13 = require("kysely");
5666
- var import_nanoid2 = require("nanoid");
5679
+ var import_common_helpers12 = require("@zenstackhq/common-helpers");
5680
+ var import_kysely14 = require("kysely");
5667
5681
  var import_ts_pattern16 = require("ts-pattern");
5668
5682
 
5669
- // src/client/executor/name-mapper.ts
5683
+ // src/client/executor/kysely-utils.ts
5670
5684
  var import_common_helpers10 = require("@zenstackhq/common-helpers");
5671
5685
  var import_kysely12 = require("kysely");
5672
- var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5686
+ function stripAlias(node) {
5687
+ if (import_kysely12.AliasNode.is(node)) {
5688
+ (0, import_common_helpers10.invariant)(import_kysely12.IdentifierNode.is(node.alias), "Expected identifier as alias");
5689
+ return {
5690
+ alias: node.alias.name,
5691
+ node: node.node
5692
+ };
5693
+ } else {
5694
+ return {
5695
+ alias: void 0,
5696
+ node
5697
+ };
5698
+ }
5699
+ }
5700
+ __name(stripAlias, "stripAlias");
5701
+
5702
+ // src/client/executor/name-mapper.ts
5703
+ var import_common_helpers11 = require("@zenstackhq/common-helpers");
5704
+ var import_kysely13 = require("kysely");
5705
+ var QueryNameMapper = class extends import_kysely13.OperationNodeTransformer {
5673
5706
  static {
5674
5707
  __name(this, "QueryNameMapper");
5675
5708
  }
@@ -5726,8 +5759,8 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5726
5759
  };
5727
5760
  }
5728
5761
  transformJoin(node) {
5729
- const { alias, node: innerNode } = this.stripAlias(node.table);
5730
- if (import_kysely12.TableNode.is(innerNode)) {
5762
+ const { alias, node: innerNode } = stripAlias(node.table);
5763
+ if (import_kysely13.TableNode.is(innerNode)) {
5731
5764
  const modelName = innerNode.table.identifier.name;
5732
5765
  if (this.hasMappedColumns(modelName)) {
5733
5766
  const select = this.createSelectAll(modelName);
@@ -5740,7 +5773,7 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5740
5773
  return super.transformJoin(node);
5741
5774
  }
5742
5775
  transformReference(node) {
5743
- if (!import_kysely12.ColumnNode.is(node.column)) {
5776
+ if (!import_kysely13.ColumnNode.is(node.column)) {
5744
5777
  return super.transformReference(node);
5745
5778
  }
5746
5779
  const { fieldDef, modelDef, scope } = this.resolveFieldFromScopes(node.column.column.name, node.table?.table.identifier.name);
@@ -5753,7 +5786,7 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5753
5786
  mappedTableName = this.mapTableName(scope.model);
5754
5787
  }
5755
5788
  }
5756
- return import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(mappedFieldName), mappedTableName ? import_kysely12.TableNode.create(mappedTableName) : void 0);
5789
+ return import_kysely13.ReferenceNode.create(import_kysely13.ColumnNode.create(mappedFieldName), mappedTableName ? import_kysely13.TableNode.create(mappedTableName) : void 0);
5757
5790
  } else {
5758
5791
  return super.transformReference(node);
5759
5792
  }
@@ -5764,11 +5797,14 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5764
5797
  return super.transformColumn(node);
5765
5798
  }
5766
5799
  const mappedName = this.mapFieldName(modelDef.name, fieldDef.name);
5767
- return import_kysely12.ColumnNode.create(mappedName);
5800
+ return import_kysely13.ColumnNode.create(mappedName);
5768
5801
  }
5769
5802
  transformUpdateQuery(node) {
5770
- const { alias, node: innerTable } = this.stripAlias(node.table);
5771
- if (!innerTable || !import_kysely12.TableNode.is(innerTable)) {
5803
+ if (!node.table) {
5804
+ return super.transformUpdateQuery(node);
5805
+ }
5806
+ const { alias, node: innerTable } = stripAlias(node.table);
5807
+ if (!innerTable || !import_kysely13.TableNode.is(innerTable)) {
5772
5808
  return super.transformUpdateQuery(node);
5773
5809
  }
5774
5810
  return this.withScope({
@@ -5785,8 +5821,8 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5785
5821
  transformDeleteQuery(node) {
5786
5822
  const scopes = this.createScopesFromFroms(node.from, false);
5787
5823
  const froms = node.from.froms.map((from) => {
5788
- const { alias, node: innerNode } = this.stripAlias(from);
5789
- if (import_kysely12.TableNode.is(innerNode)) {
5824
+ const { alias, node: innerNode } = stripAlias(from);
5825
+ if (import_kysely13.TableNode.is(innerNode)) {
5790
5826
  return this.wrapAlias(this.processTableRef(innerNode), alias);
5791
5827
  } else {
5792
5828
  return super.transformNode(from);
@@ -5795,7 +5831,7 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5795
5831
  return this.withScopes(scopes, () => {
5796
5832
  return {
5797
5833
  ...super.transformDeleteQuery(node),
5798
- from: import_kysely12.FromNode.create(froms)
5834
+ from: import_kysely13.FromNode.create(froms)
5799
5835
  };
5800
5836
  });
5801
5837
  }
@@ -5852,22 +5888,22 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5852
5888
  }
5853
5889
  }
5854
5890
  wrapAlias(node, alias) {
5855
- return alias ? import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(alias)) : node;
5891
+ return alias ? import_kysely13.AliasNode.create(node, import_kysely13.IdentifierNode.create(alias)) : node;
5856
5892
  }
5857
5893
  ensureAlias(node, alias, fallbackName) {
5858
5894
  if (!node) {
5859
5895
  return node;
5860
5896
  }
5861
- return alias ? import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(alias)) : import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(fallbackName));
5897
+ return alias ? import_kysely13.AliasNode.create(node, import_kysely13.IdentifierNode.create(alias)) : import_kysely13.AliasNode.create(node, import_kysely13.IdentifierNode.create(fallbackName));
5862
5898
  }
5863
5899
  processTableRef(node) {
5864
5900
  if (!node) {
5865
5901
  return node;
5866
5902
  }
5867
- if (!import_kysely12.TableNode.is(node)) {
5903
+ if (!import_kysely13.TableNode.is(node)) {
5868
5904
  return super.transformNode(node);
5869
5905
  }
5870
- return import_kysely12.TableNode.create(this.mapTableName(node.table.identifier.name));
5906
+ return import_kysely13.TableNode.create(this.mapTableName(node.table.identifier.name));
5871
5907
  }
5872
5908
  getMappedName(def) {
5873
5909
  const mapAttr = def.attributes?.find((attr) => attr.name === "@@map" || attr.name === "@map");
@@ -5895,25 +5931,6 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5895
5931
  return tableName;
5896
5932
  }
5897
5933
  }
5898
- stripAlias(node) {
5899
- if (!node) {
5900
- return {
5901
- alias: void 0,
5902
- node
5903
- };
5904
- }
5905
- if (import_kysely12.AliasNode.is(node)) {
5906
- (0, import_common_helpers10.invariant)(import_kysely12.IdentifierNode.is(node.alias), "Expected identifier as alias");
5907
- return {
5908
- alias: node.alias.name,
5909
- node: node.node
5910
- };
5911
- }
5912
- return {
5913
- alias: void 0,
5914
- node
5915
- };
5916
- }
5917
5934
  hasMappedColumns(modelName) {
5918
5935
  return [
5919
5936
  ...this.fieldToColumnMap.keys()
@@ -5924,8 +5941,8 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5924
5941
  return [];
5925
5942
  }
5926
5943
  return node.froms.map((from) => {
5927
- const { alias, node: innerNode } = this.stripAlias(from);
5928
- if (innerNode && import_kysely12.TableNode.is(innerNode)) {
5944
+ const { alias, node: innerNode } = stripAlias(from);
5945
+ if (innerNode && import_kysely13.TableNode.is(innerNode)) {
5929
5946
  return {
5930
5947
  model: innerNode.table.identifier.name,
5931
5948
  alias,
@@ -5941,11 +5958,11 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5941
5958
  return {
5942
5959
  ...super.transformFrom(node),
5943
5960
  froms: node.froms.map((from) => {
5944
- const { alias, node: innerNode } = this.stripAlias(from);
5961
+ const { alias, node: innerNode } = stripAlias(from);
5945
5962
  if (!innerNode) {
5946
5963
  return super.transformNode(from);
5947
5964
  }
5948
- if (import_kysely12.TableNode.is(innerNode)) {
5965
+ if (import_kysely13.TableNode.is(innerNode)) {
5949
5966
  if (this.hasMappedColumns(innerNode.table.identifier.name)) {
5950
5967
  const selectAll = this.createSelectAll(innerNode.table.identifier.name);
5951
5968
  return this.ensureAlias(selectAll, alias, innerNode.table.identifier.name);
@@ -5961,17 +5978,17 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5961
5978
  const tableName = this.mapTableName(model);
5962
5979
  return {
5963
5980
  kind: "SelectQueryNode",
5964
- from: import_kysely12.FromNode.create([
5965
- import_kysely12.TableNode.create(tableName)
5981
+ from: import_kysely13.FromNode.create([
5982
+ import_kysely13.TableNode.create(tableName)
5966
5983
  ]),
5967
5984
  selections: this.getModelFields(modelDef).map((fieldDef) => {
5968
5985
  const columnName = this.mapFieldName(model, fieldDef.name);
5969
- const columnRef = import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(columnName), import_kysely12.TableNode.create(tableName));
5986
+ const columnRef = import_kysely13.ReferenceNode.create(import_kysely13.ColumnNode.create(columnName), import_kysely13.TableNode.create(tableName));
5970
5987
  if (columnName !== fieldDef.name) {
5971
- const aliased = import_kysely12.AliasNode.create(columnRef, import_kysely12.IdentifierNode.create(fieldDef.name));
5972
- return import_kysely12.SelectionNode.create(aliased);
5988
+ const aliased = import_kysely13.AliasNode.create(columnRef, import_kysely13.IdentifierNode.create(fieldDef.name));
5989
+ return import_kysely13.SelectionNode.create(aliased);
5973
5990
  } else {
5974
- return import_kysely12.SelectionNode.create(columnRef);
5991
+ return import_kysely13.SelectionNode.create(columnRef);
5975
5992
  }
5976
5993
  })
5977
5994
  };
@@ -5982,22 +5999,22 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5982
5999
  processSelections(selections) {
5983
6000
  const result = [];
5984
6001
  selections.forEach((selection) => {
5985
- if (import_kysely12.SelectAllNode.is(selection.selection)) {
6002
+ if (import_kysely13.SelectAllNode.is(selection.selection)) {
5986
6003
  const processed = this.processSelectAll(selection.selection);
5987
6004
  if (Array.isArray(processed)) {
5988
- result.push(...processed.map((s) => import_kysely12.SelectionNode.create(s)));
6005
+ result.push(...processed.map((s) => import_kysely13.SelectionNode.create(s)));
5989
6006
  } else {
5990
- result.push(import_kysely12.SelectionNode.create(processed));
6007
+ result.push(import_kysely13.SelectionNode.create(processed));
5991
6008
  }
5992
6009
  } else {
5993
- result.push(import_kysely12.SelectionNode.create(this.processSelection(selection.selection)));
6010
+ result.push(import_kysely13.SelectionNode.create(this.processSelection(selection.selection)));
5994
6011
  }
5995
6012
  });
5996
6013
  return result;
5997
6014
  }
5998
6015
  processSelection(node) {
5999
6016
  let alias;
6000
- if (!import_kysely12.AliasNode.is(node)) {
6017
+ if (!import_kysely13.AliasNode.is(node)) {
6001
6018
  alias = this.extractFieldName(node);
6002
6019
  }
6003
6020
  const result = super.transformNode(node);
@@ -6005,21 +6022,21 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
6005
6022
  }
6006
6023
  processSelectAll(node) {
6007
6024
  const scope = this.modelScopes[this.modelScopes.length - 1];
6008
- (0, import_common_helpers10.invariant)(scope);
6025
+ (0, import_common_helpers11.invariant)(scope);
6009
6026
  if (!this.hasMappedColumns(scope.model)) {
6010
6027
  return super.transformSelectAll(node);
6011
6028
  }
6012
6029
  const modelDef = requireModel(this.schema, scope.model);
6013
6030
  return this.getModelFields(modelDef).map((fieldDef) => {
6014
6031
  const columnName = this.mapFieldName(scope.model, fieldDef.name);
6015
- const columnRef = import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(columnName));
6032
+ const columnRef = import_kysely13.ReferenceNode.create(import_kysely13.ColumnNode.create(columnName));
6016
6033
  return columnName !== fieldDef.name ? this.wrapAlias(columnRef, fieldDef.name) : columnRef;
6017
6034
  });
6018
6035
  }
6019
6036
  extractFieldName(node) {
6020
- if (import_kysely12.ReferenceNode.is(node) && import_kysely12.ColumnNode.is(node.column)) {
6037
+ if (import_kysely13.ReferenceNode.is(node) && import_kysely13.ColumnNode.is(node.column)) {
6021
6038
  return node.column.column.name;
6022
- } else if (import_kysely12.ColumnNode.is(node)) {
6039
+ } else if (import_kysely13.ColumnNode.is(node)) {
6023
6040
  return node.column.name;
6024
6041
  } else {
6025
6042
  return void 0;
@@ -6028,7 +6045,7 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
6028
6045
  };
6029
6046
 
6030
6047
  // src/client/executor/zenstack-query-executor.ts
6031
- var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13.DefaultQueryExecutor {
6048
+ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely14.DefaultQueryExecutor {
6032
6049
  static {
6033
6050
  __name(this, "ZenStackQueryExecutor");
6034
6051
  }
@@ -6036,9 +6053,10 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13
6036
6053
  driver;
6037
6054
  compiler;
6038
6055
  connectionProvider;
6056
+ suppressMutationHooks;
6039
6057
  nameMapper;
6040
- constructor(client, driver, compiler, adapter, connectionProvider, plugins = []) {
6041
- super(compiler, adapter, connectionProvider, plugins), this.client = client, this.driver = driver, this.compiler = compiler, this.connectionProvider = connectionProvider;
6058
+ constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false) {
6059
+ super(compiler, adapter, connectionProvider, plugins), this.client = client, this.driver = driver, this.compiler = compiler, this.connectionProvider = connectionProvider, this.suppressMutationHooks = suppressMutationHooks;
6042
6060
  this.nameMapper = new QueryNameMapper(client.$schema);
6043
6061
  }
6044
6062
  get kysely() {
@@ -6047,38 +6065,13 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13
6047
6065
  get options() {
6048
6066
  return this.client.$options;
6049
6067
  }
6050
- async executeQuery(compiledQuery, _queryId) {
6051
- let queryNode = compiledQuery.query;
6052
- let mutationInterceptionInfo;
6053
- if (this.isMutationNode(queryNode) && this.hasMutationHooks) {
6054
- mutationInterceptionInfo = await this.callMutationInterceptionFilters(queryNode);
6055
- }
6056
- const task = /* @__PURE__ */ __name(async () => {
6057
- if (this.isMutationNode(queryNode)) {
6058
- await this.callBeforeMutationHooks(queryNode, mutationInterceptionInfo);
6059
- }
6060
- const oldQueryNode = queryNode;
6061
- if ((import_kysely13.InsertQueryNode.is(queryNode) || import_kysely13.UpdateQueryNode.is(queryNode)) && mutationInterceptionInfo?.loadAfterMutationEntities) {
6062
- queryNode = {
6063
- ...queryNode,
6064
- returning: import_kysely13.ReturningNode.create([
6065
- import_kysely13.SelectionNode.createSelectAll()
6066
- ])
6067
- };
6068
- }
6069
- const queryParams = compiledQuery.$raw ? compiledQuery.parameters : void 0;
6070
- const result = await this.proceedQueryWithKyselyInterceptors(queryNode, queryParams);
6071
- if (this.isMutationNode(queryNode)) {
6072
- await this.callAfterMutationHooks(result.result, queryNode, mutationInterceptionInfo, result.connection);
6073
- }
6074
- if (oldQueryNode !== queryNode) {
6075
- }
6076
- return result.result;
6077
- }, "task");
6078
- return task();
6068
+ async executeQuery(compiledQuery, queryId) {
6069
+ const queryParams = compiledQuery.$raw ? compiledQuery.parameters : void 0;
6070
+ const result = await this.proceedQueryWithKyselyInterceptors(compiledQuery.query, queryParams, queryId.queryId);
6071
+ return result.result;
6079
6072
  }
6080
- proceedQueryWithKyselyInterceptors(queryNode, parameters) {
6081
- let proceed = /* @__PURE__ */ __name((q) => this.proceedQuery(q, parameters), "proceed");
6073
+ async proceedQueryWithKyselyInterceptors(queryNode, parameters, queryId) {
6074
+ let proceed = /* @__PURE__ */ __name((q) => this.proceedQuery(q, parameters, queryId), "proceed");
6082
6075
  const hooks = [];
6083
6076
  for (const plugin of this.client.$options.plugins ?? []) {
6084
6077
  if (plugin.onKyselyQuery) {
@@ -6088,10 +6081,8 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13
6088
6081
  for (const hook of hooks) {
6089
6082
  const _proceed = proceed;
6090
6083
  proceed = /* @__PURE__ */ __name(async (query) => {
6091
- let connection;
6092
6084
  const _p = /* @__PURE__ */ __name(async (q) => {
6093
6085
  const r = await _proceed(q);
6094
- connection = r.connection;
6095
6086
  return r.result;
6096
6087
  }, "_p");
6097
6088
  const hookResult = await hook({
@@ -6102,190 +6093,232 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13
6102
6093
  proceed: _p
6103
6094
  });
6104
6095
  return {
6105
- result: hookResult,
6106
- connection
6096
+ result: hookResult
6107
6097
  };
6108
6098
  }, "proceed");
6109
6099
  }
6110
- return proceed(queryNode);
6100
+ const result = await proceed(queryNode);
6101
+ return result;
6111
6102
  }
6112
- async proceedQuery(query, parameters) {
6113
- const finalQuery = this.nameMapper.transformNode(query);
6114
- let compiled = this.compileQuery(finalQuery);
6115
- if (parameters) {
6116
- compiled = {
6117
- ...compiled,
6118
- parameters
6119
- };
6120
- }
6103
+ getMutationInfo(queryNode) {
6104
+ const model = this.getMutationModel(queryNode);
6105
+ const { action, where } = (0, import_ts_pattern16.match)(queryNode).when(import_kysely14.InsertQueryNode.is, () => ({
6106
+ action: "create",
6107
+ where: void 0
6108
+ })).when(import_kysely14.UpdateQueryNode.is, (node) => ({
6109
+ action: "update",
6110
+ where: node.where
6111
+ })).when(import_kysely14.DeleteQueryNode.is, (node) => ({
6112
+ action: "delete",
6113
+ where: node.where
6114
+ })).exhaustive();
6115
+ return {
6116
+ model,
6117
+ action,
6118
+ where
6119
+ };
6120
+ }
6121
+ async proceedQuery(query, parameters, queryId) {
6122
+ let compiled;
6121
6123
  try {
6122
6124
  return await this.provideConnection(async (connection) => {
6123
- const result = await connection.executeQuery(compiled);
6124
- return {
6125
- result,
6126
- connection
6127
- };
6125
+ if (this.suppressMutationHooks || !this.isMutationNode(query) || !this.hasEntityMutationPlugins) {
6126
+ const finalQuery2 = this.nameMapper.transformNode(query);
6127
+ compiled = this.compileQuery(finalQuery2);
6128
+ if (parameters) {
6129
+ compiled = {
6130
+ ...compiled,
6131
+ parameters
6132
+ };
6133
+ }
6134
+ const result = await connection.executeQuery(compiled);
6135
+ return {
6136
+ result
6137
+ };
6138
+ }
6139
+ if ((import_kysely14.InsertQueryNode.is(query) || import_kysely14.UpdateQueryNode.is(query)) && this.hasEntityMutationPluginsWithAfterMutationHooks) {
6140
+ query = {
6141
+ ...query,
6142
+ returning: import_kysely14.ReturningNode.create([
6143
+ import_kysely14.SelectionNode.createSelectAll()
6144
+ ])
6145
+ };
6146
+ }
6147
+ const finalQuery = this.nameMapper.transformNode(query);
6148
+ compiled = this.compileQuery(finalQuery);
6149
+ if (parameters) {
6150
+ compiled = {
6151
+ ...compiled,
6152
+ parameters
6153
+ };
6154
+ }
6155
+ const currentlyInTx = this.driver.isTransactionConnection(connection);
6156
+ const connectionClient = this.createClientForConnection(connection, currentlyInTx);
6157
+ const mutationInfo = this.getMutationInfo(finalQuery);
6158
+ let beforeMutationEntities;
6159
+ const loadBeforeMutationEntities = /* @__PURE__ */ __name(async () => {
6160
+ if (beforeMutationEntities === void 0 && (import_kysely14.UpdateQueryNode.is(query) || import_kysely14.DeleteQueryNode.is(query))) {
6161
+ beforeMutationEntities = await this.loadEntities(mutationInfo.model, mutationInfo.where, connection);
6162
+ }
6163
+ return beforeMutationEntities;
6164
+ }, "loadBeforeMutationEntities");
6165
+ await this.callBeforeMutationHooks(finalQuery, mutationInfo, loadBeforeMutationEntities, connectionClient, queryId);
6166
+ const shouldCreateTx = this.hasPluginRequestingAfterMutationWithinTransaction && !this.driver.isTransactionConnection(connection);
6167
+ if (!shouldCreateTx) {
6168
+ const result = await connection.executeQuery(compiled);
6169
+ if (!this.driver.isTransactionConnection(connection)) {
6170
+ await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "all", queryId);
6171
+ } else {
6172
+ await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "inTx", queryId);
6173
+ this.driver.registerTransactionCommitCallback(connection, () => this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "outTx", queryId));
6174
+ }
6175
+ return {
6176
+ result
6177
+ };
6178
+ } else {
6179
+ await this.driver.beginTransaction(connection, {
6180
+ isolationLevel: TransactionIsolationLevel.ReadCommitted
6181
+ });
6182
+ try {
6183
+ const result = await connection.executeQuery(compiled);
6184
+ await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "inTx", queryId);
6185
+ await this.driver.commitTransaction(connection);
6186
+ await this.callAfterMutationHooks(result, finalQuery, mutationInfo, connectionClient, "outTx", queryId);
6187
+ return {
6188
+ result
6189
+ };
6190
+ } catch (err) {
6191
+ await this.driver.rollbackTransaction(connection);
6192
+ throw err;
6193
+ }
6194
+ }
6128
6195
  });
6129
6196
  } catch (err) {
6130
- const message = `Failed to execute query: ${err}, sql: ${compiled.sql}`;
6197
+ const message = `Failed to execute query: ${err}, sql: ${compiled?.sql}`;
6131
6198
  throw new QueryError(message, err);
6132
6199
  }
6133
6200
  }
6201
+ createClientForConnection(connection, inTx) {
6202
+ const innerExecutor = this.withConnectionProvider(new import_kysely14.SingleConnectionProvider(connection));
6203
+ innerExecutor.suppressMutationHooks = true;
6204
+ const innerClient = this.client.withExecutor(innerExecutor);
6205
+ if (inTx) {
6206
+ innerClient.forceTransaction();
6207
+ }
6208
+ return innerClient;
6209
+ }
6210
+ get hasEntityMutationPlugins() {
6211
+ return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6212
+ }
6213
+ get hasEntityMutationPluginsWithAfterMutationHooks() {
6214
+ return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
6215
+ }
6216
+ get hasPluginRequestingAfterMutationWithinTransaction() {
6217
+ return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.runAfterMutationWithinTransaction);
6218
+ }
6134
6219
  isMutationNode(queryNode) {
6135
- return import_kysely13.InsertQueryNode.is(queryNode) || import_kysely13.UpdateQueryNode.is(queryNode) || import_kysely13.DeleteQueryNode.is(queryNode);
6220
+ return import_kysely14.InsertQueryNode.is(queryNode) || import_kysely14.UpdateQueryNode.is(queryNode) || import_kysely14.DeleteQueryNode.is(queryNode);
6136
6221
  }
6137
6222
  withPlugin(plugin) {
6138
6223
  return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6139
6224
  ...this.plugins,
6140
6225
  plugin
6141
- ]);
6226
+ ], this.suppressMutationHooks);
6142
6227
  }
6143
6228
  withPlugins(plugins) {
6144
6229
  return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6145
6230
  ...this.plugins,
6146
6231
  ...plugins
6147
- ]);
6232
+ ], this.suppressMutationHooks);
6148
6233
  }
6149
6234
  withPluginAtFront(plugin) {
6150
6235
  return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [
6151
6236
  plugin,
6152
6237
  ...this.plugins
6153
- ]);
6238
+ ], this.suppressMutationHooks);
6154
6239
  }
6155
6240
  withoutPlugins() {
6156
- return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, []);
6241
+ return new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks);
6157
6242
  }
6158
6243
  withConnectionProvider(connectionProvider) {
6159
- const newExecutor = new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider);
6244
+ const newExecutor = new _ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks);
6160
6245
  newExecutor.client = this.client.withExecutor(newExecutor);
6161
6246
  return newExecutor;
6162
6247
  }
6163
- get hasMutationHooks() {
6164
- return this.client.$options.plugins?.some((plugin) => !!plugin.onEntityMutation);
6165
- }
6166
6248
  getMutationModel(queryNode) {
6167
- return (0, import_ts_pattern16.match)(queryNode).when(import_kysely13.InsertQueryNode.is, (node) => node.into.table.identifier.name).when(import_kysely13.UpdateQueryNode.is, (node) => node.table.table.identifier.name).when(import_kysely13.DeleteQueryNode.is, (node) => {
6168
- if (node.from.froms.length !== 1) {
6169
- throw new InternalError(`Delete query must have exactly one from table`);
6170
- }
6171
- return node.from.froms[0].table.identifier.name;
6249
+ return (0, import_ts_pattern16.match)(queryNode).when(import_kysely14.InsertQueryNode.is, (node) => {
6250
+ (0, import_common_helpers12.invariant)(node.into, "InsertQueryNode must have an into clause");
6251
+ return node.into.table.identifier.name;
6252
+ }).when(import_kysely14.UpdateQueryNode.is, (node) => {
6253
+ (0, import_common_helpers12.invariant)(node.table, "UpdateQueryNode must have a table");
6254
+ const { node: tableNode } = stripAlias(node.table);
6255
+ (0, import_common_helpers12.invariant)(import_kysely14.TableNode.is(tableNode), "UpdateQueryNode must use a TableNode");
6256
+ return tableNode.table.identifier.name;
6257
+ }).when(import_kysely14.DeleteQueryNode.is, (node) => {
6258
+ (0, import_common_helpers12.invariant)(node.from.froms.length === 1, "Delete query must have exactly one from table");
6259
+ const { node: tableNode } = stripAlias(node.from.froms[0]);
6260
+ (0, import_common_helpers12.invariant)(import_kysely14.TableNode.is(tableNode), "DeleteQueryNode must use a TableNode");
6261
+ return tableNode.table.identifier.name;
6172
6262
  }).otherwise((node) => {
6173
6263
  throw new InternalError(`Invalid query node: ${node}`);
6174
6264
  });
6175
6265
  }
6176
- async callMutationInterceptionFilters(queryNode) {
6177
- const plugins = this.client.$options.plugins;
6178
- if (plugins) {
6179
- const mutationModel = this.getMutationModel(queryNode);
6180
- const result = {
6181
- intercept: false
6182
- };
6183
- const { action, where } = (0, import_ts_pattern16.match)(queryNode).when(import_kysely13.InsertQueryNode.is, () => ({
6184
- action: "create",
6185
- where: void 0
6186
- })).when(import_kysely13.UpdateQueryNode.is, (node) => ({
6187
- action: "update",
6188
- where: node.where
6189
- })).when(import_kysely13.DeleteQueryNode.is, (node) => ({
6190
- action: "delete",
6191
- where: node.where
6192
- })).exhaustive();
6193
- for (const plugin of plugins) {
6194
- const onEntityMutation = plugin.onEntityMutation;
6195
- if (!onEntityMutation) {
6196
- continue;
6197
- }
6198
- if (!onEntityMutation.mutationInterceptionFilter) {
6199
- result.intercept = true;
6200
- } else {
6201
- const filterResult = await onEntityMutation.mutationInterceptionFilter({
6202
- model: mutationModel,
6203
- action,
6204
- queryNode
6205
- });
6206
- result.intercept ||= filterResult.intercept;
6207
- result.loadBeforeMutationEntities ||= filterResult.loadBeforeMutationEntities;
6208
- result.loadAfterMutationEntities ||= filterResult.loadAfterMutationEntities;
6209
- }
6210
- }
6211
- let beforeMutationEntities;
6212
- if (result.loadBeforeMutationEntities && (import_kysely13.UpdateQueryNode.is(queryNode) || import_kysely13.DeleteQueryNode.is(queryNode))) {
6213
- beforeMutationEntities = await this.loadEntities(mutationModel, where);
6214
- }
6215
- return {
6216
- ...result,
6217
- mutationModel,
6218
- action,
6219
- where,
6220
- beforeMutationEntities
6221
- };
6222
- } else {
6223
- return void 0;
6224
- }
6225
- }
6226
- async callBeforeMutationHooks(queryNode, mutationInterceptionInfo) {
6227
- if (!mutationInterceptionInfo?.intercept) {
6228
- return;
6229
- }
6266
+ async callBeforeMutationHooks(queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId) {
6230
6267
  if (this.options.plugins) {
6231
- const mutationModel = this.getMutationModel(queryNode);
6232
6268
  for (const plugin of this.options.plugins) {
6233
6269
  const onEntityMutation = plugin.onEntityMutation;
6234
- if (onEntityMutation?.beforeEntityMutation) {
6235
- await onEntityMutation.beforeEntityMutation({
6236
- model: mutationModel,
6237
- action: mutationInterceptionInfo.action,
6238
- queryNode,
6239
- entities: mutationInterceptionInfo.beforeMutationEntities
6240
- });
6270
+ if (!onEntityMutation?.beforeEntityMutation) {
6271
+ continue;
6241
6272
  }
6273
+ await onEntityMutation.beforeEntityMutation({
6274
+ model: mutationInfo.model,
6275
+ action: mutationInfo.action,
6276
+ queryNode,
6277
+ loadBeforeMutationEntities,
6278
+ client,
6279
+ queryId
6280
+ });
6242
6281
  }
6243
6282
  }
6244
6283
  }
6245
- async callAfterMutationHooks(queryResult, queryNode, mutationInterceptionInfo, connection) {
6246
- if (!mutationInterceptionInfo?.intercept) {
6247
- return;
6248
- }
6284
+ async callAfterMutationHooks(queryResult, queryNode, mutationInfo, client, filterFor, queryId) {
6249
6285
  const hooks = [];
6250
6286
  for (const plugin of this.options.plugins ?? []) {
6251
6287
  const onEntityMutation = plugin.onEntityMutation;
6252
- if (onEntityMutation?.afterEntityMutation) {
6253
- hooks.push(onEntityMutation.afterEntityMutation.bind(plugin));
6288
+ if (!onEntityMutation?.afterEntityMutation) {
6289
+ continue;
6254
6290
  }
6291
+ if (filterFor === "inTx" && !onEntityMutation.runAfterMutationWithinTransaction) {
6292
+ continue;
6293
+ }
6294
+ if (filterFor === "outTx" && onEntityMutation.runAfterMutationWithinTransaction) {
6295
+ continue;
6296
+ }
6297
+ hooks.push(onEntityMutation.afterEntityMutation.bind(plugin));
6255
6298
  }
6256
6299
  if (hooks.length === 0) {
6257
6300
  return;
6258
6301
  }
6259
6302
  const mutationModel = this.getMutationModel(queryNode);
6260
- const inTransaction = this.driver.isTransactionConnection(connection);
6261
- for (const hook of hooks) {
6262
- let afterMutationEntities = void 0;
6263
- if (mutationInterceptionInfo.loadAfterMutationEntities) {
6264
- if (import_kysely13.InsertQueryNode.is(queryNode) || import_kysely13.UpdateQueryNode.is(queryNode)) {
6265
- afterMutationEntities = queryResult.rows;
6266
- }
6267
- }
6268
- const action = /* @__PURE__ */ __name(async () => {
6269
- try {
6270
- await hook({
6271
- model: mutationModel,
6272
- action: mutationInterceptionInfo.action,
6273
- queryNode,
6274
- beforeMutationEntities: mutationInterceptionInfo.beforeMutationEntities,
6275
- afterMutationEntities
6276
- });
6277
- } catch (err) {
6278
- console.error(`Error in afterEntityMutation hook for model "${mutationModel}": ${err}`);
6279
- }
6280
- }, "action");
6281
- if (inTransaction) {
6282
- this.driver.registerTransactionCommitCallback(connection, action);
6303
+ const loadAfterMutationEntities = /* @__PURE__ */ __name(async () => {
6304
+ if (mutationInfo.action === "delete") {
6305
+ return void 0;
6283
6306
  } else {
6284
- await action();
6307
+ return queryResult.rows;
6285
6308
  }
6309
+ }, "loadAfterMutationEntities");
6310
+ for (const hook of hooks) {
6311
+ await hook({
6312
+ model: mutationModel,
6313
+ action: mutationInfo.action,
6314
+ queryNode,
6315
+ loadAfterMutationEntities,
6316
+ client,
6317
+ queryId
6318
+ });
6286
6319
  }
6287
6320
  }
6288
- async loadEntities(model, where) {
6321
+ async loadEntities(model, where, connection) {
6289
6322
  const selectQuery = this.kysely.selectFrom(model).selectAll();
6290
6323
  let selectQueryNode = selectQuery.toOperationNode();
6291
6324
  selectQueryNode = {
@@ -6293,16 +6326,14 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends import_kysely13
6293
6326
  where: this.andNodes(selectQueryNode.where, where)
6294
6327
  };
6295
6328
  const compiled = this.compileQuery(selectQueryNode);
6296
- const result = await this.executeQuery(compiled, {
6297
- queryId: `zenstack-${(0, import_nanoid2.nanoid)()}`
6298
- });
6329
+ const result = await connection.executeQuery(compiled);
6299
6330
  return result.rows;
6300
6331
  }
6301
6332
  andNodes(condition1, condition2) {
6302
6333
  if (condition1 && condition2) {
6303
- return import_kysely13.WhereNode.create(import_kysely13.AndNode.create(condition1, condition2));
6334
+ return import_kysely14.WhereNode.create(import_kysely14.AndNode.create(condition1, condition2));
6304
6335
  } else if (condition1) {
6305
- return import_kysely13.WhereNode.create(condition1);
6336
+ return import_kysely14.WhereNode.create(condition1);
6306
6337
  } else {
6307
6338
  return condition2;
6308
6339
  }
@@ -6324,8 +6355,8 @@ __export(functions_exports, {
6324
6355
  search: () => search,
6325
6356
  startsWith: () => startsWith
6326
6357
  });
6327
- var import_common_helpers11 = require("@zenstackhq/common-helpers");
6328
- var import_kysely14 = require("kysely");
6358
+ var import_common_helpers13 = require("@zenstackhq/common-helpers");
6359
+ var import_kysely15 = require("kysely");
6329
6360
  var import_ts_pattern17 = require("ts-pattern");
6330
6361
  var contains = /* @__PURE__ */ __name((eb, args) => {
6331
6362
  const [field, search2, caseInsensitive = false] = args;
@@ -6336,9 +6367,9 @@ var contains = /* @__PURE__ */ __name((eb, args) => {
6336
6367
  throw new Error('"search" parameter is required');
6337
6368
  }
6338
6369
  const searchExpr = eb.fn("CONCAT", [
6339
- import_kysely14.sql.lit("%"),
6370
+ import_kysely15.sql.lit("%"),
6340
6371
  search2,
6341
- import_kysely14.sql.lit("%")
6372
+ import_kysely15.sql.lit("%")
6342
6373
  ]);
6343
6374
  return eb(field, caseInsensitive ? "ilike" : "like", searchExpr);
6344
6375
  }, "contains");
@@ -6355,7 +6386,7 @@ var startsWith = /* @__PURE__ */ __name((eb, args) => {
6355
6386
  }
6356
6387
  return eb(field, "like", eb.fn("CONCAT", [
6357
6388
  search2,
6358
- import_kysely14.sql.lit("%")
6389
+ import_kysely15.sql.lit("%")
6359
6390
  ]));
6360
6391
  }, "startsWith");
6361
6392
  var endsWith = /* @__PURE__ */ __name((eb, args) => {
@@ -6367,7 +6398,7 @@ var endsWith = /* @__PURE__ */ __name((eb, args) => {
6367
6398
  throw new Error('"search" parameter is required');
6368
6399
  }
6369
6400
  return eb(field, "like", eb.fn("CONCAT", [
6370
- import_kysely14.sql.lit("%"),
6401
+ import_kysely15.sql.lit("%"),
6371
6402
  search2
6372
6403
  ]));
6373
6404
  }, "endsWith");
@@ -6408,10 +6439,10 @@ var isEmpty = /* @__PURE__ */ __name((eb, args, { dialect }) => {
6408
6439
  if (!field) {
6409
6440
  throw new Error('"field" parameter is required');
6410
6441
  }
6411
- return eb(dialect.buildArrayLength(eb, field), "=", import_kysely14.sql.lit(0));
6442
+ return eb(dialect.buildArrayLength(eb, field), "=", import_kysely15.sql.lit(0));
6412
6443
  }, "isEmpty");
6413
6444
  var now = /* @__PURE__ */ __name((eb, _args, { dialect }) => {
6414
- return (0, import_ts_pattern17.match)(dialect.provider).with("postgresql", () => eb.fn("now")).with("sqlite", () => import_kysely14.sql.raw("CURRENT_TIMESTAMP")).exhaustive();
6445
+ return (0, import_ts_pattern17.match)(dialect.provider).with("postgresql", () => eb.fn("now")).with("sqlite", () => import_kysely15.sql.raw("CURRENT_TIMESTAMP")).exhaustive();
6415
6446
  }, "now");
6416
6447
  var currentModel = /* @__PURE__ */ __name((_eb, args, { model }) => {
6417
6448
  let result = model;
@@ -6419,7 +6450,7 @@ var currentModel = /* @__PURE__ */ __name((_eb, args, { model }) => {
6419
6450
  if (casing) {
6420
6451
  result = processCasing(casing, result, model);
6421
6452
  }
6422
- return import_kysely14.sql.lit(result);
6453
+ return import_kysely15.sql.lit(result);
6423
6454
  }, "currentModel");
6424
6455
  var currentOperation = /* @__PURE__ */ __name((_eb, args, { operation }) => {
6425
6456
  let result = operation;
@@ -6427,12 +6458,12 @@ var currentOperation = /* @__PURE__ */ __name((_eb, args, { operation }) => {
6427
6458
  if (casing) {
6428
6459
  result = processCasing(casing, result, operation);
6429
6460
  }
6430
- return import_kysely14.sql.lit(result);
6461
+ return import_kysely15.sql.lit(result);
6431
6462
  }, "currentOperation");
6432
6463
  function processCasing(casing, result, model) {
6433
6464
  const opNode = casing.toOperationNode();
6434
- (0, import_common_helpers11.invariant)(import_kysely14.ValueNode.is(opNode) && typeof opNode.value === "string", '"casting" parameter must be a string value');
6435
- result = (0, import_ts_pattern17.match)(opNode.value).with("original", () => model).with("upper", () => result.toUpperCase()).with("lower", () => result.toLowerCase()).with("capitalize", () => (0, import_common_helpers11.upperCaseFirst)(result)).with("uncapitalize", () => (0, import_common_helpers11.lowerCaseFirst)(result)).otherwise(() => {
6465
+ (0, import_common_helpers13.invariant)(import_kysely15.ValueNode.is(opNode) && typeof opNode.value === "string", '"casting" parameter must be a string value');
6466
+ result = (0, import_ts_pattern17.match)(opNode.value).with("original", () => model).with("upper", () => result.toUpperCase()).with("lower", () => result.toLowerCase()).with("capitalize", () => (0, import_common_helpers13.upperCaseFirst)(result)).with("uncapitalize", () => (0, import_common_helpers13.lowerCaseFirst)(result)).otherwise(() => {
6436
6467
  throw new Error(`Invalid casing value: ${opNode.value}. Must be "original", "upper", "lower", "capitalize", or "uncapitalize".`);
6437
6468
  });
6438
6469
  return result;
@@ -6440,8 +6471,8 @@ function processCasing(casing, result, model) {
6440
6471
  __name(processCasing, "processCasing");
6441
6472
 
6442
6473
  // src/client/helpers/schema-db-pusher.ts
6443
- var import_common_helpers12 = require("@zenstackhq/common-helpers");
6444
- var import_kysely15 = require("kysely");
6474
+ var import_common_helpers14 = require("@zenstackhq/common-helpers");
6475
+ var import_kysely16 = require("kysely");
6445
6476
  var import_toposort = __toESM(require("toposort"), 1);
6446
6477
  var import_ts_pattern18 = require("ts-pattern");
6447
6478
  var SchemaDbPusher = class {
@@ -6536,7 +6567,7 @@ var SchemaDbPusher = class {
6536
6567
  }
6537
6568
  addUniqueConstraint(table, modelDef) {
6538
6569
  for (const [key, value] of Object.entries(modelDef.uniqueFields)) {
6539
- (0, import_common_helpers12.invariant)(typeof value === "object", "expecting an object");
6570
+ (0, import_common_helpers14.invariant)(typeof value === "object", "expecting an object");
6540
6571
  if ("type" in value) {
6541
6572
  const fieldDef = modelDef.fields[key];
6542
6573
  if (fieldDef.unique) {
@@ -6559,7 +6590,7 @@ var SchemaDbPusher = class {
6559
6590
  if (fieldDef.default !== void 0) {
6560
6591
  if (typeof fieldDef.default === "object" && "kind" in fieldDef.default) {
6561
6592
  if (ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "now") {
6562
- col = col.defaultTo(import_kysely15.sql`CURRENT_TIMESTAMP`);
6593
+ col = col.defaultTo(import_kysely16.sql`CURRENT_TIMESTAMP`);
6563
6594
  }
6564
6595
  } else {
6565
6596
  col = col.defaultTo(fieldDef.default);
@@ -6579,7 +6610,7 @@ var SchemaDbPusher = class {
6579
6610
  }
6580
6611
  mapFieldType(fieldDef) {
6581
6612
  if (this.schema.enums?.[fieldDef.type]) {
6582
- return this.schema.provider.type === "postgresql" ? import_kysely15.sql.ref(fieldDef.type) : "text";
6613
+ return this.schema.provider.type === "postgresql" ? import_kysely16.sql.ref(fieldDef.type) : "text";
6583
6614
  }
6584
6615
  if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") {
6585
6616
  return "serial";
@@ -6592,7 +6623,7 @@ var SchemaDbPusher = class {
6592
6623
  throw new Error(`Unsupported field type: ${type}`);
6593
6624
  });
6594
6625
  if (fieldDef.array) {
6595
- return import_kysely15.sql.raw(`${result}[]`);
6626
+ return import_kysely16.sql.raw(`${result}[]`);
6596
6627
  } else {
6597
6628
  return result;
6598
6629
  }
@@ -6604,7 +6635,7 @@ var SchemaDbPusher = class {
6604
6635
  return fieldDef.default && ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "autoincrement";
6605
6636
  }
6606
6637
  addForeignKeyConstraint(table, model, fieldName, fieldDef) {
6607
- (0, import_common_helpers12.invariant)(fieldDef.relation, "field must be a relation");
6638
+ (0, import_common_helpers14.invariant)(fieldDef.relation, "field must be a relation");
6608
6639
  if (!fieldDef.relation.fields || !fieldDef.relation.references) {
6609
6640
  return table;
6610
6641
  }
@@ -6659,7 +6690,7 @@ function valueToPromise(thing) {
6659
6690
  __name(valueToPromise, "valueToPromise");
6660
6691
 
6661
6692
  // src/client/result-processor.ts
6662
- var import_common_helpers13 = require("@zenstackhq/common-helpers");
6693
+ var import_common_helpers15 = require("@zenstackhq/common-helpers");
6663
6694
  var import_decimal2 = __toESM(require("decimal.js"), 1);
6664
6695
  var import_ts_pattern19 = require("ts-pattern");
6665
6696
  var ResultProcessor = class {
@@ -6759,14 +6790,14 @@ var ResultProcessor = class {
6759
6790
  if (value instanceof import_decimal2.default) {
6760
6791
  return value;
6761
6792
  }
6762
- (0, import_common_helpers13.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal2.default, `Expected string, number or Decimal, got ${typeof value}`);
6793
+ (0, import_common_helpers15.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal2.default, `Expected string, number or Decimal, got ${typeof value}`);
6763
6794
  return new import_decimal2.default(value);
6764
6795
  }
6765
6796
  transformBigInt(value) {
6766
6797
  if (typeof value === "bigint") {
6767
6798
  return value;
6768
6799
  }
6769
- (0, import_common_helpers13.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
6800
+ (0, import_common_helpers15.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
6770
6801
  return BigInt(value);
6771
6802
  }
6772
6803
  transformBoolean(value) {
@@ -6810,7 +6841,7 @@ var ResultProcessor = class {
6810
6841
  }
6811
6842
  transformJson(value) {
6812
6843
  return (0, import_ts_pattern19.match)(this.schema.provider.type).with("sqlite", () => {
6813
- (0, import_common_helpers13.invariant)(typeof value === "string", "Expected string, got " + typeof value);
6844
+ (0, import_common_helpers15.invariant)(typeof value === "string", "Expected string, got " + typeof value);
6814
6845
  return JSON.parse(value);
6815
6846
  }).otherwise(() => value);
6816
6847
  }
@@ -6844,15 +6875,15 @@ var ClientImpl = class _ClientImpl {
6844
6875
  if (baseClient) {
6845
6876
  this.kyselyProps = {
6846
6877
  ...baseClient.kyselyProps,
6847
- executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new import_kysely16.DefaultConnectionProvider(baseClient.kyselyProps.driver))
6878
+ executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new import_kysely17.DefaultConnectionProvider(baseClient.kyselyProps.driver))
6848
6879
  };
6849
6880
  this.kyselyRaw = baseClient.kyselyRaw;
6850
6881
  this.auth = baseClient.auth;
6851
6882
  } else {
6852
- const driver = new ZenStackDriver(options.dialect.createDriver(), new import_kysely16.Log(this.$options.log ?? []));
6883
+ const driver = new ZenStackDriver(options.dialect.createDriver(), new import_kysely17.Log(this.$options.log ?? []));
6853
6884
  const compiler = options.dialect.createQueryCompiler();
6854
6885
  const adapter = options.dialect.createAdapter();
6855
- const connectionProvider = new import_kysely16.DefaultConnectionProvider(driver);
6886
+ const connectionProvider = new import_kysely17.DefaultConnectionProvider(driver);
6856
6887
  this.kyselyProps = {
6857
6888
  config: {
6858
6889
  dialect: options.dialect,
@@ -6862,12 +6893,12 @@ var ClientImpl = class _ClientImpl {
6862
6893
  driver,
6863
6894
  executor: executor ?? new ZenStackQueryExecutor(this, driver, compiler, adapter, connectionProvider)
6864
6895
  };
6865
- this.kyselyRaw = new import_kysely16.Kysely({
6896
+ this.kyselyRaw = new import_kysely17.Kysely({
6866
6897
  ...this.kyselyProps,
6867
- executor: new import_kysely16.DefaultQueryExecutor(compiler, adapter, connectionProvider, [])
6898
+ executor: new import_kysely17.DefaultQueryExecutor(compiler, adapter, connectionProvider, [])
6868
6899
  });
6869
6900
  }
6870
- this.kysely = new import_kysely16.Kysely(this.kyselyProps);
6901
+ this.kysely = new import_kysely17.Kysely(this.kyselyProps);
6871
6902
  return createClientProxy(this);
6872
6903
  }
6873
6904
  get $qb() {
@@ -6887,13 +6918,18 @@ var ClientImpl = class _ClientImpl {
6887
6918
  }
6888
6919
  // implementation
6889
6920
  async $transaction(input, options) {
6890
- (0, import_common_helpers14.invariant)(typeof input === "function" || Array.isArray(input) && input.every((p) => p.then && p.cb), "Invalid transaction input, expected a function or an array of ZenStackPromise");
6921
+ (0, import_common_helpers16.invariant)(typeof input === "function" || Array.isArray(input) && input.every((p) => p.then && p.cb), "Invalid transaction input, expected a function or an array of ZenStackPromise");
6891
6922
  if (typeof input === "function") {
6892
6923
  return this.interactiveTransaction(input, options);
6893
6924
  } else {
6894
6925
  return this.sequentialTransaction(input, options);
6895
6926
  }
6896
6927
  }
6928
+ forceTransaction() {
6929
+ if (!this.kysely.isTransaction) {
6930
+ this.kysely = new import_kysely17.Transaction(this.kyselyProps);
6931
+ }
6932
+ }
6897
6933
  async interactiveTransaction(callback, options) {
6898
6934
  if (this.kysely.isTransaction) {
6899
6935
  return callback(this);
@@ -6998,7 +7034,7 @@ var ClientImpl = class _ClientImpl {
6998
7034
  }
6999
7035
  $executeRaw(query, ...values) {
7000
7036
  return createZenStackPromise(async () => {
7001
- const result = await (0, import_kysely16.sql)(query, ...values).execute(this.kysely);
7037
+ const result = await (0, import_kysely17.sql)(query, ...values).execute(this.kysely);
7002
7038
  return Number(result.numAffectedRows ?? 0);
7003
7039
  });
7004
7040
  }
@@ -7011,7 +7047,7 @@ var ClientImpl = class _ClientImpl {
7011
7047
  }
7012
7048
  $queryRaw(query, ...values) {
7013
7049
  return createZenStackPromise(async () => {
7014
- const result = await (0, import_kysely16.sql)(query, ...values).execute(this.kysely);
7050
+ const result = await (0, import_kysely17.sql)(query, ...values).execute(this.kysely);
7015
7051
  return result.rows;
7016
7052
  });
7017
7053
  }
@@ -7023,7 +7059,7 @@ var ClientImpl = class _ClientImpl {
7023
7059
  });
7024
7060
  }
7025
7061
  createRawCompiledQuery(query, values) {
7026
- const q = import_kysely16.CompiledQuery.raw(query, values);
7062
+ const q = import_kysely17.CompiledQuery.raw(query, values);
7027
7063
  return {
7028
7064
  ...q,
7029
7065
  $raw: true
@@ -7150,7 +7186,7 @@ function definePlugin(plugin) {
7150
7186
  __name(definePlugin, "definePlugin");
7151
7187
 
7152
7188
  // src/client/index.ts
7153
- var import_kysely17 = require("kysely");
7189
+ var import_kysely18 = require("kysely");
7154
7190
  // Annotate the CommonJS export names for ESM import in node:
7155
7191
  0 && (module.exports = {
7156
7192
  InputValidationError,