@mistriwork/engine 1.0.0-rc.72 → 1.0.0-rc.74

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.
@@ -429,6 +429,11 @@ export class HttpAdapter {
429
429
  return group;
430
430
  const seen = new Set();
431
431
  for (const condition of group) {
432
+ // A column tested against another table's rows (`in: { from }`) is a subquery no API is asked.
433
+ if (condition.within)
434
+ throw new Refusal(`${resource.name} comes from an API, so "${condition.column}" cannot be tested against ${condition.within.table}'s rows.`, {
435
+ columns: [condition.column],
436
+ });
432
437
  const declared = resource.filters[condition.column];
433
438
  const op = condition.op;
434
439
  if (!declared || (op !== '=' && op !== 'in') || !declared.ops.includes(op)) {
@@ -8,7 +8,7 @@
8
8
  * connect, or the leased writer inside a scoped transaction.
9
9
  */
10
10
  import { isProxy } from 'node:util/types';
11
- import { inlineRows } from '../shared/anyRows.js';
11
+ import { inlineRows, inlineWithin } from '../shared/anyRows.js';
12
12
  import { asksAboutRows } from '../shared/filter.js';
13
13
  import { qualifiedTable } from '../shared/sqlRelation.js';
14
14
  import { POSTGRES_STYLE, buildWhere, clampLimit, clampOffset, Refusal, WriteConflict, TransactionOperations, queueRecordLock, recordLockFilter, TransactionOutcomeUnknown, countStatement, countEachStatement, countEachRows, countsTogether, orderClause, lanesStatement, withoutLaneRow, refuseUpdateMatches, } from './adapter.js';
@@ -529,7 +529,9 @@ export class PostgresAdapter {
529
529
  return buildWhere(filter, POSTGRES_STYLE);
530
530
  const schema = await this.schema().catch(() => undefined);
531
531
  const inline = schema && inlineRows(schema, id, qualified, POSTGRES_STYLE, (child) => qualifiedTable(schema, child.id, POSTGRES_STYLE));
532
- return buildWhere(filter, POSTGRES_STYLE, 1, undefined, undefined, undefined, undefined, false, undefined, false, inline);
532
+ /* Another table's keys (`in`) are read as this table is, from its own relation: the same bound. */
533
+ const within = schema && inlineWithin(schema, POSTGRES_STYLE, (other) => qualifiedTable(schema, other.id, POSTGRES_STYLE));
534
+ return buildWhere(filter, POSTGRES_STYLE, 1, undefined, undefined, undefined, undefined, false, undefined, false, inline, within);
533
535
  }
534
536
  async queryOn(request, db, read = false) {
535
537
  const { schema, name } = read ? await this.readTable(request.table) : await this.assertTable(request.table, db);
@@ -815,11 +817,11 @@ export class PostgresAdapter {
815
817
  return { found, meta, applied };
816
818
  }
817
819
  /** Several rows of one table added by one statement inside a transaction, each refused as `insert` refuses one (postgresBatchWrites). */
818
- async insertManyNow(requests, write) {
820
+ async insertManyNow(requests, write, scoped = false) {
819
821
  const plans = [];
820
822
  for (const request of requests)
821
823
  plans.push(await this.insertPlan(request, write));
822
- return insertPlanned(plans, write);
824
+ return insertPlanned(plans, write, scoped);
823
825
  }
824
826
  /** Several rows of one table changed by one statement inside a transaction, each refused as `update` refuses one. */
825
827
  async updateManyNow(requests, write) {
@@ -1489,6 +1491,9 @@ export class PostgresAdapter {
1489
1491
  insert: (r) => this.insertNow(r, write, write, true),
1490
1492
  remove: (r) => this.removeNow(r, write, write),
1491
1493
  update: (r) => this.updateNow(r, write, write),
1494
+ // The row scope proves a batch's rows as it proves one row's, around the one statement (scopedTransaction.ts).
1495
+ insertMany: (rs) => this.insertManyNow(rs, write, true),
1496
+ updateMany: (rs) => this.updateManyNow(rs, write),
1492
1497
  },
1493
1498
  // Filed under the table's id, as the rows sent ahead are; a read asked in its turn is sent as it was asked.
1494
1499
  (request) => {
@@ -1509,6 +1514,7 @@ export class PostgresAdapter {
1509
1514
  insert: writes.insert,
1510
1515
  remove: writes.remove,
1511
1516
  update: writes.update,
1517
+ ...(writes.insertMany && writes.updateMany ? { insertMany: writes.insertMany, updateMany: writes.updateMany } : {}),
1512
1518
  }, scopedReads(false), scopedReads(true), {
1513
1519
  target: lock('UPDATE'),
1514
1520
  parent: lock('SHARE'),
@@ -1559,6 +1565,12 @@ export class PostgresAdapter {
1559
1565
  insert: (r) => invoke(r, (r) => records.insert(r)),
1560
1566
  remove: (r) => invoke(r, (r) => records.remove(r)),
1561
1567
  update: (r) => invoke(r, (r) => records.update(r)),
1568
+ ...(records.insertMany && records.updateMany
1569
+ ? {
1570
+ insertMany: (rs) => invoke(rs, (rs) => records.insertMany(rs)),
1571
+ updateMany: (rs) => invoke(rs, (rs) => records.updateMany(rs)),
1572
+ }
1573
+ : {}),
1562
1574
  // Beneath the row scope: the flows' command tells only of its own target, which it read through the scope.
1563
1575
  ...(writes.tell ? { tell: (r) => invoke(r, (r) => writes.tell(r)) } : {}),
1564
1576
  ...(writes.noted ? { noted: (r) => invoke(r, (r) => writes.noted(r)) } : {}),
@@ -19,7 +19,7 @@ export interface UpdatePlan extends InsertPlan {
19
19
  * `INSERT … RETURNING *` for each run of rows naming the same columns, its rows matched back to the
20
20
  * requests that wrote them (batchedRows).
21
21
  */
22
- export declare function insertPlanned(plans: readonly InsertPlan[], write: PgQuery): Promise<InsertResult[]>;
22
+ export declare function insertPlanned(plans: readonly InsertPlan[], write: PgQuery, scoped?: boolean): Promise<InsertResult[]>;
23
23
  /**
24
24
  * Rows changed inside a transaction, each as the adapter's single update changes one: each row's own values and
25
25
  * `expected`, one row a key. A `CASE` a column picks each row's value, the WHERE matches each key with its own
@@ -7,7 +7,7 @@ import { buildUpdateGuard } from './scoped/updateGuard.js';
7
7
  * `INSERT … RETURNING *` for each run of rows naming the same columns, its rows matched back to the
8
8
  * requests that wrote them (batchedRows).
9
9
  */
10
- export async function insertPlanned(plans, write) {
10
+ export async function insertPlanned(plans, write, scoped = false) {
11
11
  sameTable(plans.map((plan) => `${plan.found.schema}.${plan.found.name}`));
12
12
  const found = plans[0].found;
13
13
  const pk = plans[0].meta.filter((c) => c.is_pk).map((c) => c.name);
@@ -26,6 +26,11 @@ export async function insertPlanned(plans, write) {
26
26
  ' RETURNING *';
27
27
  const result = await write.query(text, params);
28
28
  batchedRows(chunk.map((plan) => plan.applied), result.rows).forEach((stored, index) => {
29
+ /* A scope re-reads each stored row by its key, as the single insert's does (postgres.ts insertNow): a key that
30
+ comes back as no text or number (a bytea's label) proves nothing, and is refused before it stands in. */
31
+ if (scoped &&
32
+ pk.some((column) => !(typeof stored[column] === 'string' || (typeof stored[column] === 'number' && Number.isFinite(stored[column])))))
33
+ throw new Refusal('The stored key cannot be checked in this row scope.');
29
34
  const row = toJsonSafe(stored);
30
35
  const key = {};
31
36
  for (const c of pk)
@@ -76,9 +76,17 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
76
76
  if (ended || typeof next !== 'string' || !next.trim())
77
77
  throw new Refusal('The read snapshot is unavailable.');
78
78
  ended = true;
79
- if (ahead)
80
- await begun;
81
- const closed = (await client.query(`COMMIT; ${BEGIN_SNAPSHOT}${session}; ${next}; COMMIT`));
79
+ /* Sent at once, not after the BEGIN's answer: an owner may end the snapshot while its last reads are still in
80
+ flight, and on a reader that pipelines the end then leaves behind them, in their flight. The server runs a
81
+ connection's statements in order, so the fresh snapshot `next` reads in still begins after every read on
82
+ this one has finished. A BEGIN that failed is heard first, as before. */
83
+ const sent = client.query(`COMMIT; ${BEGIN_SNAPSHOT}${session}; ${next}; COMMIT`);
84
+ const [opened, ending] = await Promise.allSettled([ahead ? begun : undefined, sent]);
85
+ if (opened.status === 'rejected')
86
+ throw opened.reason;
87
+ if (ending.status === 'rejected')
88
+ throw ending.reason;
89
+ const closed = ending.value;
82
90
  return Object.freeze((Array.isArray(closed) ? closed : [closed]).slice(2 + set, -1));
83
91
  };
84
92
  try {
@@ -13,9 +13,12 @@ export function scopedCommandInvoker(operations, scoped, command, runtime, verif
13
13
  return (input, work, read = false) => {
14
14
  let captured = input;
15
15
  let invalid;
16
+ /* A batch (insertMany, updateMany) is its rows' requests, each captured and judged as it would be alone: one row's
17
+ bounds, not one bound over the whole batch. */
18
+ const batch = Array.isArray(input);
16
19
  if (scoped) {
17
20
  try {
18
- captured = snapshotScopedData(input);
21
+ captured = (batch ? input.map((request) => snapshotScopedData(request)) : snapshotScopedData(input));
19
22
  }
20
23
  catch (error) {
21
24
  invalid = { error };
@@ -30,11 +33,7 @@ export function scopedCommandInvoker(operations, scoped, command, runtime, verif
30
33
  verify();
31
34
  if (command &&
32
35
  scoped &&
33
- captured &&
34
- typeof captured === 'object' &&
35
- 'table' in captured &&
36
- typeof captured.table === 'string' &&
37
- runtime(captured.table)) {
36
+ (batch ? captured : [captured]).some((request) => request && typeof request === 'object' && 'table' in request && typeof request.table === 'string' && runtime(request.table))) {
38
37
  throw new Refusal('Reserved resources are runtime-only.');
39
38
  }
40
39
  const result = await work(captured);
@@ -6,7 +6,7 @@ import { ScopedRelations, snapshotRowScope } from '../../shared/rowScope.js';
6
6
  import { compileView, compileViewCount } from '../../shared/view.js';
7
7
  import { compileBreakdown, compileBreakdownCount } from '../../shared/breakdown.js';
8
8
  import { compileAggregate } from '../../shared/aggregate.js';
9
- import { childRows } from '../../shared/anyRows.js';
9
+ import { childRows, plannedWithin, withinRows } from '../../shared/anyRows.js';
10
10
  import { readExactly, summed } from '../../shared/decimals.js';
11
11
  import { RequestFault } from '../../shared/refusal.js';
12
12
  import { storedTextOf, storedTextSelect } from './storedText.js';
@@ -118,8 +118,18 @@ references = false) {
118
118
  child is a relation of this statement, planned here with its values bound ahead of the outer filter's, so the
119
119
  EXISTS carries none. A child the reader's catalog does not hold is refused (ScopedRelations.table). */
120
120
  const planned = new Map();
121
+ /* Another table's keys (`in`) are read through the reader's own scope too: the same relation a direct read of that
122
+ table is (its tenant, its row policy), narrowed by the test's own conditions, planned here so its values bind
123
+ ahead of the outer filter's and the subquery carries none. A table the reader's catalog does not hold is
124
+ refused (ScopedRelations.table). */
125
+ const subqueries = new Map();
121
126
  for (const group of filter?.groups ?? []) {
122
127
  for (const c of group) {
128
+ if (c.within !== undefined && !subqueries.has(c.within)) {
129
+ const { table: other, key, type } = withinRows(schema, c.within);
130
+ const source = c.within.filter?.groups.length ? relations.filtered(other.id, c.within.filter) : relations.table(other.id);
131
+ subqueries.set(c.within, plannedWithin(style, source, key, type));
132
+ }
123
133
  if (c.any === undefined || planned.has(c.any))
124
134
  continue;
125
135
  const { child, join } = childRows(schema, id, c.any, style);
@@ -135,7 +145,13 @@ references = false) {
135
145
  throw new RequestFault('This read cannot ask about the rows that point at it.');
136
146
  })()
137
147
  : undefined;
138
- const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, exists, references, typeIn(table));
148
+ const within = subqueries.size
149
+ ? (rows) => subqueries.get(rows) ??
150
+ (() => {
151
+ throw new RequestFault("This read cannot compare a column with another table's rows.");
152
+ })()
153
+ : undefined;
154
+ const where = buildWhere(filter, style, prefix.params.length + 1, column, undefined, undefined, exists, references, typeIn(table), false, undefined, within);
139
155
  return { table, column, relation, prefix, where, params: [...prefix.params, ...where.params] };
140
156
  };
141
157
  /* A SQLite sum that cannot be exact says so in its cell (decimals.ts); PostgreSQL's numeric always is. */