@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.50

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.
Files changed (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -1,3 +1,4 @@
1
+ import type { OperationNode } from 'kysely'
1
2
  import { inSet, isSafeInteger, type NameSet, nameSet, namesOf, ownEntry, ownKeys, parseList } from './builtins'
2
3
  import { QueryRefusedError } from './errors'
3
4
  import { isPlainIdentifier } from './identifier'
@@ -59,6 +60,8 @@ export interface TableShape {
59
60
  readonly joinable: Readonly<Record<string, JoinShape>>
60
61
  /** The `date` columns, which a read answers as `YYYY-MM-DD` text. */
61
62
  readonly dates: NameSet
63
+ /** The JSON columns, which a query selects but never compares or orders by. */
64
+ readonly json: NameSet
62
65
  }
63
66
 
64
67
  export interface JoinShape {
@@ -72,6 +75,8 @@ export interface JoinShape {
72
75
  export interface JoinState {
73
76
  readonly join: JoinShape
74
77
  readonly select: SelectState
78
+ /** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
79
+ readonly condition?: OperationNode
75
80
  }
76
81
 
77
82
  export interface SelectState {
@@ -88,14 +93,22 @@ export interface SelectState {
88
93
 
89
94
  type Comparable<V> = Exclude<V, null | undefined>
90
95
  type Columns<Row> = keyof Row & string
96
+ /** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
97
+ export type ComparableColumn<Row> = { [K in Columns<Row>]: unknown extends Row[K] ? never : K }[Columns<Row>]
91
98
  type StringColumn<Row> = { [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never }[Columns<Row>]
92
- type NullableColumn<Row> = { [K in Columns<Row>]: null extends Row[K] ? K : never }[Columns<Row>]
99
+ type NullableColumn<Row> = { [K in ComparableColumn<Row>]: null extends Row[K] ? K : never }[ComparableColumn<Row>]
93
100
 
101
+ /**
102
+ * A `[column, operator, value]` condition on `Row`'s columns. A null test (`is`, `is not`) takes a nullable column only;
103
+ * the runtime knows no column's nullability, so an untyped condition that tests a column never null runs and matches no
104
+ * row (`is`) or every row (`is not`).
105
+ */
94
106
  export type ConditionTuple<Row> =
95
107
  | {
96
- [K in Columns<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
97
- }[Columns<Row>]
108
+ [K in ComparableColumn<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
109
+ }[ComparableColumn<Row>]
98
110
  | { [K in StringColumn<Row>]: readonly [K, PatternOperator | 'contains', string] }[StringColumn<Row>]
111
+ | { [K in NullableColumn<Row>]: readonly [K, NullOperator, null] }[NullableColumn<Row>]
99
112
 
100
113
  type Prefixed<C extends string, J> = { [K in keyof J & string as `${C}.${K}`]: J[K] }
101
114
  export type NoColumns = Record<never, never>
@@ -137,8 +150,12 @@ export class ScopedSelect<Row, Selected, Children> {
137
150
  return this.#next({ columns: names })
138
151
  }
139
152
 
140
- where<C extends Columns<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
141
- where<C extends Columns<Row>>(column: C, operator: ListOperator, values: readonly Comparable<Row[C]>[]): ScopedSelect<Row, Selected, Children>
153
+ where<C extends ComparableColumn<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
154
+ where<C extends ComparableColumn<Row>>(
155
+ column: C,
156
+ operator: ListOperator,
157
+ values: readonly Comparable<Row[C]>[],
158
+ ): ScopedSelect<Row, Selected, Children>
142
159
  where<C extends StringColumn<Row>>(column: C, operator: PatternOperator, pattern: string): ScopedSelect<Row, Selected, Children>
143
160
  where<C extends NullableColumn<Row>>(column: C, operator: NullOperator, value: null): ScopedSelect<Row, Selected, Children>
144
161
  where(column: string, operator: string, value: unknown): ScopedSelect<Row, Selected, Children> {
@@ -166,11 +183,11 @@ export class ScopedSelect<Row, Selected, Children> {
166
183
  return this.#withCondition(this.#parseCondition(column, 'contains', text))
167
184
  }
168
185
 
169
- orderBy(column: Columns<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
186
+ orderBy(column: ComparableColumn<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
170
187
  if (direction !== 'asc' && direction !== 'desc') {
171
188
  throw new QueryRefusedError('list_page', `orderBy direction must be 'asc' or 'desc'`)
172
189
  }
173
- return this.#next({ orderBy: [...this.#state.orderBy, { column: this.#column(column), direction }] })
190
+ return this.#next({ orderBy: [...this.#state.orderBy, { column: comparableColumnOf(this.#shape, column, 'orders by'), direction }] })
174
191
  }
175
192
 
176
193
  limit(limit: number): ScopedSelect<Row, Selected, Children> {
@@ -233,9 +250,21 @@ export function columnOf(shape: TableShape, name: unknown): string {
233
250
  return name
234
251
  }
235
252
 
253
+ /** A column the shape lets a query compare, order or aggregate by: `columnOf`, and never a JSON column. */
254
+ export function comparableColumnOf(shape: TableShape, name: unknown, use: string): string {
255
+ const column = columnOf(shape, name)
256
+ if (inSet(shape.json, column)) {
257
+ throw new QueryRefusedError(
258
+ 'invalid_argument',
259
+ `${column} of ${shape.table} is a JSON column, which the data layer never ${use}; read a path of it with ctx.sql (->>)`,
260
+ )
261
+ }
262
+ return column
263
+ }
264
+
236
265
  /** One `[column, operator, value]` condition over a caller's values, checked before anything reads it further. */
237
266
  export function parseCondition(shape: TableShape, column: unknown, operator: unknown, value: unknown): Compare | Contains {
238
- const name = columnOf(shape, column)
267
+ const name = comparableColumnOf(shape, column, 'compares')
239
268
  if (operator === 'contains') {
240
269
  if (typeof value !== 'string') {
241
270
  throw new QueryRefusedError('invalid_argument', 'contains takes a string')
package/src/errors.ts CHANGED
@@ -29,11 +29,13 @@ export class CapabilityError extends Error {
29
29
 
30
30
  /**
31
31
  * Why the layer refused, as a closed catalog: a server log names the reason and its fixed text, never the message,
32
- * which can quote a value the request sent.
32
+ * which can quote a value the request sent. Each text is one string literal, however long: a concatenation keeps the
33
+ * whole catalog in an SPA bundle that imports this module (`web/__tests__/bundle.test.ts`).
33
34
  */
34
35
  export const QUERY_REFUSALS = {
35
36
  invalid_argument: 'a data-layer call took an argument of another shape than its type declares',
36
- invalid_value: 'a value cannot be bound: an invalid or out-of-range date, or a non-finite number',
37
+ invalid_value:
38
+ 'a value cannot be bound: undefined, a function, symbol or object of a kind the database does not bind, a list item other than a string or finite number, a date or timestamp that is neither a valid Date nor well-formed text or lies out of range, a non-finite number, or on SQLite a bigint outside the safe integer range',
37
39
  invalid_name: 'a configured name (application, schema, table or file column) breaks its naming rule',
38
40
  unknown_column: 'a column the table does not declare, or one this operation may not set',
39
41
  unknown_table: 'a table src/db/tables.ts does not declare, or one no store, join or locator reaches',
@@ -46,7 +48,9 @@ export const QUERY_REFUSALS = {
46
48
  unexpected_row: 'the database answered a row in another shape than its migration declares',
47
49
  statement_shape: 'the compiled statement has a form the guard does not admit',
48
50
  scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
49
- list_page: 'a list limit, cursor or order outside what a page admits',
51
+ list_page: 'a list limit or order outside what a page admits',
52
+ list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order",
53
+ too_many_rows: 'all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate',
50
54
  undeclared_reach: 'the site reaches data it did not declare (sql or unscoped, or their mode)',
51
55
  sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
52
56
  sql_statement: 'ctx.sql runs one statement of an admitted kind, and none inside another',
@@ -58,7 +62,7 @@ export const QUERY_REFUSALS = {
58
62
  file_scan: "a scan verdict outside the scan job's lease",
59
63
  claim_site: 'claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request',
60
64
  on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action",
61
- public_reach: "a public procedure updates, removes, locks or claims no row, and an insert's conflict writes nothing",
65
+ public_reach: "a public procedure updates, removes, locks or claims no row, reads none with all(), and an insert's conflict writes nothing",
62
66
  file_value:
63
67
  "a file column takes a file reference this request holds and may read (an incoming file, a put, or a read under the table's read action) of the column's kind, or null",
64
68
  file_scope: 'a file is referenced from another top-level scope than the one its first reference set',
@@ -3,13 +3,13 @@
3
3
  // and claims, locks and stamps the file in the write's own transaction. The file's row is `fabrika_files`
4
4
  // (`stored-files.ts`); the column is a foreign key to it, so a file some row references is never deleted.
5
5
 
6
- import { defineValue, ownDescriptor, ownKeys } from './builtins'
6
+ import { defineValue, hasOwn, inSet, type NameSet, nameSet, ownDescriptor, ownKeys } from './builtins'
7
7
  import { runFixedStatement, type Session } from './database'
8
8
  import type { Primitive } from './description'
9
9
  import { NotFoundError, QueryRefusedError } from './errors'
10
10
  import { fileHoldingOf, fileReference, holdsFile } from './file-references'
11
11
  import { isPlainIdentifier } from './identifier'
12
- import type { TableModel } from './policy'
12
+ import { includes, type ReadReach, readsAsAction, readsAsOneOf, type TableModel } from './policy'
13
13
  import { claimStoredFile, lockStoredFile, stampStoredFile, storedFilesMetadata } from './stored-files'
14
14
 
15
15
  /** Where a site's file references belong, and what claiming a pending one needs. */
@@ -24,17 +24,59 @@ export interface FileBinding {
24
24
  scans(kind: string): boolean
25
25
  }
26
26
 
27
- /** Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's read action. */
28
- function readsFile(model: TableModel, column: string, action: string): boolean {
29
- const own = Object.hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
30
- return own === undefined ? model.actions.read.includes(action) : own === action
27
+ /**
28
+ * Whether a reference read under `reach` (one action, or an `anyOf` endpoint's held actions that read the row) lets its
29
+ * holder serve, open and copy the file: a table read action, or one of the column's own read actions, that reads every answered
30
+ * row alone (`readsAsAction`), or a table read action among `held`, the actions a job holds over the whole application.
31
+ * When every action of the reach is a table read action, each answered row was admitted by one that alone reads it,
32
+ * so a column without its own read action is readable. A column with its own read actions is answered only under one of
33
+ * them (`visibleThrough`), so `held` never widens it. A table read with `'any'` admits whoever read the row: the
34
+ * store refused every other reader.
35
+ */
36
+ function readsFile(model: TableModel, column: string, reach: ReadReach, held: NameSet): boolean {
37
+ const own = hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
38
+ if (own !== undefined) {
39
+ return readsAsOneOf(model, own, reach)
40
+ }
41
+ if (model.actions.readAny || readsThroughEvery(model, reach)) {
42
+ return true
43
+ }
44
+ const reads = model.actions.read
45
+ for (let index = 0; index < reads.length; index++) {
46
+ const read = reads[index]
47
+ if (read !== undefined && (readsAsAction(model, read, reach) || inSet(held, read))) {
48
+ return true
49
+ }
50
+ }
51
+ return false
52
+ }
53
+
54
+ /** Whether the reach holds at least one action and each is one of the table's read actions. */
55
+ function readsThroughEvery(model: TableModel, reach: ReadReach): boolean {
56
+ const actions = reach.actions
57
+ for (let index = 0; index < actions.length; index++) {
58
+ if (!includes(model.actions.read, actions[index])) {
59
+ return false
60
+ }
61
+ }
62
+ return actions.length > 0
31
63
  }
32
64
 
65
+ const NONE_HELD: NameSet = nameSet([])
66
+
33
67
  /**
34
- * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
35
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
68
+ * Puts a file reference in each file column of `rows`, read under `reach` in `session`: one statement loads every
69
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
70
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
36
71
  */
37
- export async function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]> {
72
+ export async function answerFiles<R>(
73
+ model: TableModel,
74
+ binding: FileBinding | undefined,
75
+ session: Session,
76
+ rows: R[],
77
+ reach: ReadReach,
78
+ held: NameSet = NONE_HELD,
79
+ ): Promise<R[]> {
38
80
  const columns = ownKeys(model.files)
39
81
  if (binding === undefined || columns.length === 0 || rows.length === 0) {
40
82
  return rows
@@ -62,7 +104,7 @@ export async function answerFiles<R>(model: TableModel, binding: FileBinding | u
62
104
  if (meta === undefined) {
63
105
  throw new QueryRefusedError('unexpected_row', `${model.name}.${column} references a file that is not stored`)
64
106
  }
65
- defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action)))
107
+ defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, reach, held)))
66
108
  }
67
109
  }
68
110
  return rows
package/src/framework.ts CHANGED
@@ -22,9 +22,12 @@ export type { FileBinding } from './file-columns'
22
22
  export { type FileHolding, fileHoldingOf, type FileReference, fileReference, holdsFile } from './file-references'
23
23
  export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables } from './framework-tables'
24
24
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
- export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
25
+ export type { FinishWakes, JobWakes, NewWake, ScheduledFire, Wake, WakeReason } from './job-wakes'
26
+ export type { NewNotification, NotificationAbout, Notifications, StoredNotification } from './notifications'
26
27
  export type { DataAccess, DataHandles, DataSite } from './orm'
27
- export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
28
+ export type { PushBinding, PushInboxSubscription, PushRecordOutcome, PushSubscriptionKeys, PushSubscriptions } from './push-subscriptions'
29
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
30
+ export type { RequestReceipt, RequestReceipts } from './request-receipts'
28
31
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
29
32
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
30
33