uql-orm 0.115.1 → 0.115.3
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/README.md +2 -2
- package/dist/dialect/abstractDialect.d.ts +9 -2
- package/dist/dialect/abstractDialect.js +17 -4
- package/dist/dialect/abstractSqlDialect.d.ts +5 -2
- package/dist/dialect/abstractSqlDialect.js +5 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +6 -2
- package/dist/dialect/pgLikeSqlDialect.js +13 -4
- package/dist/migrate/drift/driftDetector.js +20 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -0
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
- package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -0
- package/dist/migrate/introspection/postgresIntrospector.js +10 -0
- package/dist/migrate/introspection/tableSchemaAST.js +1 -0
- package/dist/migrate/policySql.d.ts +1 -2
- package/dist/migrate/policySql.js +15 -7
- package/dist/migrate/schemaChange.js +1 -0
- package/dist/migrate/schemaGenerator.d.ts +0 -2
- package/dist/migrate/schemaGenerator.js +9 -14
- package/dist/querier/abstractSqlQuerier.d.ts +2 -2
- package/dist/querier/abstractSqlQuerier.js +10 -9
- package/dist/schema/schemaASTBuilder.d.ts +2 -0
- package/dist/schema/schemaASTBuilder.js +1 -0
- package/dist/schema/schemaASTDiffer.js +18 -2
- package/dist/schema/types.d.ts +8 -0
- package/dist/type/migration.d.ts +4 -0
- package/dist/type/querier.d.ts +6 -0
- package/dist/util/policy.util.d.ts +4 -0
- package/dist/util/policy.util.js +4 -0
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +1 -1
package/README.md
CHANGED
|
@@ -143,7 +143,7 @@ const posts = await pool.findMany(Post, {
|
|
|
143
143
|
|
|
144
144
|
The result is typed to what the query selected: `posts[0].author?.email` compiles, `posts[0].likes` does not.
|
|
145
145
|
|
|
146
|
-
The same queries run from the browser too: [serve them over HTTP, tRPC or oRPC](https://uql-orm.dev/http), each field exposed as
|
|
146
|
+
The same queries run from the browser too: [serve them over HTTP, tRPC or oRPC](https://uql-orm.dev/http), each field exposed as its `wire` declares, held to the signed-in user by [row-level policies](https://uql-orm.dev/multi-tenancy) no call can turn off.
|
|
147
147
|
|
|
148
148
|
## Why UQL?
|
|
149
149
|
|
|
@@ -151,7 +151,7 @@ The same queries run from the browser too: [serve them over HTTP, tRPC or oRPC](
|
|
|
151
151
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
152
152
|
- **Decorators or plain data, your call.** An entity is a class with [standard TC39 decorators](https://uql-orm.dev/entities/basic), or plain data via [`defineEntity`](https://uql-orm.dev/entities/define-entity), its row type derived. Both are typed the same, mix in one project, and need no compiler flags or `reflect-metadata`.
|
|
153
153
|
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 49 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
154
|
-
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [
|
|
154
|
+
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [row-level policies](https://uql-orm.dev/multi-tenancy) holding every read and write on every engine, or enforced by Postgres's own row-level security, [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), and [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches.
|
|
155
155
|
- **SQL when you need it.** [`sql()`](https://uql-orm.dev/querying/raw-sql) fits anywhere a value or a field goes, [computed fields](https://uql-orm.dev/entities/computed-fields) are SQL you can filter and sort on, and a migration can be plain SQL.
|
|
156
156
|
- **The fastest ORM.** On a full PostgreSQL round trip it adds the least over hand-written driver code of any ORM in our open-source [benchmark](https://github.com/rogerpadilla/ts-orm-benchmark), on Bun and Node alike. The same benchmark [scores the types](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) by compiling ordinary mistakes in each ORM's API: UQL is the only one that catches them all.
|
|
157
157
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, PolicyMode, 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, ContextRef } from '../type/index.js';
|
|
2
2
|
import { type EngineName } from '../type/index.js';
|
|
3
3
|
import { type PolicyEnforcement } from '../util/policy.util.js';
|
|
4
4
|
/**
|
|
@@ -10,6 +10,8 @@ export interface DialectOptions {
|
|
|
10
10
|
readonly schema?: string;
|
|
11
11
|
/** See {@link ExtraOptions.policies}. */
|
|
12
12
|
readonly policies?: PolicyMode;
|
|
13
|
+
/** See {@link ExtraOptions.role}. */
|
|
14
|
+
readonly role?: ContextRef<string>;
|
|
13
15
|
}
|
|
14
16
|
/**
|
|
15
17
|
* The dialect's share of a pool's {@link ExtraOptions}: what changes the SQL rather than the
|
|
@@ -21,6 +23,7 @@ export declare function dialectOptionsFrom(extra: ExtraOptions | undefined): Dia
|
|
|
21
23
|
* Base abstract class for all database dialects (SQL and NoSQL).
|
|
22
24
|
*/
|
|
23
25
|
export declare abstract class AbstractDialect {
|
|
26
|
+
#private;
|
|
24
27
|
protected readonly options: DialectOptions;
|
|
25
28
|
abstract readonly dialectName: DialectName;
|
|
26
29
|
/** The engine as a message names it. */
|
|
@@ -75,8 +78,12 @@ export declare abstract class AbstractDialect {
|
|
|
75
78
|
* every row it comes back in, and MongoDB would read `$` or `.` in one as an operator or a path.
|
|
76
79
|
*/
|
|
77
80
|
assertProjectable<E>(meta: EntityMeta<E>, alias: string): void;
|
|
78
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* How its pool's statements are held to the entities' policies, refusing a database that holds no row to one.
|
|
83
|
+
* Resolved on first read, once the subclass has stated its features.
|
|
84
|
+
*/
|
|
79
85
|
get policies(): PolicyEnforcement;
|
|
86
|
+
private enforcement;
|
|
80
87
|
/**
|
|
81
88
|
* A `$where` with the entity's active filters and policies merged in - the only way any dialect should enter a
|
|
82
89
|
* new query scope, so a scope cannot be rendered with its policies skipped. Recursion within one scope renders
|
|
@@ -15,7 +15,8 @@ import { groupClauses, isGroupOp } from './operators.js';
|
|
|
15
15
|
* each pool's constructor.
|
|
16
16
|
*/
|
|
17
17
|
export function dialectOptionsFrom(extra) {
|
|
18
|
-
|
|
18
|
+
const { namingStrategy, schema, policies, role } = extra ?? {};
|
|
19
|
+
return { namingStrategy, schema, policies, role };
|
|
19
20
|
}
|
|
20
21
|
/** A name a score can be projected under: what every engine takes as a key, with nothing to escape. */
|
|
21
22
|
const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
@@ -114,13 +115,25 @@ export class AbstractDialect {
|
|
|
114
115
|
throw new UqlUsageError(`$project '${alias}' collides with a relation of '${entityName(meta)}'`);
|
|
115
116
|
}
|
|
116
117
|
}
|
|
117
|
-
|
|
118
|
+
#policies;
|
|
119
|
+
/**
|
|
120
|
+
* How its pool's statements are held to the entities' policies, refusing a database that holds no row to one.
|
|
121
|
+
* Resolved on first read, once the subclass has stated its features.
|
|
122
|
+
*/
|
|
118
123
|
get policies() {
|
|
119
|
-
|
|
124
|
+
this.#policies ??= this.enforcement();
|
|
125
|
+
return this.#policies;
|
|
126
|
+
}
|
|
127
|
+
enforcement() {
|
|
128
|
+
const { policies, role } = this.options;
|
|
129
|
+
const enforcement = enforcementOf(policies);
|
|
120
130
|
if (enforcement.database && this.features.rowSecurity === false) {
|
|
121
131
|
throw new UqlUsageError(`${this.engineName} holds no row to a policy itself: leave policies unset, for uql to hold them`);
|
|
122
132
|
}
|
|
123
|
-
|
|
133
|
+
if (role && !enforcement.database) {
|
|
134
|
+
throw new UqlUsageError("a pool's role is a database role its transactions run as, which only policies: 'native' binds");
|
|
135
|
+
}
|
|
136
|
+
return role ? { ...enforcement, role: role.$context } : enforcement;
|
|
124
137
|
}
|
|
125
138
|
/**
|
|
126
139
|
* A `$where` with the entity's active filters and policies merged in - the only way any dialect should enter a
|
|
@@ -847,8 +847,11 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
847
847
|
contextBinding(_entries: readonly (readonly [string, string])[]): BoundStatement | undefined;
|
|
848
848
|
/** A policy's read of context key `key` as a value of SQL type `type`, NULL where the transaction bound none. */
|
|
849
849
|
contextRead(key: string, _type: string): string;
|
|
850
|
-
/**
|
|
851
|
-
|
|
850
|
+
/**
|
|
851
|
+
* What answers whether `role`, or the role a transaction runs as where it names none, reads past row-level
|
|
852
|
+
* security, as one row's `bypasses`.
|
|
853
|
+
*/
|
|
854
|
+
rowSecurityBypassQuery(_role?: string): string;
|
|
852
855
|
/** ANSI-style single-quote escaping. */
|
|
853
856
|
escape(value: unknown): string;
|
|
854
857
|
/** The `$regex` predicate, case-sensitive on every engine. */
|
|
@@ -2279,8 +2279,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
2279
2279
|
contextRead(key, _type) {
|
|
2280
2280
|
throw new UqlUsageError(`${this.engineName} reads no context key in SQL, so '${key}' has no rendering`);
|
|
2281
2281
|
}
|
|
2282
|
-
/**
|
|
2283
|
-
|
|
2282
|
+
/**
|
|
2283
|
+
* What answers whether `role`, or the role a transaction runs as where it names none, reads past row-level
|
|
2284
|
+
* security, as one row's `bypasses`.
|
|
2285
|
+
*/
|
|
2286
|
+
rowSecurityBypassQuery(_role) {
|
|
2284
2287
|
throw new UqlUsageError(`${this.engineName} holds no row to a policy itself`);
|
|
2285
2288
|
}
|
|
2286
2289
|
/** ANSI-style single-quote escaping. */
|
|
@@ -23,13 +23,17 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
23
23
|
constructor(options?: PgLikeDialectOptions);
|
|
24
24
|
readonly features: SqlDialectFeatures;
|
|
25
25
|
readonly sqlValues: SqlValues;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* `set_config(..., true)`: bound to the transaction, so a pooled connection carries none past it. The role key is
|
|
28
|
+
* also the transaction's `role`, back to the connection's own (`none`) where unbound.
|
|
29
|
+
*/
|
|
27
30
|
contextBinding(entries: readonly (readonly [string, string])[]): BoundStatement | undefined;
|
|
28
31
|
/** A subselect, so the setting is read once per statement rather than per row; an empty setting is NULL. */
|
|
29
32
|
contextRead(key: string, type: string): string;
|
|
30
33
|
/** Context key `key`'s setting as a value of SQL type `type`, NULL where the transaction bound none. */
|
|
31
34
|
protected settingRead(key: string, type: string): string;
|
|
32
|
-
|
|
35
|
+
/** Where the pool binds roles, an unnamed one is the connection's own, which unbinding one goes back to. */
|
|
36
|
+
rowSecurityBypassQuery(role?: string): string;
|
|
33
37
|
/** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
|
|
34
38
|
protected refusal(message: string): string;
|
|
35
39
|
readonly escapeIdChar = "\"";
|
|
@@ -70,9 +70,16 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
70
70
|
}
|
|
71
71
|
features = PG_FEATURES;
|
|
72
72
|
sqlValues = PG_SQL_VALUES;
|
|
73
|
-
/**
|
|
73
|
+
/**
|
|
74
|
+
* `set_config(..., true)`: bound to the transaction, so a pooled connection carries none past it. The role key is
|
|
75
|
+
* also the transaction's `role`, back to the connection's own (`none`) where unbound.
|
|
76
|
+
*/
|
|
74
77
|
contextBinding(entries) {
|
|
75
|
-
const
|
|
78
|
+
const { role } = this.policies;
|
|
79
|
+
const configs = entries.flatMap(([key, value]) => [
|
|
80
|
+
sql `set_config(${contextSetting(key)}, ${value}, true)`,
|
|
81
|
+
...(key === role ? [sql `set_config(${'role'}, ${value || 'none'}, true)`] : []),
|
|
82
|
+
]);
|
|
76
83
|
return configs.length ? this.compile(sql `SELECT ${sql.join(configs)}`) : undefined;
|
|
77
84
|
}
|
|
78
85
|
/** A subselect, so the setting is read once per statement rather than per row; an empty setting is NULL. */
|
|
@@ -83,8 +90,10 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
83
90
|
settingRead(key, type) {
|
|
84
91
|
return `nullif(current_setting(${this.escape(contextSetting(key))}, true), '')::${type}`;
|
|
85
92
|
}
|
|
86
|
-
|
|
87
|
-
|
|
93
|
+
/** Where the pool binds roles, an unnamed one is the connection's own, which unbinding one goes back to. */
|
|
94
|
+
rowSecurityBypassQuery(role) {
|
|
95
|
+
const name = role === undefined ? (this.policies.role ? 'session_user' : 'current_user') : this.escape(role);
|
|
96
|
+
return `SELECT rolsuper OR rolbypassrls AS bypasses FROM pg_roles WHERE rolname = ${name}`;
|
|
88
97
|
}
|
|
89
98
|
/** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
|
|
90
99
|
refusal(message) {
|
|
@@ -15,6 +15,7 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
|
|
|
15
15
|
...detectOwnedDrifts('Check', diff.checks),
|
|
16
16
|
...detectOwnedDrifts('Trigger', diff.triggers),
|
|
17
17
|
...detectOwnedDrifts('Policy', diff.policies),
|
|
18
|
+
...diff.rowSecurity.map(rowSecurityDrift),
|
|
18
19
|
...diff.relationships.map(relationshipDrift),
|
|
19
20
|
];
|
|
20
21
|
const count = (severity) => drifts.filter((drift) => drift.severity === severity).length;
|
|
@@ -46,14 +47,28 @@ function detectPrimaryKeyDrifts(diff) {
|
|
|
46
47
|
* one uql installed that nothing declares.
|
|
47
48
|
*/
|
|
48
49
|
function detectOwnedDrifts(kind, changes) {
|
|
49
|
-
return changes.map(({ table, from, to }) => (
|
|
50
|
+
return changes.map(({ table, from, to }) => ownedDrift(table, to
|
|
51
|
+
? `${kind} "${to.name}" expected but not found in database`
|
|
52
|
+
: `${kind} "${from?.name}" exists in database but not in entity`, Boolean(to)));
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Row-level security off under uql's policies, critical since the database then holds no row to them; or left on
|
|
56
|
+
* with none, where a table forced with no policy shows no row.
|
|
57
|
+
*/
|
|
58
|
+
function rowSecurityDrift({ table, to }) {
|
|
59
|
+
return ownedDrift(table, to
|
|
60
|
+
? `Row-level security is off on "${table}", so the database holds no row to its policies`
|
|
61
|
+
: `Row-level security is on for "${table}", whose entity declares no policy`, Boolean(to));
|
|
62
|
+
}
|
|
63
|
+
/** What uql owns on `table` differing from the entity: critical where the database lacks what it `expected`. */
|
|
64
|
+
function ownedDrift(table, details, expected) {
|
|
65
|
+
return {
|
|
50
66
|
type: 'constraint_mismatch',
|
|
51
67
|
table,
|
|
68
|
+
details,
|
|
69
|
+
severity: expected ? 'critical' : 'warning',
|
|
52
70
|
suggestion: 'Generate a migration to match the entity',
|
|
53
|
-
|
|
54
|
-
? { severity: 'critical', details: `${kind} "${to.name}" expected but not found in database` }
|
|
55
|
-
: { severity: 'warning', details: `${kind} "${from?.name}" exists in database but not in entity` }),
|
|
56
|
-
}));
|
|
71
|
+
};
|
|
57
72
|
}
|
|
58
73
|
/** A key's columns as a drift names them, `none` where there is no key. */
|
|
59
74
|
function keyColumns(key) {
|
|
@@ -80,6 +80,8 @@ export declare abstract class AbstractSqlSchemaIntrospector implements SchemaInt
|
|
|
80
80
|
protected abstract triggersQuery(tableName: string): QuerySql;
|
|
81
81
|
/** The row-level policies uql installed on the table: none, but where the engine holds rows to policies. */
|
|
82
82
|
protected getPolicies(_read: TableRowReader, _tableName: string): Promise<PolicySchema[]>;
|
|
83
|
+
/** Whether row-level security holds the table: unknown, but where the engine holds rows to policies. */
|
|
84
|
+
protected getRowSecurity(_read: TableRowReader, _tableName: string): Promise<boolean | undefined>;
|
|
83
85
|
/** See {@link TableSchema.definition}: none, but where the engine keeps the statements themselves. */
|
|
84
86
|
protected getDefinition(_read: TableRowReader, _tableName: string): Promise<StoredDefinition[] | undefined>;
|
|
85
87
|
/**
|
|
@@ -60,7 +60,7 @@ export class AbstractSqlSchemaIntrospector {
|
|
|
60
60
|
if (!exists) {
|
|
61
61
|
return undefined;
|
|
62
62
|
}
|
|
63
|
-
const [columns, indexes, foreignKeys, primaryKey, checks, triggers, policies, definition] = await Promise.all([
|
|
63
|
+
const [columns, indexes, foreignKeys, primaryKey, checks, triggers, policies, rowSecurity, definition] = await Promise.all([
|
|
64
64
|
this.getColumns(read, tableName),
|
|
65
65
|
this.getIndexes(read, tableName),
|
|
66
66
|
this.getForeignKeys(read, tableName),
|
|
@@ -68,6 +68,7 @@ export class AbstractSqlSchemaIntrospector {
|
|
|
68
68
|
this.getChecks(read, tableName),
|
|
69
69
|
this.getTriggers(read, tableName),
|
|
70
70
|
this.getPolicies(read, tableName),
|
|
71
|
+
this.getRowSecurity(read, tableName),
|
|
71
72
|
this.getDefinition(read, tableName),
|
|
72
73
|
]);
|
|
73
74
|
const unique = uniqueColumns(indexes);
|
|
@@ -84,6 +85,7 @@ export class AbstractSqlSchemaIntrospector {
|
|
|
84
85
|
checks,
|
|
85
86
|
triggers,
|
|
86
87
|
policies,
|
|
88
|
+
rowSecurity,
|
|
87
89
|
definition,
|
|
88
90
|
};
|
|
89
91
|
});
|
|
@@ -117,6 +119,10 @@ export class AbstractSqlSchemaIntrospector {
|
|
|
117
119
|
async getPolicies(_read, _tableName) {
|
|
118
120
|
return [];
|
|
119
121
|
}
|
|
122
|
+
/** Whether row-level security holds the table: unknown, but where the engine holds rows to policies. */
|
|
123
|
+
async getRowSecurity(_read, _tableName) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
120
126
|
/** See {@link TableSchema.definition}: none, but where the engine keeps the statements themselves. */
|
|
121
127
|
async getDefinition(_read, _tableName) {
|
|
122
128
|
return undefined;
|
|
@@ -15,6 +15,8 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
|
|
|
15
15
|
protected triggersQuery(tableName: string): QuerySql;
|
|
16
16
|
/** Each policy uql installed, as the statement recreating it from what `pg_policies` reprints. */
|
|
17
17
|
protected getPolicies(read: TableRowReader, tableName: string): Promise<PolicySchema[]>;
|
|
18
|
+
/** Enabled and forced, as uql switches it: enabled alone still lets the owner past. */
|
|
19
|
+
protected getRowSecurity(read: TableRowReader, tableName: string): Promise<boolean | undefined>;
|
|
18
20
|
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
19
21
|
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
20
22
|
protected getTableNamesQuery(): QuerySql;
|
|
@@ -41,6 +41,16 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
41
41
|
`);
|
|
42
42
|
return rows.flatMap(({ name, definition }) => (isOwnedName(name) ? [{ name, statements: [definition] }] : []));
|
|
43
43
|
}
|
|
44
|
+
/** Enabled and forced, as uql switches it: enabled alone still lets the owner past. */
|
|
45
|
+
async getRowSecurity(read, tableName) {
|
|
46
|
+
const [row] = await read(sql `
|
|
47
|
+
SELECT c.relrowsecurity AND c.relforcerowsecurity AS held
|
|
48
|
+
FROM pg_class c
|
|
49
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
50
|
+
WHERE n.nspname = ${this.schemaExpr} AND c.relname = ${tableName}
|
|
51
|
+
`);
|
|
52
|
+
return row?.held;
|
|
53
|
+
}
|
|
44
54
|
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
45
55
|
async getChecks(read, tableName) {
|
|
46
56
|
const rows = await read(sql `
|
|
@@ -51,6 +51,7 @@ function tableNode(schema, { dialectName, schema: namespace, indexFacets }) {
|
|
|
51
51
|
table.checks.push(...(schema.checks ?? []));
|
|
52
52
|
table.triggers.push(...(schema.triggers ?? []));
|
|
53
53
|
table.policies.push(...(schema.policies ?? []));
|
|
54
|
+
table.rowSecurity = schema.rowSecurity;
|
|
54
55
|
table.definition = schema.definition;
|
|
55
56
|
return table;
|
|
56
57
|
}
|
|
@@ -3,8 +3,7 @@ import type { PolicySchema } from '../schema/types.js';
|
|
|
3
3
|
import { type EntityMeta, type FieldMeta } from '../type/index.js';
|
|
4
4
|
/**
|
|
5
5
|
* The policies a native pool's database holds `meta` to, each named for its table and label and ending in a hash of
|
|
6
|
-
* its own SQL, as a trigger is: one `FOR ALL` where it holds every statement, else one per statement.
|
|
7
|
-
* row-level security is switched with its first policy and its last, as `TableDdl.rowSecurity` says. See
|
|
6
|
+
* its own SQL, as a trigger is: one `FOR ALL` where it holds every statement, else one per statement. See
|
|
8
7
|
* architecture/row-level-security.md.
|
|
9
8
|
*/
|
|
10
9
|
export declare function renderPolicies(dialect: AbstractSqlDialect, meta: EntityMeta<object>, columnType: (field: FieldMeta) => string): PolicySchema[];
|
|
@@ -13,8 +13,7 @@ const COMMANDS = {
|
|
|
13
13
|
};
|
|
14
14
|
/**
|
|
15
15
|
* The policies a native pool's database holds `meta` to, each named for its table and label and ending in a hash of
|
|
16
|
-
* its own SQL, as a trigger is: one `FOR ALL` where it holds every statement, else one per statement.
|
|
17
|
-
* row-level security is switched with its first policy and its last, as `TableDdl.rowSecurity` says. See
|
|
16
|
+
* its own SQL, as a trigger is: one `FOR ALL` where it holds every statement, else one per statement. See
|
|
18
17
|
* architecture/row-level-security.md.
|
|
19
18
|
*/
|
|
20
19
|
export function renderPolicies(dialect, meta, columnType) {
|
|
@@ -32,14 +31,14 @@ export function renderPolicies(dialect, meta, columnType) {
|
|
|
32
31
|
};
|
|
33
32
|
return policiesOf(meta.policies).flatMap((policy, position) => {
|
|
34
33
|
const label = policy.name ?? `${policy.effect}_${position}`;
|
|
34
|
+
const [roles, when] = rolesOf(policy.when, dialect.policies.role);
|
|
35
35
|
const predicate = (where) => {
|
|
36
36
|
const bound = asWhere(meta, bindContext(meta, where, read));
|
|
37
37
|
const { rowSecurity } = dialect.features;
|
|
38
38
|
if (!(rowSecurity && rowSecurity.subqueries) && readsRelations(meta, bound)) {
|
|
39
39
|
throw new UqlUsageError(`${dialect.engineName} takes no subquery in a policy, so '${entityName(meta)}' policy '${label}' cannot read a relation there: leave policies unset on this pool, for uql to hold them`);
|
|
40
40
|
}
|
|
41
|
-
return ([...whenSql(dialect,
|
|
42
|
-
'true');
|
|
41
|
+
return ([...whenSql(dialect, when), dialect.compileDdl(bound, meta.entity)].filter(Boolean).join(' AND ') || 'true');
|
|
43
42
|
};
|
|
44
43
|
const commands = POLICY_OPS.every((op) => policy.ops.includes(op))
|
|
45
44
|
? [['ALL', undefined]]
|
|
@@ -48,7 +47,7 @@ export function renderPolicies(dialect, meta, columnType) {
|
|
|
48
47
|
const using = command === 'INSERT' ? undefined : predicate(policy.where);
|
|
49
48
|
const check = writes(command) ? predicate(policy.check ?? policy.where) : undefined;
|
|
50
49
|
const create = (name) => [
|
|
51
|
-
`CREATE POLICY ${dialect.escapeId(name)} ON ${target} AS ${policy.effect === 'allow' ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${command} TO PUBLIC`,
|
|
50
|
+
`CREATE POLICY ${dialect.escapeId(name)} ON ${target} AS ${policy.effect === 'allow' ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${command} TO ${roles.map((role) => dialect.escapeId(role)).join(', ') || 'PUBLIC'}`,
|
|
52
51
|
...(using === undefined ? [] : [`USING (${using})`]),
|
|
53
52
|
...(check === undefined ? [] : [`WITH CHECK (${check})`]),
|
|
54
53
|
].join(' ');
|
|
@@ -65,9 +64,18 @@ function writes(command) {
|
|
|
65
64
|
export function dropPolicy(dialect, table, name) {
|
|
66
65
|
return `DROP POLICY IF EXISTS ${dialect.escapeId(name)} ON ${dialect.escapeId(table)}`;
|
|
67
66
|
}
|
|
68
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* The database roles a `when` lists at the pool's role key, which `TO` holds, and the rest of it. None where it lists
|
|
69
|
+
* none, the key then left in the rest, which holds under no context.
|
|
70
|
+
*/
|
|
71
|
+
function rolesOf(when, key) {
|
|
72
|
+
const entries = Object.entries(when ?? {});
|
|
73
|
+
const roles = entries.flatMap(([it, value]) => (it === key ? [value].flat().map(String) : []));
|
|
74
|
+
return [roles, roles.length ? entries.filter(([it]) => it !== key) : entries];
|
|
75
|
+
}
|
|
76
|
+
/** A `when`'s entries as the context comparisons they are, each read as text, as the binding sends every value. */
|
|
69
77
|
function whenSql(dialect, when) {
|
|
70
|
-
return
|
|
78
|
+
return when.map(([key, value]) => {
|
|
71
79
|
const values = [value].flat().map((it) => dialect.escape(String(it)));
|
|
72
80
|
return values.length ? `${dialect.contextRead(key, 'text')} IN (${values.join(', ')})` : 'false';
|
|
73
81
|
});
|
|
@@ -84,6 +84,7 @@ export function reverseDiff(diff) {
|
|
|
84
84
|
checks: diff.checks?.map(swap),
|
|
85
85
|
triggers: diff.triggers?.map(swap),
|
|
86
86
|
policies: diff.policies?.map(swap),
|
|
87
|
+
rowSecurity: diff.rowSecurity && swap(diff.rowSecurity),
|
|
87
88
|
renamedColumns,
|
|
88
89
|
rebuild: diff.rebuild && { from: diff.rebuild.to, to: diff.rebuild.from },
|
|
89
90
|
};
|
|
@@ -58,8 +58,6 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
|
|
|
58
58
|
* MySQL refuses to rename or drop under one. An alter is its drop, then its add.
|
|
59
59
|
*/
|
|
60
60
|
generateAlterTable(diff: SchemaDiff): string[];
|
|
61
|
-
/** What switches `tableName`'s row-level security as `policies` change it, as `[off, on]`: on with its first, off with its last. */
|
|
62
|
-
private rowSecurityChange;
|
|
63
61
|
/** `CONSTRAINT <name> CHECK (...)`, in a `CREATE TABLE`, after `ADD`, or inline where a column brings it. */
|
|
64
62
|
private checkConstraint;
|
|
65
63
|
private addCheckSql;
|
|
@@ -72,6 +72,7 @@ export class SqlSchemaGenerator {
|
|
|
72
72
|
renderTriggers: (meta) => [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)].map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i)),
|
|
73
73
|
renderPolicies: (meta) => renderPolicies(this.dialect, meta, (field) => canonicalToSql(resolveColumnCanonicalType(field), this.dialect)),
|
|
74
74
|
textScoreIndexes: this.dialect.features.textScoreIndexes,
|
|
75
|
+
rowSecurity: this.dialect.features.rowSecurity !== false,
|
|
75
76
|
vectorIndexRequiresNotNull: this.features.vectorIndexRequiresNotNull,
|
|
76
77
|
});
|
|
77
78
|
}
|
|
@@ -93,11 +94,10 @@ export class SqlSchemaGenerator {
|
|
|
93
94
|
// Triggers last: each needs its own table, and a body may read any other the same schema just made.
|
|
94
95
|
...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))),
|
|
95
96
|
// Policies after them, a membership read through a table the same schema just made included.
|
|
96
|
-
...tables.flatMap((table) =>
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}),
|
|
97
|
+
...tables.flatMap((table) => [
|
|
98
|
+
...(table.rowSecurity ? this.tableDdl.rowSecurity(qualifyName(table.name, table.schema), true) : []),
|
|
99
|
+
...terminated(table.policies.flatMap((policy) => policy.statements)),
|
|
100
|
+
]),
|
|
101
101
|
];
|
|
102
102
|
}
|
|
103
103
|
/**
|
|
@@ -177,7 +177,9 @@ export class SqlSchemaGenerator {
|
|
|
177
177
|
const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, trigger.name)));
|
|
178
178
|
const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
|
|
179
179
|
const policies = cycled(diff.policies);
|
|
180
|
-
|
|
180
|
+
// Row-level security goes off after the last policy, and on before the first.
|
|
181
|
+
const switched = diff.rowSecurity ? this.tableDdl.rowSecurity(tableName, diff.rowSecurity.to === true) : [];
|
|
182
|
+
const [off, on] = diff.rowSecurity?.to ? [[], switched] : [switched, []];
|
|
181
183
|
const policyDrops = [
|
|
182
184
|
...terminated(sides(policies, 'from').map((policy) => dropPolicy(this.dialect, tableName, policy.name))),
|
|
183
185
|
...off,
|
|
@@ -215,14 +217,6 @@ export class SqlSchemaGenerator {
|
|
|
215
217
|
...policyCreates,
|
|
216
218
|
];
|
|
217
219
|
}
|
|
218
|
-
/** What switches `tableName`'s row-level security as `policies` change it, as `[off, on]`: on with its first, off with its last. */
|
|
219
|
-
rowSecurityChange(tableName, policies = []) {
|
|
220
|
-
const had = sides(policies, 'from').length > 0;
|
|
221
|
-
const has = sides(policies, 'to').length > 0;
|
|
222
|
-
return had === has
|
|
223
|
-
? [[], []]
|
|
224
|
-
: [had ? this.tableDdl.rowSecurity(tableName, false) : [], has ? this.tableDdl.rowSecurity(tableName, true) : []];
|
|
225
|
-
}
|
|
226
220
|
/** `CONSTRAINT <name> CHECK (...)`, in a `CREATE TABLE`, after `ADD`, or inline where a column brings it. */
|
|
227
221
|
checkConstraint(check) {
|
|
228
222
|
return `CONSTRAINT ${this.escapeId(check.name)} CHECK (${check.expression})`;
|
|
@@ -304,6 +298,7 @@ export class SqlSchemaGenerator {
|
|
|
304
298
|
// A kept trigger or policy as both sides, which the alter cycles only where a column it names moves under it.
|
|
305
299
|
triggers: nonEmpty([...(tableDiff?.triggers ?? []), ...kept(desired.triggers, currentTable.triggers)]),
|
|
306
300
|
policies: nonEmpty([...(tableDiff?.policies ?? []), ...kept(desired.policies, currentTable.policies)]),
|
|
301
|
+
rowSecurity: tableDiff?.rowSecurity,
|
|
307
302
|
renamedColumns: nonEmpty(renamedColumns ?? []),
|
|
308
303
|
};
|
|
309
304
|
if (!(tableDiff || alter.indexes || alter.foreignKeys || alter.renamedColumns)) {
|
|
@@ -45,8 +45,8 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
45
45
|
/** Whether a statement here runs under a context the database's policies read, which binds in a transaction. */
|
|
46
46
|
private bindsContext;
|
|
47
47
|
/**
|
|
48
|
-
* Refuses a statement under a context
|
|
49
|
-
* one tenant another's rows. A statement under none, a migration's, runs as the owner
|
|
48
|
+
* Refuses a statement under a context whose role, `role` or the connection's own, reads past the database's
|
|
49
|
+
* policies, which would show one tenant another's rows. A statement under none, a migration's, runs as the owner.
|
|
50
50
|
*/
|
|
51
51
|
private assertHeldToPolicies;
|
|
52
52
|
/** {@link runStatements} once the context is bound. */
|
|
@@ -4,7 +4,7 @@ import { getMeta } from '../entity/index.js';
|
|
|
4
4
|
import { generatesKey, idOf, namesKey, soleId } from '../entity/metadata/definition.js';
|
|
5
5
|
import { QuerySql } from '../type/querySql.js';
|
|
6
6
|
import { buildUpdateResult, cachedIn, chunk, clone, getInsertFieldKeys, insertShapeOf, getKeys, rowKey, } from '../util/index.js';
|
|
7
|
-
import { contextEntries, nextBinding, NOTHING_BOUND, unsettled } from '../util/policy.util.js';
|
|
7
|
+
import { contextEntries, nextBinding, NOTHING_BOUND, roleOf, unsettled } from '../util/policy.util.js';
|
|
8
8
|
import { sql, statementOf } from '../util/sql.js';
|
|
9
9
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
10
10
|
import { AbstractQuerier } from './abstractQuerier.js';
|
|
@@ -65,7 +65,7 @@ function inPayloadOrder(meta, rows, reported) {
|
|
|
65
65
|
const [idKey] = meta.ids;
|
|
66
66
|
return generatesKey(meta) ? reported.toSorted((a, b) => byGeneratedKey(a[idKey], b[idKey])) : reported;
|
|
67
67
|
}
|
|
68
|
-
/** Each
|
|
68
|
+
/** Each role found held to a dialect's policies, by name (`undefined` the connection's own), answered once per pool. */
|
|
69
69
|
const heldToPolicies = new WeakMap();
|
|
70
70
|
export class AbstractSqlQuerier extends AbstractQuerier {
|
|
71
71
|
dialect;
|
|
@@ -134,7 +134,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
134
134
|
async pendingBinding(ask) {
|
|
135
135
|
const { entries, bound } = nextBinding(this.#bound, getContext());
|
|
136
136
|
if (entries.length && this.bindsContext()) {
|
|
137
|
-
await this.assertHeldToPolicies(ask);
|
|
137
|
+
await this.assertHeldToPolicies(ask, roleOf(entries, this.dialect.policies.role));
|
|
138
138
|
}
|
|
139
139
|
this.#bound = bound;
|
|
140
140
|
return this.dialect.contextBinding(entries);
|
|
@@ -144,17 +144,18 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
144
144
|
return this.dialect.policies.database && contextEntries(getContext()).length > 0;
|
|
145
145
|
}
|
|
146
146
|
/**
|
|
147
|
-
* Refuses a statement under a context
|
|
148
|
-
* one tenant another's rows. A statement under none, a migration's, runs as the owner
|
|
147
|
+
* Refuses a statement under a context whose role, `role` or the connection's own, reads past the database's
|
|
148
|
+
* policies, which would show one tenant another's rows. A statement under none, a migration's, runs as the owner.
|
|
149
149
|
*/
|
|
150
|
-
assertHeldToPolicies(ask) {
|
|
150
|
+
assertHeldToPolicies(ask, role) {
|
|
151
151
|
const { dialect } = this;
|
|
152
|
-
|
|
152
|
+
const held = cachedIn(heldToPolicies, dialect, () => new Map());
|
|
153
|
+
return cachedIn(held, role, () => ask(dialect.rowSecurityBypassQuery(role)).then(({ rows }) => {
|
|
153
154
|
if (rows[0]?.['bypasses'] !== false) {
|
|
154
|
-
throw new UqlUsageError(`a pool with policies: 'native' runs a context's statements as a role ${dialect.engineName} lets past row-level security: connect as one that does not, or leave policies unset`);
|
|
155
|
+
throw new UqlUsageError(`a pool with policies: 'native' runs a context's statements as a role ${dialect.engineName} lets past row-level security: connect as, or name, one that does not, or leave policies unset`);
|
|
155
156
|
}
|
|
156
157
|
})).catch((error) => {
|
|
157
|
-
|
|
158
|
+
held.delete(role);
|
|
158
159
|
throw error;
|
|
159
160
|
});
|
|
160
161
|
}
|
|
@@ -22,6 +22,8 @@ export interface BuildSchemaASTOptions {
|
|
|
22
22
|
renderTriggers: (meta: EntityMeta<object>) => TriggerSchema[];
|
|
23
23
|
/** The row-level policies the database holds an entity's table to, none where the querier holds them. */
|
|
24
24
|
renderPolicies: (meta: EntityMeta<object>) => PolicySchema[];
|
|
25
|
+
/** Whether the engine has row-level security, which a table then states as on or off. */
|
|
26
|
+
rowSecurity: boolean;
|
|
25
27
|
}
|
|
26
28
|
/**
|
|
27
29
|
* Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
|
|
@@ -61,6 +61,7 @@ function addTableFromEntity(ctx, meta) {
|
|
|
61
61
|
table.primaryKey = keyOfColumns(columns.values());
|
|
62
62
|
table.triggers.push(...ctx.renderTriggers(meta));
|
|
63
63
|
table.policies.push(...ctx.renderPolicies(meta));
|
|
64
|
+
table.rowSecurity = ctx.rowSecurity ? table.policies.length > 0 : undefined;
|
|
64
65
|
ctx.ast.addTable(table);
|
|
65
66
|
return table;
|
|
66
67
|
}
|
|
@@ -27,6 +27,7 @@ export function diffSchemas(source, target, options = {}) {
|
|
|
27
27
|
checks: altered.flatMap((tableDiff) => tableDiff.checks),
|
|
28
28
|
triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
|
|
29
29
|
policies: altered.flatMap((tableDiff) => tableDiff.policies),
|
|
30
|
+
rowSecurity: altered.flatMap((tableDiff) => tableDiff.rowSecurity ?? []),
|
|
30
31
|
primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
|
|
31
32
|
// Relationships span tables, so they are compared over the whole schema rather than per table.
|
|
32
33
|
relationships: diffRelationshipNodes(source.relationships, target.relationships),
|
|
@@ -42,9 +43,24 @@ export function diffTable(source, target, options = {}) {
|
|
|
42
43
|
const checks = diffOwned(source.name, source.checks, target.checks);
|
|
43
44
|
const triggers = diffOwned(source.name, source.triggers, target.triggers);
|
|
44
45
|
const policies = diffOwned(source.name, source.policies, target.policies);
|
|
46
|
+
const rowSecurity = diffRowSecurity(source, target);
|
|
45
47
|
const primaryKey = diffPrimaryKey(source, target);
|
|
46
|
-
return columns.length || checks.length || triggers.length || policies.length || primaryKey
|
|
47
|
-
? { columns, checks, triggers, policies, primaryKey }
|
|
48
|
+
return columns.length || checks.length || triggers.length || policies.length || rowSecurity || primaryKey
|
|
49
|
+
? { columns, checks, triggers, policies, rowSecurity, primaryKey }
|
|
50
|
+
: undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Row-level security where the database switches it otherwise than uql's policies need: on under them, off once its
|
|
54
|
+
* last is gone. Left alone on a table holding none of uql's, whose switch is a second writer's.
|
|
55
|
+
*/
|
|
56
|
+
function diffRowSecurity(source, target) {
|
|
57
|
+
const { rowSecurity: to } = source;
|
|
58
|
+
const { rowSecurity: from } = target;
|
|
59
|
+
if (to === undefined || from === undefined || from === to) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
return to || target.policies.some((policy) => isOwnedName(policy.name))
|
|
63
|
+
? { table: source.name, from, to }
|
|
48
64
|
: undefined;
|
|
49
65
|
}
|
|
50
66
|
/**
|
package/dist/schema/types.d.ts
CHANGED
|
@@ -139,6 +139,11 @@ export interface TableNode {
|
|
|
139
139
|
readonly triggers: TriggerSchema[];
|
|
140
140
|
/** The row-level policies uql installs on this table. */
|
|
141
141
|
readonly policies: PolicySchema[];
|
|
142
|
+
/**
|
|
143
|
+
* Whether row-level security holds the table, enabled and forced: from entities, whether uql installs a policy on
|
|
144
|
+
* it; from a database, as its catalogue says. Unset where the engine has none.
|
|
145
|
+
*/
|
|
146
|
+
rowSecurity?: boolean;
|
|
142
147
|
/** Optional table comment */
|
|
143
148
|
readonly comment?: string;
|
|
144
149
|
/** The statements the engine keeps for the table, where it keeps them; none on a table built from entities. */
|
|
@@ -233,6 +238,8 @@ export interface TableDiff {
|
|
|
233
238
|
readonly checks: TableChange<CheckSchema>[];
|
|
234
239
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
235
240
|
readonly policies: TableChange<PolicySchema>[];
|
|
241
|
+
/** Set only where {@link TableNode.rowSecurity} differs as uql's policies need it. */
|
|
242
|
+
readonly rowSecurity?: TableChange<boolean>;
|
|
236
243
|
/** Set only when the two primary keys have different columns. */
|
|
237
244
|
readonly primaryKey?: PrimaryKeyDiff;
|
|
238
245
|
}
|
|
@@ -245,6 +252,7 @@ export interface SchemaDiffResult {
|
|
|
245
252
|
readonly checks: TableChange<CheckSchema>[];
|
|
246
253
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
247
254
|
readonly policies: TableChange<PolicySchema>[];
|
|
255
|
+
readonly rowSecurity: TableChange<boolean>[];
|
|
248
256
|
readonly primaryKeys: PrimaryKeyDiff[];
|
|
249
257
|
readonly relationships: RelationshipDiff[];
|
|
250
258
|
}
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -103,6 +103,8 @@ export interface TableSchema {
|
|
|
103
103
|
readonly triggers?: TriggerSchema[];
|
|
104
104
|
/** The row-level policies uql installed, each with the statement the engine would recreate it from. */
|
|
105
105
|
readonly policies?: PolicySchema[];
|
|
106
|
+
/** See {@link TableNode.rowSecurity}. */
|
|
107
|
+
readonly rowSecurity?: boolean;
|
|
106
108
|
/** The statements the engine keeps for the table, where it keeps them: SQLite's `sqlite_master`. */
|
|
107
109
|
readonly definition?: readonly StoredDefinition[];
|
|
108
110
|
}
|
|
@@ -212,6 +214,8 @@ export interface SchemaDiff {
|
|
|
212
214
|
readonly triggers?: readonly Change<TriggerSchema>[];
|
|
213
215
|
/** The row-level policies installed or declared, none kept: a changed one is a new name. */
|
|
214
216
|
readonly policies?: readonly Change<PolicySchema>[];
|
|
217
|
+
/** See {@link TableDiff.rowSecurity}. */
|
|
218
|
+
readonly rowSecurity?: Change<boolean>;
|
|
215
219
|
/** Columns renamed in place, `from` the database's name `to` the entity's, which the other changes already use. */
|
|
216
220
|
readonly renamedColumns?: readonly Rename[];
|
|
217
221
|
/**
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { SqlDialectName } from './dialect.js';
|
|
|
3
3
|
import type { EntityWrite, FieldKey, HookEvent, UpdateWrite } from './entity.js';
|
|
4
4
|
import type { LoggingOptions } from './logger.js';
|
|
5
5
|
import type { NamingStrategy } from './namingStrategy.js';
|
|
6
|
+
import type { ContextRef } from './policy.js';
|
|
6
7
|
import type { Captured, QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult, QueryUpsert, WriteResults, WriteOptions } from './query.js';
|
|
7
8
|
import type { QueryAggregate, QueryAggregateResult } from './queryAggregate.js';
|
|
8
9
|
import type { QuerySql, SqlStatement } from './querySql.js';
|
|
@@ -192,5 +193,10 @@ export type ExtraOptions = {
|
|
|
192
193
|
readonly listeners?: readonly QuerierListener[];
|
|
193
194
|
/** Who holds this pool's statements to the entities' policies: see {@link PolicyMode}. `'app'` where unset. */
|
|
194
195
|
readonly policies?: PolicyMode;
|
|
196
|
+
/**
|
|
197
|
+
* The context key naming the database role a native pool's transactions run as, `role: $context.role`: a policy's
|
|
198
|
+
* `when` on it is `CREATE POLICY ... TO` those roles. Unset, they run as the role the pool connects as.
|
|
199
|
+
*/
|
|
200
|
+
readonly role?: ContextRef<string>;
|
|
195
201
|
};
|
|
196
202
|
export {};
|
|
@@ -9,6 +9,8 @@ export type PolicyEnforcement = {
|
|
|
9
9
|
readonly guards: boolean;
|
|
10
10
|
readonly checks: boolean;
|
|
11
11
|
readonly database: boolean;
|
|
12
|
+
/** The context key naming the database role its transactions run as, where the database holds the policies. */
|
|
13
|
+
readonly role?: string;
|
|
12
14
|
};
|
|
13
15
|
/** How a pool built with `{ policies: mode }` holds its statements to the policies, the querier's way where unset. */
|
|
14
16
|
export declare function enforcementOf(mode: PolicyMode | undefined): PolicyEnforcement;
|
|
@@ -53,6 +55,8 @@ export declare const POLICY_CONTEXT_KEY: RegExp;
|
|
|
53
55
|
* under a key a policy may read. Any other is left unbound, which a policy reads as NULL.
|
|
54
56
|
*/
|
|
55
57
|
export declare function contextEntries(context: UqlContext | undefined): [string, string][];
|
|
58
|
+
/** The database role `entries` bind at the pool's role `key`: none where unset, or set empty to unbind it. */
|
|
59
|
+
export declare function roleOf(entries: readonly (readonly [string, string])[], key: string | undefined): string | undefined;
|
|
56
60
|
/** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
|
|
57
61
|
declare const UNBOUND: unique symbol;
|
|
58
62
|
/** What a transaction bound for the database's policies: the context it last bound, and every key it bound so far. */
|
package/dist/util/policy.util.js
CHANGED
|
@@ -148,6 +148,10 @@ export function contextEntries(context) {
|
|
|
148
148
|
return scalar ? [[key, String(value)]] : [];
|
|
149
149
|
});
|
|
150
150
|
}
|
|
151
|
+
/** The database role `entries` bind at the pool's role `key`: none where unset, or set empty to unbind it. */
|
|
152
|
+
export function roleOf(entries, key) {
|
|
153
|
+
return entries.find(([it]) => it === key)?.[1] || undefined;
|
|
154
|
+
}
|
|
151
155
|
/** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
|
|
152
156
|
const UNBOUND = Symbol('unbound');
|
|
153
157
|
export const NOTHING_BOUND = { context: UNBOUND, keys: [] };
|
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.115.
|
|
6
|
+
"version": "0.115.3",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -186,7 +186,7 @@ await withContext({ tenantId: 42, userId: 'u1' }, () => pool.findMany(Invoice, {
|
|
|
186
186
|
- `explainPolicies(Invoice, 'read')` answers the `where` the querier ANDs in under the ambient context (and `check` for a write): what to look at when a read reaches no row.
|
|
187
187
|
- `$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.
|
|
188
188
|
- 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 check the row alone cannot settle is read back 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 }`.
|
|
189
|
-
- `{ 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. 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
|
|
189
|
+
- `{ 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 installs as `TO` those roles. 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
|
|
190
190
|
|
|
191
191
|
## Queries
|
|
192
192
|
|