uql-orm 0.115.3 → 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/abstractSqlDialect.d.ts +2 -0
- package/dist/dialect/abstractSqlDialect.js +2 -0
- package/dist/dialect/pgLikeSqlDialect.js +2 -2
- package/dist/migrate/ddl/tableDdl.d.ts +3 -10
- package/dist/migrate/ddl/tableDdl.js +9 -8
- package/dist/migrate/drift/driftDetector.js +4 -9
- package/dist/migrate/index.d.ts +1 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -3
- package/dist/migrate/introspection/postgresIntrospector.js +3 -3
- package/dist/migrate/policySql.js +9 -13
- package/dist/migrate/schemaGenerator.js +9 -7
- package/dist/schema/schemaASTBuilder.d.ts +0 -2
- package/dist/schema/schemaASTBuilder.js +1 -1
- package/dist/schema/schemaASTDiffer.js +5 -9
- package/dist/schema/types.d.ts +6 -6
- package/dist/type/migration.d.ts +4 -2
- package/dist/type/querier.d.ts +1 -1
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +1 -1
|
@@ -845,6 +845,8 @@ 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
852
|
/**
|
|
@@ -2275,6 +2275,8 @@ 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`);
|
|
@@ -92,8 +92,8 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
92
92
|
}
|
|
93
93
|
/** Where the pool binds roles, an unnamed one is the connection's own, which unbinding one goes back to. */
|
|
94
94
|
rowSecurityBypassQuery(role) {
|
|
95
|
-
const name = role === undefined ? (this.policies.role ? 'session_user' :
|
|
96
|
-
return `SELECT
|
|
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`;
|
|
97
97
|
}
|
|
98
98
|
/** `USING MESSAGE`, so the text is taken as it is rather than as a format reading each `%`. */
|
|
99
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,7 +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
|
+
...diff.rowSecurity.filter(({ to }) => to === 'forced').map(rowSecurityDrift),
|
|
19
19
|
...diff.relationships.map(relationshipDrift),
|
|
20
20
|
];
|
|
21
21
|
const count = (severity) => drifts.filter((drift) => drift.severity === severity).length;
|
|
@@ -51,14 +51,9 @@ function detectOwnedDrifts(kind, changes) {
|
|
|
51
51
|
? `${kind} "${to.name}" expected but not found in database`
|
|
52
52
|
: `${kind} "${from?.name}" exists in database but not in entity`, Boolean(to)));
|
|
53
53
|
}
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
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));
|
|
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);
|
|
62
57
|
}
|
|
63
58
|
/** What uql owns on `table` differing from the entity: critical where the database lacks what it `expected`. */
|
|
64
59
|
function ownedDrift(table, details, expected) {
|
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.
|
|
@@ -81,7 +81,7 @@ export declare abstract class AbstractSqlSchemaIntrospector implements SchemaInt
|
|
|
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
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<
|
|
84
|
+
protected getRowSecurity(_read: TableRowReader, _tableName: string): Promise<RowSecurity | undefined>;
|
|
85
85
|
/** See {@link TableSchema.definition}: none, but where the engine keeps the statements themselves. */
|
|
86
86
|
protected getDefinition(_read: TableRowReader, _tableName: string): Promise<StoredDefinition[] | undefined>;
|
|
87
87
|
/**
|
|
@@ -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,8 +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
|
-
/**
|
|
19
|
-
protected getRowSecurity(read: TableRowReader, tableName: string): Promise<
|
|
18
|
+
/** Forcing counts only where it is enabled, as Postgres reads it. */
|
|
19
|
+
protected getRowSecurity(read: TableRowReader, tableName: string): Promise<RowSecurity | undefined>;
|
|
20
20
|
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
21
21
|
protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
|
|
22
22
|
protected getTableNamesQuery(): QuerySql;
|
|
@@ -41,15 +41,15 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
|
|
|
41
41
|
`);
|
|
42
42
|
return rows.flatMap(({ name, definition }) => (isOwnedName(name) ? [{ name, statements: [definition] }] : []));
|
|
43
43
|
}
|
|
44
|
-
/**
|
|
44
|
+
/** Forcing counts only where it is enabled, as Postgres reads it. */
|
|
45
45
|
async getRowSecurity(read, tableName) {
|
|
46
46
|
const [row] = await read(sql `
|
|
47
|
-
SELECT c.relrowsecurity
|
|
47
|
+
SELECT CASE WHEN NOT c.relrowsecurity THEN 'off' WHEN c.relforcerowsecurity THEN 'forced' ELSE 'enabled' END AS state
|
|
48
48
|
FROM pg_class c
|
|
49
49
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
50
50
|
WHERE n.nspname = ${this.schemaExpr} AND c.relname = ${tableName}
|
|
51
51
|
`);
|
|
52
|
-
return row?.
|
|
52
|
+
return row?.state;
|
|
53
53
|
}
|
|
54
54
|
/** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
|
|
55
55
|
async getChecks(read, tableName) {
|
|
@@ -31,14 +31,14 @@ export function renderPolicies(dialect, meta, columnType) {
|
|
|
31
31
|
};
|
|
32
32
|
return policiesOf(meta.policies).flatMap((policy, position) => {
|
|
33
33
|
const label = policy.name ?? `${policy.effect}_${position}`;
|
|
34
|
-
const [roles, when] = rolesOf(policy.when, dialect.policies.role);
|
|
35
34
|
const predicate = (where) => {
|
|
36
35
|
const bound = asWhere(meta, bindContext(meta, where, read));
|
|
37
36
|
const { rowSecurity } = dialect.features;
|
|
38
37
|
if (!(rowSecurity && rowSecurity.subqueries) && readsRelations(meta, bound)) {
|
|
39
38
|
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
39
|
}
|
|
41
|
-
return ([...whenSql(dialect, when), dialect.compileDdl(bound, meta.entity)].filter(Boolean).join(' AND ') ||
|
|
40
|
+
return ([...whenSql(dialect, policy.when), dialect.compileDdl(bound, meta.entity)].filter(Boolean).join(' AND ') ||
|
|
41
|
+
'true');
|
|
42
42
|
};
|
|
43
43
|
const commands = POLICY_OPS.every((op) => policy.ops.includes(op))
|
|
44
44
|
? [['ALL', undefined]]
|
|
@@ -47,7 +47,7 @@ export function renderPolicies(dialect, meta, columnType) {
|
|
|
47
47
|
const using = command === 'INSERT' ? undefined : predicate(policy.where);
|
|
48
48
|
const check = writes(command) ? predicate(policy.check ?? policy.where) : undefined;
|
|
49
49
|
const create = (name) => [
|
|
50
|
-
`CREATE POLICY ${dialect.escapeId(name)} ON ${target} AS ${policy.effect === 'allow' ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${command} TO
|
|
50
|
+
`CREATE POLICY ${dialect.escapeId(name)} ON ${target} AS ${policy.effect === 'allow' ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${command} TO PUBLIC`,
|
|
51
51
|
...(using === undefined ? [] : [`USING (${using})`]),
|
|
52
52
|
...(check === undefined ? [] : [`WITH CHECK (${check})`]),
|
|
53
53
|
].join(' ');
|
|
@@ -65,18 +65,14 @@ export function dropPolicy(dialect, table, name) {
|
|
|
65
65
|
return `DROP POLICY IF EXISTS ${dialect.escapeId(name)} ON ${dialect.escapeId(table)}`;
|
|
66
66
|
}
|
|
67
67
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
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
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. */
|
|
77
71
|
function whenSql(dialect, when) {
|
|
78
|
-
|
|
72
|
+
const { role } = dialect.policies;
|
|
73
|
+
return Object.entries(when ?? {}).map(([key, value]) => {
|
|
79
74
|
const values = [value].flat().map((it) => dialect.escape(String(it)));
|
|
80
|
-
|
|
75
|
+
const read = key === role ? dialect.currentRole : dialect.contextRead(key, 'text');
|
|
76
|
+
return values.length ? `${read} IN (${values.join(', ')})` : 'false';
|
|
81
77
|
});
|
|
82
78
|
}
|
|
@@ -72,7 +72,6 @@ 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,
|
|
76
75
|
vectorIndexRequiresNotNull: this.features.vectorIndexRequiresNotNull,
|
|
77
76
|
});
|
|
78
77
|
}
|
|
@@ -95,7 +94,9 @@ export class SqlSchemaGenerator {
|
|
|
95
94
|
...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))),
|
|
96
95
|
// Policies after them, a membership read through a table the same schema just made included.
|
|
97
96
|
...tables.flatMap((table) => [
|
|
98
|
-
...(table.rowSecurity
|
|
97
|
+
...(table.rowSecurity
|
|
98
|
+
? this.tableDdl.rowSecurity(qualifyName(table.name, table.schema), table.rowSecurity)
|
|
99
|
+
: []),
|
|
99
100
|
...terminated(table.policies.flatMap((policy) => policy.statements)),
|
|
100
101
|
]),
|
|
101
102
|
];
|
|
@@ -177,14 +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
|
-
// Row-level security
|
|
181
|
-
const
|
|
182
|
-
const
|
|
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, []];
|
|
183
185
|
const policyDrops = [
|
|
184
186
|
...terminated(sides(policies, 'from').map((policy) => dropPolicy(this.dialect, tableName, policy.name))),
|
|
185
|
-
...
|
|
187
|
+
...after,
|
|
186
188
|
];
|
|
187
|
-
const policyCreates = [...
|
|
189
|
+
const policyCreates = [...before, ...terminated(sides(policies, 'to').flatMap((policy) => policy.statements))];
|
|
188
190
|
if (rebuild) {
|
|
189
191
|
return [
|
|
190
192
|
...triggerDrops,
|
|
@@ -22,8 +22,6 @@ 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;
|
|
27
25
|
}
|
|
28
26
|
/**
|
|
29
27
|
* Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
|
|
@@ -61,7 +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 =
|
|
64
|
+
table.rowSecurity = table.policies.length ? 'forced' : undefined;
|
|
65
65
|
ctx.ast.addTable(table);
|
|
66
66
|
return table;
|
|
67
67
|
}
|
|
@@ -50,18 +50,14 @@ export function diffTable(source, target, options = {}) {
|
|
|
50
50
|
: undefined;
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
|
-
* Row-level security
|
|
54
|
-
*
|
|
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
55
|
*/
|
|
56
56
|
function diffRowSecurity(source, target) {
|
|
57
|
-
const { rowSecurity: to } = source;
|
|
58
57
|
const { rowSecurity: from } = target;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
return to || target.policies.some((policy) => isOwnedName(policy.name))
|
|
63
|
-
? { table: source.name, from, to }
|
|
64
|
-
: undefined;
|
|
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;
|
|
65
61
|
}
|
|
66
62
|
/**
|
|
67
63
|
* What one side declares and the other has not installed, by name, for an object named after a hash of its
|
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';
|
|
@@ -140,10 +140,10 @@ export interface TableNode {
|
|
|
140
140
|
/** The row-level policies uql installs on this table. */
|
|
141
141
|
readonly policies: PolicySchema[];
|
|
142
142
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
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
145
|
*/
|
|
146
|
-
rowSecurity?:
|
|
146
|
+
rowSecurity?: RowSecurity;
|
|
147
147
|
/** Optional table comment */
|
|
148
148
|
readonly comment?: string;
|
|
149
149
|
/** The statements the engine keeps for the table, where it keeps them; none on a table built from entities. */
|
|
@@ -239,7 +239,7 @@ export interface TableDiff {
|
|
|
239
239
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
240
240
|
readonly policies: TableChange<PolicySchema>[];
|
|
241
241
|
/** Set only where {@link TableNode.rowSecurity} differs as uql's policies need it. */
|
|
242
|
-
readonly rowSecurity?: TableChange<
|
|
242
|
+
readonly rowSecurity?: TableChange<RowSecurity>;
|
|
243
243
|
/** Set only when the two primary keys have different columns. */
|
|
244
244
|
readonly primaryKey?: PrimaryKeyDiff;
|
|
245
245
|
}
|
|
@@ -252,7 +252,7 @@ export interface SchemaDiffResult {
|
|
|
252
252
|
readonly checks: TableChange<CheckSchema>[];
|
|
253
253
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
254
254
|
readonly policies: TableChange<PolicySchema>[];
|
|
255
|
-
readonly rowSecurity: TableChange<
|
|
255
|
+
readonly rowSecurity: TableChange<RowSecurity>[];
|
|
256
256
|
readonly primaryKeys: PrimaryKeyDiff[];
|
|
257
257
|
readonly relationships: RelationshipDiff[];
|
|
258
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
|
*/
|
|
@@ -104,7 +106,7 @@ export interface TableSchema {
|
|
|
104
106
|
/** The row-level policies uql installed, each with the statement the engine would recreate it from. */
|
|
105
107
|
readonly policies?: PolicySchema[];
|
|
106
108
|
/** See {@link TableNode.rowSecurity}. */
|
|
107
|
-
readonly rowSecurity?:
|
|
109
|
+
readonly rowSecurity?: RowSecurity;
|
|
108
110
|
/** The statements the engine keeps for the table, where it keeps them: SQLite's `sqlite_master`. */
|
|
109
111
|
readonly definition?: readonly StoredDefinition[];
|
|
110
112
|
}
|
|
@@ -215,7 +217,7 @@ export interface SchemaDiff {
|
|
|
215
217
|
/** The row-level policies installed or declared, none kept: a changed one is a new name. */
|
|
216
218
|
readonly policies?: readonly Change<PolicySchema>[];
|
|
217
219
|
/** See {@link TableDiff.rowSecurity}. */
|
|
218
|
-
readonly rowSecurity?: Change<
|
|
220
|
+
readonly rowSecurity?: Change<RowSecurity>;
|
|
219
221
|
/** Columns renamed in place, `from` the database's name `to` the entity's, which the other changes already use. */
|
|
220
222
|
readonly renamedColumns?: readonly Rename[];
|
|
221
223
|
/**
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -195,7 +195,7 @@ export type ExtraOptions = {
|
|
|
195
195
|
readonly policies?: PolicyMode;
|
|
196
196
|
/**
|
|
197
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
|
|
198
|
+
* `when` on it compares that role exactly. Unset, they run as the role the pool connects as.
|
|
199
199
|
*/
|
|
200
200
|
readonly role?: ContextRef<string>;
|
|
201
201
|
};
|
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. `role: $context.role` beside it runs each transaction as the database role the context names, and a `when` on that key
|
|
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
|
|