@fabrika/db 0.9.0-dev.13 → 0.9.0-dev.14

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/src/guard.ts CHANGED
@@ -43,6 +43,15 @@ export interface ViewParentLink {
43
43
  readonly column: string
44
44
  readonly table: string
45
45
  readonly key: string
46
+ /** The view's own access views, which list its rows beside the parent's reach (ADR-0076). */
47
+ readonly access?: readonly ViewAccessLink[]
48
+ }
49
+
50
+ /** An access view of a child view: `V.<key> in (select A.<row> from A where <bindings>)`. */
51
+ export interface ViewAccessLink {
52
+ readonly key: string
53
+ readonly view: string
54
+ readonly row: string
46
55
  }
47
56
 
48
57
  /** A subquery of the scope predicate the shape check admitted, and the one table it reads. */
@@ -189,22 +198,27 @@ function checkRoot(root: OperationNode, context: GuardContext, admitted: Admitte
189
198
 
190
199
  /**
191
200
  * What a capability reaches before its action's condition narrows it: everything (a global grant), a Ref's chain of
192
- * equalities, and its relation rows after them, or a Within's memberships of values and relation rows.
201
+ * equalities, and after them a union of its relation rows and its secondary paths' memberships of bound values, or a
202
+ * Within's memberships of values and relation rows. A relation's rows may be narrowed: `(<relation rows> and (<scope
203
+ * tree>))`, the condition's subqueries beside the relation's, never nested in it.
193
204
  */
194
205
  function isReach(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth = 0): boolean {
195
206
  const equality = (leaf: unknown) => isScopeEquality(leaf, table)
196
- const related = (leaf: unknown) => isRelationMembership(leaf, table, subqueries, admitted, depth)
207
+ const related = (leaf: unknown) =>
208
+ isRelationMembership(leaf, table, subqueries, admitted, depth)
209
+ || isNarrowed(leaf, table, subqueries, admitted, depth, (left) => isRelationMembership(left, table, subqueries, admitted, depth))
197
210
  const member = (leaf: unknown) => isScopeMembership(leaf, table) || related(leaf)
198
211
  return isEverything(node)
199
212
  || isTreeOf(node, 'AndNode', equality)
200
213
  || isUnionOf(node, member)
201
- || (kindOf(node) === 'AndNode' && isTreeOf(read(node, 'left'), 'AndNode', equality) && isUnionOf(read(node, 'right'), related))
214
+ || (kindOf(node) === 'AndNode' && isTreeOf(read(node, 'left'), 'AndNode', equality) && isUnionOf(read(node, 'right'), member))
202
215
  }
203
216
 
204
217
  /**
205
218
  * A child view's rows read through its parent: `V.<column> in (select P.<key> from P where <P's reach>)`, after an AND
206
219
  * of equalities when one row is addressed. P's reach is one the guard admits for a statement on P, never `true`; a
207
- * subquery without WHERE reads every parent row.
220
+ * subquery without WHERE reads every parent row. Where the view narrows a relation (`relationWhen`), that relation's
221
+ * reach is a membership of its own, narrowed by the view's condition, in a parenthesized OR of such memberships.
208
222
  */
209
223
  function isThroughParent(
210
224
  node: unknown,
@@ -213,12 +227,46 @@ function isThroughParent(
213
227
  subqueries: GuardContext['subqueries'],
214
228
  admitted: Admitted[],
215
229
  ): boolean {
216
- const member = (leaf: unknown) => isParentMembership(leaf, table, parent, subqueries, admitted)
230
+ const membership = (leaf: unknown) =>
231
+ isParentMembership(leaf, table, parent, subqueries, admitted) || isViewAccess(leaf, table, parent.access ?? [], subqueries, admitted)
232
+ const member = (leaf: unknown) => isUnionOf(leaf, (branch) => membership(branch) || isNarrowed(branch, table, subqueries, admitted, 0, membership))
217
233
  return member(node)
218
234
  || (kindOf(node) === 'AndNode' && hasOnly(node, CONNECTIVE_KEYS) && isTreeOf(read(node, 'left'), 'AndNode', (leaf) => isScopeEquality(leaf, table))
219
235
  && member(read(node, 'right')))
220
236
  }
221
237
 
238
+ /**
239
+ * `V.<key> in (select A.<row> from A where <bindings>)` for one access view the view declares: the only test of a view's
240
+ * own column that places its rows, because the access view's SQL is the reviewed rule that decides them.
241
+ */
242
+ function isViewAccess(
243
+ node: unknown,
244
+ table: string,
245
+ links: readonly ViewAccessLink[],
246
+ subqueries: GuardContext['subqueries'],
247
+ admitted: Admitted[],
248
+ ): boolean {
249
+ if (kindOf(node) !== 'BinaryOperationNode' || !hasOnly(node, BINARY_KEYS) || read(read(node, 'operator'), 'operator') !== 'in') {
250
+ return false
251
+ }
252
+ const select = read(node, 'rightOperand')
253
+ const froms = read(read(select, 'from'), 'froms')
254
+ const selections = read(select, 'selections')
255
+ if (!isArray(froms) || froms.length !== 1 || !isArray(selections) || selections.length !== 1) {
256
+ return false
257
+ }
258
+ for (let index = 0; index < links.length; index++) {
259
+ const link = links[index]
260
+ if (
261
+ link !== undefined && isReference(read(node, 'leftOperand'), table, link.key) && tableName(froms[0]) === link.view
262
+ && isReference(read(selections[0], 'selection'), link.view, link.row)
263
+ ) {
264
+ return isScopeSubquery(select, subqueries, admitted, 1, true)
265
+ }
266
+ }
267
+ return false
268
+ }
269
+
222
270
  function isParentMembership(
223
271
  node: unknown,
224
272
  table: string,
@@ -258,6 +306,21 @@ function isParentMembership(
258
306
  return true
259
307
  }
260
308
 
309
+ /** `(<left> and (<scope tree over table>))`: one branch of a reach, `left`, narrowed by a condition on the table's rows. */
310
+ function isNarrowed(
311
+ node: unknown,
312
+ table: string,
313
+ subqueries: GuardContext['subqueries'],
314
+ admitted: Admitted[],
315
+ depth: number,
316
+ left: (node: unknown) => boolean,
317
+ ): boolean {
318
+ const inner = read(node, 'node')
319
+ const right = read(inner, 'right')
320
+ return kindOf(node) === 'ParensNode' && hasOnly(node, PARENS_KEYS) && kindOf(inner) === 'AndNode' && hasOnly(inner, CONNECTIVE_KEYS)
321
+ && left(read(inner, 'left')) && kindOf(right) === 'ParensNode' && isScopeTree(right, table, subqueries, admitted, depth)
322
+ }
323
+
261
324
  /** One leaf, or a parenthesized OR tree of them. */
262
325
  function isUnionOf(node: unknown, leaf: (node: unknown) => boolean): boolean {
263
326
  return leaf(node) || (kindOf(node) === 'ParensNode' && kindOf(read(node, 'node')) === 'OrNode' && isTreeOf(read(node, 'node'), 'OrNode', leaf))
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export type {
7
7
  LeaseFence,
8
8
  Ref,
9
9
  RefGrant,
10
+ RelationHold,
10
11
  RowGrant,
11
12
  RowRef,
12
13
  Within,
package/src/job-leases.ts CHANGED
@@ -383,13 +383,14 @@ function refuseEnded(fence: LeaseFence): void {
383
383
  }
384
384
 
385
385
  const SQL_CLOCK: DialectTexts = {
386
- postgres: 'select clock_timestamp() as now',
386
+ postgres: `select date_trunc('milliseconds', clock_timestamp() + interval '999 microseconds') as now`,
387
387
  sqlite: `select ${N} as now`,
388
388
  }
389
389
 
390
390
  /**
391
391
  * The database's clock inside `session`'s transaction: a queue claim compares and moves `due` by it, so no process
392
- * clock decides when a row is due.
392
+ * clock decides when a row is due. On Postgres it is rounded up to the millisecond a `Date` holds, so it is never
393
+ * earlier than a `due` that `now()` wrote with microseconds.
393
394
  */
394
395
  export async function databaseNow(session: Session): Promise<Date> {
395
396
  const [row] = await rows(session, SQL_CLOCK, [])
package/src/nodes.ts CHANGED
@@ -354,6 +354,18 @@ export function locateNode(table: string, columns: readonly string[], scope: Ope
354
354
  return Object.freeze(node)
355
355
  }
356
356
 
357
+ /** `select T.<name> from T where <scope> group by T.<name>`: each value of `name` the scoped rows hold, once. */
358
+ export function valuesNode(table: string, name: string, scope: OperationNode): SelectQueryNode {
359
+ const node: SelectQueryNode = {
360
+ kind: 'SelectQueryNode',
361
+ from: FromNode.create([TableNode.create(table)]),
362
+ selections: [selection(table, name)],
363
+ where: scopedWhere(undefined, scope),
364
+ groupBy: GroupByNode.create([GroupByItemNode.create(column(table, name))]),
365
+ }
366
+ return Object.freeze(node)
367
+ }
368
+
357
369
  /**
358
370
  * The same check, locked: `for share` keeps the row from moving until the transaction that checked it ends, `for
359
371
  * update` also keeps every other writer and locker of it waiting.
package/src/orm.ts CHANGED
@@ -329,7 +329,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
329
329
 
330
330
  /** The predicate of the target object, over the whole chain its `Ref` carries. */
331
331
  function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
332
- return refScope(context.relations, context.model, selfLinks(context.model), grant, new Date())
332
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date())
333
333
  }
334
334
 
335
335
  function targetRow(
@@ -428,7 +428,7 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
428
428
  return freeze({
429
429
  list: bound(site, async (options?: unknown) => {
430
430
  const grant = namedRef(context, capability, dimension)
431
- const scope = refScope(context.relations, context.model, context.model.chain, grant, new Date())
431
+ const scope = refScope(context, context.model, context.model.chain, grant, new Date())
432
432
  return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
433
433
  }),
434
434
  insert: writing(
@@ -774,6 +774,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
774
774
  return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
775
775
  }
776
776
 
777
+ /**
778
+ * How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
779
+ * compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
780
+ * statement's size. Every chunk runs in the claim's one fenced transaction.
781
+ */
782
+ const CLAIM_UPDATE_IDS = 50
783
+
777
784
  /**
778
785
  * Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
779
786
  * attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
@@ -837,17 +844,20 @@ async function claimRows(
837
844
  for (const [attempts, ids] of byAttempts) {
838
845
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
839
846
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
840
- const updated = await session.run<Readonly<Record<string, unknown>>>(
841
- updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
842
- { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
843
- )
844
- for (const row of updated) {
845
- const id = row['id']
846
- const next = row['version']
847
- if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
848
- throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
847
+ for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
848
+ const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
849
+ const updated = await session.run<Readonly<Record<string, unknown>>>(
850
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
851
+ { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
852
+ )
853
+ for (const row of updated) {
854
+ const id = row['id']
855
+ const next = row['version']
856
+ if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
857
+ throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
858
+ }
859
+ claimed.set(id, { version: next, attempts: attempts + 1, due })
849
860
  }
850
- claimed.set(id, { version: next, attempts: attempts + 1, due })
851
861
  }
852
862
  }
853
863
  // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
@@ -1032,7 +1042,7 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
1032
1042
  return refused(site, 'read_only', `${table} is a view, which no handler writes`)
1033
1043
  }
1034
1044
  // A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
1035
- if (delegates(model)) {
1045
+ if (delegates(model) || context.writers.length > 0) {
1036
1046
  return refused(
1037
1047
  site,
1038
1048
  'undeclared_reach',