@crombolo/data 0.37.0 → 0.38.1

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 +3 -2
  2. package/src/audit.ts +163 -133
  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 +8 -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 +74 -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/jobs.ts +56 -0
  60. package/src/schema/plan.ts +4 -0
  61. package/src/schema-ops.ts +15 -12
  62. package/src/schema-state.ts +53 -38
  63. package/src/search.ts +175 -129
  64. package/src/setup.ts +17 -13
  65. package/src/site-search.ts +134 -83
  66. package/src/table-types.ts +152 -0
  67. package/src/tables.gen.ts +859 -0
  68. package/src/tree-invariants.ts +21 -12
  69. package/src/url-options.ts +17 -13
  70. package/src/workflow-store.ts +17 -13
  71. package/src/bundle-tables/capability.ts +0 -377
  72. package/src/bundle-tables/chain.ts +0 -105
  73. package/src/bundle-tables/ddl.ts +0 -124
  74. package/src/bundle-tables/guard.ts +0 -116
  75. package/src/bundle-tables/names.ts +0 -58
@@ -37,9 +37,21 @@ export class WebhookRepository {
37
37
  }
38
38
 
39
39
  async all(): Promise<WebhookRow[]> {
40
- const rows = await this.#db.query(
41
- 'SELECT key, name, description, url, enabled, events, content_type_keys, headers FROM webhook ORDER BY create_date, key',
42
- )
40
+ const rows = await this.#db.q
41
+ .selectFrom('webhook')
42
+ .select([
43
+ 'key',
44
+ 'name',
45
+ 'description',
46
+ 'url',
47
+ 'enabled',
48
+ 'events',
49
+ 'content_type_keys',
50
+ 'headers',
51
+ ])
52
+ .orderBy('create_date')
53
+ .orderBy('key')
54
+ .execute()
43
55
  return rows.map((row) => ({
44
56
  key: String(row.key),
45
57
  name: (row.name as string | null) ?? null,
@@ -58,35 +70,35 @@ export class WebhookRepository {
58
70
 
59
71
  async save(webhook: WebhookRow): Promise<void> {
60
72
  const now = DbDate.toDb(new Date())
61
- const values = [
62
- webhook.name,
63
- webhook.description,
64
- webhook.url,
65
- this.#db.dialect.boolValue(webhook.enabled),
66
- JSON.stringify(webhook.events),
67
- JSON.stringify(webhook.contentTypeKeys),
68
- webhook.sealedHeaders,
69
- now,
70
- ]
71
- const updated = await this.#db.query(
72
- `UPDATE webhook SET name = ?, description = ?, url = ?, enabled = ?, events = ?,
73
- content_type_keys = ?, headers = ?, update_date = ?
74
- WHERE key = ? RETURNING key`,
75
- [...values, webhook.key.toLowerCase()],
76
- )
73
+ const values = {
74
+ name: webhook.name,
75
+ description: webhook.description,
76
+ url: webhook.url,
77
+ enabled: this.#db.dialect.boolValue(webhook.enabled),
78
+ events: JSON.stringify(webhook.events),
79
+ content_type_keys: JSON.stringify(webhook.contentTypeKeys),
80
+ headers: webhook.sealedHeaders,
81
+ update_date: now,
82
+ }
83
+ const updated = await this.#db.q
84
+ .updateTable('webhook')
85
+ .set(values)
86
+ .where('key', '=', webhook.key.toLowerCase())
87
+ .returning('key')
88
+ .execute()
77
89
  if (updated.length > 0) return
78
- await this.#db.exec(
79
- `INSERT INTO webhook (name, description, url, enabled, events, content_type_keys, headers,
80
- update_date, key, create_date)
81
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
82
- [...values, webhook.key.toLowerCase(), now],
83
- )
90
+ await this.#db.q
91
+ .insertInto('webhook')
92
+ .values({ ...values, key: webhook.key.toLowerCase(), create_date: now })
93
+ .execute()
84
94
  }
85
95
 
86
96
  async remove(key: string): Promise<boolean> {
87
- const rows = await this.#db.query('DELETE FROM webhook WHERE key = ? RETURNING key', [
88
- key.toLowerCase(),
89
- ])
97
+ const rows = await this.#db.q
98
+ .deleteFrom('webhook')
99
+ .where('key', '=', key.toLowerCase())
100
+ .returning('key')
101
+ .execute()
90
102
  return rows.length > 0
91
103
  }
92
104
  }
@@ -125,8 +137,18 @@ export interface WebhookLogEntry {
125
137
  date: Date
126
138
  }
127
139
 
128
- const DELIVERY_COLUMNS =
129
- 'id, subscriber, event_alias, payload, state, attempts, last_error, run_after, create_date, event_id'
140
+ const DELIVERY_COLUMNS = [
141
+ 'id',
142
+ 'subscriber',
143
+ 'event_alias',
144
+ 'payload',
145
+ 'state',
146
+ 'attempts',
147
+ 'last_error',
148
+ 'run_after',
149
+ 'create_date',
150
+ 'event_id',
151
+ ] as const
130
152
 
131
153
  const hydrateDelivery = (row: Record<string, unknown>): WebhookDelivery => {
132
154
  let payload: unknown = null
@@ -174,24 +196,24 @@ export class WebhookDeliveryRepository {
174
196
  const ids: string[] = []
175
197
  for (const delivery of deliveries) {
176
198
  const id = randomUUID()
177
- const rows = await this.#db.query(
178
- `INSERT INTO webhook_delivery (${DELIVERY_COLUMNS}, update_date)
179
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
180
- ON CONFLICT DO NOTHING RETURNING id`,
181
- [
199
+ const rows = await this.#db.q
200
+ .insertInto('webhook_delivery')
201
+ .values({
182
202
  id,
183
- delivery.subscriber,
184
- delivery.eventAlias,
185
- JSON.stringify(delivery.payload),
186
- 'pending',
187
- 0,
188
- null,
189
- DbDate.toDb(now),
190
- DbDate.toDb(now),
191
- delivery.eventId ?? null,
192
- DbDate.toDb(now),
193
- ],
194
- )
203
+ subscriber: delivery.subscriber,
204
+ event_alias: delivery.eventAlias,
205
+ payload: JSON.stringify(delivery.payload),
206
+ state: 'pending',
207
+ attempts: 0,
208
+ last_error: null,
209
+ run_after: DbDate.toDb(now),
210
+ create_date: DbDate.toDb(now),
211
+ event_id: delivery.eventId ?? null,
212
+ update_date: DbDate.toDb(now),
213
+ })
214
+ .onConflict((oc) => oc.doNothing())
215
+ .returning('id')
216
+ .execute()
195
217
  if (rows.length > 0) ids.push(id)
196
218
  }
197
219
  return ids
@@ -199,124 +221,145 @@ export class WebhookDeliveryRepository {
199
221
 
200
222
  /** Claims older than `olderThan` belong to a node that died: they go back in the queue. */
201
223
  async releaseStale(olderThan: Date): Promise<number> {
202
- const rows = await this.#db.query(
203
- `UPDATE webhook_delivery SET state = 'pending', update_date = ?
204
- WHERE state = 'running' AND update_date < ? RETURNING id`,
205
- [DbDate.toDb(new Date()), DbDate.toDb(olderThan)],
206
- )
224
+ const rows = await this.#db.q
225
+ .updateTable('webhook_delivery')
226
+ .set({ state: 'pending', update_date: DbDate.toDb(new Date()) })
227
+ .where('state', '=', 'running')
228
+ .where('update_date', '<', DbDate.toDb(olderThan))
229
+ .returning('id')
230
+ .execute()
207
231
  return rows.length
208
232
  }
209
233
 
210
234
  /** Puts failed deliveries back, all or one; answers how many. */
211
235
  async retry(id?: string): Promise<number> {
212
236
  const now = DbDate.toDb(new Date())
213
- const rows = await this.#db.query(
214
- `UPDATE webhook_delivery SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
215
- WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
216
- id ? [now, now, id] : [now, now],
217
- )
237
+ const rows = await this.#db.q
238
+ .updateTable('webhook_delivery')
239
+ .set({ state: 'pending', attempts: 0, run_after: now, update_date: now })
240
+ .where('state', '=', 'failed')
241
+ .$if(Boolean(id), (q) => q.where('id', '=', id as string))
242
+ .returning('id')
243
+ .execute()
218
244
  return rows.length
219
245
  }
220
246
 
221
247
  /** Delivered rows and log entries older than `before` go; failed ones stay until retried. */
222
248
  async prune(before: Date): Promise<number> {
223
- const done = await this.#db.query(
224
- `DELETE FROM webhook_delivery WHERE state = 'done' AND update_date < ? RETURNING id`,
225
- [DbDate.toDb(before)],
226
- )
227
- const logged = await this.#db.query(
228
- 'DELETE FROM webhook_log WHERE log_date < ? RETURNING key',
229
- [DbDate.toDb(before)],
230
- )
249
+ const done = await this.#db.q
250
+ .deleteFrom('webhook_delivery')
251
+ .where('state', '=', 'done')
252
+ .where('update_date', '<', DbDate.toDb(before))
253
+ .returning('id')
254
+ .execute()
255
+ const logged = await this.#db.q
256
+ .deleteFrom('webhook_log')
257
+ .where('log_date', '<', DbDate.toDb(before))
258
+ .returning('key')
259
+ .execute()
231
260
  return done.length + logged.length
232
261
  }
233
262
 
234
263
  async failed(limit = 100): Promise<WebhookDelivery[]> {
235
- const rows = await this.#db.query(
236
- `SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery WHERE state = 'failed'
237
- ORDER BY update_date DESC LIMIT ?`,
238
- [limit],
239
- )
264
+ const rows = await this.#db.q
265
+ .selectFrom('webhook_delivery')
266
+ .select(DELIVERY_COLUMNS)
267
+ .where('state', '=', 'failed')
268
+ .orderBy('update_date', 'desc')
269
+ .limit(limit)
270
+ .execute()
240
271
  return rows.map(hydrateDelivery)
241
272
  }
242
273
 
243
274
  async all(): Promise<WebhookDelivery[]> {
244
- const rows = await this.#db.query(
245
- `SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery ORDER BY create_date`,
246
- )
275
+ const rows = await this.#db.q
276
+ .selectFrom('webhook_delivery')
277
+ .select(DELIVERY_COLUMNS)
278
+ .orderBy('create_date')
279
+ .execute()
247
280
  return rows.map(hydrateDelivery)
248
281
  }
249
282
 
250
283
  async due(now = new Date(), limit = 25): Promise<WebhookDelivery[]> {
251
- const rows = await this.#db.query(
252
- `SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery WHERE state = ? AND run_after <= ?
253
- ORDER BY run_after, create_date LIMIT ?`,
254
- ['pending', DbDate.toDb(now), limit],
255
- )
284
+ const rows = await this.#db.q
285
+ .selectFrom('webhook_delivery')
286
+ .select(DELIVERY_COLUMNS)
287
+ .where('state', '=', 'pending')
288
+ .where('run_after', '<=', DbDate.toDb(now))
289
+ .orderBy('run_after')
290
+ .orderBy('create_date')
291
+ .limit(limit)
292
+ .execute()
256
293
  return rows.map(hydrateDelivery)
257
294
  }
258
295
 
259
296
  /** Takes a delivery, or finds another node already has. */
260
297
  async claim(id: string): Promise<WebhookDelivery | undefined> {
261
- const rows = await this.#db.query(
262
- `UPDATE webhook_delivery SET state = ?, attempts = attempts + 1, update_date = ?
263
- WHERE id = ? AND state = ? RETURNING ${DELIVERY_COLUMNS}`,
264
- ['running', DbDate.toDb(new Date()), id, 'pending'],
265
- )
266
- return rows[0] ? hydrateDelivery(rows[0]) : undefined
298
+ const row = await this.#db.q
299
+ .updateTable('webhook_delivery')
300
+ .set((eb) => ({
301
+ state: 'running',
302
+ attempts: eb('attempts', '+', 1),
303
+ update_date: DbDate.toDb(new Date()),
304
+ }))
305
+ .where('id', '=', id)
306
+ .where('state', '=', 'pending')
307
+ .returning(DELIVERY_COLUMNS)
308
+ .executeTakeFirst()
309
+ return row ? hydrateDelivery(row) : undefined
267
310
  }
268
311
 
269
312
  async succeed(id: string): Promise<void> {
270
- await this.#db.exec(
271
- 'UPDATE webhook_delivery SET state = ?, last_error = NULL, update_date = ? WHERE id = ?',
272
- ['done', DbDate.toDb(new Date()), id],
273
- )
313
+ await this.#db.q
314
+ .updateTable('webhook_delivery')
315
+ .set({ state: 'done', last_error: null, update_date: DbDate.toDb(new Date()) })
316
+ .where('id', '=', id)
317
+ .execute()
274
318
  }
275
319
 
276
320
  /** `retryAt` puts it back in the queue; without one it has failed for good. */
277
321
  async fail(id: string, error: string, retryAt?: Date): Promise<void> {
278
- await this.#db.exec(
279
- 'UPDATE webhook_delivery SET state = ?, last_error = ?, run_after = ?, update_date = ? WHERE id = ?',
280
- [
281
- retryAt ? 'pending' : 'failed',
282
- error.slice(0, 2000),
283
- DbDate.toDb(retryAt ?? new Date()),
284
- DbDate.toDb(new Date()),
285
- id,
286
- ],
287
- )
322
+ await this.#db.q
323
+ .updateTable('webhook_delivery')
324
+ .set({
325
+ state: retryAt ? 'pending' : 'failed',
326
+ last_error: error.slice(0, 2000),
327
+ run_after: DbDate.toDb(retryAt ?? new Date()),
328
+ update_date: DbDate.toDb(new Date()),
329
+ })
330
+ .where('id', '=', id)
331
+ .execute()
288
332
  }
289
333
 
290
334
  async byId(id: string): Promise<WebhookDelivery | undefined> {
291
- const rows = await this.#db.query(
292
- `SELECT ${DELIVERY_COLUMNS} FROM webhook_delivery WHERE id = ?`,
293
- [id],
294
- )
295
- return rows[0] ? hydrateDelivery(rows[0]) : undefined
335
+ const row = await this.#db.q
336
+ .selectFrom('webhook_delivery')
337
+ .select(DELIVERY_COLUMNS)
338
+ .where('id', '=', id)
339
+ .executeTakeFirst()
340
+ return row ? hydrateDelivery(row) : undefined
296
341
  }
297
342
 
298
343
  async log(entry: Omit<WebhookLogEntry, 'key' | 'date'>, date = new Date()): Promise<void> {
299
- await this.#db.exec(
300
- `INSERT INTO webhook_log (key, delivery_id, subscriber, event_alias, url, status_code, success,
301
- exception, retry_count, request_headers, request_body, response_headers, response_body, log_date)
302
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
303
- [
304
- randomUUID(),
305
- entry.deliveryId,
306
- entry.subscriber,
307
- entry.eventAlias,
308
- entry.url,
309
- entry.statusCode,
310
- this.#db.dialect.boolValue(entry.success),
311
- this.#db.dialect.boolValue(entry.exception),
312
- entry.retryCount,
313
- clip(entry.requestHeaders),
314
- clip(entry.requestBody),
315
- clip(entry.responseHeaders),
316
- clip(entry.responseBody),
317
- DbDate.toDb(date),
318
- ],
319
- )
344
+ await this.#db.q
345
+ .insertInto('webhook_log')
346
+ .values({
347
+ key: randomUUID(),
348
+ delivery_id: entry.deliveryId,
349
+ subscriber: entry.subscriber,
350
+ event_alias: entry.eventAlias,
351
+ url: entry.url,
352
+ status_code: entry.statusCode,
353
+ success: this.#db.dialect.boolValue(entry.success),
354
+ exception: this.#db.dialect.boolValue(entry.exception),
355
+ retry_count: entry.retryCount,
356
+ request_headers: clip(entry.requestHeaders),
357
+ request_body: clip(entry.requestBody),
358
+ response_headers: clip(entry.responseHeaders),
359
+ response_body: clip(entry.responseBody),
360
+ log_date: DbDate.toDb(date),
361
+ })
362
+ .execute()
320
363
  }
321
364
 
322
365
  /** The log, newest first; one subscriber's when named. */
@@ -325,20 +368,36 @@ export class WebhookDeliveryRepository {
325
368
  skip: number
326
369
  take: number
327
370
  }): Promise<{ total: number; items: WebhookLogEntry[] }> {
328
- const where = options.subscriber ? 'WHERE subscriber = ?' : ''
329
- const params = options.subscriber ? [options.subscriber] : []
330
- const total = await this.#db.query<{ n: number }>(
331
- `SELECT COUNT(*) AS n FROM webhook_log ${where}`,
332
- params,
333
- )
334
- const rows = await this.#db.query(
335
- `SELECT key, delivery_id, subscriber, event_alias, url, status_code, success, exception,
336
- retry_count, request_headers, request_body, response_headers, response_body, log_date
337
- FROM webhook_log ${where} ORDER BY log_date DESC, retry_count DESC, key LIMIT ? OFFSET ?`,
338
- [...params, options.take, options.skip],
339
- )
371
+ const { subscriber } = options
372
+ const log = this.#db.q
373
+ .selectFrom('webhook_log')
374
+ .$if(Boolean(subscriber), (q) => q.where('subscriber', '=', subscriber as string))
375
+ const total = await log.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
376
+ const rows = await log
377
+ .select([
378
+ 'key',
379
+ 'delivery_id',
380
+ 'subscriber',
381
+ 'event_alias',
382
+ 'url',
383
+ 'status_code',
384
+ 'success',
385
+ 'exception',
386
+ 'retry_count',
387
+ 'request_headers',
388
+ 'request_body',
389
+ 'response_headers',
390
+ 'response_body',
391
+ 'log_date',
392
+ ])
393
+ .orderBy('log_date', 'desc')
394
+ .orderBy('retry_count', 'desc')
395
+ .orderBy('key')
396
+ .limit(options.take)
397
+ .offset(options.skip)
398
+ .execute()
340
399
  return {
341
- total: Number(total[0]?.n ?? 0),
400
+ total: Number(total?.n ?? 0),
342
401
  items: rows.map((row) => ({
343
402
  key: String(row.key),
344
403
  deliveryId: String(row.delivery_id),
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Migration 054: what an administrator granted each bundle (story 222). One row
3
+ * per bundle, replaced on each grant: the package and version it was granted
4
+ * for, the permissions, who granted them and when. A bundle with no row, or
5
+ * declaring more than its row holds, is off.
6
+ */
7
+ import { sql } from 'kysely'
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { STATE_MEDIA_MEMBER_GRANTS } from './media-member-grants.ts'
11
+
12
+ export const STATE_BUNDLE_GRANTS = '{4b198f00-0054-4ca8-bc39-97d92fca0054}'
13
+
14
+ export const bundleGrantsMigration: Migration = {
15
+ from: STATE_MEDIA_MEMBER_GRANTS,
16
+ to: STATE_BUNDLE_GRANTS,
17
+ name: 'AddBundleGrants',
18
+ kind: 'expand',
19
+ release: '0.38.1',
20
+ async up(db: Db) {
21
+ const t = db.dialect.types
22
+ await db.q.schema
23
+ .createTable('bundle_grant')
24
+ .addColumn('bundle_id', sql.raw(t.varchar(64)), (c) => c.primaryKey())
25
+ .addColumn('package_name', sql.raw(t.varchar(214)), (c) => c.notNull())
26
+ .addColumn('version', sql.raw(t.varchar(64)), (c) => c.notNull())
27
+ .addColumn('permissions', sql.raw(t.json), (c) => c.notNull())
28
+ .addColumn('granted_by', sql.raw(t.varchar(255)))
29
+ .addColumn('granted_at', sql.raw(t.timestamp), (c) => c.notNull())
30
+ .execute()
31
+ },
32
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Migration 055: background jobs for the site and its bundles (story 187). One
3
+ * queue for every owner, claimed atomically and retried with back-off, and each
4
+ * schedule's last occurrence, compared and set so exactly one node runs it.
5
+ */
6
+ import { sql } from 'kysely'
7
+ import type { Db } from '../database.ts'
8
+ import type { Migration } from '../migrations.ts'
9
+ import { STATE_BUNDLE_GRANTS } from './bundle-grants.ts'
10
+
11
+ export const STATE_JOBS = '{4b198f00-0055-4ca8-bc39-97d92fca0055}'
12
+
13
+ export const jobsMigration: Migration = {
14
+ from: STATE_BUNDLE_GRANTS,
15
+ to: STATE_JOBS,
16
+ name: 'AddJobs',
17
+ kind: 'expand',
18
+ release: '0.38.1',
19
+ async up(db: Db) {
20
+ const t = db.dialect.types
21
+ const type = (name: string) => sql.raw(name)
22
+ await db.q.schema
23
+ .createTable('job')
24
+ .addColumn('id', type(t.uuid), (c) => c.primaryKey())
25
+ .addColumn('owner', type(t.varchar(64)), (c) => c.notNull())
26
+ .addColumn('name', type(t.varchar(128)), (c) => c.notNull())
27
+ .addColumn('payload', type(t.json), (c) => c.notNull())
28
+ .addColumn('state', type(t.varchar(16)), (c) => c.notNull())
29
+ .addColumn('attempts', type(t.integer), (c) => c.notNull())
30
+ .addColumn('max_attempts', type(t.integer), (c) => c.notNull())
31
+ .addColumn('next_attempt_at', type(t.timestamp), (c) => c.notNull())
32
+ .addColumn('claimed_by', type(t.varchar(255)))
33
+ .addColumn('claimed_at', type(t.timestamp))
34
+ .addColumn('progress', type(t.json))
35
+ .addColumn('last_error', type(t.text))
36
+ .addColumn('queued_by', type(t.varchar(255)))
37
+ .addColumn('created_at', type(t.timestamp), (c) => c.notNull())
38
+ .addColumn('finished_at', type(t.timestamp))
39
+ .execute()
40
+ await db.q.schema
41
+ .createIndex('ix_job_due')
42
+ .on('job')
43
+ .columns(['state', 'next_attempt_at'])
44
+ .execute()
45
+ await db.q.schema
46
+ .createIndex('ix_job_owner')
47
+ .on('job')
48
+ .columns(['owner', 'created_at'])
49
+ .execute()
50
+ await db.q.schema
51
+ .createTable('job_schedule')
52
+ .addColumn('schedule_key', type(t.varchar(200)), (c) => c.primaryKey())
53
+ .addColumn('last_occurrence', type(t.timestamp), (c) => c.notNull())
54
+ .execute()
55
+ },
56
+ }
@@ -18,6 +18,7 @@ import { approvalsMigration } from './approvals.ts'
18
18
  import { assistantMigration } from './assistant.ts'
19
19
  import { auditLogMigration } from './audit-log.ts'
20
20
  import { bundleComponentsMigration } from './bundle-components.ts'
21
+ import { bundleGrantsMigration } from './bundle-grants.ts'
21
22
  import { bundlePackageMigration } from './bundle-package.ts'
22
23
  import { bundlesRenameMigration } from './bundles-rename.ts'
23
24
  import { changeReportMigration } from './change-report.ts'
@@ -39,6 +40,7 @@ import { formWorkflowsMigration } from './form-workflows.ts'
39
40
  import { formsMigration } from './forms.ts'
40
41
  import { groupPermissionsMigration } from './group-permissions.ts'
41
42
  import { identityMigration } from './identity.ts'
43
+ import { jobsMigration } from './jobs.ts'
42
44
  import { logViewerMigration } from './log-viewer.ts'
43
45
  import { mediaAccessMigration } from './media-access.ts'
44
46
  import { mediaCacheMigration } from './media-cache.ts'
@@ -121,4 +123,6 @@ export const cromboloPlan = new MigrationPlan([
121
123
  mediaCacheMigration,
122
124
  mediaMemberUploadsMigration,
123
125
  mediaMemberGrantsMigration,
126
+ bundleGrantsMigration,
127
+ jobsMigration,
124
128
  ])
package/src/schema-ops.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * `RENAME COLUMN`, so nothing here needs the copy-table dance.
5
5
  */
6
6
  import type { Db } from './database.ts'
7
+ import { sql } from './query.ts'
7
8
 
8
9
  export interface SchemaOps {
9
10
  addColumn(table: string, column: string, definition: string): Promise<void>
@@ -16,20 +17,22 @@ export interface SchemaOps {
16
17
  }
17
18
 
18
19
  export function schemaOps(db: Db): SchemaOps {
19
- const q = (identifier: string) => db.dialect.quote(identifier)
20
+ const schema = db.q.schema
20
21
  return {
21
22
  addColumn: (table, column, definition) =>
22
- db.exec(`ALTER TABLE ${q(table)} ADD COLUMN ${q(column)} ${definition}`),
23
- dropColumn: (table, column) => db.exec(`ALTER TABLE ${q(table)} DROP COLUMN ${q(column)}`),
24
- renameColumn: (table, from, to) =>
25
- db.exec(`ALTER TABLE ${q(table)} RENAME COLUMN ${q(from)} TO ${q(to)}`),
26
- renameTable: (from, to) => db.exec(`ALTER TABLE ${q(from)} RENAME TO ${q(to)}`),
27
- addIndex: (name, table, columns, unique = false) =>
28
- db.exec(
29
- `CREATE ${unique ? 'UNIQUE ' : ''}INDEX ${q(name)} ON ${q(table)} (${columns.map(q).join(', ')})`,
30
- ),
23
+ schema.alterTable(table).addColumn(column, sql.raw(definition)).execute(),
24
+ dropColumn: (table, column) => schema.alterTable(table).dropColumn(column).execute(),
25
+ renameColumn: (table, from, to) => schema.alterTable(table).renameColumn(from, to).execute(),
26
+ renameTable: (from, to) => schema.alterTable(from).renameTo(to).execute(),
27
+ addIndex: (name, table, columns, unique = false) => {
28
+ const index = schema
29
+ .createIndex(name)
30
+ .on(table)
31
+ .columns([...columns])
32
+ return (unique ? index.unique() : index).execute()
33
+ },
31
34
  // Postgres drops an index by name alone; SQLite too. `table` documents intent.
32
- dropIndex: (name) => db.exec(`DROP INDEX ${q(name)}`),
33
- dropTable: (table) => db.exec(`DROP TABLE ${q(table)}`),
35
+ dropIndex: (name) => schema.dropIndex(name).execute(),
36
+ dropTable: (table) => schema.dropTable(table).execute(),
34
37
  }
35
38
  }