uql-orm 0.114.3 → 0.115.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
- package/dist/cockroachdb/cockroachDialect.js +5 -0
- package/dist/d1/d1Querier.d.ts +2 -4
- package/dist/d1/d1Querier.js +0 -4
- package/dist/d1/d1SqliteDialect.js +1 -1
- package/dist/dialect/abstractDialect.d.ts +17 -8
- package/dist/dialect/abstractDialect.js +30 -16
- package/dist/dialect/abstractSqlDialect.d.ts +11 -2
- package/dist/dialect/abstractSqlDialect.js +17 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
- package/dist/dialect/operators.d.ts +2 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
- package/dist/dialect/pgLikeSqlDialect.js +20 -0
- package/dist/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
- package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
- package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
- package/dist/entity/metadata/definition.js +69 -30
- package/dist/http/api.d.ts +1 -1
- package/dist/http/wireQuery.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/migrate/ddl/tableDdl.d.ts +5 -0
- package/dist/migrate/ddl/tableDdl.js +9 -0
- package/dist/migrate/drift/driftDetector.js +2 -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 +14 -1
- package/dist/migrate/introspection/tableSchemaAST.js +1 -0
- package/dist/migrate/policySql.d.ts +12 -0
- package/dist/migrate/policySql.js +74 -0
- package/dist/migrate/schemaChange.js +1 -0
- package/dist/migrate/schemaGenerator.d.ts +2 -0
- package/dist/migrate/schemaGenerator.js +37 -11
- package/dist/mongodb/mongoDialect.js +3 -1
- package/dist/mongodb/mongodbQuerier.d.ts +2 -5
- package/dist/mongodb/mongodbQuerier.js +14 -26
- package/dist/mssql/mssqlDialect.js +2 -0
- package/dist/neon/neonQuerier.d.ts +1 -2
- package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
- package/dist/nestjs/uqlContextInterceptor.js +1 -1
- package/dist/nestjs/uqlModule.d.ts +2 -2
- package/dist/nestjs/uqlModule.js +1 -1
- package/dist/querier/abstractQuerier.d.ts +68 -30
- package/dist/querier/abstractQuerier.js +249 -168
- package/dist/querier/abstractQuerierPool.js +2 -0
- package/dist/querier/abstractSqlQuerier.d.ts +22 -13
- package/dist/querier/abstractSqlQuerier.js +75 -27
- package/dist/querier/queryError.js +1 -0
- package/dist/schema/schemaAST.js +1 -0
- package/dist/schema/schemaASTBuilder.d.ts +3 -1
- package/dist/schema/schemaASTBuilder.js +1 -0
- package/dist/schema/schemaASTDiffer.js +4 -2
- package/dist/schema/types.d.ts +12 -4
- package/dist/sqlite/bindValues.d.ts +1 -1
- package/dist/sqlite/hranaQuerier.d.ts +2 -2
- package/dist/sqlite/sqliteDialect.js +2 -0
- package/dist/turso/tursoSessionQuerier.d.ts +2 -2
- package/dist/type/column.d.ts +10 -0
- package/dist/type/definedEntity.d.ts +9 -4
- package/dist/type/dialect.d.ts +13 -0
- package/dist/type/entity.d.ts +10 -0
- package/dist/type/index.d.ts +1 -0
- package/dist/type/index.js +1 -0
- package/dist/type/migration.d.ts +5 -1
- package/dist/type/policy.d.ts +91 -0
- package/dist/type/policy.js +1 -0
- package/dist/type/querier.d.ts +16 -2
- package/dist/type/querierPool.d.ts +2 -2
- package/dist/type/query.d.ts +20 -35
- package/dist/type/query.js +2 -0
- package/dist/type/universalQuerier.d.ts +6 -6
- package/dist/util/contextRefs.d.ts +6 -0
- package/dist/util/contextRefs.js +5 -0
- package/dist/util/dialect.util.d.ts +10 -16
- package/dist/util/dialect.util.js +70 -64
- package/dist/util/fieldOption.util.js +1 -0
- package/dist/util/policy.util.d.ts +100 -0
- package/dist/util/policy.util.js +234 -0
- package/dist/util/uqlError.d.ts +2 -5
- package/dist/util/uqlError.js +2 -5
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +24 -14
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../dialect/index.js';
|
|
2
|
-
import type { EntityData, EntityMeta, ExtraOptions, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, ReportedWrite } from '../type/index.js';
|
|
2
|
+
import type { EntityData, EntityMeta, ExtraOptions, WrittenId, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, BoundStatement, ReportedWrite } from '../type/index.js';
|
|
3
3
|
import type { SqlExecution } from '../util/sql.util.js';
|
|
4
|
-
import { AbstractQuerier, type
|
|
5
|
-
/** A statement as it is sent: its SQL and the values it binds. */
|
|
6
|
-
export type BoundStatement = {
|
|
7
|
-
readonly sql: string;
|
|
8
|
-
readonly values: unknown[];
|
|
9
|
-
};
|
|
4
|
+
import { AbstractQuerier, type ReportingWrites } from './abstractQuerier.js';
|
|
10
5
|
export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
|
|
11
6
|
#private;
|
|
12
7
|
readonly dialect: AbstractSqlDialect;
|
|
@@ -42,6 +37,20 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
42
37
|
* where `atomic` (a split write) asks for one, opened before the queue is taken, which its `BEGIN` waits on.
|
|
43
38
|
*/
|
|
44
39
|
protected runStatements(statements: readonly BoundStatement[], atomic?: boolean): Promise<readonly SqlExecution[]>;
|
|
40
|
+
/**
|
|
41
|
+
* The statement binding the ambient context into the open transaction ahead of its next statement: none where it is
|
|
42
|
+
* bound already, or there is nothing to bind. `ask` runs the question of the connected role.
|
|
43
|
+
*/
|
|
44
|
+
private pendingBinding;
|
|
45
|
+
/** Whether a statement here runs under a context the database's policies read, which binds in a transaction. */
|
|
46
|
+
private bindsContext;
|
|
47
|
+
/**
|
|
48
|
+
* Refuses a statement under a context where the connected role reads past the database's policies, which would show
|
|
49
|
+
* one tenant another's rows. A statement under none, a migration's, runs as the owner it connects as.
|
|
50
|
+
*/
|
|
51
|
+
private assertHeldToPolicies;
|
|
52
|
+
/** {@link runStatements} once the context is bound. */
|
|
53
|
+
private runBound;
|
|
45
54
|
/** Runs `statements` one after another on the connection, each timed. */
|
|
46
55
|
private inTurn;
|
|
47
56
|
/** Runs `task` on the connection, connected, after everything queued before it. */
|
|
@@ -123,17 +132,16 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
123
132
|
/** The writes reading their rows off their own statement, where {@link AbstractSqlDialect.reportsWrite} says so. */
|
|
124
133
|
protected reportingWrites<E>(meta: EntityMeta<E>, write: ReportedWrite): ReportingWrites | undefined;
|
|
125
134
|
/**
|
|
126
|
-
* The id each row got: off the upsert's `RETURNING` where it has one, else off the header
|
|
127
|
-
*
|
|
128
|
-
* asked before the statement fills `onInsert` keys in).
|
|
135
|
+
* The id each row got: off the upsert's `RETURNING` where it has one, else off the header, none for a row skipped by
|
|
136
|
+
* `DO NOTHING` or its `$where`.
|
|
129
137
|
*/
|
|
130
|
-
protected internalUpsertMany<E extends object>(entity: Type<E>, q: QueryUpsert<E>, payload: E[]): Promise<(
|
|
138
|
+
protected internalUpsertMany<E extends object>(entity: Type<E>, q: QueryUpsert<E>, payload: E[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
131
139
|
/** The ids an upsert's header reports, by index: a statement of one row assigning a found row names its key. */
|
|
132
140
|
private headerIds;
|
|
133
141
|
/**
|
|
134
142
|
* The rows of `payload` an upsert writes, in its order, with the fields `keys` names, off its `RETURNING`: matched by
|
|
135
|
-
* the conflict keys `keys` includes, as no engine promises that order. `undefined` for a row it kept
|
|
136
|
-
*
|
|
143
|
+
* the conflict keys `keys` includes, as no engine promises that order. `undefined` for a row it kept. The statement
|
|
144
|
+
* fills `payload`'s `onInsert` fields.
|
|
137
145
|
*/
|
|
138
146
|
private upsertedRows;
|
|
139
147
|
/**
|
|
@@ -151,6 +159,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
151
159
|
* victim's on SQL Server, left nothing open to roll back.
|
|
152
160
|
*/
|
|
153
161
|
protected endTransaction(commit: boolean): Promise<void>;
|
|
162
|
+
/** A rollback to a savepoint undoes the context bound inside it, so the next statement binds it again. */
|
|
154
163
|
protected savepoint(command: SavepointCommand, name: string): Promise<void>;
|
|
155
164
|
/**
|
|
156
165
|
* How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { getContext } from '../context/context.js';
|
|
1
2
|
import { AGGREGATE_VALUE_ALIAS, KEY_DEFAULT_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
|
|
2
3
|
import { getMeta } from '../entity/index.js';
|
|
3
|
-
import { generatesKey, idOf,
|
|
4
|
+
import { generatesKey, idOf, namesKey, soleId } from '../entity/metadata/definition.js';
|
|
4
5
|
import { QuerySql } from '../type/querySql.js';
|
|
5
|
-
import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf,
|
|
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';
|
|
6
8
|
import { sql, statementOf } from '../util/sql.js';
|
|
7
9
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
8
10
|
import { AbstractQuerier } from './abstractQuerier.js';
|
|
@@ -63,9 +65,12 @@ function inPayloadOrder(meta, rows, reported) {
|
|
|
63
65
|
const [idKey] = meta.ids;
|
|
64
66
|
return generatesKey(meta) ? reported.toSorted((a, b) => byGeneratedKey(a[idKey], b[idKey])) : reported;
|
|
65
67
|
}
|
|
68
|
+
/** Each dialect whose connected role was found held to its policies, answered once per pool. */
|
|
69
|
+
const heldToPolicies = new WeakMap();
|
|
66
70
|
export class AbstractSqlQuerier extends AbstractQuerier {
|
|
67
71
|
dialect;
|
|
68
72
|
hasOpenTransaction = false;
|
|
73
|
+
#bound = NOTHING_BOUND;
|
|
69
74
|
/** Cached `auto_increment_increment` stride; see {@link loadInsertIdIncrement}. */
|
|
70
75
|
#insertIdIncrement;
|
|
71
76
|
constructor(dialect, extra) {
|
|
@@ -109,7 +114,52 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
109
114
|
* the driver has {@link executeBatch}, a failure tagged with the statement it names; else in turn, in a transaction
|
|
110
115
|
* where `atomic` (a split write) asks for one, opened before the queue is taken, which its `BEGIN` waits on.
|
|
111
116
|
*/
|
|
112
|
-
runStatements(statements, atomic = false) {
|
|
117
|
+
async runStatements(statements, atomic = false) {
|
|
118
|
+
if (!this.dialect.policies.database) {
|
|
119
|
+
return this.runBound(statements, atomic);
|
|
120
|
+
}
|
|
121
|
+
if (!this.scopeHere()) {
|
|
122
|
+
return this.bindsContext()
|
|
123
|
+
? this.atomically(() => this.runStatements(statements, atomic))
|
|
124
|
+
: this.runBound(statements, atomic);
|
|
125
|
+
}
|
|
126
|
+
const binding = await this.pendingBinding((sql) => this.onConnection(() => this.execute(sql)));
|
|
127
|
+
const results = await this.runBound(binding ? [binding, ...statements] : statements, atomic);
|
|
128
|
+
return binding ? results.slice(1) : results;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The statement binding the ambient context into the open transaction ahead of its next statement: none where it is
|
|
132
|
+
* bound already, or there is nothing to bind. `ask` runs the question of the connected role.
|
|
133
|
+
*/
|
|
134
|
+
async pendingBinding(ask) {
|
|
135
|
+
const { entries, bound } = nextBinding(this.#bound, getContext());
|
|
136
|
+
if (entries.length && this.bindsContext()) {
|
|
137
|
+
await this.assertHeldToPolicies(ask);
|
|
138
|
+
}
|
|
139
|
+
this.#bound = bound;
|
|
140
|
+
return this.dialect.contextBinding(entries);
|
|
141
|
+
}
|
|
142
|
+
/** Whether a statement here runs under a context the database's policies read, which binds in a transaction. */
|
|
143
|
+
bindsContext() {
|
|
144
|
+
return this.dialect.policies.database && contextEntries(getContext()).length > 0;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Refuses a statement under a context where the connected role reads past the database's policies, which would show
|
|
148
|
+
* one tenant another's rows. A statement under none, a migration's, runs as the owner it connects as.
|
|
149
|
+
*/
|
|
150
|
+
assertHeldToPolicies(ask) {
|
|
151
|
+
const { dialect } = this;
|
|
152
|
+
return cachedIn(heldToPolicies, dialect, () => ask(dialect.rowSecurityBypassQuery()).then(({ rows }) => {
|
|
153
|
+
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
|
+
}
|
|
156
|
+
})).catch((error) => {
|
|
157
|
+
heldToPolicies.delete(dialect);
|
|
158
|
+
throw error;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** {@link runStatements} once the context is bound. */
|
|
162
|
+
runBound(statements, atomic) {
|
|
113
163
|
const executeBatch = statements.length > 1 ? this.executeBatch?.bind(this) : undefined;
|
|
114
164
|
if (!executeBatch) {
|
|
115
165
|
const inTurn = () => this.inTurn(statements);
|
|
@@ -234,15 +284,20 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
234
284
|
*/
|
|
235
285
|
async *internalFindManyStream(entity, q, opts) {
|
|
236
286
|
const tuning = this.vectorTuning(entity, q);
|
|
237
|
-
|
|
238
|
-
|
|
287
|
+
const binds = this.bindsContext();
|
|
288
|
+
if (!this.scopeHere() && (binds || this.tunedInTransaction(tuning))) {
|
|
289
|
+
throw new UqlUsageError(`a stream ${binds ? 'binding its context for the policies' : 'of $candidates'} needs an open transaction on ${this.dialect.engineName}; run it inside pool.transaction(...)`);
|
|
239
290
|
}
|
|
240
291
|
const ctx = this.dialect.createContext();
|
|
241
292
|
const read = rowReader(this.dialect.find(ctx, entity, q, opts));
|
|
242
293
|
this.assertBindBudget(ctx.values);
|
|
243
294
|
await this.lazyConnect();
|
|
244
|
-
for
|
|
245
|
-
|
|
295
|
+
// The stream holds the querier for its loop, so its leading statements run on the connection directly.
|
|
296
|
+
const binding = this.scopeHere() && this.dialect.policies.database
|
|
297
|
+
? await this.pendingBinding((sql) => this.execute(sql))
|
|
298
|
+
: undefined;
|
|
299
|
+
for (const { sql, values } of binding ? [binding, ...tuning] : tuning) {
|
|
300
|
+
await this.timed(sql, values, () => this.execute(sql, values));
|
|
246
301
|
}
|
|
247
302
|
for await (const row of this.timedStream(ctx.sql, ctx.values, this.internalStream(ctx.sql, ctx.values))) {
|
|
248
303
|
yield read(row);
|
|
@@ -394,31 +449,19 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
394
449
|
#reportingWrites = {
|
|
395
450
|
update: (entity, q, payload, opts, keys) => this.readRows((ctx) => this.dialect.update(ctx, entity, q, payload, opts, keys)),
|
|
396
451
|
delete: (entity, q, opts, keys) => this.readRows((ctx) => this.dialect.delete(ctx, entity, q, opts, keys)),
|
|
397
|
-
upsert: (entity, q, payload, keys) =>
|
|
398
|
-
const nullKey = getKeys(q.$conflict).find((key) => payload.some((row) => row[key] === null));
|
|
399
|
-
if (nullKey !== undefined) {
|
|
400
|
-
throw new UqlUsageError(`a row's '${nullKey}' is null: no row reads back by it, so its upsert cannot report it`);
|
|
401
|
-
}
|
|
402
|
-
return this.upsertedRows(entity, q, clone(payload), keys);
|
|
403
|
-
},
|
|
452
|
+
upsert: (entity, q, payload, keys) => this.upsertedRows(entity, q, clone(payload), keys),
|
|
404
453
|
insert: (entity, rows, keys) => this.insertedRows(entity, rows, keys),
|
|
405
454
|
};
|
|
406
455
|
/**
|
|
407
|
-
* The id each row got: off the upsert's `RETURNING` where it has one, else off the header
|
|
408
|
-
*
|
|
409
|
-
* asked before the statement fills `onInsert` keys in).
|
|
456
|
+
* The id each row got: off the upsert's `RETURNING` where it has one, else off the header, none for a row skipped by
|
|
457
|
+
* `DO NOTHING` or its `$where`.
|
|
410
458
|
*/
|
|
411
459
|
async internalUpsertMany(entity, q, payload) {
|
|
412
|
-
if (!payload.length) {
|
|
413
|
-
return [];
|
|
414
|
-
}
|
|
415
460
|
payload = clone(payload);
|
|
416
461
|
const meta = getMeta(entity);
|
|
417
|
-
|
|
418
|
-
const ids = this.dialect.features.reportsWrites.includes('upsert')
|
|
462
|
+
return this.dialect.features.reportsWrites.includes('upsert')
|
|
419
463
|
? (await this.upsertedRows(entity, q, payload, [...meta.ids, ...getKeys(q.$conflict)])).map((row) => row && idOf(meta, row))
|
|
420
|
-
:
|
|
421
|
-
return this.withUnreportedIds(entity, q.$conflict, payload, ids, kept);
|
|
464
|
+
: this.headerIds(entity, q, payload);
|
|
422
465
|
}
|
|
423
466
|
/** The ids an upsert's header reports, by index: a statement of one row assigning a found row names its key. */
|
|
424
467
|
async headerIds(entity, q, payload) {
|
|
@@ -434,14 +477,14 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
434
477
|
}
|
|
435
478
|
/**
|
|
436
479
|
* The rows of `payload` an upsert writes, in its order, with the fields `keys` names, off its `RETURNING`: matched by
|
|
437
|
-
* the conflict keys `keys` includes, as no engine promises that order. `undefined` for a row it kept
|
|
438
|
-
*
|
|
480
|
+
* the conflict keys `keys` includes, as no engine promises that order. `undefined` for a row it kept. The statement
|
|
481
|
+
* fills `payload`'s `onInsert` fields.
|
|
439
482
|
*/
|
|
440
483
|
async upsertedRows(entity, q, payload, keys) {
|
|
441
484
|
const conflictKeys = getKeys(q.$conflict);
|
|
442
485
|
const read = await this.readEach(this.upsertGroups(entity, q, payload).map(({ indexes }) => (ctx) => this.dialect.upsert(ctx, entity, q, indexes.map((index) => payload[index]), keys)));
|
|
443
486
|
const written = new Map(read.flat().map((row) => [rowKey(row, conflictKeys), row]));
|
|
444
|
-
return payload.map((row) =>
|
|
487
|
+
return payload.map((row) => written.get(rowKey(row, conflictKeys)));
|
|
445
488
|
}
|
|
446
489
|
/**
|
|
447
490
|
* An upsert's statements: one per shape, each split again to fit the bind budget, less what its assignments bind
|
|
@@ -468,6 +511,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
468
511
|
await this.lazyConnect();
|
|
469
512
|
await this.internalBegin(opts);
|
|
470
513
|
this.hasOpenTransaction = true;
|
|
514
|
+
this.#bound = NOTHING_BOUND;
|
|
471
515
|
}
|
|
472
516
|
/**
|
|
473
517
|
* A `COMMIT` that fails can leave the transaction open (SQLite answers `SQLITE_BUSY` and keeps it), so the
|
|
@@ -487,11 +531,15 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
487
531
|
this.hasOpenTransaction = false;
|
|
488
532
|
}
|
|
489
533
|
}
|
|
534
|
+
/** A rollback to a savepoint undoes the context bound inside it, so the next statement binds it again. */
|
|
490
535
|
async savepoint(command, name) {
|
|
491
536
|
const sql = this.dialect.savepointStatement(command, name);
|
|
492
537
|
if (sql) {
|
|
493
538
|
await this.runTransactionCommand(sql);
|
|
494
539
|
}
|
|
540
|
+
if (command === 'rollback') {
|
|
541
|
+
this.#bound = unsettled(this.#bound);
|
|
542
|
+
}
|
|
495
543
|
}
|
|
496
544
|
/**
|
|
497
545
|
* How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
|
package/dist/schema/schemaAST.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { EntityMeta, EntityWhereMeta, FieldOptions, AbstractType } from '../type/index.js';
|
|
2
2
|
import { SchemaAST } from './schemaAST.js';
|
|
3
|
-
import { type ForeignKeyAction, type TriggerSchema } from './types.js';
|
|
3
|
+
import { type ForeignKeyAction, type PolicySchema, type TriggerSchema } from './types.js';
|
|
4
4
|
/** What a build needs from its dialect, which `SqlSchemaGenerator.buildAST` supplies. */
|
|
5
5
|
export interface BuildSchemaASTOptions {
|
|
6
6
|
/** A table's own name, unqualified. */
|
|
@@ -20,6 +20,8 @@ export interface BuildSchemaASTOptions {
|
|
|
20
20
|
vectorIndexRequiresNotNull: boolean;
|
|
21
21
|
/** The triggers an entity's table carries, as its dialect renders them. */
|
|
22
22
|
renderTriggers: (meta: EntityMeta<object>) => TriggerSchema[];
|
|
23
|
+
/** The row-level policies the database holds an entity's table to, none where the querier holds them. */
|
|
24
|
+
renderPolicies: (meta: EntityMeta<object>) => PolicySchema[];
|
|
23
25
|
}
|
|
24
26
|
/**
|
|
25
27
|
* Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
|
|
@@ -26,6 +26,7 @@ export function diffSchemas(source, target, options = {}) {
|
|
|
26
26
|
indexes: matched.flatMap(([sourceTable, targetTable]) => diffTableIndexes(sourceTable, targetTable)),
|
|
27
27
|
checks: altered.flatMap((tableDiff) => tableDiff.checks),
|
|
28
28
|
triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
|
|
29
|
+
policies: altered.flatMap((tableDiff) => tableDiff.policies),
|
|
29
30
|
primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
|
|
30
31
|
// Relationships span tables, so they are compared over the whole schema rather than per table.
|
|
31
32
|
relationships: diffRelationshipNodes(source.relationships, target.relationships),
|
|
@@ -40,9 +41,10 @@ export function diffTable(source, target, options = {}) {
|
|
|
40
41
|
const columns = diffTableColumns(source, target, opts);
|
|
41
42
|
const checks = diffOwned(source.name, source.checks, target.checks);
|
|
42
43
|
const triggers = diffOwned(source.name, source.triggers, target.triggers);
|
|
44
|
+
const policies = diffOwned(source.name, source.policies, target.policies);
|
|
43
45
|
const primaryKey = diffPrimaryKey(source, target);
|
|
44
|
-
return columns.length || checks.length || triggers.length || primaryKey
|
|
45
|
-
? { columns, checks, triggers, primaryKey }
|
|
46
|
+
return columns.length || checks.length || triggers.length || policies.length || primaryKey
|
|
47
|
+
? { columns, checks, triggers, policies, primaryKey }
|
|
46
48
|
: undefined;
|
|
47
49
|
}
|
|
48
50
|
/**
|
package/dist/schema/types.d.ts
CHANGED
|
@@ -52,13 +52,17 @@ export interface CheckSchema {
|
|
|
52
52
|
readonly expression: string;
|
|
53
53
|
}
|
|
54
54
|
/**
|
|
55
|
-
*
|
|
56
|
-
* it; read back, they are the engine's own, which is what a rollback restores.
|
|
55
|
+
* An object uql installs on a table, compared by name alone as a check is: its name ends in a hash of its SQL. The
|
|
56
|
+
* statements create it; read back, they are the engine's own, which is what a rollback restores.
|
|
57
57
|
*/
|
|
58
|
-
export interface
|
|
58
|
+
export interface OwnedSchema {
|
|
59
59
|
readonly name: string;
|
|
60
60
|
readonly statements: readonly string[];
|
|
61
61
|
}
|
|
62
|
+
/** A trigger uql installs. */
|
|
63
|
+
export type TriggerSchema = OwnedSchema;
|
|
64
|
+
/** A row-level policy the database holds a table to. */
|
|
65
|
+
export type PolicySchema = OwnedSchema;
|
|
62
66
|
/**
|
|
63
67
|
* Default action for foreign key ON DELETE and ON UPDATE clauses.
|
|
64
68
|
*/
|
|
@@ -133,6 +137,8 @@ export interface TableNode {
|
|
|
133
137
|
readonly checks: CheckSchema[];
|
|
134
138
|
/** The triggers uql installs on this table. */
|
|
135
139
|
readonly triggers: TriggerSchema[];
|
|
140
|
+
/** The row-level policies uql installs on this table. */
|
|
141
|
+
readonly policies: PolicySchema[];
|
|
136
142
|
/** Optional table comment */
|
|
137
143
|
readonly comment?: string;
|
|
138
144
|
/** The statements the engine keeps for the table, where it keeps them; none on a table built from entities. */
|
|
@@ -223,9 +229,10 @@ export type TableChange<T> = Change<T> & {
|
|
|
223
229
|
/** The differences within a table that exists on both sides. */
|
|
224
230
|
export interface TableDiff {
|
|
225
231
|
readonly columns: ColumnDiff[];
|
|
226
|
-
/** A check or
|
|
232
|
+
/** A check, trigger or policy only one side has. Never both: a changed one is a new name, one dropped and one added. */
|
|
227
233
|
readonly checks: TableChange<CheckSchema>[];
|
|
228
234
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
235
|
+
readonly policies: TableChange<PolicySchema>[];
|
|
229
236
|
/** Set only when the two primary keys have different columns. */
|
|
230
237
|
readonly primaryKey?: PrimaryKeyDiff;
|
|
231
238
|
}
|
|
@@ -237,6 +244,7 @@ export interface SchemaDiffResult {
|
|
|
237
244
|
readonly indexes: IndexDiff[];
|
|
238
245
|
readonly checks: TableChange<CheckSchema>[];
|
|
239
246
|
readonly triggers: TableChange<TriggerSchema>[];
|
|
247
|
+
readonly policies: TableChange<PolicySchema>[];
|
|
240
248
|
readonly primaryKeys: PrimaryKeyDiff[];
|
|
241
249
|
readonly relationships: RelationshipDiff[];
|
|
242
250
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BoundStatement } from '../
|
|
1
|
+
import type { BoundStatement } from '../type/index.js';
|
|
2
2
|
/** What every SQLite driver binds. No `boolean`, which the drivers refuse and the dialect writes as an integer. */
|
|
3
3
|
export type SqliteBindValue = null | string | number | bigint | Uint8Array;
|
|
4
4
|
/** The compiler hands values over untyped, which the dialect has already normalized to what SQLite binds. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AbstractSqlQuerier
|
|
2
|
-
import type { ExtraOptions, RawRow, TransactionOptions } from '../type/index.js';
|
|
1
|
+
import { AbstractSqlQuerier } from '../querier/index.js';
|
|
2
|
+
import type { BoundStatement, ExtraOptions, RawRow, TransactionOptions } from '../type/index.js';
|
|
3
3
|
import type { SqlExecution } from '../util/sql.util.js';
|
|
4
4
|
import { type SqliteBindValue } from './bindValues.js';
|
|
5
5
|
import type { SqliteDialect } from './sqliteDialect.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AbstractSqlQuerier
|
|
1
|
+
import { AbstractSqlQuerier } from '../querier/index.js';
|
|
2
2
|
import { type SqliteBindValue } from '../sqlite/bindValues.js';
|
|
3
3
|
import type { SqliteDialect } from '../sqlite/sqliteDialect.js';
|
|
4
|
-
import type { ExtraOptions, RawRow } from '../type/index.js';
|
|
4
|
+
import type { BoundStatement, ExtraOptions, RawRow } from '../type/index.js';
|
|
5
5
|
import type { SqlExecution } from '../util/sql.util.js';
|
|
6
6
|
/** What a statement comes back with on a session: each row an array of its values, named by `columns`. */
|
|
7
7
|
export type TursoResultSet = {
|
package/dist/type/column.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
2
|
import type { TYPE_BOUNDS, VALUE_DECIDERS } from '../util/fieldOption.util.js';
|
|
3
3
|
import type { ColumnType, DdlDefault, FamilyOf, FieldOptions, HasCompositeKey, IdValue, JsonColumnType, OnFieldCallback, StampEvent, TsTypeOf } from './entity.js';
|
|
4
|
+
import type { TenantKey } from './policy.js';
|
|
4
5
|
import type { Wire } from './query.js';
|
|
5
6
|
import type { QuerySql } from './querySql.js';
|
|
6
7
|
import type { StandardSchemaV1 } from './standardSchema.js';
|
|
@@ -32,6 +33,8 @@ export type FilledOptions = {
|
|
|
32
33
|
readonly onInsert: unknown;
|
|
33
34
|
} | {
|
|
34
35
|
readonly autoIncrement: true;
|
|
36
|
+
} | {
|
|
37
|
+
readonly tenant: string;
|
|
35
38
|
};
|
|
36
39
|
/** The `null` a column's row holds: none unless `nullable()` said so. */
|
|
37
40
|
export type NullOf<O> = O extends {
|
|
@@ -98,6 +101,13 @@ export interface ColumnBuilder<in out O, in out V, F extends Family> extends Col
|
|
|
98
101
|
softDelete(value?: OnFieldCallback<V>): With<O, V, {
|
|
99
102
|
readonly softDelete: unknown;
|
|
100
103
|
}, F>;
|
|
104
|
+
/**
|
|
105
|
+
* Makes it the row's tenant, read off `$context.tenantId` unless given another key: every statement is held to the
|
|
106
|
+
* context's tenant, and an insert leaving it out is given it.
|
|
107
|
+
*/
|
|
108
|
+
tenant(...contextKey: TenantKey<V>): With<O, V, {
|
|
109
|
+
readonly tenant: string;
|
|
110
|
+
}, F>;
|
|
101
111
|
unique(): With<O, V, {
|
|
102
112
|
readonly unique: true;
|
|
103
113
|
}, F>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
|
|
2
2
|
import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, KeyHolding, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
|
|
3
|
+
import type { PolicySection } from './policy.js';
|
|
3
4
|
import type { EntityAccess, Wire } from './query.js';
|
|
4
5
|
import type { QuerySql, RelationAggregate } from './querySql.js';
|
|
5
6
|
import type { Type, AbstractType } from './utility.js';
|
|
@@ -162,6 +163,7 @@ type DefinedSections<Row, Key, Columns, B, Abstract> = {
|
|
|
162
163
|
checks(checks: CheckSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
|
|
163
164
|
triggers(triggers: TriggerSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
|
|
164
165
|
filters(filters: FilterSection<Row>): DefinedEntity<Row, Key, Columns, B, Abstract>;
|
|
166
|
+
policies(policies: PolicySection<Row>): DefinedEntity<Row, Key, Columns, B, Abstract>;
|
|
165
167
|
/** Functions each lifecycle event runs on the row, in order, given the querier writing it. */
|
|
166
168
|
hooks(hooks: {
|
|
167
169
|
readonly [E in HookEvent]?: readonly DefinedHook<Row>[];
|
|
@@ -172,10 +174,13 @@ type DefinedSections<Row, Key, Columns, B, Abstract> = {
|
|
|
172
174
|
*/
|
|
173
175
|
relations<const R, const A extends AggregateThunks = {}>(relations: (rel: RelationBuilder<Columns>) => R, aggregates?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & AggregateRow<A>, Key, Columns, Abstract>;
|
|
174
176
|
};
|
|
175
|
-
/**
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
177
|
+
/** The sections that read the row relations complete, so they may follow `relations`. */
|
|
178
|
+
type RowSection = 'filters' | 'policies';
|
|
179
|
+
/** A defined entity's class once its relations are in: its filters and policies may follow, and read through them. */
|
|
180
|
+
export type RelatedEntity<Row, Key, Columns, Abstract = false, Left extends RowSection = RowSection> = DefinedClass<Row, Key, Columns, Abstract> & Pick<{
|
|
181
|
+
filters(filters: FilterSection<Row>): RelatedEntity<Row, Key, Columns, Abstract, Exclude<Left, 'filters'>>;
|
|
182
|
+
policies(policies: PolicySection<Row>): RelatedEntity<Row, Key, Columns, Abstract, Exclude<Left, 'policies'>>;
|
|
183
|
+
}, Left>;
|
|
179
184
|
/** A defined entity's class while its sections may still be declared. */
|
|
180
185
|
export type DefinedEntity<Row, Key, Columns, B, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & DefinedSections<Row, Key, Columns, B, Abstract>;
|
|
181
186
|
/** The class `defineEntity` declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
|
package/dist/type/dialect.d.ts
CHANGED
|
@@ -155,6 +155,19 @@ export interface DialectFeatures {
|
|
|
155
155
|
* side of a value the nulls fall on.
|
|
156
156
|
*/
|
|
157
157
|
readonly nullsSortLowest: boolean;
|
|
158
|
+
/**
|
|
159
|
+
* Whether the engine holds rows to an entity's policies itself, with `CREATE POLICY`, and whether a policy may read
|
|
160
|
+
* another table (CockroachDB's may not), or `false` where the querier alone holds them. See
|
|
161
|
+
* architecture/row-level-security.md.
|
|
162
|
+
*/
|
|
163
|
+
readonly rowSecurity: {
|
|
164
|
+
readonly subqueries: boolean;
|
|
165
|
+
} | false;
|
|
166
|
+
/**
|
|
167
|
+
* Whether the querier opens a transaction of its own around a write split in steps. Where not, its steps land one by
|
|
168
|
+
* one, atomic only inside a transaction the caller opens (MongoDB), or none at all (D1).
|
|
169
|
+
*/
|
|
170
|
+
readonly transactions: boolean;
|
|
158
171
|
}
|
|
159
172
|
/** How a dialect spells a row lock, once {@link DialectFeatures.rowLocks} says it has one. */
|
|
160
173
|
export interface RowLockFeatures {
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { EnumValues, ForeignKeyAction, IndexType } from '../schema/types.js';
|
|
2
2
|
import type { SqlDialectName } from './dialect.js';
|
|
3
|
+
import type { PolicyMeta, PolicySection } from './policy.js';
|
|
3
4
|
import type { Querier } from './querier.js';
|
|
4
5
|
import type { EntityAccess, FilterOptions, RelationQuery, Wire } from './query.js';
|
|
5
6
|
import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
|
|
@@ -321,6 +322,11 @@ export type FieldOptions<V = unknown> = {
|
|
|
321
322
|
* stamps `new Date()`, anything else is the value or callback stamped, `softDelete: () => Date.now()`.
|
|
322
323
|
*/
|
|
323
324
|
readonly softDelete?: true | OnFieldCallback<V>;
|
|
325
|
+
/**
|
|
326
|
+
* Makes the column the row's tenant, read off this context key (`tenantId` by default): every statement is held to
|
|
327
|
+
* the context's tenant, and an insert leaving it out is given it. See architecture/row-level-security.md.
|
|
328
|
+
*/
|
|
329
|
+
readonly tenant?: string;
|
|
324
330
|
/**
|
|
325
331
|
* Makes the column an optimistic lock: an update matches the version its payload carries and writes
|
|
326
332
|
* the next one, so a write against a row someone else moved on throws instead of overwriting it. The
|
|
@@ -762,6 +768,8 @@ export type EntityMeta<E> = {
|
|
|
762
768
|
version?: FieldKey<E>;
|
|
763
769
|
/** Named, default-on `$where` filters applied to every query unless bypassed. */
|
|
764
770
|
filters?: Record<string, FilterOptions<E>>;
|
|
771
|
+
/** Row-level policies, in the order declared. See architecture/row-level-security.md. */
|
|
772
|
+
policies?: PolicyMeta<E>[];
|
|
765
773
|
/** What a client may do over an API, see {@link Wire}; a subclass declaring none takes its base's. */
|
|
766
774
|
wire?: Wire<EntityAccess>;
|
|
767
775
|
fields: {
|
|
@@ -935,6 +943,8 @@ export type EntityOptions<E = unknown> = {
|
|
|
935
943
|
/** What a client may do over an API: see {@link Wire}. */
|
|
936
944
|
readonly wire?: Wire<EntityAccess>;
|
|
937
945
|
readonly filters?: FilterSection<E>;
|
|
946
|
+
/** Row-level policies: see {@link PolicySection}. */
|
|
947
|
+
readonly policies?: PolicySection<E>;
|
|
938
948
|
readonly indexes?: IndexSection<E>;
|
|
939
949
|
/** Table-level `CHECK` constraints. See {@link CheckOptions}. */
|
|
940
950
|
readonly checks?: CheckSection<E>;
|
package/dist/type/index.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export * from './query.js';
|
|
|
11
11
|
export * from './queryAggregate.js';
|
|
12
12
|
export * from './queryLock.js';
|
|
13
13
|
export * from './querySql.js';
|
|
14
|
+
export * from './policy.js';
|
|
14
15
|
export * from './definedEntity.js';
|
|
15
16
|
export * from './queryWhere.js';
|
|
16
17
|
export * from './universalQuerier.js';
|
package/dist/type/index.js
CHANGED
|
@@ -11,6 +11,7 @@ export * from './query.js';
|
|
|
11
11
|
export * from './queryAggregate.js';
|
|
12
12
|
export * from './queryLock.js';
|
|
13
13
|
export * from './querySql.js';
|
|
14
|
+
export * from './policy.js';
|
|
14
15
|
export * from './definedEntity.js';
|
|
15
16
|
export * from './queryWhere.js';
|
|
16
17
|
export * from './universalQuerier.js';
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AnyMigrationOperation } from '../migrate/builder/types.js';
|
|
2
2
|
import type { SchemaAST } from '../schema/schemaAST.js';
|
|
3
3
|
import type { DiffOptions } from '../schema/schemaASTDiffer.js';
|
|
4
|
-
import type { CheckSchema, ColumnNode, ForeignKeyAction, IndexType, TableNode, TriggerSchema } from '../schema/types.js';
|
|
4
|
+
import type { CheckSchema, ColumnNode, ForeignKeyAction, IndexType, TableNode, PolicySchema, TriggerSchema } from '../schema/types.js';
|
|
5
5
|
import type { Except, IndexEntry, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, AbstractType, VectorIndexOptions } from './index.js';
|
|
6
6
|
/**
|
|
7
7
|
* Defines a migration using a simple object literal. `Q` is `MongoQuerier` for a MongoDB migration.
|
|
@@ -101,6 +101,8 @@ export interface TableSchema {
|
|
|
101
101
|
readonly checks?: CheckSchema[];
|
|
102
102
|
/** The triggers uql installed, each with the statements the engine would recreate it from. */
|
|
103
103
|
readonly triggers?: TriggerSchema[];
|
|
104
|
+
/** The row-level policies uql installed, each with the statement the engine would recreate it from. */
|
|
105
|
+
readonly policies?: PolicySchema[];
|
|
104
106
|
/** The statements the engine keeps for the table, where it keeps them: SQLite's `sqlite_master`. */
|
|
105
107
|
readonly definition?: readonly StoredDefinition[];
|
|
106
108
|
}
|
|
@@ -208,6 +210,8 @@ export interface SchemaDiff {
|
|
|
208
210
|
* a column a trigger names, so a table whose columns change takes every trigger off and puts it back.
|
|
209
211
|
*/
|
|
210
212
|
readonly triggers?: readonly Change<TriggerSchema>[];
|
|
213
|
+
/** The row-level policies installed or declared, none kept: a changed one is a new name. */
|
|
214
|
+
readonly policies?: readonly Change<PolicySchema>[];
|
|
211
215
|
/** Columns renamed in place, `from` the database's name `to` the entity's, which the other changes already use. */
|
|
212
216
|
readonly renamedColumns?: readonly Rename[];
|
|
213
217
|
/**
|