@crombolo/data 0.37.0 → 0.39.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.
Files changed (76) hide show
  1. package/package.json +3 -2
  2. package/src/audit.ts +164 -134
  3. package/src/change-report.ts +66 -43
  4. package/src/cluster.ts +119 -59
  5. package/src/content-query.ts +205 -200
  6. package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
  7. package/src/custom-tables/chain.ts +150 -0
  8. package/src/custom-tables/ddl.ts +159 -0
  9. package/src/custom-tables/handle.ts +141 -0
  10. package/src/{bundle-tables → custom-tables}/index.ts +3 -2
  11. package/src/custom-tables/names.ts +94 -0
  12. package/src/custom-tables/owners.ts +299 -0
  13. package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
  14. package/src/custom-tables/values.ts +181 -0
  15. package/src/database.ts +40 -5
  16. package/src/dialect.ts +43 -16
  17. package/src/index.ts +9 -1
  18. package/src/migrations.ts +130 -88
  19. package/src/query.ts +158 -0
  20. package/src/relations.ts +49 -28
  21. package/src/repositories/approvals.ts +130 -89
  22. package/src/repositories/bundle-grants.ts +105 -0
  23. package/src/repositories/bundles.ts +85 -76
  24. package/src/repositories/content-applied.ts +47 -28
  25. package/src/repositories/content-events.ts +114 -67
  26. package/src/repositories/content-notifications.ts +102 -74
  27. package/src/repositories/content-types.ts +449 -320
  28. package/src/repositories/data-types.ts +105 -56
  29. package/src/repositories/delivery-member-tokens.ts +37 -28
  30. package/src/repositories/dictionary.ts +77 -58
  31. package/src/repositories/documents.ts +956 -580
  32. package/src/repositories/domains.ts +28 -16
  33. package/src/repositories/dynamic-roots.ts +32 -17
  34. package/src/repositories/external-logins.ts +38 -24
  35. package/src/repositories/folders.ts +7 -4
  36. package/src/repositories/form-entries.ts +120 -103
  37. package/src/repositories/form-workflows.ts +87 -62
  38. package/src/repositories/jobs.ts +296 -0
  39. package/src/repositories/languages.ts +51 -38
  40. package/src/repositories/log-searches.ts +7 -5
  41. package/src/repositories/media-access.ts +173 -123
  42. package/src/repositories/media-listing.ts +155 -92
  43. package/src/repositories/members.ts +189 -162
  44. package/src/repositories/nodes.ts +227 -181
  45. package/src/repositories/notifications.ts +22 -17
  46. package/src/repositories/public-access.ts +77 -61
  47. package/src/repositories/redirects.ts +113 -70
  48. package/src/repositories/references.ts +55 -44
  49. package/src/repositories/remote-jobs.ts +45 -35
  50. package/src/repositories/tags.ts +11 -10
  51. package/src/repositories/templates.ts +24 -14
  52. package/src/repositories/transfer-answers.ts +58 -50
  53. package/src/repositories/transfer-runs.ts +93 -75
  54. package/src/repositories/two-factor.ts +74 -55
  55. package/src/repositories/user-data.ts +54 -36
  56. package/src/repositories/users.ts +345 -300
  57. package/src/repositories/webhooks.ts +196 -137
  58. package/src/schema/bundle-grants.ts +32 -0
  59. package/src/schema/bundles-disabled.ts +29 -0
  60. package/src/schema/jobs.ts +56 -0
  61. package/src/schema/plan.ts +6 -0
  62. package/src/schema-ops.ts +15 -12
  63. package/src/schema-state.ts +53 -38
  64. package/src/search.ts +175 -129
  65. package/src/setup.ts +17 -13
  66. package/src/site-search.ts +134 -83
  67. package/src/table-types.ts +152 -0
  68. package/src/tables.gen.ts +861 -0
  69. package/src/tree-invariants.ts +21 -12
  70. package/src/url-options.ts +17 -13
  71. package/src/workflow-store.ts +17 -13
  72. package/src/bundle-tables/capability.ts +0 -377
  73. package/src/bundle-tables/chain.ts +0 -105
  74. package/src/bundle-tables/ddl.ts +0 -124
  75. package/src/bundle-tables/guard.ts +0 -116
  76. package/src/bundle-tables/names.ts +0 -58
@@ -128,19 +128,28 @@ export async function loadTreeSnapshot(
128
128
  db: Db,
129
129
  objectTypes: readonly string[] = TREE_OBJECT_TYPES,
130
130
  ): Promise<TreeSnapshot> {
131
- const marks = objectTypes.map(() => '?').join(', ')
132
- const scoped = `SELECT id FROM node WHERE node_object_type IN (${marks})`
131
+ const scoped = () =>
132
+ db.q
133
+ .selectFrom('node')
134
+ .select('id')
135
+ .where('node_object_type', 'in', [...objectTypes])
133
136
  const [nodes, documents, versions, content] = await Promise.all([
134
- db.query('SELECT id, parent_id, level, path, sort_order, trashed, node_object_type FROM node'),
135
- db.query(`SELECT node_id, published FROM document WHERE node_id IN (${scoped})`, [
136
- ...objectTypes,
137
- ]),
138
- db.query(
139
- `SELECT cv.id, cv.node_id, cv.current, dv.published FROM content_version cv
140
- LEFT JOIN document_version dv ON dv.id = cv.id WHERE cv.node_id IN (${scoped})`,
141
- [...objectTypes],
142
- ),
143
- db.query(`SELECT node_id FROM content WHERE node_id IN (${scoped})`, [...objectTypes]),
137
+ db.q
138
+ .selectFrom('node')
139
+ .select(['id', 'parent_id', 'level', 'path', 'sort_order', 'trashed', 'node_object_type'])
140
+ .execute(),
141
+ db.q
142
+ .selectFrom('document')
143
+ .select(['node_id', 'published'])
144
+ .where('node_id', 'in', scoped())
145
+ .execute(),
146
+ db.q
147
+ .selectFrom('content_version as cv')
148
+ .leftJoin('document_version as dv', 'dv.id', 'cv.id')
149
+ .select(['cv.id', 'cv.node_id', 'cv.current', 'dv.published'])
150
+ .where('cv.node_id', 'in', scoped())
151
+ .execute(),
152
+ db.q.selectFrom('content').select('node_id').where('node_id', 'in', scoped()).execute(),
144
153
  ])
145
154
  return {
146
155
  nodes: nodes.map((row) => ({
@@ -4,6 +4,7 @@
4
4
  * the published cache. docs/rendering.md, "URLs".
5
5
  */
6
6
  import type { Db } from './database.ts'
7
+ import { now } from './query.ts'
7
8
 
8
9
  export const URL_OPTIONS_KEY = 'crombolo:urls'
9
10
 
@@ -35,10 +36,12 @@ export function parseUrlOptions(value: string | undefined): UrlOptions {
35
36
  }
36
37
 
37
38
  export async function readUrlOptions(db: Db): Promise<UrlOptions> {
38
- const rows = await db.query<{ value: string }>('SELECT value FROM key_value WHERE key = ?', [
39
- URL_OPTIONS_KEY,
40
- ])
41
- return parseUrlOptions(rows[0]?.value)
39
+ const rows = await db.q
40
+ .selectFrom('key_value')
41
+ .select('value')
42
+ .where('key', '=', URL_OPTIONS_KEY)
43
+ .execute()
44
+ return parseUrlOptions(rows[0]?.value ?? undefined)
42
45
  }
43
46
 
44
47
  /** Stores the setting; answers what it was before. */
@@ -46,16 +49,17 @@ export async function writeUrlOptions(db: Db, options: UrlOptions): Promise<UrlO
46
49
  return db.transaction(async (tx) => {
47
50
  const before = await readUrlOptions(tx)
48
51
  const value = JSON.stringify({ hideTopLevel: options.hideTopLevel })
49
- const now = tx.dialect.now()
50
- const updated = await tx.query<{ key: string }>(
51
- `UPDATE key_value SET value = ?, update_date = ${now} WHERE key = ? RETURNING key`,
52
- [value, URL_OPTIONS_KEY],
53
- )
52
+ const updated = await tx.q
53
+ .updateTable('key_value')
54
+ .set({ value, update_date: now(tx) })
55
+ .where('key', '=', URL_OPTIONS_KEY)
56
+ .returning('key')
57
+ .execute()
54
58
  if (updated.length === 0)
55
- await tx.exec(`INSERT INTO key_value (key, value, update_date) VALUES (?, ?, ${now})`, [
56
- URL_OPTIONS_KEY,
57
- value,
58
- ])
59
+ await tx.q
60
+ .insertInto('key_value')
61
+ .values({ key: URL_OPTIONS_KEY, value, update_date: now(tx) })
62
+ .execute()
59
63
  return before
60
64
  })
61
65
  }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { type SchemaWorkflow, startStages } from '@crombolo/core'
7
7
  import type { Db } from './database.ts'
8
+ import { now } from './query.ts'
8
9
  import { ApprovalRepository } from './repositories/approvals.ts'
9
10
 
10
11
  export const WORKFLOWS_KEY = 'crombolo:workflows'
@@ -31,10 +32,12 @@ export function parseStoredWorkflows(value: string | undefined): StoredWorkflow[
31
32
  }
32
33
 
33
34
  export async function readWorkflows(db: Db): Promise<StoredWorkflow[]> {
34
- const rows = await db.query<{ value: string }>('SELECT value FROM key_value WHERE key = ?', [
35
- WORKFLOWS_KEY,
36
- ])
37
- return parseStoredWorkflows(rows[0]?.value)
35
+ const row = await db.q
36
+ .selectFrom('key_value')
37
+ .select('value')
38
+ .where('key', '=', WORKFLOWS_KEY)
39
+ .executeTakeFirst()
40
+ return parseStoredWorkflows(row?.value ?? undefined)
38
41
  }
39
42
 
40
43
  /** Stores the workflows; answers what was there before. */
@@ -45,16 +48,17 @@ export async function writeWorkflows(
45
48
  return db.transaction(async (tx) => {
46
49
  const before = await readWorkflows(tx)
47
50
  const value = JSON.stringify(workflows)
48
- const now = tx.dialect.now()
49
- const updated = await tx.query<{ key: string }>(
50
- `UPDATE key_value SET value = ?, update_date = ${now} WHERE key = ? RETURNING key`,
51
- [value, WORKFLOWS_KEY],
52
- )
51
+ const updated = await tx.q
52
+ .updateTable('key_value')
53
+ .set({ value, update_date: now(tx) })
54
+ .where('key', '=', WORKFLOWS_KEY)
55
+ .returning('key')
56
+ .execute()
53
57
  if (updated.length === 0)
54
- await tx.exec(`INSERT INTO key_value (key, value, update_date) VALUES (?, ?, ${now})`, [
55
- WORKFLOWS_KEY,
56
- value,
57
- ])
58
+ await tx.q
59
+ .insertInto('key_value')
60
+ .values({ key: WORKFLOWS_KEY, value, update_date: now(tx) })
61
+ .execute()
58
62
  return before
59
63
  })
60
64
  }
@@ -1,377 +0,0 @@
1
- /**
2
- * The `tables` capability: a bundle's runtime access to its own tables, and
3
- * nothing else. `docs/bundles.md`, Part 4.
4
- *
5
- * Three things keep it inside the bundle's tables:
6
- *
7
- * - **No identifier comes from the caller.** Every table and column name is
8
- * looked up in the bundle's resolved schema and quoted from there, and an
9
- * unknown one is refused before any SQL is built. Values are always bound.
10
- * - **No `Db` is reachable.** The capability, each table handle and the
11
- * transaction handle are frozen, null-prototype objects whose members are
12
- * closures; the connection is never a property of any of them.
13
- * - **Every statement passes the guard**, which refuses one naming any table
14
- * that is not this bundle's.
15
- */
16
- import type { Db } from '../database.ts'
17
- import { DbDate, fromDbBool } from '../dialect.ts'
18
- import type { ColumnSpec, Columns, InsertOf, JsonValue, RowOf, TablesShape } from './builder.ts'
19
- import { guardStatement } from './guard.ts'
20
- import type { ResolvedSchema, ResolvedTable } from './schema.ts'
21
-
22
- /** A request the capability refused: nothing reached the database. */
23
- export class BundleQueryError extends Error {
24
- constructor(
25
- readonly bundle: string,
26
- reason: string,
27
- ) {
28
- super(`Bundle "${bundle}": ${reason}.`)
29
- }
30
- }
31
-
32
- type Scalar<V> = Exclude<V, null>
33
-
34
- /** A condition on one column. A bare value means equality, and `null` means `isNull`. */
35
- export type Condition<V> =
36
- | V
37
- | {
38
- eq?: Scalar<V>
39
- in?: readonly Scalar<V>[]
40
- lt?: Scalar<V>
41
- lte?: Scalar<V>
42
- gt?: Scalar<V>
43
- gte?: Scalar<V>
44
- isNull?: true
45
- notNull?: true
46
- }
47
-
48
- export type Where<R> = { [K in keyof R]?: Condition<R[K]> } & {
49
- and?: readonly Where<R>[]
50
- or?: readonly Where<R>[]
51
- }
52
-
53
- export interface SelectQuery<R> {
54
- where?: Where<R>
55
- orderBy?: { [K in keyof R]?: 'asc' | 'desc' }
56
- /** At most 10,000; 1,000 when not given. */
57
- limit?: number
58
- offset?: number
59
- }
60
-
61
- export interface TableHandle<C extends Columns> {
62
- select(query?: SelectQuery<RowOf<C>>): Promise<RowOf<C>[]>
63
- count(query?: { where?: Where<RowOf<C>> }): Promise<number>
64
- insert(rows: InsertOf<C> | readonly InsertOf<C>[]): Promise<void>
65
- /** A `where` is required; an unfiltered write is `truncate`. */
66
- update(query: { where: Where<RowOf<C>>; set: Partial<RowOf<C>> }): Promise<void>
67
- delete(query: { where: Where<RowOf<C>> }): Promise<void>
68
- /** Every row, gone. */
69
- truncate(): Promise<void>
70
- }
71
-
72
- export type TableHandles<S extends TablesShape> = { readonly [T in keyof S]: TableHandle<S[T]> }
73
-
74
- export type BundleTablesCapability<S extends TablesShape = TablesShape> = TableHandles<S> & {
75
- /** Runs `fn` in one transaction, handing it the same tables bound to it. */
76
- transaction<R>(fn: (tables: TableHandles<S>) => Promise<R>): Promise<R>
77
- }
78
-
79
- const MAX_LIMIT = 10_000
80
- const DEFAULT_LIMIT = 1_000
81
- const MAX_DEPTH = 8
82
- const MAX_IN = 1_000
83
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
84
- const OPERATORS = new Set(['eq', 'in', 'lt', 'lte', 'gt', 'gte', 'isNull', 'notNull'])
85
- const COMPARISONS: Record<string, string> = { eq: '=', lt: '<', lte: '<=', gt: '>', gte: '>=' }
86
-
87
- /** A plain object, and not a class instance or an array, read by its own keys only. */
88
- function isPlain(value: unknown): value is Record<string, unknown> {
89
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false
90
- const proto = Object.getPrototypeOf(value)
91
- return proto === Object.prototype || proto === null
92
- }
93
-
94
- function frozen<T extends object>(members: T): T {
95
- return Object.freeze(Object.assign(Object.create(null), members)) as T
96
- }
97
-
98
- interface Compiler {
99
- bundle: string
100
- dialectName: Db['dialect']['name']
101
- boolValue: Db['dialect']['boolValue']
102
- quote: Db['dialect']['quote']
103
- }
104
-
105
- function refuse(bundle: string, reason: string): never {
106
- throw new BundleQueryError(bundle, reason)
107
- }
108
-
109
- /** A value as the column stores it, or a refusal. */
110
- function toDb(
111
- c: Compiler,
112
- table: ResolvedTable,
113
- column: string,
114
- spec: ColumnSpec,
115
- value: unknown,
116
- ): unknown {
117
- const where = `"${table.name}.${column}"`
118
- if (value === null || value === undefined) {
119
- if (!spec.nullable) refuse(c.bundle, `${where} cannot be null`)
120
- return null
121
- }
122
- switch (spec.type) {
123
- case 'uuid':
124
- // Lowercased, so a key compares equal however it was written, on both dialects.
125
- if (typeof value !== 'string' || !UUID.test(value)) refuse(c.bundle, `${where} takes a uuid`)
126
- return value.toLowerCase()
127
- case 'text':
128
- if (typeof value !== 'string') refuse(c.bundle, `${where} takes a string`)
129
- return value
130
- case 'varchar':
131
- if (typeof value !== 'string') refuse(c.bundle, `${where} takes a string`)
132
- if (value.length > (spec.length ?? 0))
133
- refuse(c.bundle, `${where} holds at most ${spec.length} characters`)
134
- return value
135
- case 'integer':
136
- case 'bigint':
137
- if (typeof value !== 'number' || !Number.isSafeInteger(value))
138
- refuse(c.bundle, `${where} takes a whole number`)
139
- if (spec.type === 'integer' && Math.abs(value) > 2_147_483_647)
140
- refuse(c.bundle, `${where} is an integer, and ${value} needs a bigint`)
141
- return value
142
- case 'boolean':
143
- if (typeof value !== 'boolean') refuse(c.bundle, `${where} takes true or false`)
144
- return c.boolValue(value)
145
- case 'timestamp': {
146
- const date =
147
- value instanceof Date ? value : typeof value === 'string' ? new Date(value) : undefined
148
- if (!date || Number.isNaN(date.getTime())) refuse(c.bundle, `${where} takes a date`)
149
- return DbDate.toDb(date)
150
- }
151
- case 'json':
152
- try {
153
- return JSON.stringify(value)
154
- } catch {
155
- return refuse(c.bundle, `${where} takes a value JSON can hold`)
156
- }
157
- }
158
- }
159
-
160
- function fromDb(spec: ColumnSpec, value: unknown): unknown {
161
- if (value === null || value === undefined) return null
162
- switch (spec.type) {
163
- case 'uuid':
164
- return String(value).toLowerCase()
165
- case 'varchar':
166
- case 'text':
167
- return String(value)
168
- case 'integer':
169
- case 'bigint':
170
- return Number(value)
171
- case 'boolean':
172
- return fromDbBool(value)
173
- case 'timestamp':
174
- return DbDate.fromDb(value) ?? null
175
- case 'json':
176
- return JSON.parse(String(value)) as JsonValue
177
- }
178
- }
179
-
180
- /** The column a caller named, from the schema, or a refusal. */
181
- function columnOf(c: Compiler, table: ResolvedTable, name: string): ColumnSpec {
182
- const column = table.columns.get(name)
183
- if (!column) refuse(c.bundle, `"${table.name}" has no column ${JSON.stringify(name)}`)
184
- return column.spec
185
- }
186
-
187
- function compileWhere(
188
- c: Compiler,
189
- table: ResolvedTable,
190
- where: unknown,
191
- params: unknown[],
192
- depth: number,
193
- ): string {
194
- if (depth > MAX_DEPTH) refuse(c.bundle, `a filter is nested more than ${MAX_DEPTH} deep`)
195
- if (!isPlain(where)) refuse(c.bundle, 'a filter must be a plain object')
196
- const parts: string[] = []
197
- for (const key of Object.keys(where)) {
198
- const value = where[key]
199
- if (key === 'and' || key === 'or') {
200
- if (!Array.isArray(value) || value.length === 0)
201
- refuse(c.bundle, `"${key}" takes a non-empty list of filters`)
202
- const inner = value.map((item) => compileWhere(c, table, item, params, depth + 1))
203
- parts.push(`(${inner.join(key === 'and' ? ' AND ' : ' OR ')})`)
204
- continue
205
- }
206
- const spec = columnOf(c, table, key)
207
- const col = c.quote(key)
208
- if (value === null) {
209
- parts.push(`${col} IS NULL`)
210
- continue
211
- }
212
- if (isPlain(value)) {
213
- const ops = Object.keys(value)
214
- if (ops.length === 0) refuse(c.bundle, `the condition on "${key}" is empty`)
215
- for (const op of ops) {
216
- if (!OPERATORS.has(op)) refuse(c.bundle, `${JSON.stringify(op)} is not a condition`)
217
- const operand = value[op]
218
- if (op === 'isNull' || op === 'notNull') {
219
- if (operand !== true) refuse(c.bundle, `"${op}" takes true`)
220
- parts.push(`${col} ${op === 'isNull' ? 'IS NULL' : 'IS NOT NULL'}`)
221
- continue
222
- }
223
- if (spec.type === 'json')
224
- refuse(c.bundle, `"${key}" is json, which can only be tested for null`)
225
- if (op === 'in') {
226
- if (!Array.isArray(operand) || operand.length === 0 || operand.length > MAX_IN)
227
- refuse(c.bundle, `"in" takes a list of 1 to ${MAX_IN} values`)
228
- for (const item of operand)
229
- params.push(toDb(c, table, key, { ...spec, nullable: false }, item))
230
- parts.push(`${col} IN (${operand.map(() => '?').join(', ')})`)
231
- continue
232
- }
233
- params.push(toDb(c, table, key, { ...spec, nullable: false }, operand))
234
- parts.push(`${col} ${COMPARISONS[op]} ?`)
235
- }
236
- continue
237
- }
238
- if (spec.type === 'json')
239
- refuse(c.bundle, `"${key}" is json, which can only be tested for null`)
240
- params.push(toDb(c, table, key, { ...spec, nullable: false }, value))
241
- parts.push(`${col} = ?`)
242
- }
243
- if (parts.length === 0) refuse(c.bundle, 'a filter names no condition')
244
- return parts.join(' AND ')
245
- }
246
-
247
- function readRow(table: ResolvedTable, row: Record<string, unknown>): Record<string, unknown> {
248
- const out: Record<string, unknown> = {}
249
- for (const [name, column] of table.columns) out[name] = fromDb(column.spec, row[name])
250
- return out
251
- }
252
-
253
- function tableHandle(db: Db, schema: ResolvedSchema, table: ResolvedTable): TableHandle<Columns> {
254
- const c: Compiler = {
255
- bundle: schema.id,
256
- dialectName: db.dialect.name,
257
- boolValue: (value) => db.dialect.boolValue(value),
258
- quote: (identifier) => db.dialect.quote(identifier),
259
- }
260
- const name = c.quote(table.physical)
261
- const guard = (sql: string) => guardStatement(schema.id, schema.prefix, sql)
262
- const columnList = [...table.columns.keys()].map(c.quote).join(', ')
263
-
264
- const whereClause = (where: unknown, params: unknown[], required: boolean): string => {
265
- if (where === undefined) {
266
- if (required)
267
- refuse(c.bundle, 'an update or a delete needs a "where"; use truncate to empty a table')
268
- return ''
269
- }
270
- return ` WHERE ${compileWhere(c, table, where, params, 0)}`
271
- }
272
-
273
- return frozen({
274
- async select(query: SelectQuery<Record<string, unknown>> = {}) {
275
- if (!isPlain(query)) refuse(c.bundle, 'a query must be a plain object')
276
- const params: unknown[] = []
277
- let sql = `SELECT ${columnList} FROM ${name}${whereClause(query.where, params, false)}`
278
- if (query.orderBy !== undefined) {
279
- if (!isPlain(query.orderBy)) refuse(c.bundle, '"orderBy" must be a plain object')
280
- const order = Object.keys(query.orderBy).map((key) => {
281
- columnOf(c, table, key)
282
- const direction = (query.orderBy as Record<string, unknown>)[key]
283
- if (direction !== 'asc' && direction !== 'desc')
284
- refuse(c.bundle, `the order of "${key}" is "asc" or "desc"`)
285
- return `${c.quote(key)} ${direction === 'asc' ? 'ASC' : 'DESC'}`
286
- })
287
- if (order.length > 0) sql += ` ORDER BY ${order.join(', ')}`
288
- }
289
- const limit: unknown = query.limit ?? DEFAULT_LIMIT
290
- const offset: unknown = query.offset ?? 0
291
- if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 0 || limit > MAX_LIMIT)
292
- refuse(c.bundle, `"limit" is a whole number from 0 to ${MAX_LIMIT}`)
293
- if (typeof offset !== 'number' || !Number.isInteger(offset) || offset < 0)
294
- refuse(c.bundle, '"offset" is a whole number from 0')
295
- sql += ' LIMIT ? OFFSET ?'
296
- params.push(limit, offset)
297
- const rows = await db.query<Record<string, unknown>>(guard(sql), params)
298
- return rows.map((row) => readRow(table, row))
299
- },
300
-
301
- async count(query: { where?: unknown } = {}) {
302
- if (!isPlain(query)) refuse(c.bundle, 'a query must be a plain object')
303
- const params: unknown[] = []
304
- const sql = `SELECT COUNT(*) AS ${c.quote('n')} FROM ${name}${whereClause(query.where, params, false)}`
305
- const rows = await db.query<{ n: unknown }>(guard(sql), params)
306
- return Number(rows[0]?.n ?? 0)
307
- },
308
-
309
- async insert(input: unknown) {
310
- const rows = Array.isArray(input) ? input : [input]
311
- if (rows.length === 0) return
312
- for (const row of rows) {
313
- if (!isPlain(row)) refuse(c.bundle, 'a row must be a plain object')
314
- for (const key of Object.keys(row)) columnOf(c, table, key)
315
- const names: string[] = []
316
- const params: unknown[] = []
317
- for (const [column, resolved] of table.columns) {
318
- const given = Object.hasOwn(row, column)
319
- if (!given) {
320
- if (resolved.spec.default !== undefined || resolved.spec.nullable) continue
321
- refuse(c.bundle, `a row of "${table.name}" needs "${column}"`)
322
- }
323
- names.push(c.quote(column))
324
- params.push(toDb(c, table, column, resolved.spec, row[column]))
325
- }
326
- await db.exec(
327
- guard(
328
- `INSERT INTO ${name} (${names.join(', ')}) VALUES (${names.map(() => '?').join(', ')})`,
329
- ),
330
- params,
331
- )
332
- }
333
- },
334
-
335
- async update(query: { where?: unknown; set?: unknown }) {
336
- if (!isPlain(query)) refuse(c.bundle, 'an update must be a plain object')
337
- if (!isPlain(query.set) || Object.keys(query.set).length === 0)
338
- refuse(c.bundle, 'an update needs a "set" naming at least one column')
339
- const set = query.set
340
- const params: unknown[] = []
341
- const assignments = Object.keys(set).map((column) => {
342
- params.push(toDb(c, table, column, columnOf(c, table, column), set[column]))
343
- return `${c.quote(column)} = ?`
344
- })
345
- const where = whereClause(query.where, params, true)
346
- await db.exec(guard(`UPDATE ${name} SET ${assignments.join(', ')}${where}`), params)
347
- },
348
-
349
- async delete(query: { where?: unknown }) {
350
- if (!isPlain(query)) refuse(c.bundle, 'a delete must be a plain object')
351
- const params: unknown[] = []
352
- await db.exec(guard(`DELETE FROM ${name}${whereClause(query.where, params, true)}`), params)
353
- },
354
-
355
- async truncate() {
356
- await db.exec(guard(`DELETE FROM ${name}`))
357
- },
358
- }) as TableHandle<Columns>
359
- }
360
-
361
- function handlesOver(db: Db, schema: ResolvedSchema): TableHandles<TablesShape> {
362
- const handles: Record<string, TableHandle<Columns>> = {}
363
- for (const [name, table] of schema.tables) handles[name] = tableHandle(db, schema, table)
364
- return frozen(handles) as TableHandles<TablesShape>
365
- }
366
-
367
- /** The capability over a bundle's resolved schema, bound to a connection it never exposes. */
368
- export function createTablesCapability<S extends TablesShape = TablesShape>(
369
- db: Db,
370
- schema: ResolvedSchema,
371
- ): BundleTablesCapability<S> {
372
- return frozen({
373
- ...handlesOver(db, schema),
374
- transaction: <R>(fn: (tables: TableHandles<TablesShape>) => Promise<R>) =>
375
- db.transaction((tx) => fn(handlesOver(tx, schema))),
376
- }) as unknown as BundleTablesCapability<S>
377
- }
@@ -1,105 +0,0 @@
1
- /**
2
- * A bundle's compiled steps as a migration chain, run by the same `migrate`,
3
- * under the same lock and into the same ledger as core's — only its state key
4
- * and its ledger rows' `bundle` differ. And purging one: dropping exactly the
5
- * tables under its prefix, found in the database rather than the declaration,
6
- * because a purged bundle is one the site no longer wires.
7
- */
8
- import type { Db } from '../database.ts'
9
- import { deleteKeyValue, type Migration, MigrationPlan, recordInLedger } from '../migrations.ts'
10
- import { createTablesCapability } from './capability.ts'
11
- import { renderStep } from './ddl.ts'
12
- import { guardStatement } from './guard.ts'
13
- import { bundlePrefix } from './names.ts'
14
- import type { CompiledStep, CompiledTables } from './schema.ts'
15
-
16
- function migrationOf(step: CompiledStep): Migration {
17
- return {
18
- from: step.from,
19
- to: step.to,
20
- name: step.name,
21
- kind: step.kind,
22
- release: step.release,
23
- contracts: step.contracts,
24
- checksum: step.checksum,
25
- async up(db) {
26
- for (const sql of renderStep(db.dialect, step)) await db.exec(sql)
27
- },
28
- backfill: step.backfill
29
- ? (db) =>
30
- (step.backfill as NonNullable<CompiledStep['backfill']>)(
31
- createTablesCapability(db, step.after),
32
- )
33
- : undefined,
34
- }
35
- }
36
-
37
- /** The chain `migrate` walks. Throws when the declaration has problems: compile first. */
38
- export function bundlePlan(compiled: CompiledTables): MigrationPlan {
39
- if (compiled.problems.length > 0)
40
- throw new Error(
41
- `The bundle "${compiled.id}"'s tables cannot be planned:\n- ${compiled.problems.join('\n- ')}`,
42
- )
43
- return new MigrationPlan(compiled.steps.map(migrationOf), {
44
- stateKey: compiled.stateKey,
45
- initialState: compiled.initialState,
46
- bundle: compiled.id,
47
- })
48
- }
49
-
50
- /**
51
- * Creates a bundle's tables directly, step by step, without its ledger or its
52
- * state. Only for proving what core's own migrations do around a bundle's
53
- * tables: an install is always `migrate`.
54
- */
55
- export async function applyBundleStepsUnledgered(db: Db, compiled: CompiledTables): Promise<void> {
56
- for (const migration of bundlePlan(compiled).migrations)
57
- await db.transaction(async (tx) => {
58
- await migration.up(tx)
59
- await migration.backfill?.(tx)
60
- })
61
- }
62
-
63
- /** Every table in the database under a bundle's prefix. */
64
- export async function bundleTablesIn(db: Db, id: string): Promise<string[]> {
65
- const prefix = bundlePrefix(id)
66
- const rows =
67
- db.dialect.name === 'sqlite'
68
- ? await db.query<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table'")
69
- : await db.query<{ name: string }>(
70
- "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE'",
71
- )
72
- // Compared as text rather than with LIKE, where `_` is a wildcard.
73
- return rows
74
- .map((row) => row.name)
75
- .filter((name) => name.startsWith(prefix))
76
- .sort()
77
- }
78
-
79
- /**
80
- * Drops every table under the bundle's prefix and forgets its state, so adding
81
- * it again starts its chain from the beginning. Ledgered as a `purge`.
82
- */
83
- export async function purgeBundleTables(
84
- db: Db,
85
- id: string,
86
- options: { by?: string; stateKey: string },
87
- ): Promise<string[]> {
88
- const prefix = bundlePrefix(id)
89
- const tables = await bundleTablesIn(db, id)
90
- const started = performance.now()
91
- await db.transaction(async (tx) => {
92
- for (const table of tables)
93
- await tx.exec(guardStatement(id, prefix, `DROP TABLE ${tx.dialect.quote(table)}`))
94
- })
95
- await deleteKeyValue(db, options.stateKey)
96
- await recordInLedger(db, {
97
- name: `purge ${id}`,
98
- kind: 'purge',
99
- durationMs: Math.round(performance.now() - started),
100
- appliedBy: options.by ?? null,
101
- note: tables.length > 0 ? `dropped ${tables.join(', ')}` : 'no tables',
102
- bundle: id,
103
- })
104
- return tables
105
- }