@crombolo/data 0.36.2 → 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
@@ -36,10 +36,11 @@ export class ContentAppliedRepository {
36
36
  for (let i = 0; i < keys.length; i += 500) {
37
37
  const chunk = keys.slice(i, i + 500).map(normaliseUuid)
38
38
  if (chunk.length === 0) continue
39
- const rows = await this.#db.query<{ node_key: string; state: string }>(
40
- `SELECT node_key, state FROM content_applied WHERE node_key IN (${chunk.map(() => '?').join(', ')})`,
41
- chunk,
42
- )
39
+ const rows = await this.#db.q
40
+ .selectFrom('content_applied')
41
+ .select(['node_key', 'state'])
42
+ .where('node_key', 'in', chunk)
43
+ .execute()
43
44
  for (const row of rows) {
44
45
  const state = parse(row.state)
45
46
  if (state) out.set(normaliseUuid(String(row.node_key)), state)
@@ -51,37 +52,55 @@ export class ContentAppliedRepository {
51
52
  /** Records what a run applied to a node, keeping what it replaced. */
52
53
  async record(key: string, runId: string, state: AppliedState): Promise<void> {
53
54
  const nodeKey = normaliseUuid(key)
54
- const rows = await this.#db.query<{ run_id: string; state: string }>(
55
- 'SELECT run_id, state FROM content_applied WHERE node_key = ?',
56
- [nodeKey],
57
- )
58
- const was = rows[0]
55
+ const was = await this.#db.q
56
+ .selectFrom('content_applied')
57
+ .select(['run_id', 'state'])
58
+ .where('node_key', '=', nodeKey)
59
+ .executeTakeFirst()
59
60
  const now = DbDate.toDb(new Date())
60
61
  if (!was) {
61
- await this.#db.exec(
62
- `INSERT INTO content_applied (node_key, run_id, state, applied_at, previous_run_id, previous_state)
63
- VALUES (?, ?, ?, ?, NULL, NULL)`,
64
- [nodeKey, runId, JSON.stringify(state), now],
65
- )
62
+ await this.#db.q
63
+ .insertInto('content_applied')
64
+ .values({
65
+ node_key: nodeKey,
66
+ run_id: runId,
67
+ state: JSON.stringify(state),
68
+ applied_at: now,
69
+ previous_run_id: null,
70
+ previous_state: null,
71
+ })
72
+ .execute()
66
73
  return
67
74
  }
68
- await this.#db.exec(
69
- `UPDATE content_applied SET run_id = ?, state = ?, applied_at = ?, previous_run_id = ?, previous_state = ?
70
- WHERE node_key = ?`,
71
- [runId, JSON.stringify(state), now, String(was.run_id), String(was.state), nodeKey],
72
- )
75
+ await this.#db.q
76
+ .updateTable('content_applied')
77
+ .set({
78
+ run_id: runId,
79
+ state: JSON.stringify(state),
80
+ applied_at: now,
81
+ previous_run_id: String(was.run_id),
82
+ previous_state: String(was.state),
83
+ })
84
+ .where('node_key', '=', nodeKey)
85
+ .execute()
73
86
  }
74
87
 
75
88
  /** Undoes what a run recorded: the state before it, or no record where it made the first. */
76
89
  async revert(runId: string): Promise<void> {
77
- await this.#db.exec('DELETE FROM content_applied WHERE run_id = ? AND previous_state IS NULL', [
78
- runId,
79
- ])
80
- await this.#db.exec(
81
- `UPDATE content_applied SET run_id = previous_run_id, state = previous_state,
82
- previous_run_id = NULL, previous_state = NULL
83
- WHERE run_id = ?`,
84
- [runId],
85
- )
90
+ await this.#db.q
91
+ .deleteFrom('content_applied')
92
+ .where('run_id', '=', runId)
93
+ .where('previous_state', 'is', null)
94
+ .execute()
95
+ await this.#db.q
96
+ .updateTable('content_applied')
97
+ .set((eb) => ({
98
+ run_id: eb.ref('previous_run_id').$notNull(),
99
+ state: eb.ref('previous_state').$notNull(),
100
+ previous_run_id: null,
101
+ previous_state: null,
102
+ }))
103
+ .where('run_id', '=', runId)
104
+ .execute()
86
105
  }
87
106
  }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { Db } from '../database.ts'
8
8
  import { DbDate } from '../dialect.ts'
9
+ import { sql } from '../query.ts'
9
10
 
10
11
  export type ContentEventState = 'pending' | 'running' | 'dispatched' | 'failed'
11
12
 
@@ -35,8 +36,19 @@ export interface QueueCounts {
35
36
  oldestPending: Date | null
36
37
  }
37
38
 
38
- const COLUMNS =
39
- 'id, kind, entity_type, entity_key, facts, actor, occurred_at, state, attempts, last_error, run_after'
39
+ const COLUMNS = [
40
+ 'id',
41
+ 'kind',
42
+ 'entity_type',
43
+ 'entity_key',
44
+ 'facts',
45
+ 'actor',
46
+ 'occurred_at',
47
+ 'state',
48
+ 'attempts',
49
+ 'last_error',
50
+ 'run_after',
51
+ ] as const
40
52
 
41
53
  const json = (value: unknown): Record<string, unknown> => {
42
54
  try {
@@ -69,9 +81,15 @@ export async function queueCounts(
69
81
  db: Db,
70
82
  table: 'content_event' | 'webhook_delivery' | 'content_notification',
71
83
  ): Promise<QueueCounts> {
72
- const rows = await db.query<{ state: string; n: number; oldest: unknown }>(
73
- `SELECT state, COUNT(*) AS n, MIN(create_date) AS oldest FROM ${table} GROUP BY state`,
74
- )
84
+ const rows = await db.q
85
+ .selectFrom(table)
86
+ .select((eb) => [
87
+ 'state',
88
+ eb.fn.countAll<number>().as('n'),
89
+ eb.fn.min('create_date').as('oldest'),
90
+ ])
91
+ .groupBy('state')
92
+ .execute()
75
93
  const of = (state: string) => rows.find((row) => row.state === state)
76
94
  return {
77
95
  pending: Number(of('pending')?.n ?? 0),
@@ -92,111 +110,140 @@ export class ContentEventRepository {
92
110
  async record(event: NewContentEvent, now = new Date()): Promise<string> {
93
111
  const id = crypto.randomUUID()
94
112
  const at = DbDate.toDb(now)
95
- await this.#db.exec(
96
- `INSERT INTO content_event (${COLUMNS}, create_date, update_date)
97
- VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL, ?, ?, ?)`,
98
- [
113
+ await this.#db.q
114
+ .insertInto('content_event')
115
+ .values({
99
116
  id,
100
- event.kind,
101
- event.entityType,
102
- event.entityKey,
103
- JSON.stringify(event.facts),
104
- JSON.stringify(event.actor),
105
- at,
106
- at,
107
- at,
108
- at,
109
- ],
110
- )
117
+ kind: event.kind,
118
+ entity_type: event.entityType,
119
+ entity_key: event.entityKey,
120
+ facts: JSON.stringify(event.facts),
121
+ actor: JSON.stringify(event.actor),
122
+ occurred_at: at,
123
+ state: 'pending',
124
+ attempts: 0,
125
+ last_error: null,
126
+ run_after: at,
127
+ create_date: at,
128
+ update_date: at,
129
+ })
130
+ .execute()
111
131
  return id
112
132
  }
113
133
 
114
134
  async due(now = new Date(), limit = 50): Promise<string[]> {
115
- const rows = await this.#db.query<{ id: string }>(
116
- `SELECT id FROM content_event WHERE state = 'pending' AND run_after <= ?
117
- ORDER BY occurred_at, create_date LIMIT ?`,
118
- [DbDate.toDb(now), limit],
119
- )
135
+ const rows = await this.#db.q
136
+ .selectFrom('content_event')
137
+ .select('id')
138
+ .where('state', '=', 'pending')
139
+ .where('run_after', '<=', DbDate.toDb(now))
140
+ .orderBy('occurred_at')
141
+ .orderBy('create_date')
142
+ .limit(limit)
143
+ .execute()
120
144
  return rows.map((row) => String(row.id))
121
145
  }
122
146
 
123
147
  /** Takes an event, or finds another node already has. */
124
148
  async claim(id: string): Promise<ContentEvent | undefined> {
125
- const rows = await this.#db.query(
126
- `UPDATE content_event SET state = 'running', attempts = attempts + 1, update_date = ?
127
- WHERE id = ? AND state = 'pending' RETURNING ${COLUMNS}`,
128
- [DbDate.toDb(new Date()), id],
129
- )
149
+ const rows = await this.#db.q
150
+ .updateTable('content_event')
151
+ .set({
152
+ state: 'running',
153
+ attempts: sql<number>`attempts + 1`,
154
+ update_date: DbDate.toDb(new Date()),
155
+ })
156
+ .where('id', '=', id)
157
+ .where('state', '=', 'pending')
158
+ .returning(COLUMNS)
159
+ .execute()
130
160
  return rows[0] ? hydrate(rows[0]) : undefined
131
161
  }
132
162
 
133
163
  async dispatched(id: string): Promise<void> {
134
- await this.#db.exec(
135
- `UPDATE content_event SET state = 'dispatched', last_error = NULL, update_date = ? WHERE id = ?`,
136
- [DbDate.toDb(new Date()), id],
137
- )
164
+ await this.#db.q
165
+ .updateTable('content_event')
166
+ .set({ state: 'dispatched', last_error: null, update_date: DbDate.toDb(new Date()) })
167
+ .where('id', '=', id)
168
+ .execute()
138
169
  }
139
170
 
140
171
  /** `retryAt` puts it back in the queue; without one it has failed until someone retries it. */
141
172
  async fail(id: string, error: string, retryAt?: Date): Promise<void> {
142
- await this.#db.exec(
143
- 'UPDATE content_event SET state = ?, last_error = ?, run_after = ?, update_date = ? WHERE id = ?',
144
- [
145
- retryAt ? 'pending' : 'failed',
146
- error.slice(0, 2000),
147
- DbDate.toDb(retryAt ?? new Date()),
148
- DbDate.toDb(new Date()),
149
- id,
150
- ],
151
- )
173
+ await this.#db.q
174
+ .updateTable('content_event')
175
+ .set({
176
+ state: retryAt ? 'pending' : 'failed',
177
+ last_error: error.slice(0, 2000),
178
+ run_after: DbDate.toDb(retryAt ?? new Date()),
179
+ update_date: DbDate.toDb(new Date()),
180
+ })
181
+ .where('id', '=', id)
182
+ .execute()
152
183
  }
153
184
 
154
185
  /** Claims older than `olderThan` belong to a node that died: they go back in the queue. */
155
186
  async releaseStale(olderThan: Date): Promise<number> {
156
- const rows = await this.#db.query(
157
- `UPDATE content_event SET state = 'pending', update_date = ?
158
- WHERE state = 'running' AND update_date < ? RETURNING id`,
159
- [DbDate.toDb(new Date()), DbDate.toDb(olderThan)],
160
- )
187
+ const rows = await this.#db.q
188
+ .updateTable('content_event')
189
+ .set({ state: 'pending', update_date: DbDate.toDb(new Date()) })
190
+ .where('state', '=', 'running')
191
+ .where('update_date', '<', DbDate.toDb(olderThan))
192
+ .returning('id')
193
+ .execute()
161
194
  return rows.length
162
195
  }
163
196
 
164
197
  /** Puts failed events back, all or one; answers how many. */
165
198
  async retry(id?: string): Promise<number> {
166
199
  const now = DbDate.toDb(new Date())
167
- const rows = await this.#db.query(
168
- `UPDATE content_event SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
169
- WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
170
- id ? [now, now, id] : [now, now],
171
- )
200
+ const rows = await this.#db.q
201
+ .updateTable('content_event')
202
+ .set({ state: 'pending', attempts: 0, run_after: now, update_date: now })
203
+ .where('state', '=', 'failed')
204
+ .$if(Boolean(id), (q) => q.where('id', '=', id as string))
205
+ .returning('id')
206
+ .execute()
172
207
  return rows.length
173
208
  }
174
209
 
175
210
  async prune(before: Date): Promise<number> {
176
- const rows = await this.#db.query(
177
- `DELETE FROM content_event WHERE state = 'dispatched' AND update_date < ? RETURNING id`,
178
- [DbDate.toDb(before)],
179
- )
211
+ const rows = await this.#db.q
212
+ .deleteFrom('content_event')
213
+ .where('state', '=', 'dispatched')
214
+ .where('update_date', '<', DbDate.toDb(before))
215
+ .returning('id')
216
+ .execute()
180
217
  return rows.length
181
218
  }
182
219
 
183
220
  async byId(id: string): Promise<ContentEvent | undefined> {
184
- const rows = await this.#db.query(`SELECT ${COLUMNS} FROM content_event WHERE id = ?`, [id])
185
- return rows[0] ? hydrate(rows[0]) : undefined
221
+ const row = await this.#db.q
222
+ .selectFrom('content_event')
223
+ .select(COLUMNS)
224
+ .where('id', '=', id)
225
+ .executeTakeFirst()
226
+ return row ? hydrate(row) : undefined
186
227
  }
187
228
 
188
229
  async failed(limit = 100): Promise<ContentEvent[]> {
189
- const rows = await this.#db.query(
190
- `SELECT ${COLUMNS} FROM content_event WHERE state = 'failed' ORDER BY occurred_at DESC LIMIT ?`,
191
- [limit],
192
- )
230
+ const rows = await this.#db.q
231
+ .selectFrom('content_event')
232
+ .select(COLUMNS)
233
+ .where('state', '=', 'failed')
234
+ .orderBy('occurred_at', 'desc')
235
+ .limit(limit)
236
+ .execute()
193
237
  return rows.map(hydrate)
194
238
  }
195
239
 
196
240
  async all(): Promise<ContentEvent[]> {
197
- const rows = await this.#db.query(
198
- `SELECT ${COLUMNS} FROM content_event ORDER BY occurred_at, create_date`,
199
- )
241
+ const rows = await this.#db.q
242
+ .selectFrom('content_event')
243
+ .select(COLUMNS)
244
+ .orderBy('occurred_at')
245
+ .orderBy('create_date')
246
+ .execute()
200
247
  return rows.map(hydrate)
201
248
  }
202
249
  }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { Db } from '../database.ts'
8
8
  import { DbDate } from '../dialect.ts'
9
+ import { sql } from '../query.ts'
9
10
 
10
11
  export type ContentNotificationState = 'pending' | 'running' | 'done' | 'failed' | 'skipped'
11
12
 
@@ -39,8 +40,21 @@ export interface NewContentNotification {
39
40
  eventId?: string
40
41
  }
41
42
 
42
- const COLUMNS = `id, recipient_user_key, action_id, node_key, node_name, actor_user_key, actor_name,
43
- detail, occurred_at, state, attempts, last_error, run_after`
43
+ const COLUMNS = [
44
+ 'id',
45
+ 'recipient_user_key',
46
+ 'action_id',
47
+ 'node_key',
48
+ 'node_name',
49
+ 'actor_user_key',
50
+ 'actor_name',
51
+ 'detail',
52
+ 'occurred_at',
53
+ 'state',
54
+ 'attempts',
55
+ 'last_error',
56
+ 'run_after',
57
+ ] as const
44
58
 
45
59
  function hydrate(row: Record<string, unknown>): ContentNotification {
46
60
  const text = (value: unknown) => (value === null || value === undefined ? null : String(value))
@@ -73,51 +87,55 @@ export class ContentNotificationRepository {
73
87
  const now = DbDate.toDb(new Date())
74
88
  await this.#db.transaction(async (tx) => {
75
89
  for (const row of rows)
76
- await tx.exec(
77
- `INSERT INTO content_notification (id, recipient_user_key, action_id, node_key, node_name,
78
- actor_user_key, actor_name, detail, occurred_at, state, attempts, last_error, run_after,
79
- create_date, update_date, event_id)
80
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL, ?, ?, ?, ?)
81
- ON CONFLICT DO NOTHING`,
82
- [
83
- crypto.randomUUID(),
84
- row.recipientUserKey,
85
- row.actionId,
86
- row.nodeKey,
87
- row.nodeName,
88
- row.actorUserKey,
89
- row.actorName,
90
- row.detail,
91
- DbDate.toDb(row.occurredAt),
92
- DbDate.toDb(row.runAfter),
93
- now,
94
- now,
95
- row.eventId ?? null,
96
- ],
97
- )
90
+ await tx.q
91
+ .insertInto('content_notification')
92
+ .values({
93
+ id: crypto.randomUUID(),
94
+ recipient_user_key: row.recipientUserKey,
95
+ action_id: row.actionId,
96
+ node_key: row.nodeKey,
97
+ node_name: row.nodeName,
98
+ actor_user_key: row.actorUserKey,
99
+ actor_name: row.actorName,
100
+ detail: row.detail,
101
+ occurred_at: DbDate.toDb(row.occurredAt),
102
+ state: 'pending',
103
+ attempts: 0,
104
+ last_error: null,
105
+ run_after: DbDate.toDb(row.runAfter),
106
+ create_date: now,
107
+ update_date: now,
108
+ event_id: row.eventId ?? null,
109
+ })
110
+ .onConflict((oc) => oc.doNothing())
111
+ .execute()
98
112
  })
99
113
  }
100
114
 
101
115
  /** The people with something due to them: each one is a single e-mail. */
102
116
  async dueRecipients(now = new Date(), limit = 25): Promise<string[]> {
103
- const rows = await this.#db.query<{ recipient_user_key: string }>(
104
- `SELECT recipient_user_key FROM content_notification
105
- WHERE state = 'pending' AND run_after <= ?
106
- GROUP BY recipient_user_key ORDER BY MIN(run_after) LIMIT ?`,
107
- [DbDate.toDb(now), limit],
108
- )
117
+ const rows = await this.#db.q
118
+ .selectFrom('content_notification')
119
+ .select('recipient_user_key')
120
+ .where('state', '=', 'pending')
121
+ .where('run_after', '<=', DbDate.toDb(now))
122
+ .groupBy('recipient_user_key')
123
+ .orderBy((eb) => eb.fn.min('run_after'))
124
+ .limit(limit)
125
+ .execute()
109
126
  return rows.map((row) => String(row.recipient_user_key))
110
127
  }
111
128
 
112
129
  /** Takes everything due to one person, or nothing when another node got there first. */
113
130
  async claimFor(recipientUserKey: string, now = new Date()): Promise<ContentNotification[]> {
114
- const rows = await this.#db.query(
115
- `UPDATE content_notification
116
- SET state = 'running', attempts = attempts + 1, update_date = ?
117
- WHERE recipient_user_key = ? AND state = 'pending' AND run_after <= ?
118
- RETURNING ${COLUMNS}`,
119
- [DbDate.toDb(now), recipientUserKey, DbDate.toDb(now)],
120
- )
131
+ const rows = await this.#db.q
132
+ .updateTable('content_notification')
133
+ .set({ state: 'running', attempts: sql<number>`attempts + 1`, update_date: DbDate.toDb(now) })
134
+ .where('recipient_user_key', '=', recipientUserKey)
135
+ .where('state', '=', 'pending')
136
+ .where('run_after', '<=', DbDate.toDb(now))
137
+ .returning(COLUMNS)
138
+ .execute()
121
139
  return rows.map(hydrate).sort((a, b) => a.occurredAt.getTime() - b.occurredAt.getTime())
122
140
  }
123
141
 
@@ -128,18 +146,16 @@ export class ContentNotificationRepository {
128
146
  runAfter?: Date,
129
147
  ) {
130
148
  if (ids.length === 0) return
131
- const marks = ids.map(() => '?').join(', ')
132
- await this.#db.exec(
133
- `UPDATE content_notification SET state = ?, last_error = ?, update_date = ?${runAfter ? ', run_after = ?' : ''}
134
- WHERE id IN (${marks})`,
135
- [
149
+ await this.#db.q
150
+ .updateTable('content_notification')
151
+ .set({
136
152
  state,
137
- error?.slice(0, 2000) ?? null,
138
- DbDate.toDb(new Date()),
139
- ...(runAfter ? [DbDate.toDb(runAfter)] : []),
140
- ...ids,
141
- ],
142
- )
153
+ last_error: error?.slice(0, 2000) ?? null,
154
+ update_date: DbDate.toDb(new Date()),
155
+ ...(runAfter ? { run_after: DbDate.toDb(runAfter) } : {}),
156
+ })
157
+ .where('id', 'in', ids)
158
+ .execute()
143
159
  }
144
160
 
145
161
  succeed(ids: readonly string[]): Promise<void> {
@@ -158,54 +174,66 @@ export class ContentNotificationRepository {
158
174
 
159
175
  /** Rows a node took and never finished — it died — go back in the queue. */
160
176
  async releaseStale(olderThan: Date): Promise<number> {
161
- const rows = await this.#db.query(
162
- `UPDATE content_notification SET state = 'pending', update_date = ?
163
- WHERE state = 'running' AND update_date < ? RETURNING id`,
164
- [DbDate.toDb(new Date()), DbDate.toDb(olderThan)],
165
- )
177
+ const rows = await this.#db.q
178
+ .updateTable('content_notification')
179
+ .set({ state: 'pending', update_date: DbDate.toDb(new Date()) })
180
+ .where('state', '=', 'running')
181
+ .where('update_date', '<', DbDate.toDb(olderThan))
182
+ .returning('id')
183
+ .execute()
166
184
  return rows.length
167
185
  }
168
186
 
169
187
  /** Puts failed notifications back, all or one; answers how many. */
170
188
  async retry(id?: string): Promise<number> {
171
189
  const now = DbDate.toDb(new Date())
172
- const rows = await this.#db.query(
173
- `UPDATE content_notification SET state = 'pending', attempts = 0, run_after = ?, update_date = ?
174
- WHERE state = 'failed'${id ? ' AND id = ?' : ''} RETURNING id`,
175
- id ? [now, now, id] : [now, now],
176
- )
190
+ const rows = await this.#db.q
191
+ .updateTable('content_notification')
192
+ .set({ state: 'pending', attempts: 0, run_after: now, update_date: now })
193
+ .where('state', '=', 'failed')
194
+ .$if(Boolean(id), (q) => q.where('id', '=', id as string))
195
+ .returning('id')
196
+ .execute()
177
197
  return rows.length
178
198
  }
179
199
 
180
200
  async failed(limit = 100): Promise<ContentNotification[]> {
181
- const rows = await this.#db.query(
182
- `SELECT ${COLUMNS} FROM content_notification WHERE state = 'failed'
183
- ORDER BY occurred_at DESC LIMIT ?`,
184
- [limit],
185
- )
201
+ const rows = await this.#db.q
202
+ .selectFrom('content_notification')
203
+ .select(COLUMNS)
204
+ .where('state', '=', 'failed')
205
+ .orderBy('occurred_at', 'desc')
206
+ .limit(limit)
207
+ .execute()
186
208
  return rows.map(hydrate)
187
209
  }
188
210
 
189
211
  async prune(before: Date): Promise<number> {
190
- const rows = await this.#db.query(
191
- `DELETE FROM content_notification WHERE state IN ('done', 'skipped') AND update_date < ? RETURNING id`,
192
- [DbDate.toDb(before)],
193
- )
212
+ const rows = await this.#db.q
213
+ .deleteFrom('content_notification')
214
+ .where('state', 'in', ['done', 'skipped'])
215
+ .where('update_date', '<', DbDate.toDb(before))
216
+ .returning('id')
217
+ .execute()
194
218
  return rows.length
195
219
  }
196
220
 
197
221
  async forRecipient(recipientUserKey: string): Promise<ContentNotification[]> {
198
- const rows = await this.#db.query(
199
- `SELECT ${COLUMNS} FROM content_notification WHERE recipient_user_key = ? ORDER BY occurred_at`,
200
- [recipientUserKey],
201
- )
222
+ const rows = await this.#db.q
223
+ .selectFrom('content_notification')
224
+ .select(COLUMNS)
225
+ .where('recipient_user_key', '=', recipientUserKey)
226
+ .orderBy('occurred_at')
227
+ .execute()
202
228
  return rows.map(hydrate)
203
229
  }
204
230
 
205
231
  async all(): Promise<ContentNotification[]> {
206
- const rows = await this.#db.query(
207
- `SELECT ${COLUMNS} FROM content_notification ORDER BY occurred_at`,
208
- )
232
+ const rows = await this.#db.q
233
+ .selectFrom('content_notification')
234
+ .select(COLUMNS)
235
+ .orderBy('occurred_at')
236
+ .execute()
209
237
  return rows.map(hydrate)
210
238
  }
211
239
  }