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

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.
@@ -96,7 +96,7 @@ type BatchResult = {
96
96
  count: number;
97
97
  };
98
98
  type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
99
- [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>> : PrimitiveFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
99
+ [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations> : PrimitiveFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
100
100
  } & {
101
101
  $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
102
102
  } & {
@@ -104,12 +104,16 @@ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Scala
104
104
  OR?: WhereInput<Schema, Model, ScalarOnly>[];
105
105
  NOT?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
106
106
  };
107
- type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | {
107
+ type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | ({
108
108
  equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
109
109
  in?: (keyof GetEnum<Schema, T>)[];
110
110
  notIn?: (keyof GetEnum<Schema, T>)[];
111
- not?: EnumFilter<Schema, T, Nullable>;
112
- };
111
+ not?: EnumFilter<Schema, T, Nullable, WithAggregations>;
112
+ } & (WithAggregations extends true ? {
113
+ _count?: NumberFilter<Schema, 'Int', false, false>;
114
+ _min?: EnumFilter<Schema, T, false, false>;
115
+ _max?: EnumFilter<Schema, T, false, false>;
116
+ } : {}));
113
117
  type ArrayFilter<Schema extends SchemaDef, T extends string> = {
114
118
  equals?: MapScalarType<Schema, T>[] | null;
115
119
  has?: MapScalarType<Schema, T> | null;
@@ -96,7 +96,7 @@ type BatchResult = {
96
96
  count: number;
97
97
  };
98
98
  type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = {
99
- [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>> : PrimitiveFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
99
+ [Key in GetModelFields<Schema, Model> as ScalarOnly extends true ? Key extends RelationFields<Schema, Model> ? never : Key : Key]?: Key extends RelationFields<Schema, Model> ? RelationFilter<Schema, Model, Key> : FieldIsArray<Schema, Model, Key> extends true ? ArrayFilter<Schema, GetModelFieldType<Schema, Model, Key>> : GetModelFieldType<Schema, Model, Key> extends GetEnums<Schema> ? EnumFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations> : PrimitiveFilter<Schema, GetModelFieldType<Schema, Model, Key>, ModelFieldIsOptional<Schema, Model, Key>, WithAggregations>;
100
100
  } & {
101
101
  $expr?: (eb: ExpressionBuilder<ToKyselySchema<Schema>, Model>) => OperandExpression<SqlBool>;
102
102
  } & {
@@ -104,12 +104,16 @@ type WhereInput<Schema extends SchemaDef, Model extends GetModels<Schema>, Scala
104
104
  OR?: WhereInput<Schema, Model, ScalarOnly>[];
105
105
  NOT?: OrArray<WhereInput<Schema, Model, ScalarOnly>>;
106
106
  };
107
- type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | {
107
+ type EnumFilter<Schema extends SchemaDef, T extends GetEnums<Schema>, Nullable extends boolean, WithAggregations extends boolean> = NullableIf<keyof GetEnum<Schema, T>, Nullable> | ({
108
108
  equals?: NullableIf<keyof GetEnum<Schema, T>, Nullable>;
109
109
  in?: (keyof GetEnum<Schema, T>)[];
110
110
  notIn?: (keyof GetEnum<Schema, T>)[];
111
- not?: EnumFilter<Schema, T, Nullable>;
112
- };
111
+ not?: EnumFilter<Schema, T, Nullable, WithAggregations>;
112
+ } & (WithAggregations extends true ? {
113
+ _count?: NumberFilter<Schema, 'Int', false, false>;
114
+ _min?: EnumFilter<Schema, T, false, false>;
115
+ _max?: EnumFilter<Schema, T, false, false>;
116
+ } : {}));
113
117
  type ArrayFilter<Schema extends SchemaDef, T extends string> = {
114
118
  equals?: MapScalarType<Schema, T>[] | null;
115
119
  has?: MapScalarType<Schema, T> | null;
package/dist/index.cjs CHANGED
@@ -42,7 +42,7 @@ __export(src_exports, {
42
42
  module.exports = __toCommonJS(src_exports);
43
43
 
44
44
  // src/client/client-impl.ts
45
- var import_common_helpers13 = require("@zenstackhq/common-helpers");
45
+ var import_common_helpers14 = require("@zenstackhq/common-helpers");
46
46
  var import_kysely16 = require("kysely");
47
47
 
48
48
  // src/client/crud/operations/aggregate.ts
@@ -5386,10 +5386,11 @@ var InputValidator = class {
5386
5386
  makeGroupBySchema(model) {
5387
5387
  const modelDef = requireModel(this.schema, model);
5388
5388
  const nonRelationFields = Object.keys(modelDef.fields).filter((field) => !modelDef.fields[field]?.relation);
5389
+ const bySchema = nonRelationFields.length > 0 ? this.orArray(import_zod.z.enum(nonRelationFields), true) : import_zod.z.never();
5389
5390
  let schema = import_zod.z.strictObject({
5390
5391
  where: this.makeWhereSchema(model, false).optional(),
5391
5392
  orderBy: this.orArray(this.makeOrderBySchema(model, false, true), true).optional(),
5392
- by: this.orArray(import_zod.z.enum(nonRelationFields), true),
5393
+ by: bySchema,
5393
5394
  having: this.makeHavingSchema(model).optional(),
5394
5395
  skip: this.makeSkipSchema().optional(),
5395
5396
  take: this.makeTakeSchema().optional(),
@@ -5666,6 +5667,7 @@ var import_nanoid2 = require("nanoid");
5666
5667
  var import_ts_pattern16 = require("ts-pattern");
5667
5668
 
5668
5669
  // src/client/executor/name-mapper.ts
5670
+ var import_common_helpers10 = require("@zenstackhq/common-helpers");
5669
5671
  var import_kysely12 = require("kysely");
5670
5672
  var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5671
5673
  static {
@@ -5674,7 +5676,7 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5674
5676
  schema;
5675
5677
  modelToTableMap = /* @__PURE__ */ new Map();
5676
5678
  fieldToColumnMap = /* @__PURE__ */ new Map();
5677
- modelStack = [];
5679
+ modelScopes = [];
5678
5680
  constructor(schema) {
5679
5681
  super(), this.schema = schema;
5680
5682
  for (const [modelName, modelDef] of Object.entries(schema.models)) {
@@ -5690,150 +5692,182 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5690
5692
  }
5691
5693
  }
5692
5694
  }
5693
- get currentModel() {
5694
- return this.modelStack[this.modelStack.length - 1];
5695
- }
5696
- transformCreateTable(node) {
5697
- try {
5698
- this.modelStack.push(node.table.table.identifier.name);
5699
- return super.transformCreateTable(node);
5700
- } finally {
5701
- this.modelStack.pop();
5695
+ // #region overrides
5696
+ transformSelectQuery(node) {
5697
+ if (!node.from?.froms) {
5698
+ return super.transformSelectQuery(node);
5702
5699
  }
5700
+ const scopes = this.createScopesFromFroms(node.from, true);
5701
+ return this.withScopes(scopes, () => {
5702
+ return {
5703
+ ...super.transformSelectQuery(node),
5704
+ // convert "from" to nested query as needed
5705
+ from: this.processFrom(node.from)
5706
+ };
5707
+ });
5703
5708
  }
5704
5709
  transformInsertQuery(node) {
5705
- try {
5706
- if (node.into?.table.identifier.name) {
5707
- this.modelStack.push(node.into.table.identifier.name);
5708
- }
5710
+ if (!node.into) {
5709
5711
  return super.transformInsertQuery(node);
5710
- } finally {
5711
- if (node.into?.table.identifier.name) {
5712
- this.modelStack.pop();
5713
- }
5714
5712
  }
5713
+ return this.withScope({
5714
+ model: node.into.table.identifier.name
5715
+ }, () => ({
5716
+ ...super.transformInsertQuery(node),
5717
+ // map table name
5718
+ into: this.processTableRef(node.into)
5719
+ }));
5715
5720
  }
5716
5721
  transformReturning(node) {
5717
- return import_kysely12.ReturningNode.create(this.transformSelections(node.selections, node));
5722
+ return {
5723
+ kind: node.kind,
5724
+ // map column names in returning selections (include returningAll)
5725
+ selections: this.processSelections(node.selections)
5726
+ };
5718
5727
  }
5719
- transformUpdateQuery(node) {
5720
- let pushed = false;
5721
- if (node.table && import_kysely12.TableNode.is(node.table)) {
5722
- this.modelStack.push(node.table.table.identifier.name);
5723
- pushed = true;
5724
- }
5725
- try {
5726
- return super.transformUpdateQuery(node);
5727
- } finally {
5728
- if (pushed) {
5729
- this.modelStack.pop();
5728
+ transformJoin(node) {
5729
+ const { alias, node: innerNode } = this.stripAlias(node.table);
5730
+ if (import_kysely12.TableNode.is(innerNode)) {
5731
+ const modelName = innerNode.table.identifier.name;
5732
+ if (this.hasMappedColumns(modelName)) {
5733
+ const select = this.createSelectAll(modelName);
5734
+ return {
5735
+ ...super.transformJoin(node),
5736
+ table: this.wrapAlias(select, alias ?? modelName)
5737
+ };
5730
5738
  }
5731
5739
  }
5740
+ return super.transformJoin(node);
5732
5741
  }
5733
- transformDeleteQuery(node) {
5734
- let pushed = false;
5735
- if (node.from?.froms && node.from.froms.length === 1 && node.from.froms[0]) {
5736
- const from = node.from.froms[0];
5737
- if (import_kysely12.TableNode.is(from)) {
5738
- this.modelStack.push(from.table.identifier.name);
5739
- pushed = true;
5740
- } else if (import_kysely12.AliasNode.is(from) && import_kysely12.TableNode.is(from.node)) {
5741
- this.modelStack.push(from.node.table.identifier.name);
5742
- pushed = true;
5743
- }
5742
+ transformReference(node) {
5743
+ if (!import_kysely12.ColumnNode.is(node.column)) {
5744
+ return super.transformReference(node);
5744
5745
  }
5745
- try {
5746
- return super.transformDeleteQuery(node);
5747
- } finally {
5748
- if (pushed) {
5749
- this.modelStack.pop();
5746
+ const { fieldDef, modelDef, scope } = this.resolveFieldFromScopes(node.column.column.name, node.table?.table.identifier.name);
5747
+ if (fieldDef && !scope.namesMapped) {
5748
+ const mappedFieldName = this.mapFieldName(modelDef.name, fieldDef.name);
5749
+ let mappedTableName = node.table?.table.identifier.name;
5750
+ if (mappedTableName) {
5751
+ if (scope.alias === mappedTableName) {
5752
+ } else if (scope.model === mappedTableName) {
5753
+ mappedTableName = this.mapTableName(scope.model);
5754
+ }
5750
5755
  }
5756
+ return import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(mappedFieldName), mappedTableName ? import_kysely12.TableNode.create(mappedTableName) : void 0);
5757
+ } else {
5758
+ return super.transformReference(node);
5751
5759
  }
5752
5760
  }
5753
- transformSelectQuery(node) {
5754
- if (!node.from?.froms || node.from.froms.length === 0) {
5755
- return super.transformSelectQuery(node);
5756
- }
5757
- if (node.from.froms.length > 1) {
5758
- throw new InternalError(`SelectQueryNode must have a single table in from clause`);
5761
+ transformColumn(node) {
5762
+ const { modelDef, fieldDef, scope } = this.resolveFieldFromScopes(node.column.name);
5763
+ if (!fieldDef || scope.namesMapped) {
5764
+ return super.transformColumn(node);
5759
5765
  }
5760
- let pushed = false;
5761
- const from = node.from.froms[0];
5762
- if (import_kysely12.TableNode.is(from)) {
5763
- this.modelStack.push(from.table.identifier.name);
5764
- pushed = true;
5765
- } else if (import_kysely12.AliasNode.is(from) && import_kysely12.TableNode.is(from.node)) {
5766
- this.modelStack.push(from.node.table.identifier.name);
5767
- pushed = true;
5766
+ const mappedName = this.mapFieldName(modelDef.name, fieldDef.name);
5767
+ return import_kysely12.ColumnNode.create(mappedName);
5768
+ }
5769
+ transformUpdateQuery(node) {
5770
+ const { alias, node: innerTable } = this.stripAlias(node.table);
5771
+ if (!innerTable || !import_kysely12.TableNode.is(innerTable)) {
5772
+ return super.transformUpdateQuery(node);
5768
5773
  }
5769
- const selections = node.selections ? this.transformSelections(node.selections, node) : node.selections;
5770
- try {
5774
+ return this.withScope({
5775
+ model: innerTable.table.identifier.name,
5776
+ alias
5777
+ }, () => {
5771
5778
  return {
5772
- ...super.transformSelectQuery(node),
5773
- selections
5779
+ ...super.transformUpdateQuery(node),
5780
+ // map table name
5781
+ table: this.wrapAlias(this.processTableRef(innerTable), alias)
5774
5782
  };
5775
- } finally {
5776
- if (pushed) {
5777
- this.modelStack.pop();
5783
+ });
5784
+ }
5785
+ transformDeleteQuery(node) {
5786
+ const scopes = this.createScopesFromFroms(node.from, false);
5787
+ const froms = node.from.froms.map((from) => {
5788
+ const { alias, node: innerNode } = this.stripAlias(from);
5789
+ if (import_kysely12.TableNode.is(innerNode)) {
5790
+ return this.wrapAlias(this.processTableRef(innerNode), alias);
5791
+ } else {
5792
+ return super.transformNode(from);
5778
5793
  }
5779
- }
5794
+ });
5795
+ return this.withScopes(scopes, () => {
5796
+ return {
5797
+ ...super.transformDeleteQuery(node),
5798
+ from: import_kysely12.FromNode.create(froms)
5799
+ };
5800
+ });
5780
5801
  }
5781
- transformSelections(selections, contextNode) {
5782
- const result = [];
5783
- for (const selection of selections) {
5784
- let selectAllFromModel = void 0;
5785
- let isSelectAll = false;
5786
- if (import_kysely12.SelectAllNode.is(selection.selection)) {
5787
- selectAllFromModel = this.currentModel;
5788
- isSelectAll = true;
5789
- } else if (import_kysely12.ReferenceNode.is(selection.selection) && import_kysely12.SelectAllNode.is(selection.selection.column)) {
5790
- selectAllFromModel = selection.selection.table?.table.identifier.name ?? this.currentModel;
5791
- isSelectAll = true;
5792
- }
5793
- if (isSelectAll) {
5794
- if (!selectAllFromModel) {
5795
- continue;
5802
+ // #endregion
5803
+ // #region utils
5804
+ resolveFieldFromScopes(name, qualifier) {
5805
+ for (const scope of this.modelScopes.toReversed()) {
5806
+ if (qualifier) {
5807
+ if (scope.alias) {
5808
+ if (qualifier !== scope.alias) {
5809
+ continue;
5810
+ }
5796
5811
  } else {
5797
- const scalarFields = this.getModelScalarFields(contextNode, selectAllFromModel);
5798
- const fromModelDef = requireModel(this.schema, selectAllFromModel);
5799
- const mappedTableName = this.getMappedName(fromModelDef) ?? selectAllFromModel;
5800
- result.push(...scalarFields.map((fieldName) => {
5801
- const fieldRef = import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(this.mapFieldName(fieldName)), import_kysely12.TableNode.create(mappedTableName));
5802
- return import_kysely12.SelectionNode.create(this.fieldHasMappedName(fieldName) ? import_kysely12.AliasNode.create(fieldRef, import_kysely12.IdentifierNode.create(fieldName)) : fieldRef);
5803
- }));
5812
+ if (qualifier !== scope.model) {
5813
+ continue;
5814
+ }
5804
5815
  }
5805
- } else {
5806
- result.push(this.transformSelectionWithAlias(selection));
5816
+ }
5817
+ const modelDef = getModel(this.schema, scope.model);
5818
+ if (!modelDef) {
5819
+ continue;
5820
+ }
5821
+ if (modelDef.fields[name]) {
5822
+ return {
5823
+ modelDef,
5824
+ fieldDef: modelDef.fields[name],
5825
+ scope
5826
+ };
5807
5827
  }
5808
5828
  }
5809
- return result;
5829
+ return {
5830
+ modelDef: void 0,
5831
+ fieldDef: void 0,
5832
+ scope: void 0
5833
+ };
5810
5834
  }
5811
- transformSelectionWithAlias(node) {
5812
- if (import_kysely12.ColumnNode.is(node.selection) && this.fieldHasMappedName(node.selection.column.name)) {
5813
- return import_kysely12.SelectionNode.create(import_kysely12.AliasNode.create(this.transformColumn(node.selection), import_kysely12.IdentifierNode.create(node.selection.column.name)));
5814
- } else if (import_kysely12.ReferenceNode.is(node.selection) && this.fieldHasMappedName(node.selection.column.column.name)) {
5815
- return import_kysely12.SelectionNode.create(import_kysely12.AliasNode.create(this.transformReference(node.selection), import_kysely12.IdentifierNode.create(node.selection.column.column.name)));
5816
- } else {
5817
- return this.transformSelection(node);
5835
+ pushScope(scope) {
5836
+ this.modelScopes.push(scope);
5837
+ }
5838
+ withScope(scope, fn) {
5839
+ this.pushScope(scope);
5840
+ try {
5841
+ return fn();
5842
+ } finally {
5843
+ this.modelScopes.pop();
5818
5844
  }
5819
5845
  }
5820
- fieldHasMappedName(name) {
5821
- if (!this.currentModel) {
5822
- return false;
5846
+ withScopes(scopes, fn) {
5847
+ scopes.forEach((s) => this.pushScope(s));
5848
+ try {
5849
+ return fn();
5850
+ } finally {
5851
+ scopes.forEach(() => this.modelScopes.pop());
5823
5852
  }
5824
- return this.fieldToColumnMap.has(`${this.currentModel}.${name}`);
5825
5853
  }
5826
- transformTable(node) {
5827
- const tableName = node.table.identifier.name;
5828
- const mappedName = this.modelToTableMap.get(tableName);
5829
- if (mappedName) {
5830
- return import_kysely12.TableNode.create(mappedName);
5831
- } else {
5854
+ wrapAlias(node, alias) {
5855
+ return alias ? import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(alias)) : node;
5856
+ }
5857
+ ensureAlias(node, alias, fallbackName) {
5858
+ if (!node) {
5832
5859
  return node;
5833
5860
  }
5861
+ return alias ? import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(alias)) : import_kysely12.AliasNode.create(node, import_kysely12.IdentifierNode.create(fallbackName));
5834
5862
  }
5835
- transformColumn(node) {
5836
- return import_kysely12.ColumnNode.create(this.mapFieldName(node.column.name));
5863
+ processTableRef(node) {
5864
+ if (!node) {
5865
+ return node;
5866
+ }
5867
+ if (!import_kysely12.TableNode.is(node)) {
5868
+ return super.transformNode(node);
5869
+ }
5870
+ return import_kysely12.TableNode.create(this.mapTableName(node.table.identifier.name));
5837
5871
  }
5838
5872
  getMappedName(def) {
5839
5873
  const mapAttr = def.attributes?.find((attr) => attr.name === "@@map" || attr.name === "@map");
@@ -5845,28 +5879,151 @@ var QueryNameMapper = class extends import_kysely12.OperationNodeTransformer {
5845
5879
  }
5846
5880
  return void 0;
5847
5881
  }
5848
- mapFieldName(fieldName) {
5849
- if (!this.currentModel) {
5850
- return fieldName;
5882
+ mapFieldName(model, field) {
5883
+ const mappedName = this.fieldToColumnMap.get(`${model}.${field}`);
5884
+ if (mappedName) {
5885
+ return mappedName;
5886
+ } else {
5887
+ return field;
5851
5888
  }
5852
- const mappedName = this.fieldToColumnMap.get(`${this.currentModel}.${fieldName}`);
5889
+ }
5890
+ mapTableName(tableName) {
5891
+ const mappedName = this.modelToTableMap.get(tableName);
5853
5892
  if (mappedName) {
5854
5893
  return mappedName;
5855
5894
  } else {
5856
- return fieldName;
5895
+ return tableName;
5857
5896
  }
5858
5897
  }
5859
- requireCurrentModel(node) {
5860
- if (!this.currentModel) {
5861
- throw new InternalError(`Missing model context for "${node}"`);
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
+ hasMappedColumns(modelName) {
5918
+ return [
5919
+ ...this.fieldToColumnMap.keys()
5920
+ ].some((key) => key.startsWith(modelName + "."));
5921
+ }
5922
+ createScopesFromFroms(node, namesMapped) {
5923
+ if (!node) {
5924
+ return [];
5862
5925
  }
5926
+ return node.froms.map((from) => {
5927
+ const { alias, node: innerNode } = this.stripAlias(from);
5928
+ if (innerNode && import_kysely12.TableNode.is(innerNode)) {
5929
+ return {
5930
+ model: innerNode.table.identifier.name,
5931
+ alias,
5932
+ namesMapped
5933
+ };
5934
+ } else {
5935
+ return void 0;
5936
+ }
5937
+ }).filter((s) => !!s);
5863
5938
  }
5864
- getModelScalarFields(contextNode, model) {
5865
- this.requireCurrentModel(contextNode);
5866
- model = model ?? this.currentModel;
5939
+ // convert a "from" node to a nested query if there are columns with name mapping
5940
+ processFrom(node) {
5941
+ return {
5942
+ ...super.transformFrom(node),
5943
+ froms: node.froms.map((from) => {
5944
+ const { alias, node: innerNode } = this.stripAlias(from);
5945
+ if (!innerNode) {
5946
+ return super.transformNode(from);
5947
+ }
5948
+ if (import_kysely12.TableNode.is(innerNode)) {
5949
+ if (this.hasMappedColumns(innerNode.table.identifier.name)) {
5950
+ const selectAll = this.createSelectAll(innerNode.table.identifier.name);
5951
+ return this.ensureAlias(selectAll, alias, innerNode.table.identifier.name);
5952
+ }
5953
+ }
5954
+ return this.transformNode(from);
5955
+ })
5956
+ };
5957
+ }
5958
+ // create a `SelectQueryNode` for the given model with all columns mapped
5959
+ createSelectAll(model) {
5867
5960
  const modelDef = requireModel(this.schema, model);
5868
- const scalarFields = Object.entries(modelDef.fields).filter(([, fieldDef]) => !fieldDef.relation && !fieldDef.computed && !fieldDef.originModel).map(([fieldName]) => fieldName);
5869
- return scalarFields;
5961
+ const tableName = this.mapTableName(model);
5962
+ return {
5963
+ kind: "SelectQueryNode",
5964
+ from: import_kysely12.FromNode.create([
5965
+ import_kysely12.TableNode.create(tableName)
5966
+ ]),
5967
+ selections: this.getModelFields(modelDef).map((fieldDef) => {
5968
+ const columnName = this.mapFieldName(model, fieldDef.name);
5969
+ const columnRef = import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(columnName), import_kysely12.TableNode.create(tableName));
5970
+ 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);
5973
+ } else {
5974
+ return import_kysely12.SelectionNode.create(columnRef);
5975
+ }
5976
+ })
5977
+ };
5978
+ }
5979
+ getModelFields(modelDef) {
5980
+ return Object.values(modelDef.fields).filter((f) => !f.relation && !f.computed && !f.originModel);
5981
+ }
5982
+ processSelections(selections) {
5983
+ const result = [];
5984
+ selections.forEach((selection) => {
5985
+ if (import_kysely12.SelectAllNode.is(selection.selection)) {
5986
+ const processed = this.processSelectAll(selection.selection);
5987
+ if (Array.isArray(processed)) {
5988
+ result.push(...processed.map((s) => import_kysely12.SelectionNode.create(s)));
5989
+ } else {
5990
+ result.push(import_kysely12.SelectionNode.create(processed));
5991
+ }
5992
+ } else {
5993
+ result.push(import_kysely12.SelectionNode.create(this.processSelection(selection.selection)));
5994
+ }
5995
+ });
5996
+ return result;
5997
+ }
5998
+ processSelection(node) {
5999
+ let alias;
6000
+ if (!import_kysely12.AliasNode.is(node)) {
6001
+ alias = this.extractFieldName(node);
6002
+ }
6003
+ const result = super.transformNode(node);
6004
+ return this.wrapAlias(result, alias);
6005
+ }
6006
+ processSelectAll(node) {
6007
+ const scope = this.modelScopes[this.modelScopes.length - 1];
6008
+ (0, import_common_helpers10.invariant)(scope);
6009
+ if (!this.hasMappedColumns(scope.model)) {
6010
+ return super.transformSelectAll(node);
6011
+ }
6012
+ const modelDef = requireModel(this.schema, scope.model);
6013
+ return this.getModelFields(modelDef).map((fieldDef) => {
6014
+ const columnName = this.mapFieldName(scope.model, fieldDef.name);
6015
+ const columnRef = import_kysely12.ReferenceNode.create(import_kysely12.ColumnNode.create(columnName));
6016
+ return columnName !== fieldDef.name ? this.wrapAlias(columnRef, fieldDef.name) : columnRef;
6017
+ });
6018
+ }
6019
+ extractFieldName(node) {
6020
+ if (import_kysely12.ReferenceNode.is(node) && import_kysely12.ColumnNode.is(node.column)) {
6021
+ return node.column.column.name;
6022
+ } else if (import_kysely12.ColumnNode.is(node)) {
6023
+ return node.column.name;
6024
+ } else {
6025
+ return void 0;
6026
+ }
5870
6027
  }
5871
6028
  };
5872
6029
 
@@ -6167,7 +6324,7 @@ __export(functions_exports, {
6167
6324
  search: () => search,
6168
6325
  startsWith: () => startsWith
6169
6326
  });
6170
- var import_common_helpers10 = require("@zenstackhq/common-helpers");
6327
+ var import_common_helpers11 = require("@zenstackhq/common-helpers");
6171
6328
  var import_kysely14 = require("kysely");
6172
6329
  var import_ts_pattern17 = require("ts-pattern");
6173
6330
  var contains = /* @__PURE__ */ __name((eb, args) => {
@@ -6274,8 +6431,8 @@ var currentOperation = /* @__PURE__ */ __name((_eb, args, { operation }) => {
6274
6431
  }, "currentOperation");
6275
6432
  function processCasing(casing, result, model) {
6276
6433
  const opNode = casing.toOperationNode();
6277
- (0, import_common_helpers10.invariant)(import_kysely14.ValueNode.is(opNode) && typeof opNode.value === "string", '"casting" parameter must be a string value');
6278
- result = (0, import_ts_pattern17.match)(opNode.value).with("original", () => model).with("upper", () => result.toUpperCase()).with("lower", () => result.toLowerCase()).with("capitalize", () => (0, import_common_helpers10.upperCaseFirst)(result)).with("uncapitalize", () => (0, import_common_helpers10.lowerCaseFirst)(result)).otherwise(() => {
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(() => {
6279
6436
  throw new Error(`Invalid casing value: ${opNode.value}. Must be "original", "upper", "lower", "capitalize", or "uncapitalize".`);
6280
6437
  });
6281
6438
  return result;
@@ -6283,7 +6440,7 @@ function processCasing(casing, result, model) {
6283
6440
  __name(processCasing, "processCasing");
6284
6441
 
6285
6442
  // src/client/helpers/schema-db-pusher.ts
6286
- var import_common_helpers11 = require("@zenstackhq/common-helpers");
6443
+ var import_common_helpers12 = require("@zenstackhq/common-helpers");
6287
6444
  var import_kysely15 = require("kysely");
6288
6445
  var import_toposort = __toESM(require("toposort"), 1);
6289
6446
  var import_ts_pattern18 = require("ts-pattern");
@@ -6379,7 +6536,7 @@ var SchemaDbPusher = class {
6379
6536
  }
6380
6537
  addUniqueConstraint(table, modelDef) {
6381
6538
  for (const [key, value] of Object.entries(modelDef.uniqueFields)) {
6382
- (0, import_common_helpers11.invariant)(typeof value === "object", "expecting an object");
6539
+ (0, import_common_helpers12.invariant)(typeof value === "object", "expecting an object");
6383
6540
  if ("type" in value) {
6384
6541
  const fieldDef = modelDef.fields[key];
6385
6542
  if (fieldDef.unique) {
@@ -6447,7 +6604,7 @@ var SchemaDbPusher = class {
6447
6604
  return fieldDef.default && ExpressionUtils.isCall(fieldDef.default) && fieldDef.default.function === "autoincrement";
6448
6605
  }
6449
6606
  addForeignKeyConstraint(table, model, fieldName, fieldDef) {
6450
- (0, import_common_helpers11.invariant)(fieldDef.relation, "field must be a relation");
6607
+ (0, import_common_helpers12.invariant)(fieldDef.relation, "field must be a relation");
6451
6608
  if (!fieldDef.relation.fields || !fieldDef.relation.references) {
6452
6609
  return table;
6453
6610
  }
@@ -6502,7 +6659,7 @@ function valueToPromise(thing) {
6502
6659
  __name(valueToPromise, "valueToPromise");
6503
6660
 
6504
6661
  // src/client/result-processor.ts
6505
- var import_common_helpers12 = require("@zenstackhq/common-helpers");
6662
+ var import_common_helpers13 = require("@zenstackhq/common-helpers");
6506
6663
  var import_decimal2 = __toESM(require("decimal.js"), 1);
6507
6664
  var import_ts_pattern19 = require("ts-pattern");
6508
6665
  var ResultProcessor = class {
@@ -6602,14 +6759,14 @@ var ResultProcessor = class {
6602
6759
  if (value instanceof import_decimal2.default) {
6603
6760
  return value;
6604
6761
  }
6605
- (0, import_common_helpers12.invariant)(typeof value === "string" || typeof value === "number" || value instanceof import_decimal2.default, `Expected string, number or Decimal, got ${typeof value}`);
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}`);
6606
6763
  return new import_decimal2.default(value);
6607
6764
  }
6608
6765
  transformBigInt(value) {
6609
6766
  if (typeof value === "bigint") {
6610
6767
  return value;
6611
6768
  }
6612
- (0, import_common_helpers12.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
6769
+ (0, import_common_helpers13.invariant)(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
6613
6770
  return BigInt(value);
6614
6771
  }
6615
6772
  transformBoolean(value) {
@@ -6653,7 +6810,7 @@ var ResultProcessor = class {
6653
6810
  }
6654
6811
  transformJson(value) {
6655
6812
  return (0, import_ts_pattern19.match)(this.schema.provider.type).with("sqlite", () => {
6656
- (0, import_common_helpers12.invariant)(typeof value === "string", "Expected string, got " + typeof value);
6813
+ (0, import_common_helpers13.invariant)(typeof value === "string", "Expected string, got " + typeof value);
6657
6814
  return JSON.parse(value);
6658
6815
  }).otherwise(() => value);
6659
6816
  }
@@ -6730,7 +6887,7 @@ var ClientImpl = class _ClientImpl {
6730
6887
  }
6731
6888
  // implementation
6732
6889
  async $transaction(input, options) {
6733
- (0, import_common_helpers13.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");
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");
6734
6891
  if (typeof input === "function") {
6735
6892
  return this.interactiveTransaction(input, options);
6736
6893
  } else {