@danielhritcu/zenstack-orm 3.5.20 → 3.5.22

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
1
  import * as _zenstackhq_schema from '@zenstackhq/schema';
2
- import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, GetModel, ProcedureDef, BuiltinType, FieldDef, ModelDef, DataSourceProviderType, IsDelegateModel, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, GetTypeDefFieldType, TypeDefFieldIsArray, UpdatedAtInfo, FieldIsDelegateDiscriminator, FieldType, RelationInfo, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, BindingExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
2
+ import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, GetModel, ProcedureDef, HasRls, BuiltinType, FieldDef, ModelDef, DataSourceProviderType, IsDelegateModel, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, GetTypeDefFieldType, TypeDefFieldIsArray, UpdatedAtInfo, FieldIsDelegateDiscriminator, FieldType, RelationInfo, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, BindingExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
3
3
  import * as kysely from 'kysely';
4
4
  import { Kysely, OperationNodeVisitor, OperationNode, SelectQueryNode, SelectionNode, ColumnNode, AliasNode, TableNode, FromNode, ReferenceNode, AndNode, OrNode, ValueListNode, ParensNode, JoinNode, RawNode, WhereNode, InsertQueryNode, DeleteQueryNode, ReturningNode, CreateTableNode, AddColumnNode, ColumnDefinitionNode, DropTableNode, OrderByNode, OrderByItemNode, GroupByNode, GroupByItemNode, UpdateQueryNode, ColumnUpdateNode, LimitNode, OffsetNode, OnConflictNode, OnDuplicateKeyNode, CheckConstraintNode, DataTypeNode, SelectAllNode, IdentifierNode, SchemableIdentifierNode, ValueNode, PrimitiveValueListNode, OperatorNode, CreateIndexNode, DropIndexNode, ListNode, PrimaryKeyConstraintNode, UniqueConstraintNode, ReferencesNode, WithNode, CommonTableExpressionNode, CommonTableExpressionNameNode, HavingNode, CreateSchemaNode, DropSchemaNode, AlterTableNode, DropColumnNode, RenameColumnNode, AlterColumnNode, ModifyColumnNode, AddConstraintNode, DropConstraintNode, ForeignKeyConstraintNode, CreateViewNode, DropViewNode, GeneratedNode, DefaultValueNode, OnNode, ValuesNode, SelectModifierNode, CreateTypeNode, DropTypeNode, ExplainNode, DefaultInsertValueNode, AggregateFunctionNode, OverNode, PartitionByNode, PartitionByItemNode, SetOperationNode, BinaryOperationNode, UnaryOperationNode, UsingNode, FunctionNode, CaseNode, WhenNode, JSONReferenceNode, JSONPathNode, JSONPathLegNode, JSONOperatorChainNode, TupleNode, MergeQueryNode, MatchedNode, AddIndexNode, CastNode, FetchNode, TopNode, OutputNode, RenameConstraintNode, RefreshMaterializedViewNode, OrActionNode, CollateNode, Generated, QueryId, RootOperationNode, QueryResult, UnknownRow, Dialect, ExpressionBuilder, Expression, KyselyConfig, OperandExpression, SelectQueryBuilder, SqlBool, AliasableExpression, ExpressionWrapper } from 'kysely';
5
5
  import Decimal from 'decimal.js';
@@ -782,6 +782,11 @@ type ClientOptions<Schema extends SchemaDef> = QueryOptions<Schema> & {
782
782
  * Custom procedure definitions.
783
783
  */
784
784
  procedures: ProceduresOptions<Schema>;
785
+ } : {}) & (HasRls<Schema> extends true ? {
786
+ /**
787
+ * Row Level Security configuration.
788
+ */
789
+ rls: Record<string, unknown>;
785
790
  } : {});
786
791
  /**
787
792
  * Config for omitting fields in ORM query results.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _zenstackhq_schema from '@zenstackhq/schema';
2
- import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, GetModel, ProcedureDef, BuiltinType, FieldDef, ModelDef, DataSourceProviderType, IsDelegateModel, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, GetTypeDefFieldType, TypeDefFieldIsArray, UpdatedAtInfo, FieldIsDelegateDiscriminator, FieldType, RelationInfo, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, BindingExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
2
+ import { SchemaDef, GetModels, ScalarFields, ForeignKeyFields, GetModelFields, FieldHasDefault, GetModelFieldType, ModelFieldIsOptional, GetModelField, NonRelationFields, GetModel, ProcedureDef, HasRls, BuiltinType, FieldDef, ModelDef, DataSourceProviderType, IsDelegateModel, RelationFields, FieldIsArray, RelationFieldType, FieldIsRelation, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefField, TypeDefFieldIsOptional, GetTypeDefFieldType, TypeDefFieldIsArray, UpdatedAtInfo, FieldIsDelegateDiscriminator, FieldType, RelationInfo, Expression as Expression$1, LiteralExpression, ArrayExpression, FieldExpression, MemberExpression, BinaryExpression, UnaryExpression, CallExpression, BindingExpression, ThisExpression, NullExpression } from '@zenstackhq/schema';
3
3
  import * as kysely from 'kysely';
4
4
  import { Kysely, OperationNodeVisitor, OperationNode, SelectQueryNode, SelectionNode, ColumnNode, AliasNode, TableNode, FromNode, ReferenceNode, AndNode, OrNode, ValueListNode, ParensNode, JoinNode, RawNode, WhereNode, InsertQueryNode, DeleteQueryNode, ReturningNode, CreateTableNode, AddColumnNode, ColumnDefinitionNode, DropTableNode, OrderByNode, OrderByItemNode, GroupByNode, GroupByItemNode, UpdateQueryNode, ColumnUpdateNode, LimitNode, OffsetNode, OnConflictNode, OnDuplicateKeyNode, CheckConstraintNode, DataTypeNode, SelectAllNode, IdentifierNode, SchemableIdentifierNode, ValueNode, PrimitiveValueListNode, OperatorNode, CreateIndexNode, DropIndexNode, ListNode, PrimaryKeyConstraintNode, UniqueConstraintNode, ReferencesNode, WithNode, CommonTableExpressionNode, CommonTableExpressionNameNode, HavingNode, CreateSchemaNode, DropSchemaNode, AlterTableNode, DropColumnNode, RenameColumnNode, AlterColumnNode, ModifyColumnNode, AddConstraintNode, DropConstraintNode, ForeignKeyConstraintNode, CreateViewNode, DropViewNode, GeneratedNode, DefaultValueNode, OnNode, ValuesNode, SelectModifierNode, CreateTypeNode, DropTypeNode, ExplainNode, DefaultInsertValueNode, AggregateFunctionNode, OverNode, PartitionByNode, PartitionByItemNode, SetOperationNode, BinaryOperationNode, UnaryOperationNode, UsingNode, FunctionNode, CaseNode, WhenNode, JSONReferenceNode, JSONPathNode, JSONPathLegNode, JSONOperatorChainNode, TupleNode, MergeQueryNode, MatchedNode, AddIndexNode, CastNode, FetchNode, TopNode, OutputNode, RenameConstraintNode, RefreshMaterializedViewNode, OrActionNode, CollateNode, Generated, QueryId, RootOperationNode, QueryResult, UnknownRow, Dialect, ExpressionBuilder, Expression, KyselyConfig, OperandExpression, SelectQueryBuilder, SqlBool, AliasableExpression, ExpressionWrapper } from 'kysely';
5
5
  import Decimal from 'decimal.js';
@@ -782,6 +782,11 @@ type ClientOptions<Schema extends SchemaDef> = QueryOptions<Schema> & {
782
782
  * Custom procedure definitions.
783
783
  */
784
784
  procedures: ProceduresOptions<Schema>;
785
+ } : {}) & (HasRls<Schema> extends true ? {
786
+ /**
787
+ * Row Level Security configuration.
788
+ */
789
+ rls: Record<string, unknown>;
785
790
  } : {});
786
791
  /**
787
792
  * Config for omitting fields in ORM query results.
package/dist/index.js CHANGED
@@ -7937,7 +7937,7 @@ __name(performanceNow, "performanceNow");
7937
7937
 
7938
7938
  // src/client/executor/zenstack-query-executor.ts
7939
7939
  import { invariant as invariant11 } from "@zenstackhq/common-helpers";
7940
- import { AndNode, ColumnNode as ColumnNode3, ColumnUpdateNode as ColumnUpdateNode2, createQueryId as createQueryId2, DefaultQueryExecutor, DeleteQueryNode, expressionBuilder as expressionBuilder7, InsertQueryNode, PrimitiveValueListNode as PrimitiveValueListNode2, ReturningNode, SelectionNode as SelectionNode2, SingleConnectionProvider, TableNode as TableNode3, UpdateQueryNode, ValueNode as ValueNode2, ValuesNode as ValuesNode2, WhereNode } from "kysely";
7940
+ import { AndNode, ColumnNode as ColumnNode3, ColumnUpdateNode as ColumnUpdateNode2, createQueryId as createQueryId3, DefaultQueryExecutor, DeleteQueryNode, expressionBuilder as expressionBuilder7, InsertQueryNode, PrimitiveValueListNode as PrimitiveValueListNode2, ReturningNode, SelectionNode as SelectionNode2, SingleConnectionProvider, TableNode as TableNode3, UpdateQueryNode, ValueNode as ValueNode2, ValuesNode as ValuesNode2, WhereNode } from "kysely";
7941
7941
  import { match as match12 } from "ts-pattern";
7942
7942
 
7943
7943
  // src/client/executor/name-mapper.ts
@@ -8520,6 +8520,32 @@ var QueryNameMapper = class extends OperationNodeTransformer {
8520
8520
  }
8521
8521
  };
8522
8522
 
8523
+ // src/client/executor/rls.ts
8524
+ import { createQueryId as createQueryId2 } from "kysely";
8525
+ function buildRlsSetConfigSql(rlsDef, rlsValues) {
8526
+ const parts = [];
8527
+ for (const [name, keyDef] of Object.entries(rlsDef.keys)) {
8528
+ const rawValue = rlsValues[name];
8529
+ const resolved = keyDef.resolve(rawValue);
8530
+ const escaped = String(resolved).replace(/'/g, "''");
8531
+ parts.push(`set_config('${keyDef.set}', '${escaped}', true)`);
8532
+ }
8533
+ return `SELECT ${parts.join(", ")}`;
8534
+ }
8535
+ __name(buildRlsSetConfigSql, "buildRlsSetConfigSql");
8536
+ async function applyRlsContext(connection, rlsDef, rlsValues) {
8537
+ const sql9 = buildRlsSetConfigSql(rlsDef, rlsValues);
8538
+ await connection.executeQuery({
8539
+ sql: sql9,
8540
+ parameters: [],
8541
+ query: {
8542
+ kind: "RawNode"
8543
+ },
8544
+ queryId: createQueryId2()
8545
+ });
8546
+ }
8547
+ __name(applyRlsContext, "applyRlsContext");
8548
+
8523
8549
  // src/client/executor/temp-alias-transformer.ts
8524
8550
  import { IdentifierNode as IdentifierNode2, OperationNodeTransformer as OperationNodeTransformer2 } from "kysely";
8525
8551
  var TempAliasTransformer = class extends OperationNodeTransformer2 {
@@ -8583,6 +8609,7 @@ var ZenStackQueryExecutor = class _ZenStackQueryExecutor extends DefaultQueryExe
8583
8609
  // #region constructor, fields and props
8584
8610
  nameMapper;
8585
8611
  dialect;
8612
+ rlsInitializedConnections = /* @__PURE__ */ new WeakSet();
8586
8613
  constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false) {
8587
8614
  super(compiler, adapter, connectionProvider, plugins), this.client = client, this.driver = driver, this.compiler = compiler, this.connectionProvider = connectionProvider, this.suppressMutationHooks = suppressMutationHooks;
8588
8615
  if (client.$schema.provider.type === "postgresql" || // postgres queries need to be schema-qualified
@@ -8984,23 +9011,67 @@ In such cases, ZenStack cannot reliably determine the IDs of the mutated entitie
8984
9011
  }
8985
9012
  async internalExecuteQuery(query, connection, queryId, parameters) {
8986
9013
  const finalQuery = this.processQueryNode(query);
8987
- let compiledQuery = this.compileQuery(finalQuery, queryId ?? createQueryId2());
9014
+ let compiledQuery = this.compileQuery(finalQuery, queryId ?? createQueryId3());
8988
9015
  if (parameters) {
8989
9016
  compiledQuery = {
8990
9017
  ...compiledQuery,
8991
9018
  parameters
8992
9019
  };
8993
9020
  }
9021
+ const rlsDef = this.client.$schema.rls;
9022
+ const rlsValues = this.client.$options.rls;
9023
+ const isTransaction = this.driver.isTransactionConnection(connection);
9024
+ const needsRls = rlsDef && rlsValues;
9025
+ const needsRlsInit = needsRls && (!isTransaction || !this.rlsInitializedConnections.has(connection));
8994
9026
  const trackSlowQuery = this.options.diagnostics !== void 0;
8995
9027
  const startTimestamp = trackSlowQuery ? performance.now() : void 0;
8996
9028
  const startedAt = trackSlowQuery ? /* @__PURE__ */ new Date() : void 0;
8997
9029
  try {
9030
+ if (needsRlsInit) {
9031
+ if (!isTransaction) {
9032
+ await connection.executeQuery({
9033
+ sql: "BEGIN",
9034
+ parameters: [],
9035
+ query: {
9036
+ kind: "RawNode"
9037
+ },
9038
+ queryId: createQueryId3()
9039
+ });
9040
+ }
9041
+ await applyRlsContext(connection, rlsDef, rlsValues);
9042
+ if (isTransaction) {
9043
+ this.rlsInitializedConnections.add(connection);
9044
+ }
9045
+ }
8998
9046
  const result = await connection.executeQuery(compiledQuery);
9047
+ if (needsRlsInit && !isTransaction) {
9048
+ await connection.executeQuery({
9049
+ sql: "COMMIT",
9050
+ parameters: [],
9051
+ query: {
9052
+ kind: "RawNode"
9053
+ },
9054
+ queryId: createQueryId3()
9055
+ });
9056
+ }
8999
9057
  if (startTimestamp !== void 0) {
9000
9058
  this.trackSlowQuery(compiledQuery, startTimestamp, startedAt);
9001
9059
  }
9002
9060
  return this.ensureProperQueryResult(compiledQuery.query, result);
9003
9061
  } catch (err) {
9062
+ if (needsRlsInit && !isTransaction) {
9063
+ try {
9064
+ await connection.executeQuery({
9065
+ sql: "ROLLBACK",
9066
+ parameters: [],
9067
+ query: {
9068
+ kind: "RawNode"
9069
+ },
9070
+ queryId: createQueryId3()
9071
+ });
9072
+ } catch {
9073
+ }
9074
+ }
9004
9075
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiledQuery.sql, compiledQuery.parameters);
9005
9076
  }
9006
9077
  }