uql-orm 0.114.4 → 0.115.0

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.
Files changed (84) hide show
  1. package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
  2. package/dist/cockroachdb/cockroachDialect.js +5 -0
  3. package/dist/d1/d1Querier.d.ts +2 -4
  4. package/dist/d1/d1Querier.js +0 -4
  5. package/dist/d1/d1SqliteDialect.js +1 -1
  6. package/dist/dialect/abstractDialect.d.ts +17 -8
  7. package/dist/dialect/abstractDialect.js +30 -16
  8. package/dist/dialect/abstractSqlDialect.d.ts +11 -2
  9. package/dist/dialect/abstractSqlDialect.js +17 -2
  10. package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
  11. package/dist/dialect/operators.d.ts +2 -2
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
  13. package/dist/dialect/pgLikeSqlDialect.js +20 -0
  14. package/dist/entity/columnOptionsBuilder.d.ts +2 -1
  15. package/dist/entity/columnOptionsBuilder.js +3 -0
  16. package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
  17. package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
  18. package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
  19. package/dist/entity/metadata/definition.js +69 -30
  20. package/dist/http/api.d.ts +1 -1
  21. package/dist/http/wireQuery.js +1 -1
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +2 -0
  24. package/dist/migrate/ddl/tableDdl.d.ts +5 -0
  25. package/dist/migrate/ddl/tableDdl.js +9 -0
  26. package/dist/migrate/drift/driftDetector.js +2 -1
  27. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
  28. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
  29. package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
  30. package/dist/migrate/introspection/postgresIntrospector.js +14 -1
  31. package/dist/migrate/introspection/tableSchemaAST.js +1 -0
  32. package/dist/migrate/policySql.d.ts +12 -0
  33. package/dist/migrate/policySql.js +74 -0
  34. package/dist/migrate/schemaChange.js +1 -0
  35. package/dist/migrate/schemaGenerator.d.ts +2 -0
  36. package/dist/migrate/schemaGenerator.js +37 -11
  37. package/dist/mongodb/mongoDialect.js +3 -1
  38. package/dist/mongodb/mongodbQuerier.d.ts +0 -2
  39. package/dist/mongodb/mongodbQuerier.js +0 -4
  40. package/dist/mssql/mssqlDialect.js +2 -0
  41. package/dist/neon/neonQuerier.d.ts +1 -2
  42. package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
  43. package/dist/nestjs/uqlContextInterceptor.js +1 -1
  44. package/dist/nestjs/uqlModule.d.ts +2 -2
  45. package/dist/nestjs/uqlModule.js +1 -1
  46. package/dist/querier/abstractQuerier.d.ts +31 -4
  47. package/dist/querier/abstractQuerier.js +120 -52
  48. package/dist/querier/abstractQuerierPool.js +2 -0
  49. package/dist/querier/abstractSqlQuerier.d.ts +16 -6
  50. package/dist/querier/abstractSqlQuerier.js +66 -6
  51. package/dist/querier/queryError.js +1 -0
  52. package/dist/schema/schemaAST.js +1 -0
  53. package/dist/schema/schemaASTBuilder.d.ts +3 -1
  54. package/dist/schema/schemaASTBuilder.js +1 -0
  55. package/dist/schema/schemaASTDiffer.js +4 -2
  56. package/dist/schema/types.d.ts +12 -4
  57. package/dist/sqlite/bindValues.d.ts +1 -1
  58. package/dist/sqlite/hranaQuerier.d.ts +2 -2
  59. package/dist/sqlite/sqliteDialect.js +2 -0
  60. package/dist/turso/tursoSessionQuerier.d.ts +2 -2
  61. package/dist/type/column.d.ts +10 -0
  62. package/dist/type/definedEntity.d.ts +9 -4
  63. package/dist/type/dialect.d.ts +13 -0
  64. package/dist/type/entity.d.ts +10 -0
  65. package/dist/type/index.d.ts +1 -0
  66. package/dist/type/index.js +1 -0
  67. package/dist/type/migration.d.ts +5 -1
  68. package/dist/type/policy.d.ts +91 -0
  69. package/dist/type/policy.js +1 -0
  70. package/dist/type/querier.d.ts +14 -0
  71. package/dist/type/querierPool.d.ts +2 -2
  72. package/dist/type/query.d.ts +18 -31
  73. package/dist/type/query.js +2 -0
  74. package/dist/util/contextRefs.d.ts +6 -0
  75. package/dist/util/contextRefs.js +5 -0
  76. package/dist/util/dialect.util.d.ts +10 -11
  77. package/dist/util/dialect.util.js +70 -56
  78. package/dist/util/fieldOption.util.js +1 -0
  79. package/dist/util/policy.util.d.ts +100 -0
  80. package/dist/util/policy.util.js +234 -0
  81. package/dist/util/uqlError.d.ts +2 -5
  82. package/dist/util/uqlError.js +2 -5
  83. package/package.json +1 -1
  84. package/skills/uql-orm/SKILL.md +23 -13
@@ -4,6 +4,8 @@ import type { QueryContext, SqlDialectFeatures, AbstractType } from '../type/ind
4
4
  /** CockroachDB: the Postgres wire and SQL, with native vectors. */
5
5
  export declare class CockroachDialect extends PgLikeSqlDialect {
6
6
  readonly dialectName = "cockroachdb";
7
+ /** Bare: a policy takes no subquery here. */
8
+ contextRead(key: string, type: string): string;
7
9
  /**
8
10
  * pgvector's but `l1`: `<+>` and `vector_l1_ops` answer "unimplemented: operator class ... is not
9
11
  * supported" (verified live on v26.2), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
@@ -4,6 +4,10 @@ import { getMeta } from '../entity/index.js';
4
4
  /** CockroachDB: the Postgres wire and SQL, with native vectors. */
5
5
  export class CockroachDialect extends PgLikeSqlDialect {
6
6
  dialectName = 'cockroachdb';
7
+ /** Bare: a policy takes no subquery here. */
8
+ contextRead(key, type) {
9
+ return this.settingRead(key, type);
10
+ }
7
11
  /**
8
12
  * pgvector's but `l1`: `<+>` and `vector_l1_ops` answer "unimplemented: operator class ... is not
9
13
  * supported" (verified live on v26.2), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
@@ -24,6 +28,7 @@ export class CockroachDialect extends PgLikeSqlDialect {
24
28
  nullsSortLowest: true,
25
29
  triggers: { ...PG_FEATURES.triggers, fires: 'eachRowIf', deferrable: false },
26
30
  namedLocks: 'journal',
31
+ rowSecurity: { subqueries: false },
27
32
  };
28
33
  /**
29
34
  * Not Postgres' `pg_class.reltuples`, which CockroachDB answers `NULL` for even straight after an
@@ -1,6 +1,6 @@
1
- import { AbstractSqlQuerier, type BoundStatement } from '../querier/index.js';
1
+ import { AbstractSqlQuerier } from '../querier/index.js';
2
2
  import { type SqliteBindValue } from '../sqlite/bindValues.js';
3
- import type { ExtraOptions, RawRow } from '../type/index.js';
3
+ import type { BoundStatement, ExtraOptions, RawRow } from '../type/index.js';
4
4
  import type { SqlExecution } from '../util/sql.util.js';
5
5
  import type { D1SqliteDialect } from './d1SqliteDialect.js';
6
6
  /** What a statement answers on D1: the rows it read, and how many rows it changed. */
@@ -32,7 +32,5 @@ export declare class D1Querier extends AbstractSqlQuerier {
32
32
  protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
33
33
  /** D1 answers `BEGIN` with `D1_ERROR: not authorized`: a `batch()` is its only transaction. */
34
34
  protected internalBegin(): Promise<void>;
35
- /** A write split in steps a list cannot carry lands step by step, there being no transaction to hold it. */
36
- protected atomically<T>(write: () => Promise<T>): Promise<T>;
37
35
  private prepared;
38
36
  }
@@ -19,10 +19,6 @@ export class D1Querier extends AbstractSqlQuerier {
19
19
  async internalBegin() {
20
20
  throw new UqlUsageError('Cloudflare D1 has no transactions: write the changes as one statement, or idempotently');
21
21
  }
22
- /** A write split in steps a list cannot carry lands step by step, there being no transaction to hold it. */
23
- atomically(write) {
24
- return write();
25
- }
26
22
  prepared(sql, values) {
27
23
  const stmt = this.db.prepare(sql);
28
24
  const args = toBindValues(values);
@@ -7,7 +7,7 @@ import { UqlUsageError } from '../util/uqlError.js';
7
7
  */
8
8
  export class D1SqliteDialect extends SqliteDialect {
9
9
  /** A vector stays text: D1 answers a BLOB as an array of its byte values, which reads like a vector. */
10
- features = { ...SQLITE_FEATURES, vectorBytes: false };
10
+ features = { ...SQLITE_FEATURES, transactions: false, vectorBytes: false };
11
11
  get engineName() {
12
12
  return 'Cloudflare D1';
13
13
  }
@@ -1,5 +1,6 @@
1
- import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, FieldOptions, InsertIdSource, NamingStrategy, Query, StatementOptions, QueryWhere, AbstractType } from '../type/index.js';
1
+ import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, PolicyMode, FieldOptions, InsertIdSource, NamingStrategy, Query, StatementOptions, QueryWhere, AbstractType } from '../type/index.js';
2
2
  import { type EngineName } from '../type/index.js';
3
+ import { type PolicyEnforcement } from '../util/policy.util.js';
3
4
  /**
4
5
  * Options for initializing a dialect.
5
6
  */
@@ -7,6 +8,8 @@ export interface DialectOptions {
7
8
  readonly namingStrategy?: NamingStrategy;
8
9
  /** Default schema for entities naming none; unset leaves them unqualified. See {@link AbstractDialect.resolveSchema}. */
9
10
  readonly schema?: string;
11
+ /** See {@link ExtraOptions.policies}. */
12
+ readonly policies?: PolicyMode;
10
13
  }
11
14
  /**
12
15
  * The dialect's share of a pool's {@link ExtraOptions}: what changes the SQL rather than the
@@ -72,16 +75,22 @@ export declare abstract class AbstractDialect {
72
75
  * every row it comes back in, and MongoDB would read `$` or `.` in one as an operator or a path.
73
76
  */
74
77
  assertProjectable<E>(meta: EntityMeta<E>, alias: string): void;
78
+ /** How its pool's statements are held to the entities' policies, refusing a database that holds no row to one. */
79
+ get policies(): PolicyEnforcement;
75
80
  /**
76
- * A `$where` with the entity's active filters merged in - the only way any dialect should enter a
77
- * new query scope, so a scope cannot be rendered with its `security: true` filters skipped.
78
- * Recursion within one scope renders the returned map directly instead.
81
+ * A `$where` with the entity's active filters and policies merged in - the only way any dialect should enter a
82
+ * new query scope, so a scope cannot be rendered with its policies skipped. Recursion within one scope renders
83
+ * the returned map directly instead.
79
84
  */
80
85
  protected scopedWhere<E>(meta: EntityMeta<E>, where?: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
81
86
  /**
82
- * Whether a `$where` reads a relation at any depth: filters by one, or by a relation aggregate. What
83
- * cannot host that read - a MongoDB filter, a write without {@link DialectFeatures.correlatedWrites} -
84
- * has the rows it names read first.
87
+ * Whether a statement's `$where`, its filters and policies merged in as {@link scopedWhere} merges them, reads a
88
+ * relation at any depth: filters by one, or by a relation aggregate. What cannot host that read - a MongoDB filter,
89
+ * a write without {@link DialectFeatures.correlatedWrites} - has the rows it names read first.
85
90
  */
86
- constrainsRelations<E>(entity: AbstractType<E>, where: QueryWhere<E> | undefined): boolean;
91
+ constrainsRelations<E>(entity: AbstractType<E>, where: QueryWhere<E> | undefined, opts?: StatementOptions): boolean;
92
+ /** `opts` as a scope is merged with: past the policies where the querier is not who holds them. */
93
+ private scopeOptions;
87
94
  }
95
+ /** Whether `where` reads a relation of `meta` at any depth, by its key or a relation aggregate. */
96
+ export declare function readsRelations<E>(meta: EntityMeta<E>, where: QueryWhere<E>): boolean;
@@ -1,8 +1,9 @@
1
1
  import { getMeta } from '../entity/index.js';
2
- import { ENGINE_NAMES, parseQueryLock } from '../type/index.js';
2
+ import { ENGINE_NAMES, parseQueryLock, PAST_POLICIES } from '../type/index.js';
3
3
  import { QuerySql } from '../type/querySql.js';
4
4
  import { applyFilters } from '../util/dialect.util.js';
5
5
  import { aggregateOf, definedEntries, entityName, someKey } from '../util/index.js';
6
+ import { enforcementOf } from '../util/policy.util.js';
6
7
  import { assertNoUndefined, assertWhere } from '../util/query.util.js';
7
8
  import { qualifyName } from '../util/sql.util.js';
8
9
  import { UqlUsageError } from '../util/uqlError.js';
@@ -14,7 +15,7 @@ import { groupClauses, isGroupOp } from './operators.js';
14
15
  * each pool's constructor.
15
16
  */
16
17
  export function dialectOptionsFrom(extra) {
17
- return { namingStrategy: extra?.namingStrategy, schema: extra?.schema };
18
+ return { namingStrategy: extra?.namingStrategy, schema: extra?.schema, policies: extra?.policies };
18
19
  }
19
20
  /** A name a score can be projected under: what every engine takes as a key, with nothing to escape. */
20
21
  const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -113,29 +114,42 @@ export class AbstractDialect {
113
114
  throw new UqlUsageError(`$project '${alias}' collides with a relation of '${entityName(meta)}'`);
114
115
  }
115
116
  }
117
+ /** How its pool's statements are held to the entities' policies, refusing a database that holds no row to one. */
118
+ get policies() {
119
+ const enforcement = enforcementOf(this.options.policies);
120
+ if (enforcement.database && this.features.rowSecurity === false) {
121
+ throw new UqlUsageError(`${this.engineName} holds no row to a policy itself: leave policies unset, for uql to hold them`);
122
+ }
123
+ return enforcement;
124
+ }
116
125
  /**
117
- * A `$where` with the entity's active filters merged in - the only way any dialect should enter a
118
- * new query scope, so a scope cannot be rendered with its `security: true` filters skipped.
119
- * Recursion within one scope renders the returned map directly instead.
126
+ * A `$where` with the entity's active filters and policies merged in - the only way any dialect should enter a
127
+ * new query scope, so a scope cannot be rendered with its policies skipped. Recursion within one scope renders
128
+ * the returned map directly instead.
120
129
  */
121
130
  scopedWhere(meta, where = {}, opts) {
122
131
  assertWhere(meta, where);
123
- const scoped = applyFilters(meta, where, opts);
132
+ const scoped = applyFilters(meta, where, this.scopeOptions(opts));
124
133
  assertNoUndefined(scoped, `$where on '${entityName(meta)}'`);
125
134
  return scoped;
126
135
  }
127
136
  /**
128
- * Whether a `$where` reads a relation at any depth: filters by one, or by a relation aggregate. What
129
- * cannot host that read - a MongoDB filter, a write without {@link DialectFeatures.correlatedWrites} -
130
- * has the rows it names read first.
137
+ * Whether a statement's `$where`, its filters and policies merged in as {@link scopedWhere} merges them, reads a
138
+ * relation at any depth: filters by one, or by a relation aggregate. What cannot host that read - a MongoDB filter,
139
+ * a write without {@link DialectFeatures.correlatedWrites} - has the rows it names read first.
131
140
  */
132
- constrainsRelations(entity, where) {
133
- if (!where) {
134
- return false;
135
- }
141
+ constrainsRelations(entity, where, opts) {
136
142
  const meta = getMeta(entity);
137
- return someKey(where, (key) => isGroupOp(key)
138
- ? groupClauses(key, where[key]).some((it) => !(it instanceof QuerySql) && this.constrainsRelations(entity, it))
139
- : !!meta.relations[key] || aggregateOf(meta.fields[key]) !== undefined);
143
+ return readsRelations(meta, applyFilters(meta, where ?? {}, this.scopeOptions(opts)));
140
144
  }
145
+ /** `opts` as a scope is merged with: past the policies where the querier is not who holds them. */
146
+ scopeOptions(opts) {
147
+ return this.policies.scopes ? opts : { ...opts, [PAST_POLICIES]: true };
148
+ }
149
+ }
150
+ /** Whether `where` reads a relation of `meta` at any depth, by its key or a relation aggregate. */
151
+ export function readsRelations(meta, where) {
152
+ return someKey(where, (key) => isGroupOp(key)
153
+ ? groupClauses(key, where[key]).some((it) => !(it instanceof QuerySql) && readsRelations(meta, it))
154
+ : !!meta.relations[key] || aggregateOf(meta.fields[key]) !== undefined);
141
155
  }
@@ -1,4 +1,4 @@
1
- import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictKeys, type QueryUpsert, type QueryContext, type QueryContextOptions, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type AbstractType, type UpdatePayload, type ReportedWrite } from '../type/index.js';
1
+ import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type BoundStatement, type Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictKeys, type QueryUpsert, type QueryContext, type QueryContextOptions, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type AbstractType, type UpdatePayload, type ReportedWrite } from '../type/index.js';
2
2
  import { type WriteScope, type SortDirection } from '../util/index.js';
3
3
  import type { HydrateKind } from './hydrateColumn.js';
4
4
  import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
@@ -713,7 +713,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
713
713
  * predicate with no entity filter applied; a migration's is `sql` reading none.
714
714
  */
715
715
  compileDdl(sql: QuerySql): string;
716
- compileDdl<E>(sql: EntityWhereMeta<E>, entity: AbstractType<E>, opts?: DdlRenderOptions): string;
716
+ compileDdl<E>(sql: EntityWhereMeta<E> | QueryWhere<E>, entity: AbstractType<E>, opts?: DdlRenderOptions): string;
717
717
  getRawValue(ctx: QueryContext, opts: QuerySqlFnOptions & {
718
718
  value: QuerySql;
719
719
  }): void;
@@ -840,6 +840,15 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
840
840
  private sizeCondition;
841
841
  /** `<distance> <op> ?`, the `$where` half of a vector search, its bounds checked here since `/http` input is untyped. */
842
842
  private vectorNearCondition;
843
+ /**
844
+ * The statement binding `entries`, each a context key and its text, into the open transaction, where the policies
845
+ * the engine holds read them: none on an engine holding none.
846
+ */
847
+ contextBinding(_entries: readonly (readonly [string, string])[]): BoundStatement | undefined;
848
+ /** A policy's read of context key `key` as a value of SQL type `type`, NULL where the transaction bound none. */
849
+ contextRead(key: string, _type: string): string;
850
+ /** What answers whether the connected role reads past row-level security, as one row's `bypasses`. */
851
+ rowSecurityBypassQuery(): string;
843
852
  /** ANSI-style single-quote escaping. */
844
853
  escape(value: unknown): string;
845
854
  /** The `$regex` predicate, case-sensitive on every engine. */
@@ -521,8 +521,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
521
521
  const local = this.escapeId(join.parent ? this.columnOf(join.parent.meta, reference.local) : this.columnOf(meta, reference.local));
522
522
  ctx.append(`${joinAlias}.${foreign} = ${parentAlias}.${local}`);
523
523
  });
524
- // Unconditional, not gated by `join.query.$where`: a joined relation's own filters (in
525
- // particular `security: true` ones) must apply even to a bare `$populate: { rel: true }`
524
+ // Unconditional, not gated by `join.query.$where`: a joined relation's own filters and
525
+ // policies must apply even to a bare `$populate: { rel: true }`
526
526
  // with no explicit `$where` - and equally to a join `$sort` brought in on its own.
527
527
  // `where()` -> `renderWhere()` no-ops cleanly (appends nothing) when there is nothing to add.
528
528
  this.where(ctx, join.entity, join.query.$where ?? {}, { prefix: join.alias, clause: 'AND' });
@@ -2268,6 +2268,21 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2268
2268
  });
2269
2269
  return this.boundConditions(ctx, distance, comparisons);
2270
2270
  }
2271
+ /**
2272
+ * The statement binding `entries`, each a context key and its text, into the open transaction, where the policies
2273
+ * the engine holds read them: none on an engine holding none.
2274
+ */
2275
+ contextBinding(_entries) {
2276
+ return undefined;
2277
+ }
2278
+ /** A policy's read of context key `key` as a value of SQL type `type`, NULL where the transaction bound none. */
2279
+ contextRead(key, _type) {
2280
+ throw new UqlUsageError(`${this.engineName} reads no context key in SQL, so '${key}' has no rendering`);
2281
+ }
2282
+ /** What answers whether the connected role reads past row-level security, as one row's `bypasses`. */
2283
+ rowSecurityBypassQuery() {
2284
+ throw new UqlUsageError(`${this.engineName} holds no row to a policy itself`);
2285
+ }
2271
2286
  /** ANSI-style single-quote escaping. */
2272
2287
  escape(value) {
2273
2288
  return escapeAnsiSqlLiteral(value);
@@ -49,6 +49,8 @@ export const MYSQL_FEATURES = {
49
49
  deferrable: false,
50
50
  },
51
51
  namedLocks: 'session',
52
+ rowSecurity: false,
53
+ transactions: true,
52
54
  };
53
55
  /** The one `JSON_TABLE` column an exploded array reads each element through, as a JSON document. */
54
56
  const ELEM_COLUMN = 'v';
@@ -1,4 +1,4 @@
1
- import { type EntityMeta, type QueryCompareOp, type QueryGroupOp, type QueryOrderedOp, type QuerySizeComparisonOps, type QueryVectorQuery, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp } from '../type/index.js';
1
+ import { type EntityMeta, type QueryCompareOp, type QueryGroupOp, type QueryOrderedOp, type QuerySizeComparisonOps, type QueryVectorQuery, type QueryWhere, type QueryWhereFieldOp } from '../type/index.js';
2
2
  /**
3
3
  * How each grouping operator renders: the operator joining its clauses, and whether the group is
4
4
  * negated (`$not` is `NOT (a AND b)`). Total over {@link QueryGroupOp}.
@@ -28,7 +28,7 @@ export declare function isGroupOp(key: string): key is QueryGroupOp;
28
28
  * straight to `Query`, so a scalar can arrive where an array belongs. Shared so both backends
29
29
  * refuse the same payload rather than one throwing and the other failing further in.
30
30
  */
31
- export declare function groupClauses<E>(key: QueryGroupOp, val: QueryWhereArray<E> | undefined): QueryWhereArray<E>;
31
+ export declare function groupClauses<T>(key: QueryGroupOp, val: readonly T[] | undefined): readonly T[];
32
32
  /**
33
33
  * Whether a `$where` names any rows, as the WHERE it renders would: an empty operator map and a group
34
34
  * none of whose clauses names one render nothing, which a write reads as the whole table.
@@ -1,5 +1,5 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import type { SqlDialectName, SqlValues } from '../type/index.js';
2
+ import type { BoundStatement, SqlDialectName, SqlValues } from '../type/index.js';
3
3
  import { type DriverCapabilities, type EntityMeta, type FieldOptions, type JsonColumnType, type Query, type QueryContext, type QueryTextSearchOptions, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  import type { DialectOptions } from './abstractDialect.js';
5
5
  import { AbstractSqlDialect, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
@@ -23,6 +23,13 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
23
23
  constructor(options?: PgLikeDialectOptions);
24
24
  readonly features: SqlDialectFeatures;
25
25
  readonly sqlValues: SqlValues;
26
+ /** `set_config(..., true)`: bound to the transaction, so a pooled connection carries none past it. */
27
+ contextBinding(entries: readonly (readonly [string, string])[]): BoundStatement | undefined;
28
+ /** A subselect, so the setting is read once per statement rather than per row; an empty setting is NULL. */
29
+ contextRead(key: string, type: string): string;
30
+ /** Context key `key`'s setting as a value of SQL type `type`, NULL where the transaction bound none. */
31
+ protected settingRead(key: string, type: string): string;
32
+ rowSecurityBypassQuery(): string;
26
33
  /** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
27
34
  protected refusal(message: string): string;
28
35
  readonly escapeIdChar = "\"";
@@ -1,6 +1,8 @@
1
1
  import { QuerySql, } from '../type/index.js';
2
2
  import { fulltextConfig, fulltextIndexOver, hasVectorNear, textSearchFields } from '../util/dialect.util.js';
3
3
  import { isIntegerColumn, jsonPathKeys } from '../util/field.util.js';
4
+ import { contextSetting } from '../util/policy.util.js';
5
+ import { sql } from '../util/sql.js';
4
6
  import { escapePgSqlLiteral, PG_UTC, pgArrayText } from '../util/sqlLiteral.js';
5
7
  import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
6
8
  import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
@@ -50,6 +52,8 @@ export const PG_FEATURES = {
50
52
  deferrable: true,
51
53
  },
52
54
  namedLocks: 'session',
55
+ rowSecurity: { subqueries: true },
56
+ transactions: true,
53
57
  };
54
58
  export const PG_SQL_VALUES = { ...ANSI_SQL_VALUES, uuid: 'gen_random_uuid()' };
55
59
  /** What Postgres and CockroachDB share: JSONB, full-text search, pgvector's operators, and the upsert. */
@@ -66,6 +70,22 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
66
70
  }
67
71
  features = PG_FEATURES;
68
72
  sqlValues = PG_SQL_VALUES;
73
+ /** `set_config(..., true)`: bound to the transaction, so a pooled connection carries none past it. */
74
+ contextBinding(entries) {
75
+ const configs = entries.map(([key, value]) => sql `set_config(${contextSetting(key)}, ${value}, true)`);
76
+ return configs.length ? this.compile(sql `SELECT ${sql.join(configs)}`) : undefined;
77
+ }
78
+ /** A subselect, so the setting is read once per statement rather than per row; an empty setting is NULL. */
79
+ contextRead(key, type) {
80
+ return `(SELECT ${this.settingRead(key, type)})`;
81
+ }
82
+ /** Context key `key`'s setting as a value of SQL type `type`, NULL where the transaction bound none. */
83
+ settingRead(key, type) {
84
+ return `nullif(current_setting(${this.escape(contextSetting(key))}, true), '')::${type}`;
85
+ }
86
+ rowSecurityBypassQuery() {
87
+ return 'SELECT rolsuper OR rolbypassrls AS bypasses FROM pg_roles WHERE rolname = current_user';
88
+ }
69
89
  /** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
70
90
  refusal(message) {
71
91
  return `RAISE EXCEPTION USING MESSAGE = ${message};`;
@@ -1,5 +1,5 @@
1
1
  import type { ForeignKeyAction } from '../schema/types.js';
2
- import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance, type Wire } from '../type/index.js';
2
+ import { COLUMN_OPTIONS, type ColumnType, type ContextKeyRef, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance, type Wire } from '../type/index.js';
3
3
  /**
4
4
  * Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
5
5
  * `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
@@ -15,6 +15,7 @@ export declare class ColumnOptionsBuilder {
15
15
  onUpdate(onUpdate: OnFieldCallback): ColumnOptionsBuilder;
16
16
  updatable(updatable: false): ColumnOptionsBuilder;
17
17
  softDelete(softDelete?: OnFieldCallback): ColumnOptionsBuilder;
18
+ tenant(contextKey?: ContextKeyRef): ColumnOptionsBuilder;
18
19
  unique(): ColumnOptionsBuilder;
19
20
  index(index?: string | false): ColumnOptionsBuilder;
20
21
  name(name: string): ColumnOptionsBuilder;
@@ -32,6 +32,9 @@ export class ColumnOptionsBuilder {
32
32
  softDelete(softDelete) {
33
33
  return this.with({ softDelete: softDelete ?? true });
34
34
  }
35
+ tenant(contextKey) {
36
+ return this.with({ tenant: contextKey?.$context ?? 'tenantId' });
37
+ }
35
38
  unique() {
36
39
  return this.with({ unique: true });
37
40
  }
@@ -139,7 +139,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
139
139
  createdAt: Date;
140
140
  } & {
141
141
  bio?: string | null | undefined;
142
- }, false>;
142
+ }, false, "filters" | "policies">;
143
143
  export interface Author extends InstanceType<typeof Author> {
144
144
  }
145
145
  export declare const label: (author: Author) => string;
@@ -1,4 +1,4 @@
1
- export declare const Book: import("../../../index.js").DefinedClass<object & {
1
+ export declare const Book: import("../../../index.js").RelatedEntity<object & {
2
2
  id: number;
3
3
  title: string;
4
4
  stock: number;
@@ -194,4 +194,4 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
194
194
  authorId: number;
195
195
  } & {} & {
196
196
  readonly shout: string | null;
197
- } & {}, false>;
197
+ } & {}, false, "policies">;
@@ -121,6 +121,6 @@ export declare const Folder: import("../../../index.js").RelatedEntity<object &
121
121
  size: number;
122
122
  } & {
123
123
  parentId?: number | null | undefined;
124
- }, false>;
124
+ }, false, "filters" | "policies">;
125
125
  export interface Folder extends InstanceType<typeof Folder> {
126
126
  }
@@ -1,6 +1,7 @@
1
1
  import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
2
2
  import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
3
  import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, isRecord, whereWith, } from '../../util/index.js';
4
+ import { contextKeys, EVERY_ROW_POLICY, POLICY_CONTEXT_KEY, POLICY_OPS, policyMeta, TENANT_POLICY, tenantPolicy, } from '../../util/policy.util.js';
4
5
  import { UqlUsageError } from '../../util/uqlError.js';
5
6
  import { ownRegistrations } from '../decorator/bag.js';
6
7
  /**
@@ -107,9 +108,7 @@ function addTrigger(meta, { [SECTION_ENTRY]: _entry, ...trigger }) {
107
108
  if (typeof trigger.run !== 'function' && !hasKeys(trigger.run)) {
108
109
  throw new UqlUsageError(`'${entity.name}' has a trigger whose body names at least one engine to run on`);
109
110
  }
110
- if (trigger.name && meta.triggers?.some((it) => it.name === trigger.name)) {
111
- throw new UqlUsageError(`'${entity.name}' already has a trigger named '${trigger.name}'`);
112
- }
111
+ assertUnnamed(meta, 'trigger', meta.triggers, trigger.name);
113
112
  (meta.triggers ??= []).push({ ...trigger, of: trigger.of?.map((ref) => ref[REF_KEY]) });
114
113
  }
115
114
  function addFilter(meta, name, opts) {
@@ -117,13 +116,47 @@ function addFilter(meta, name, opts) {
117
116
  if (name === SOFT_DELETE_FILTER) {
118
117
  throw new UqlUsageError(`'${entity.name}' filter name '${SOFT_DELETE_FILTER}' is reserved; a 'softDelete()' column registers it`);
119
118
  }
120
- // Widened for a caller the types did not reach, which is the only one this can refuse.
121
- const { security, onMissing } = opts;
122
- if (security && onMissing === 'skip') {
123
- throw new UqlUsageError(`'${entity.name}' security filter '${name}' cannot use onMissing: 'skip' (it must fail closed)`);
119
+ // Widened for a caller the types did not reach: a filter that held security is a policy now.
120
+ if (Object.hasOwn(opts, 'security')) {
121
+ throw new UqlUsageError(`'${entity.name}' filter '${name}' names security: what must hold whatever a call asks is a policy, in .policies()`);
124
122
  }
125
123
  (meta.filters ??= {})[name] = opts;
126
124
  }
125
+ /** Registers a policy, refusing one stating no single effect, a name taken and a statement no policy holds. */
126
+ function addPolicy(meta, declared) {
127
+ const { entity } = meta;
128
+ const policy = policyMeta(declared);
129
+ if (!policy || (declared.allow !== undefined && declared.must !== undefined)) {
130
+ throw new UqlUsageError(`'${entity.name}' has a policy stating none or both of allow and must: state one`);
131
+ }
132
+ const unknown = policy.ops.find((op) => !POLICY_OPS.includes(op));
133
+ if (unknown !== undefined || !policy.ops.length) {
134
+ throw new UqlUsageError(`'${entity.name}' has a policy holding '${String(unknown ?? 'no statement')}': name read, insert, update or delete`);
135
+ }
136
+ if (policy.name === TENANT_POLICY || policy.name === EVERY_ROW_POLICY) {
137
+ throw new UqlUsageError(`'${entity.name}' policy name '${policy.name}' is reserved for the policies uql derives`);
138
+ }
139
+ assertUnnamed(meta, 'policy', meta.policies, policy.name);
140
+ const misnamed = [...contextKeys([policy.where, policy.check]), ...Object.keys(policy.when ?? {})].find((key) => !POLICY_CONTEXT_KEY.test(key));
141
+ if (misnamed !== undefined) {
142
+ throw new UqlUsageError(`'${entity.name}' has a policy reading context key '${misnamed}': name keys as identifiers`);
143
+ }
144
+ (meta.policies ??= []).push(policy);
145
+ }
146
+ /** The one field of `meta` `marks` picks, refusing a second: a row has one of each `option`. */
147
+ function soleMarked(meta, option, marks) {
148
+ const keys = fieldKeys(meta, marks);
149
+ if (keys.length > 1) {
150
+ throw new UqlUsageError(`'${meta.entity.name}' must have at most one field with '${option}'`);
151
+ }
152
+ return keys[0];
153
+ }
154
+ /** Refuses `name` where one of `taken`, the entity's triggers or policies, already has it. */
155
+ function assertUnnamed({ entity }, kind, taken, name) {
156
+ if (name && taken?.some((it) => it.name === name)) {
157
+ throw new UqlUsageError(`'${entity.name}' already has a ${kind} named '${name}'`);
158
+ }
159
+ }
127
160
  /** Registers the fields, relations and hooks decorators or `defineEntity` declared, before anything is finalized. */
128
161
  function applyMembers(meta, members) {
129
162
  for (const [key, spec] of definedEntries(members?.fields ?? {})) {
@@ -181,7 +214,7 @@ export function defineEntity(options) {
181
214
  return entity;
182
215
  }
183
216
  /** The sections a defined entity declares as methods. `aggregates` is no method: `relations` takes it as its second argument. */
184
- const SECTIONS = ['computed', 'indexes', 'checks', 'triggers', 'filters', 'hooks', 'relations'];
217
+ const SECTIONS = ['computed', 'indexes', 'checks', 'triggers', 'filters', 'policies', 'hooks', 'relations'];
185
218
  /** Records one section of a pending defined entity, refusing a second of it and one declared after the entity was read. */
186
219
  function declareSection(entity, section, declared) {
187
220
  const pending = pendingEntity(entity);
@@ -225,6 +258,7 @@ function settleEntity(entity) {
225
258
  checks: sections.checks,
226
259
  triggers: sections.triggers,
227
260
  filters: sections.filters,
261
+ policies: sections.policies,
228
262
  }, {
229
263
  fields,
230
264
  hooks: Object.fromEntries(definedEntries(sections.hooks ?? {}).map(([event, runs]) => [event, runs.map((run) => ({ run }))])),
@@ -323,6 +357,9 @@ export function registerEntity(entity, opts = {}, members) {
323
357
  for (const [name, filter] of definedEntries(opts.filters ?? {})) {
324
358
  addFilter(meta, name, filter);
325
359
  }
360
+ for (const policy of opts.policies ?? []) {
361
+ addPolicy(meta, policy);
362
+ }
326
363
  // `derivedName` records that the class name stood in, which is what a naming strategy derives from.
327
364
  meta.name = table;
328
365
  meta.derivedName = opts.name === undefined;
@@ -339,28 +376,29 @@ export function registerEntity(entity, opts = {}, members) {
339
376
  throw new UqlUsageError(`'${entity.name}.${key}' measures by '${field.distance}', but its vector index ranks by '${ranked}': name one metric`);
340
377
  }
341
378
  }
342
- // Derive soft-delete from the (inheritance-merged) fields, so own and inherited markers are handled
343
- // uniformly. Exactly one field may be marked; it auto-registers the built-in `softDelete` read
344
- // filter (a reserved name - see addFilter - so it never clobbers a user filter).
345
- const softDeleteKeys = fieldKeys(meta, ({ softDelete }) => softDelete !== undefined && softDelete !== false);
346
- if (softDeleteKeys.length > 1) {
347
- throw new UqlUsageError(`'${entity.name}' must have at most one field with 'softDelete'`);
348
- }
349
- if (softDeleteKeys.length) {
350
- meta.softDelete = softDeleteKeys[0];
351
- (meta.filters ??= {})[SOFT_DELETE_FILTER] = { where: whereWith(meta.softDelete, null), default: true };
352
- }
353
- // The optimistic lock, derived the same way and just as singular: one row has one version.
354
- const versionKeys = fieldKeys(meta, (field) => field.version);
355
- if (versionKeys.length > 1) {
356
- throw new UqlUsageError(`'${entity.name}' must have at most one field with 'version'`);
357
- }
358
- if (versionKeys.length) {
359
- meta.version = versionKeys[0];
360
- // Implied rather than stated: the DDL default covers a row written around the ORM, and `onInsert`
361
- // covers MongoDB, which has no DDL to default. Both, so every backend starts a row at the same 0.
362
- const field = meta.fields[meta.version];
363
- meta.fields[meta.version] = { ...field, defaultValue: 0, onInsert: 0 };
379
+ // Each marker is derived from the inheritance-merged fields, own and inherited alike, and marks one field at most.
380
+ // Soft delete registers the reserved `softDelete` filter (see addFilter), so it never clobbers a user's own.
381
+ const softDelete = soleMarked(meta, 'softDelete', ({ softDelete }) => softDelete !== undefined && softDelete !== false);
382
+ if (softDelete) {
383
+ meta.softDelete = softDelete;
384
+ (meta.filters ??= {})[SOFT_DELETE_FILTER] = { where: whereWith(softDelete, null), default: true };
385
+ }
386
+ // The tenant: a `must` holding each row to the context's tenant, replacing an inherited one.
387
+ const tenant = soleMarked(meta, 'tenant', (field) => field.tenant !== undefined);
388
+ if (tenant) {
389
+ const contextKey = meta.fields[tenant].tenant;
390
+ if (!POLICY_CONTEXT_KEY.test(contextKey)) {
391
+ throw new UqlUsageError(`'${entity.name}' reads its tenant off context key '${contextKey}': name it as an identifier`);
392
+ }
393
+ const own = (meta.policies ?? []).filter((policy) => policy.name !== TENANT_POLICY);
394
+ meta.policies = [tenantPolicy(tenant, contextKey), ...own];
395
+ }
396
+ // The optimistic lock, a default stated rather than implied: the DDL default covers a row written around the ORM,
397
+ // and `onInsert` covers MongoDB, which has no DDL to default, so every backend starts a row at the same 0.
398
+ const version = soleMarked(meta, 'version', (field) => field.version);
399
+ if (version) {
400
+ meta.version = version;
401
+ meta.fields[meta.version] = { ...meta.fields[meta.version], defaultValue: 0, onInsert: 0 };
364
402
  }
365
403
  const ids = getIdKeys(meta);
366
404
  if (!ids.length && !meta.abstract) {
@@ -797,6 +835,7 @@ function extendMeta(target, source) {
797
835
  }
798
836
  target.indexes = inheritedEntries(source.indexes, target.indexes, (index) => index.name);
799
837
  target.checks = inheritedEntries(source.checks, target.checks, (check) => check.name);
838
+ target.policies = inheritedEntries(source.policies, target.policies, (policy) => policy.name);
800
839
  target.triggers = inheritedEntries(source.triggers, target.triggers, (trigger) => trigger.name);
801
840
  }
802
841
  /** `source`'s entries ahead of `own`, each once, and a same-named `own` entry replaces its base's. */
@@ -13,7 +13,7 @@ export type ApiOptions<Ctx = unknown> = EntityPathOptions & {
13
13
  use?: readonly ApiMiddleware<Ctx>[];
14
14
  /**
15
15
  * Derive the ambient {@link UqlContext} (e.g. `{ tenantId, userId }`) from the transport's context, which the whole
16
- * call then runs inside, so `security` filters scope it. Derive it from a verified source (a session, a JWT).
16
+ * call then runs inside, so policies scope it. Derive it from a verified source (a session, a JWT).
17
17
  * Without it, a call runs in whatever context its caller set (a tRPC middleware's).
18
18
  */
19
19
  contextOf?: (context: Ctx) => UqlContext | undefined | Promise<UqlContext | undefined>;
@@ -7,7 +7,7 @@ import { UqlUsageError } from '../util/uqlError.js';
7
7
  /**
8
8
  * The keys a query takes from the wire, with the type of each: every query clause ({@link QUERY_CLAUSES}) the wire
9
9
  * carries. Any other key is refused: dropping a clause answers a read other than the one asked for, and `filters` or
10
- * `context` would bypass a security filter or inject ambient context.
10
+ * `context` would skip a filter or inject ambient context.
11
11
  */
12
12
  const WIRE_VALUES = new Map(getKeys(QUERY_CLAUSES)
13
13
  .filter((key) => carriedOverHttp(QUERY_CLAUSES[key]))
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { captureContext, getContext, withContext } from './context/context.js';
2
+ export { explainPolicies } from './util/policy.util.js';
3
+ export { $context } from './util/contextRefs.js';
2
4
  export * from './entity/decorator/entity.js';
3
5
  export * from './entity/decorator/members.js';
4
6
  export { f } from './entity/column.js';
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { captureContext, getContext, withContext } from './context/context.js';
2
+ export { explainPolicies } from './util/policy.util.js';
3
+ export { $context } from './util/contextRefs.js';
2
4
  export * from './entity/decorator/entity.js';
3
5
  export * from './entity/decorator/members.js';
4
6
  export { f } from './entity/column.js';
@@ -43,6 +43,11 @@ export declare class TableDdl {
43
43
  * changes a column only by rebuilding its table, which a diff states as `rebuild`.
44
44
  */
45
45
  protected alterClauses(column: ColumnSchema, _from?: ColumnSchema): string[];
46
+ /**
47
+ * What switches `table`'s row-level security on, forced so its owner is held too, or off: on with its first policy,
48
+ * off with its last, since forced with none it shows no row to anyone.
49
+ */
50
+ rowSecurity(table: string, on: boolean): string[];
46
51
  /** One `ALTER TABLE` making every clause, and none for no clause. */
47
52
  protected alterTable(table: string, clauses: readonly string[]): string[];
48
53
  renameColumn(table: string, oldName: string, newName: string): string;