uql-orm 0.116.3 → 0.116.4

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.
@@ -10,11 +10,11 @@ export declare class CockroachDialect extends PgLikeSqlDialect {
10
10
  rowSecurityApplies(): string;
11
11
  /**
12
12
  * pgvector's but `l1`: `<+>` and `vector_l1_ops` answer "unimplemented: operator class ... is not
13
- * supported" (verified live on v26.2), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
13
+ * supported" (verified live on v26.4), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
14
14
  * Re-check that issue before adding it.
15
15
  */
16
16
  readonly vectorMetrics: Map<import("../type/vector.js").VectorDistance, import("../type/vector.js").VectorMetric>;
17
- /** Neither `regconfig` nor `WEBSEARCH_TO_TSQUERY` exist here (v26.3): the config goes as text, the search as plain words. */
17
+ /** Neither `regconfig` nor `WEBSEARCH_TO_TSQUERY` exist here (v26.4): the config goes as text, the search as plain words. */
18
18
  protected readonly textConfigCast = "";
19
19
  protected readonly textQueryFn = "PLAINTO_TSQUERY";
20
20
  /** Its own beam for either type that builds its vector index; it refuses pgvector's `hnsw.ef_search`. */
@@ -23,7 +23,7 @@ export declare class CockroachDialect extends PgLikeSqlDialect {
23
23
  readonly features: SqlDialectFeatures;
24
24
  /**
25
25
  * Not Postgres' `pg_class.reltuples`, which CockroachDB answers `NULL` for even straight after an
26
- * `ANALYZE` (verified live on v26.2) - it keeps its optimizer's row counts in its own statistics
26
+ * `ANALYZE` (verified live on v26.4) - it keeps its optimizer's row counts in its own statistics
27
27
  * instead, and `SHOW STATISTICS` is how they are read. Bracketed so it can be selected from; the
28
28
  * newest row wins, and a table never analyzed has none at all, which reads as `0`.
29
29
  */
@@ -14,11 +14,11 @@ export class CockroachDialect extends PgLikeSqlDialect {
14
14
  }
15
15
  /**
16
16
  * pgvector's but `l1`: `<+>` and `vector_l1_ops` answer "unimplemented: operator class ... is not
17
- * supported" (verified live on v26.2), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
17
+ * supported" (verified live on v26.4), tracked at https://github.com/cockroachdb/cockroach/issues/147839.
18
18
  * Re-check that issue before adding it.
19
19
  */
20
20
  vectorMetrics = new Map([...PG_VECTOR_METRICS].filter(([metric]) => metric !== 'l1'));
21
- /** Neither `regconfig` nor `WEBSEARCH_TO_TSQUERY` exist here (v26.3): the config goes as text, the search as plain words. */
21
+ /** Neither `regconfig` nor `WEBSEARCH_TO_TSQUERY` exist here (v26.4): the config goes as text, the search as plain words. */
22
22
  textConfigCast = '';
23
23
  textQueryFn = 'PLAINTO_TSQUERY';
24
24
  /** Its own beam for either type that builds its vector index; it refuses pgvector's `hnsw.ef_search`. */
@@ -36,7 +36,7 @@ export class CockroachDialect extends PgLikeSqlDialect {
36
36
  };
37
37
  /**
38
38
  * Not Postgres' `pg_class.reltuples`, which CockroachDB answers `NULL` for even straight after an
39
- * `ANALYZE` (verified live on v26.2) - it keeps its optimizer's row counts in its own statistics
39
+ * `ANALYZE` (verified live on v26.4) - it keeps its optimizer's row counts in its own statistics
40
40
  * instead, and `SHOW STATISTICS` is how they are read. Bracketed so it can be selected from; the
41
41
  * newest row wins, and a table never analyzed has none at all, which reads as `0`.
42
42
  */
@@ -9,18 +9,33 @@ function typesWith(types, features) {
9
9
  return new Map(types.map((type) => [type, expressed]));
10
10
  }
11
11
  const DECLARE_VECTOR = "; declare type: 'vector' instead";
12
+ /** What every Postgres index type takes. Only `btree` and `gist` add `INCLUDE`, and only `btree` a nulls order. */
13
+ const PG_INDEX_FEATURES = ['expression', 'partial', 'opsClass', 'jsonPath'];
14
+ /** CockroachDB's, which has no operator class. Neither an inverted nor a vector index takes `INCLUDE`. */
15
+ const CRDB_INDEX_FEATURES = ['expression', 'partial', 'jsonPath'];
12
16
  /** Each engine's {@link IndexCapabilities}, total over the engines. */
13
17
  export const INDEX_CAPABILITIES = {
14
18
  /** Postgres 18's `pg_am`, with pgvector's two, and `fulltext`, which builds a `gin` one. */
15
19
  postgres: {
16
- types: typesWith(['btree', 'hash', 'gin', 'gist', 'brin', 'hnsw', 'ivfflat', 'fulltext'], ['expression', 'partial', 'nullsOrder', 'opsClass', 'include', 'jsonPath']),
20
+ types: new Map([
21
+ ...typesWith(['btree'], [...PG_INDEX_FEATURES, 'include', 'nullsOrder']),
22
+ ...typesWith(['gist'], [...PG_INDEX_FEATURES, 'include']),
23
+ ...typesWith(['hash', 'gin', 'brin', 'hnsw', 'ivfflat', 'fulltext'], PG_INDEX_FEATURES),
24
+ ]),
17
25
  keywords: NONE,
18
26
  hints: NONE,
19
27
  inline: false,
20
28
  },
21
- /** v26.3 answers `hash` and `brin` "unimplemented", `ivfflat` "unrecognized"; no nulls order nor operator class. */
29
+ /**
30
+ * v26.4 answers `brin` "unimplemented" and `ivfflat` "unrecognized". A `hash` index is hash-sharded, spreading
31
+ * sequential keys over 16 buckets, and keys on no computed column.
32
+ */
22
33
  cockroachdb: {
23
- types: typesWith(['btree', 'gin', 'gist', 'hnsw', 'vector', 'fulltext'], ['expression', 'partial', 'include', 'jsonPath']),
34
+ types: new Map([
35
+ ...typesWith(['btree'], [...CRDB_INDEX_FEATURES, 'include']),
36
+ ...typesWith(['hash'], ['partial', 'include']),
37
+ ...typesWith(['gin', 'gist', 'hnsw', 'vector', 'fulltext'], CRDB_INDEX_FEATURES),
38
+ ]),
24
39
  keywords: new Map([['vector', 'VECTOR INDEX']]),
25
40
  hints: new Map([['ivfflat', DECLARE_VECTOR]]),
26
41
  inline: true,
@@ -17,6 +17,9 @@ export declare class PgIndexDdl extends IndexDdl {
17
17
  /** CockroachDB's native `CREATE VECTOR INDEX`, for `type: 'vector'`; it has neither `NULLS FIRST/LAST` nor `jsonb_path_ops`. */
18
18
  export declare class CockroachIndexDdl extends PgIndexDdl {
19
19
  protected isVectorIndex(index: IndexSchema): boolean;
20
+ /** Hash-sharded: `(a) USING hash INCLUDE (b)`, since `USING hash (a)` answers "unimplemented". */
21
+ protected indexAccessMethod(index: IndexSchema): string;
22
+ protected indexInclude(index: IndexSchema): string;
20
23
  /** Its build-time candidate list alone: pgvector's `WITH (m = 16)` answers "invalid storage parameter", `hnsw` included. */
21
24
  protected indexTuning(index: IndexSchema): string;
22
25
  }
@@ -54,6 +54,13 @@ export class CockroachIndexDdl extends PgIndexDdl {
54
54
  isVectorIndex(index) {
55
55
  return index.type === 'vector' || super.isVectorIndex(index);
56
56
  }
57
+ /** Hash-sharded: `(a) USING hash INCLUDE (b)`, since `USING hash (a)` answers "unimplemented". */
58
+ indexAccessMethod(index) {
59
+ return index.type === 'hash' ? '' : super.indexAccessMethod(index);
60
+ }
61
+ indexInclude(index) {
62
+ return (index.type === 'hash' ? ' USING hash' : '') + super.indexInclude(index);
63
+ }
57
64
  /** Its build-time candidate list alone: pgvector's `WITH (m = 16)` answers "invalid storage parameter", `hnsw` included. */
58
65
  indexTuning(index) {
59
66
  return this.isVectorIndex(index) && index.efConstruction !== undefined
@@ -35,6 +35,8 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
35
35
  protected getColumns(read: TableRowReader, tableName: string): Promise<ReadColumn[]>;
36
36
  /** Whether `information_schema.columns c` lists a column the table shows: every one, on Postgres. */
37
37
  protected readonly visibleColumnSql: QuerySql;
38
+ /** Whether index entry `a` is a column the table shows, or an expression: every one, on Postgres. */
39
+ protected readonly visibleIndexEntrySql: QuerySql;
38
40
  /**
39
41
  * `attname` where the entry is a column, `pg_get_indexdef` for that one position where it is an
40
42
  * expression. Neither alone will do: an expression entry has `attnum = 0`, so joining `pg_attribute`
@@ -72,7 +74,7 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
72
74
  protected isAutoIncrement(columnDefault: string | null, isIdentity: string): boolean;
73
75
  }
74
76
  /**
75
- * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.2.5
77
+ * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.4
76
78
  * still rejects `NULLS FIRST/LAST` and operator classes as "unimplemented", and it sorts nulls first
77
79
  * on an ASC column where Postgres sorts them last. Reading a nulls order back would therefore report
78
80
  * every ascending index as drifted, against an entity that could not have asked for one.
@@ -81,11 +83,13 @@ export declare class CockroachSchemaIntrospector extends PostgresSchemaIntrospec
81
83
  protected readonly indexFacets: ReadonlySet<IndexFacet>;
82
84
  /** Not `rowid`, the `NOT VISIBLE` key it gives a table declared without one, which no entity can name. */
83
85
  protected readonly visibleColumnSql: QuerySql;
86
+ /** Not the hidden shard column a hash-sharded index keys on first. */
87
+ protected readonly visibleIndexEntrySql: QuerySql;
84
88
  /** None: it rejects a stated nulls order, so reading one back gives an index it would refuse to rebuild. */
85
89
  protected readonly nullsFirstSql: QuerySql;
86
90
  /**
87
- * Every index reports the access method `prefix` and no operator class, so a vector index is read off
88
- * its definition, `USING cspann (vec vector_cosine_ops)`: its type, and its last key's class.
91
+ * Every index reports the access method `prefix` and no operator class, so its type is read off its definition:
92
+ * `USING cspann (vec vector_cosine_ops)` a vector one, with its last key's class, and `(a) USING HASH` a hash one.
89
93
  */
90
94
  protected readonly indexMethodSql: QuerySql;
91
95
  protected readonly opsClassSql: QuerySql;
@@ -132,6 +132,8 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
132
132
  }
133
133
  /** Whether `information_schema.columns c` lists a column the table shows: every one, on Postgres. */
134
134
  visibleColumnSql = sql `TRUE`;
135
+ /** Whether index entry `a` is a column the table shows, or an expression: every one, on Postgres. */
136
+ visibleIndexEntrySql = sql `TRUE`;
135
137
  /**
136
138
  * `attname` where the entry is a column, `pg_get_indexdef` for that one position where it is an
137
139
  * expression. Neither alone will do: an expression entry has `attnum = 0`, so joining `pg_attribute`
@@ -170,6 +172,7 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
170
172
  AND NOT EXISTS (
171
173
  SELECT 1 FROM pg_constraint con WHERE con.conindid = ix.indexrelid AND con.contype = 'x'
172
174
  )
175
+ AND ${this.visibleIndexEntrySql}
173
176
  ORDER BY i.relname, k.n
174
177
  `);
175
178
  // One row per index entry, ordered by position, so the rows of an index are its entries in order.
@@ -345,7 +348,7 @@ function mapIndexEntry(row) {
345
348
  };
346
349
  }
347
350
  /**
348
- * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.2.5
351
+ * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.4
349
352
  * still rejects `NULLS FIRST/LAST` and operator classes as "unimplemented", and it sorts nulls first
350
353
  * on an ASC column where Postgres sorts them last. Reading a nulls order back would therefore report
351
354
  * every ascending index as drifted, against an entity that could not have asked for one.
@@ -356,15 +359,22 @@ export class CockroachSchemaIntrospector extends PostgresSchemaIntrospector {
356
359
  'include',
357
360
  'vector',
358
361
  'distance',
362
+ 'hash',
359
363
  ]);
360
364
  /** Not `rowid`, the `NOT VISIBLE` key it gives a table declared without one, which no entity can name. */
361
365
  visibleColumnSql = sql `c.is_hidden = 'NO'`;
366
+ /** Not the hidden shard column a hash-sharded index keys on first. */
367
+ visibleIndexEntrySql = sql `(a.attname IS NULL OR NOT EXISTS (
368
+ SELECT 1 FROM information_schema.columns c
369
+ WHERE c.table_schema = n.nspname AND c.table_name = t.relname AND c.column_name = a.attname AND c.is_hidden = 'YES'
370
+ ))`;
362
371
  /** None: it rejects a stated nulls order, so reading one back gives an index it would refuse to rebuild. */
363
372
  nullsFirstSql = sql `NULL::BOOL`;
364
373
  /**
365
- * Every index reports the access method `prefix` and no operator class, so a vector index is read off
366
- * its definition, `USING cspann (vec vector_cosine_ops)`: its type, and its last key's class.
374
+ * Every index reports the access method `prefix` and no operator class, so its type is read off its definition:
375
+ * `USING cspann (vec vector_cosine_ops)` a vector one, with its last key's class, and `(a) USING HASH` a hash one.
367
376
  */
368
- indexMethodSql = sql `CASE WHEN pg_get_indexdef(ix.indexrelid) LIKE '% USING cspann %' THEN 'vector' ELSE am.amname END`;
377
+ indexMethodSql = sql `CASE substring(pg_get_indexdef(ix.indexrelid) from ' USING (cspann|HASH)')
378
+ WHEN 'cspann' THEN 'vector' WHEN 'HASH' THEN 'hash' ELSE am.amname END`;
369
379
  opsClassSql = sql `CASE WHEN k.n = ix.indnkeyatts THEN substring(pg_get_indexdef(ix.indexrelid) from '(\\w+_ops)\\)') END`;
370
380
  }
@@ -15,7 +15,8 @@ const mysqlLock = (name) => {
15
15
  };
16
16
  /**
17
17
  * The journal's lock row, inserted only where it is absent, which one run alone can: the lock of an engine with no
18
- * named one. CockroachDB's write to it cannot stay uncommitted for the run, which a function it creates would wait on.
18
+ * usable named one. CockroachDB's advisory lock held for a session excludes nobody, and one held by a transaction, or
19
+ * an uncommitted write to this row, stalls the run's own DDL on its other connection (verified on v26.4).
19
20
  */
20
21
  const journalRowLock = (name) => {
21
22
  const { table, name: column } = journalIds(name);
@@ -36,7 +36,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
36
36
  * The collection's metadata count, which the driver exposes as its own call and which takes no
37
37
  * filter - the reason {@link UniversalQuerier.estimatedCount} takes none either.
38
38
  */
39
- estimatedCount<E extends Document>(entity: Type<E>): Promise<number>;
39
+ protected internalEstimatedCount<E extends Document>(entity: Type<E>): Promise<number>;
40
40
  internalInsertMany<E extends Document>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
41
41
  internalUpdateMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, payload: UpdatePayload<E>, opts?: StatementOptions): Promise<number>;
42
42
  /** The filter and update of an update of the documents matching `where` with `payload`, its `onUpdate` fills included. */
@@ -134,7 +134,7 @@ export class MongodbQuerier extends AbstractQuerier {
134
134
  * The collection's metadata count, which the driver exposes as its own call and which takes no
135
135
  * filter - the reason {@link UniversalQuerier.estimatedCount} takes none either.
136
136
  */
137
- async estimatedCount(entity) {
137
+ async internalEstimatedCount(entity) {
138
138
  return this.execute('estimatedCount', (session) => this.collection(entity).estimatedDocumentCount({ session }));
139
139
  }
140
140
  async internalInsertMany(entity, rows) {
@@ -113,8 +113,9 @@ export declare abstract class AbstractQuerier implements Querier {
113
113
  }, Q>, opts?: QueryOptions): Promise<QueryAggregateResult<E, Q>[]>;
114
114
  aggregate<E extends object, const Q extends QueryAggregate<E>>(entity: Type<E>, q: Captured<QueryAggregate<E, Q>, Q>, opts?: QueryOptions): Promise<QueryAggregateResult<E, Q>[]>;
115
115
  protected abstract internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
116
- /** Abstract outright: nothing is shared to do around it. See {@link UniversalQuerier.estimatedCount}. */
117
- abstract estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
116
+ /** See {@link UniversalQuerier.estimatedCount}, refused where the pool holds the entity's policies, as CockroachDB's is. */
117
+ estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
118
+ protected abstract internalEstimatedCount<E extends object>(entity: Type<E>): Promise<number>;
118
119
  insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written']>;
119
120
  insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written'][]>;
120
121
  /**
@@ -334,6 +334,14 @@ export class AbstractQuerier {
334
334
  aggregate(...args) {
335
335
  return this.internalAggregate(...entityArgs(args));
336
336
  }
337
+ /** See {@link UniversalQuerier.estimatedCount}, refused where the pool holds the entity's policies, as CockroachDB's is. */
338
+ async estimatedCount(entity) {
339
+ const { scopes, database } = this.dialect.policies;
340
+ if ((scopes || database) && getMeta(entity).policies?.length) {
341
+ throw new UqlSecurityError(`cannot estimate '${entity.name}', which its policies hold: count it instead`);
342
+ }
343
+ return this.internalEstimatedCount(entity);
344
+ }
337
345
  async insertOne(entity, payload, opts) {
338
346
  const [written] = await this.insertWritten(entity, [payload], opts);
339
347
  return written;
@@ -112,7 +112,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
112
112
  */
113
113
  private runCount;
114
114
  protected internalCount<E extends object>(entity: Type<E>, q: QueryPage<E>, opts?: StatementOptions): Promise<number>;
115
- estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
115
+ protected internalEstimatedCount<E extends object>(entity: Type<E>): Promise<number>;
116
116
  protected internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: StatementOptions): Promise<RawRow[]>;
117
117
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
118
118
  /**
@@ -334,7 +334,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
334
334
  async internalCount(entity, q, opts) {
335
335
  return this.runCount((ctx) => this.dialect.count(ctx, entity, q, opts));
336
336
  }
337
- async estimatedCount(entity) {
337
+ async internalEstimatedCount(entity) {
338
338
  return this.runCount((ctx) => this.dialect.estimatedCount(ctx, entity));
339
339
  }
340
340
  async internalAggregate(entity, q, opts) {
@@ -3,10 +3,10 @@ import type { IndexNode, TableNode } from './types.js';
3
3
  /**
4
4
  * What an introspector reports about an index, and so all a diff may compare; apart from `IndexFeature`, what an engine emits.
5
5
  * `vector` is whether it is a vector index at all, for an engine with one vector index whatever type declared it;
6
- * `distance` is the metric a vector index was built for.
6
+ * `distance` is the metric a vector index was built for. `hash` is whether it is hash-sharded, for an engine reading no other type.
7
7
  * `textIndex` is a text index's weights and language, kept by an engine that lists its fields in no declared order.
8
8
  */
9
- export type IndexFacet = 'order' | 'nulls' | 'opsClass' | 'accessMethod' | 'include' | 'vector' | 'distance' | 'textIndex';
9
+ export type IndexFacet = 'order' | 'nulls' | 'opsClass' | 'accessMethod' | 'include' | 'vector' | 'distance' | 'hash' | 'textIndex';
10
10
  type ComparableIndex = Pick<IndexNode, 'name' | 'entries' | 'unique' | 'where'>;
11
11
  /**
12
12
  * Whether the table has this index already, by shape rather than name, uniqueness included. An index
@@ -129,6 +129,10 @@ export function describeIndexDifferences(source, target, facets) {
129
129
  const [expected, actual] = [source, target].map((index) => (isVectorIndexType(index.type) ? 'yes' : 'no'));
130
130
  differences.push(`vector index: ${actual} -> ${expected}`);
131
131
  }
132
+ if (facets.has('hash') && (source.type === 'hash') !== (target.type === 'hash')) {
133
+ const [expected, actual] = [source, target].map((index) => (index.type === 'hash' ? 'yes' : 'no'));
134
+ differences.push(`hash-sharded: ${actual} -> ${expected}`);
135
+ }
132
136
  if (facets.has('include')) {
133
137
  // Order carries no meaning in an `INCLUDE` list, so it is compared as a set.
134
138
  const [sourceInclude, targetInclude] = [source.include ?? [], target.include ?? []].map((columns) => [...columns].sort().join(', '));
@@ -125,7 +125,8 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
125
125
  aggregate<E extends object, const Q extends QueryAggregate<E>>(entity: Type<E>, q: Captured<QueryAggregate<E, Q>, Q>, opts?: QueryOptions): Promise<QueryAggregateResult<E, Q>[]>;
126
126
  /**
127
127
  * The table's row count as the engine's statistics state it, without reading a row: approximate, as
128
- * stale as the last `ANALYZE`, and unfiltered, so soft-deleted rows count. SQLite has none and throws.
128
+ * stale as the last `ANALYZE`, and unfiltered, so soft-deleted rows count. SQLite has none and throws, and it is
129
+ * refused for an entity whose policies the pool holds, since it would count the rows they hide.
129
130
  */
130
131
  estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
131
132
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.116.3",
6
+ "version": "0.116.4",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -189,7 +189,7 @@ await withContext({ tenantId: 42, userId: 'u1' }, () => pool.findMany(Invoice, {
189
189
  - A policy is data: `{ allow: where }` or `{ must: where }`, beside `ops` (`'read'`, `'insert'`, `'update'`, `'delete'`, every one where unset), `when` (context keys at a value, or one of a list) and `name`. Its `where` holds every row a statement touches, found and written; `$old: {...}` in it holds only the row as found (a row failing it is not reached) and `$new: {...}` only the row as written (a write failing it is refused). A read or delete sees `$old`, an insert `$new`, an update both. A group pairing both, `$or: [{ $old: ... }, { $new: ... }]`, is a transition: only in a `must` with `ops: ['update']`, held on every engine (natively by a trigger), soft deletes included. There is no `check`. A row is reached when any `allow` holding the statement reaches it and every `must` holds. An entity declaring no `allow` is allowed every row its `must`s (and tenant) leave; one declaring some reaches no row in a statement none of them holds. An update or delete is held to the `read` ones too. A soft delete is an update: the `update` policies hold it, and `delete` ones a hard delete. `{}` reaches every row. A policy stated once as a constant serves every entity with the fields it names.
190
190
  - `explainPolicies(Invoice, 'update')` answers what the policies hold a statement to under the ambient context, as a policy states it: `$old` the rows it reaches, `$new` what a row it writes must hold, `$and` an update's transitions. What to look at when a read reaches no row.
191
191
  - `$context.tenantId` reads the context key in a predicate, typed by `UqlContext`: once it declares keys, a misspelled one, or one in `when`, does not compile; a relation is read like any `$where` (`{ allow: { members: { userId: $context.userId } } }`). A key the context lacks or holds null matches nothing, as SQL's NULL compares: no context, no rows.
192
- - Policies hold every read, populate, relation filter and count, and every write: an insert gets each field a policy pins to one value (`companyId`), a write setting another is refused with `UqlSecurityError`, and a `$new` condition the row alone cannot settle, or a transition, is read in the write's transaction (MongoDB needs `transaction()` for one; D1 refuses it). Nothing per call turns a policy off: run trusted, cross-tenant work on a pool built with `{ policies: false }`.
192
+ - Policies hold every read, populate, relation filter and count, and every write: an insert gets each field a policy pins to one value (`companyId`), a write setting another is refused with `UqlSecurityError`, and a `$new` condition the row alone cannot settle, or a transition, is read in the write's transaction (MongoDB needs `transaction()` for one; D1 refuses it). Nothing per call turns a policy off: run trusted, cross-tenant work on a pool built with `{ policies: false }`. `estimatedCount` throws for an entity whose policies the pool holds, since it counts the rows they hide: use `count`.
193
193
  - `{ policies: 'native' }` on a Postgres or CockroachDB pool has the database hold them: migrations install `CREATE POLICY` (RLS enabled and forced), each transaction binds the context with `set_config`, and raw SQL is held too. Connect it as a role that is no superuser and lacks `BYPASSRLS`; a statement under a context is refused otherwise. `role: $context.role` beside it runs each transaction as the database role the context names, and a `when` on that key compares that role exactly (`current_user`). CockroachDB takes no relation in a native policy, and a Postgres insert must be readable by the context inserting it. https://uql-orm.dev/multi-tenancy.md
194
194
 
195
195
  ## Queries