uql-orm 0.115.2 → 0.115.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.
- package/dist/dialect/abstractDialect.d.ts +9 -2
- package/dist/dialect/abstractDialect.js +17 -4
- package/dist/dialect/abstractSqlDialect.d.ts +7 -2
- package/dist/dialect/abstractSqlDialect.js +7 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +6 -2
- package/dist/dialect/pgLikeSqlDialect.js +13 -4
- package/dist/migrate/ddl/tableDdl.d.ts +3 -10
- package/dist/migrate/ddl/tableDdl.js +9 -8
- package/dist/migrate/drift/driftDetector.js +15 -5
- package/dist/migrate/index.d.ts +1 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
- package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
- 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 +8 -4
- package/dist/migrate/schemaChange.js +1 -0
- package/dist/migrate/schemaGenerator.d.ts +0 -2
- package/dist/migrate/schemaGenerator.js +13 -16
- package/dist/querier/abstractSqlQuerier.d.ts +2 -2
- package/dist/querier/abstractSqlQuerier.js +10 -9
- package/dist/schema/schemaASTBuilder.js +1 -0
- package/dist/schema/schemaASTDiffer.js +14 -2
- package/dist/schema/types.d.ts +9 -1
- package/dist/type/migration.d.ts +6 -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
|
@@ -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
|
|
@@ -845,10 +845,15 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
845
845
|
* the engine holds read them: none on an engine holding none.
|
|
846
846
|
*/
|
|
847
847
|
contextBinding(_entries: readonly (readonly [string, string])[]): BoundStatement | undefined;
|
|
848
|
+
/** The role a statement runs as, ANSI's spelling. */
|
|
849
|
+
readonly currentRole: string;
|
|
848
850
|
/** A policy's read of context key `key` as a value of SQL type `type`, NULL where the transaction bound none. */
|
|
849
851
|
contextRead(key: string, _type: string): string;
|
|
850
|
-
/**
|
|
851
|
-
|
|
852
|
+
/**
|
|
853
|
+
* What answers whether `role`, or the role a transaction runs as where it names none, reads past row-level
|
|
854
|
+
* security, as one row's `bypasses`.
|
|
855
|
+
*/
|
|
856
|
+
rowSecurityBypassQuery(_role?: string): string;
|
|
852
857
|
/** ANSI-style single-quote escaping. */
|
|
853
858
|
escape(value: unknown): string;
|
|
854
859
|
/** The `$regex` predicate, case-sensitive on every engine. */
|
|
@@ -2275,12 +2275,17 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
2275
2275
|
contextBinding(_entries) {
|
|
2276
2276
|
return undefined;
|
|
2277
2277
|
}
|
|
2278
|
+
/** The role a statement runs as, ANSI's spelling. */
|
|
2279
|
+
currentRole = 'current_user';
|
|
2278
2280
|
/** A policy's read of context key `key` as a value of SQL type `type`, NULL where the transaction bound none. */
|
|
2279
2281
|
contextRead(key, _type) {
|
|
2280
2282
|
throw new UqlUsageError(`${this.engineName} reads no context key in SQL, so '${key}' has no rendering`);
|
|
2281
2283
|
}
|
|
2282
|
-
/**
|
|
2283
|
-
|
|
2284
|
+
/**
|
|
2285
|
+
* What answers whether `role`, or the role a transaction runs as where it names none, reads past row-level
|
|
2286
|
+
* security, as one row's `bypasses`.
|
|
2287
|
+
*/
|
|
2288
|
+
rowSecurityBypassQuery(_role) {
|
|
2284
2289
|
throw new UqlUsageError(`${this.engineName} holds no row to a policy itself`);
|
|
2285
2290
|
}
|
|
2286
2291
|
/** 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' : this.currentRole) : this.escape(role);
|
|
96
|
+
return `SELECT EXISTS (SELECT FROM pg_roles WHERE rolname = ${name} AND (rolsuper OR rolbypassrls)) AS bypasses`;
|
|
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) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
|
|
2
|
-
import type { ColumnSchema, PrimaryKeySchema } from '../../type/index.js';
|
|
2
|
+
import type { ColumnSchema, PrimaryKeySchema, RowSecurity } from '../../type/index.js';
|
|
3
3
|
import { UqlUsageError } from '../../util/uqlError.js';
|
|
4
4
|
/** A column to change into `to`, from what it was where that is known: the builder alters a column it never read. */
|
|
5
5
|
export type ColumnAlteration = {
|
|
@@ -11,10 +11,6 @@ export type Commented = {
|
|
|
11
11
|
readonly name: string;
|
|
12
12
|
readonly comment?: string;
|
|
13
13
|
};
|
|
14
|
-
/**
|
|
15
|
-
* Table DDL that engines spell differently. Like {@link IndexDdl}, it belongs to the migrator, so no runtime
|
|
16
|
-
* entry carries it. This class holds the portable form, which SQLite takes; other families override what differs.
|
|
17
|
-
*/
|
|
18
14
|
export declare class TableDdl {
|
|
19
15
|
protected readonly dialect: AbstractSqlDialect;
|
|
20
16
|
constructor(dialect: AbstractSqlDialect);
|
|
@@ -43,11 +39,8 @@ export declare class TableDdl {
|
|
|
43
39
|
* changes a column only by rebuilding its table, which a diff states as `rebuild`.
|
|
44
40
|
*/
|
|
45
41
|
protected alterClauses(column: ColumnSchema, _from?: ColumnSchema): string[];
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
* off with its last, since forced with none it shows no row to anyone.
|
|
49
|
-
*/
|
|
50
|
-
rowSecurity(table: string, on: boolean): string[];
|
|
42
|
+
/** What puts `table`'s row-level security in `state`, whatever it was. */
|
|
43
|
+
rowSecurity(table: string, state: RowSecurity): string[];
|
|
51
44
|
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
52
45
|
protected alterTable(table: string, clauses: readonly string[]): string[];
|
|
53
46
|
renameColumn(table: string, oldName: string, newName: string): string;
|
|
@@ -5,6 +5,12 @@ import { formatDefaultValue } from './defaultSql.js';
|
|
|
5
5
|
* Table DDL that engines spell differently. Like {@link IndexDdl}, it belongs to the migrator, so no runtime
|
|
6
6
|
* entry carries it. This class holds the portable form, which SQLite takes; other families override what differs.
|
|
7
7
|
*/
|
|
8
|
+
/** The clauses putting a table's row-level security in each state. */
|
|
9
|
+
const ROW_SECURITY = {
|
|
10
|
+
forced: ['ENABLE ROW LEVEL SECURITY', 'FORCE ROW LEVEL SECURITY'],
|
|
11
|
+
enabled: ['ENABLE ROW LEVEL SECURITY', 'NO FORCE ROW LEVEL SECURITY'],
|
|
12
|
+
off: ['NO FORCE ROW LEVEL SECURITY', 'DISABLE ROW LEVEL SECURITY'],
|
|
13
|
+
};
|
|
8
14
|
export class TableDdl {
|
|
9
15
|
dialect;
|
|
10
16
|
constructor(dialect) {
|
|
@@ -60,14 +66,9 @@ export class TableDdl {
|
|
|
60
66
|
alterClauses(column, _from) {
|
|
61
67
|
throw rebuildRefusal(this.dialect, `Altering the column "${column.name}"`);
|
|
62
68
|
}
|
|
63
|
-
/**
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
*/
|
|
67
|
-
rowSecurity(table, on) {
|
|
68
|
-
return this.alterTable(table, on
|
|
69
|
-
? ['ENABLE ROW LEVEL SECURITY', 'FORCE ROW LEVEL SECURITY']
|
|
70
|
-
: ['NO FORCE ROW LEVEL SECURITY', 'DISABLE ROW LEVEL SECURITY']);
|
|
69
|
+
/** What puts `table`'s row-level security in `state`, whatever it was. */
|
|
70
|
+
rowSecurity(table, state) {
|
|
71
|
+
return this.alterTable(table, ROW_SECURITY[state]);
|
|
71
72
|
}
|
|
72
73
|
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
73
74
|
alterTable(table, clauses) {
|
|
@@ -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.filter(({ to }) => to === 'forced').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,23 @@ 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
|
+
/** Row-level security not forced under uql's policies, critical. Unforced with none left, the policies left report it. */
|
|
55
|
+
function rowSecurityDrift({ table, from }) {
|
|
56
|
+
return ownedDrift(table, `Row-level security on "${table}" is ${from}, where its policies need it forced`, true);
|
|
57
|
+
}
|
|
58
|
+
/** What uql owns on `table` differing from the entity: critical where the database lacks what it `expected`. */
|
|
59
|
+
function ownedDrift(table, details, expected) {
|
|
60
|
+
return {
|
|
50
61
|
type: 'constraint_mismatch',
|
|
51
62
|
table,
|
|
63
|
+
details,
|
|
64
|
+
severity: expected ? 'critical' : 'warning',
|
|
52
65
|
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
|
-
}));
|
|
66
|
+
};
|
|
57
67
|
}
|
|
58
68
|
/** A key's columns as a drift names them, `none` where there is no key. */
|
|
59
69
|
function keyColumns(key) {
|
package/dist/migrate/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { Change, ColumnSchema, Config, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigratorOptions, PrimaryKeySchema, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
|
|
1
|
+
export type { Change, ColumnSchema, Config, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigratorOptions, PrimaryKeySchema, RowSecurity, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
|
|
2
2
|
export * from './builder/index.js';
|
|
3
3
|
export { EntityCodeGenerator, type EntityCodeGeneratorOptions, type GeneratedEntity, } from './codegen/entityCodeGenerator.js';
|
|
4
4
|
export { buildMigrationModule, type MigrationModuleOptions, type MigrationQuerierType, } from './codegen/migrationFile.js';
|
|
@@ -4,7 +4,7 @@ import type { SchemaAST } from '../../schema/schemaAST.js';
|
|
|
4
4
|
import { SqlExpression } from '../../schema/sqlExpression.js';
|
|
5
5
|
import type { CheckSchema, ColumnDefault, PolicySchema, TriggerSchema } from '../../schema/types.js';
|
|
6
6
|
import { type ForeignKeyAction } from '../../schema/types.js';
|
|
7
|
-
import type { ColumnRenames, ColumnSchema, Except, ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerierPool, QuerySql, RawRow, SchemaIntrospector, SqlQuerier, StoredDefinition, TableSchema } from '../../type/index.js';
|
|
7
|
+
import type { ColumnRenames, ColumnSchema, Except, ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerierPool, QuerySql, RawRow, RowSecurity, SchemaIntrospector, SqlQuerier, StoredDefinition, TableSchema } from '../../type/index.js';
|
|
8
8
|
/**
|
|
9
9
|
* Reads the rows of one statement while introspecting a table, an identical statement sent once: SQLite's
|
|
10
10
|
* `table_info` is both the column list and the key, and on D1 and Turso every PRAGMA is a round trip.
|
|
@@ -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<RowSecurity | 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;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { IndexFacet } from '../../schema/indexDifferences.js';
|
|
2
2
|
import { type CheckSchema, type ColumnDefault, type PolicySchema } from '../../schema/types.js';
|
|
3
|
-
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql } from '../../type/index.js';
|
|
3
|
+
import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerySql, RowSecurity } from '../../type/index.js';
|
|
4
4
|
import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
|
|
5
5
|
/**
|
|
6
6
|
* PostgreSQL schema introspector
|
|
@@ -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
|
+
/** Forcing counts only where it is enabled, as Postgres reads it. */
|
|
19
|
+
protected getRowSecurity(read: TableRowReader, tableName: string): Promise<RowSecurity | 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
|
+
/** Forcing counts only where it is enabled, as Postgres reads it. */
|
|
45
|
+
async getRowSecurity(read, tableName) {
|
|
46
|
+
const [row] = await read(sql `
|
|
47
|
+
SELECT CASE WHEN NOT c.relrowsecurity THEN 'off' WHEN c.relforcerowsecurity THEN 'forced' ELSE 'enabled' END AS state
|
|
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?.state;
|
|
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) {
|
|
@@ -65,10 +64,15 @@ 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
|
+
* A `when` as the context comparisons it is, each read as text, as the binding sends every value. The pool's role key
|
|
69
|
+
* reads the role itself, not `TO`: see architecture/row-level-security.md.
|
|
70
|
+
*/
|
|
69
71
|
function whenSql(dialect, when) {
|
|
72
|
+
const { role } = dialect.policies;
|
|
70
73
|
return Object.entries(when ?? {}).map(([key, value]) => {
|
|
71
74
|
const values = [value].flat().map((it) => dialect.escape(String(it)));
|
|
72
|
-
|
|
75
|
+
const read = key === role ? dialect.currentRole : dialect.contextRead(key, 'text');
|
|
76
|
+
return values.length ? `${read} IN (${values.join(', ')})` : 'false';
|
|
73
77
|
});
|
|
74
78
|
}
|
|
@@ -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;
|
|
@@ -93,11 +93,12 @@ export class SqlSchemaGenerator {
|
|
|
93
93
|
// Triggers last: each needs its own table, and a body may read any other the same schema just made.
|
|
94
94
|
...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))),
|
|
95
95
|
// Policies after them, a membership read through a table the same schema just made included.
|
|
96
|
-
...tables.flatMap((table) =>
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
96
|
+
...tables.flatMap((table) => [
|
|
97
|
+
...(table.rowSecurity
|
|
98
|
+
? this.tableDdl.rowSecurity(qualifyName(table.name, table.schema), table.rowSecurity)
|
|
99
|
+
: []),
|
|
100
|
+
...terminated(table.policies.flatMap((policy) => policy.statements)),
|
|
101
|
+
]),
|
|
101
102
|
];
|
|
102
103
|
}
|
|
103
104
|
/**
|
|
@@ -177,12 +178,15 @@ export class SqlSchemaGenerator {
|
|
|
177
178
|
const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, trigger.name)));
|
|
178
179
|
const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
|
|
179
180
|
const policies = cycled(diff.policies);
|
|
180
|
-
|
|
181
|
+
// Row-level security is forced before the first policy, and eased after the last.
|
|
182
|
+
const to = diff.rowSecurity?.to;
|
|
183
|
+
const switched = to ? this.tableDdl.rowSecurity(tableName, to) : [];
|
|
184
|
+
const [after, before] = to === 'forced' ? [[], switched] : [switched, []];
|
|
181
185
|
const policyDrops = [
|
|
182
186
|
...terminated(sides(policies, 'from').map((policy) => dropPolicy(this.dialect, tableName, policy.name))),
|
|
183
|
-
...
|
|
187
|
+
...after,
|
|
184
188
|
];
|
|
185
|
-
const policyCreates = [...
|
|
189
|
+
const policyCreates = [...before, ...terminated(sides(policies, 'to').flatMap((policy) => policy.statements))];
|
|
186
190
|
if (rebuild) {
|
|
187
191
|
return [
|
|
188
192
|
...triggerDrops,
|
|
@@ -215,14 +219,6 @@ export class SqlSchemaGenerator {
|
|
|
215
219
|
...policyCreates,
|
|
216
220
|
];
|
|
217
221
|
}
|
|
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
222
|
/** `CONSTRAINT <name> CHECK (...)`, in a `CREATE TABLE`, after `ADD`, or inline where a column brings it. */
|
|
227
223
|
checkConstraint(check) {
|
|
228
224
|
return `CONSTRAINT ${this.escapeId(check.name)} CHECK (${check.expression})`;
|
|
@@ -304,6 +300,7 @@ export class SqlSchemaGenerator {
|
|
|
304
300
|
// A kept trigger or policy as both sides, which the alter cycles only where a column it names moves under it.
|
|
305
301
|
triggers: nonEmpty([...(tableDiff?.triggers ?? []), ...kept(desired.triggers, currentTable.triggers)]),
|
|
306
302
|
policies: nonEmpty([...(tableDiff?.policies ?? []), ...kept(desired.policies, currentTable.policies)]),
|
|
303
|
+
rowSecurity: tableDiff?.rowSecurity,
|
|
307
304
|
renamedColumns: nonEmpty(renamedColumns ?? []),
|
|
308
305
|
};
|
|
309
306
|
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
|
}
|
|
@@ -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 = table.policies.length ? 'forced' : 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,11 +43,22 @@ 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 }
|
|
48
50
|
: undefined;
|
|
49
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Row-level security forced under uql's policies, and unforced once its last is gone, never disabled: a table someone
|
|
54
|
+
* else enabled stays so. Left alone on a table holding none of uql's.
|
|
55
|
+
*/
|
|
56
|
+
function diffRowSecurity(source, target) {
|
|
57
|
+
const { rowSecurity: from } = target;
|
|
58
|
+
const left = from === 'forced' && target.policies.some((policy) => isOwnedName(policy.name));
|
|
59
|
+
const to = source.rowSecurity ?? (left ? 'enabled' : undefined);
|
|
60
|
+
return from && to && from !== to ? { table: source.name, from, to } : undefined;
|
|
61
|
+
}
|
|
50
62
|
/**
|
|
51
63
|
* What one side declares and the other has not installed, by name, for an object named after a hash of its
|
|
52
64
|
* SQL. Only uql's own are ever dropped: the rest are a second writer's.
|
package/dist/schema/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Alteration, Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
|
|
1
|
+
import type { Alteration, Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition, RowSecurity } from '../type/migration.js';
|
|
2
2
|
import type { JsonScalar } from '../type/utility.js';
|
|
3
3
|
import type { IndexFacet } from './indexDifferences.js';
|
|
4
4
|
import type { SqlExpression } from './sqlExpression.js';
|
|
@@ -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
|
+
* The table's row-level security: `forced` where uql installs a policy on it, so its owner is held too; from a
|
|
144
|
+
* database, as its catalogue says. Unset where uql states nothing, or the engine has none.
|
|
145
|
+
*/
|
|
146
|
+
rowSecurity?: RowSecurity;
|
|
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<RowSecurity>;
|
|
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<RowSecurity>[];
|
|
248
256
|
readonly primaryKeys: PrimaryKeyDiff[];
|
|
249
257
|
readonly relationships: RelationshipDiff[];
|
|
250
258
|
}
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -89,6 +89,8 @@ export interface ColumnSchema extends Except<ColumnNode, 'type' | 'table'> {
|
|
|
89
89
|
readonly precision?: number;
|
|
90
90
|
readonly scale?: number;
|
|
91
91
|
}
|
|
92
|
+
/** A table's row-level security: enabled and forced, enabled alone (its owner reads past it), or off. */
|
|
93
|
+
export type RowSecurity = 'forced' | 'enabled' | 'off';
|
|
92
94
|
/**
|
|
93
95
|
* Represents a database table schema
|
|
94
96
|
*/
|
|
@@ -103,6 +105,8 @@ export interface TableSchema {
|
|
|
103
105
|
readonly triggers?: TriggerSchema[];
|
|
104
106
|
/** The row-level policies uql installed, each with the statement the engine would recreate it from. */
|
|
105
107
|
readonly policies?: PolicySchema[];
|
|
108
|
+
/** See {@link TableNode.rowSecurity}. */
|
|
109
|
+
readonly rowSecurity?: RowSecurity;
|
|
106
110
|
/** The statements the engine keeps for the table, where it keeps them: SQLite's `sqlite_master`. */
|
|
107
111
|
readonly definition?: readonly StoredDefinition[];
|
|
108
112
|
}
|
|
@@ -212,6 +216,8 @@ export interface SchemaDiff {
|
|
|
212
216
|
readonly triggers?: readonly Change<TriggerSchema>[];
|
|
213
217
|
/** The row-level policies installed or declared, none kept: a changed one is a new name. */
|
|
214
218
|
readonly policies?: readonly Change<PolicySchema>[];
|
|
219
|
+
/** See {@link TableDiff.rowSecurity}. */
|
|
220
|
+
readonly rowSecurity?: Change<RowSecurity>;
|
|
215
221
|
/** Columns renamed in place, `from` the database's name `to` the entity's, which the other changes already use. */
|
|
216
222
|
readonly renamedColumns?: readonly Rename[];
|
|
217
223
|
/**
|
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 compares that role exactly. 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.4",
|
|
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 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
|
|
190
190
|
|
|
191
191
|
## Queries
|
|
192
192
|
|