@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.37.0",
3
+ "version": "0.39.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,6 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.37.0"
31
+ "@crombolo/core": "0.39.0",
32
+ "kysely": "0.29.6"
32
33
  }
33
34
  }
package/src/audit.ts CHANGED
@@ -3,10 +3,13 @@
3
3
  * added, read and aged out; nothing edits one. docs/audit-log.md.
4
4
  */
5
5
  import { normaliseUuid } from '@crombolo/core'
6
+ import type { Expression, ExpressionBuilder, SqlBool } from 'kysely'
6
7
  import type { Db } from './database.ts'
7
8
  import { DbDate } from './dialect.ts'
9
+ import { sql } from './query.ts'
8
10
  import { STATE_AUDIT_LOG } from './schema/audit-log.ts'
9
11
  import { escapeLike } from './search-text.ts'
12
+ import type { CoreTables } from './tables.gen.ts'
10
13
 
11
14
  export type AuditCategory =
12
15
  | 'content'
@@ -32,7 +35,7 @@ export const AUDIT_CATEGORIES: readonly AuditCategory[] = [
32
35
  ]
33
36
 
34
37
  /** Where an entry came from: a request (with its address), the command line, or a background job. */
35
- export type AuditSource = 'request' | 'cli' | 'job'
38
+ export type AuditSource = 'request' | 'cli' | 'job' | 'boot'
36
39
 
37
40
  export interface AuditEntryInput {
38
41
  category: AuditCategory
@@ -138,6 +141,11 @@ const LIMITS = {
138
141
  detail: 4000,
139
142
  } as const
140
143
 
144
+ type Condition = (eb: ExpressionBuilder<CoreTables, 'audit_entry'>) => Expression<SqlBool>
145
+
146
+ const likeLower = (column: string, pattern: string) =>
147
+ sql<SqlBool>`lower(${sql.ref(column)}) like ${pattern} escape '\\'`
148
+
141
149
  function clip(value: string | null | undefined, limit: number): string | null {
142
150
  if (value === null || value === undefined || value === '') return null
143
151
  return value.length > limit ? value.slice(0, limit) : value
@@ -181,106 +189,114 @@ export class AuditLog {
181
189
  entry.entityKey && UUID.test(entry.entityKey)
182
190
  ? normaliseUuid(entry.entityKey)
183
191
  : entry.entityKey
184
- await this.#db.exec(
185
- `INSERT INTO audit_entry (occurred_at, category, action, user_key, user_name, entity_type,
186
- entity_key, entity_name, source, ip_address, forwarded_for, detail)
187
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
188
- [
189
- DbDate.toDb(entry.occurredAt ?? new Date()),
190
- entry.category,
191
- clip(entry.action, LIMITS.action),
192
- userKey,
193
- clip(entry.userName, LIMITS.userName),
194
- clip(entry.entityType, LIMITS.entityType),
195
- clip(entityKey, LIMITS.entityKey),
196
- clip(entry.entityName, LIMITS.entityName),
197
- entry.source,
198
- clip(entry.ipAddress, LIMITS.ipAddress),
199
- clip(entry.forwardedFor, LIMITS.forwardedFor),
200
- clip(entry.detail, LIMITS.detail),
201
- ],
202
- )
192
+ await this.#db.q
193
+ .insertInto('audit_entry')
194
+ .values({
195
+ occurred_at: DbDate.toDb(entry.occurredAt ?? new Date()),
196
+ category: entry.category,
197
+ action: clip(entry.action, LIMITS.action) as string,
198
+ user_key: userKey,
199
+ user_name: clip(entry.userName, LIMITS.userName),
200
+ entity_type: clip(entry.entityType, LIMITS.entityType),
201
+ entity_key: clip(entityKey, LIMITS.entityKey),
202
+ entity_name: clip(entry.entityName, LIMITS.entityName),
203
+ source: entry.source,
204
+ ip_address: clip(entry.ipAddress, LIMITS.ipAddress),
205
+ forwarded_for: clip(entry.forwardedFor, LIMITS.forwardedFor),
206
+ detail: clip(entry.detail, LIMITS.detail),
207
+ })
208
+ .execute()
203
209
  }
204
210
  }
205
211
 
206
212
  /** The conditions a filter comes to, or undefined when it can match nothing. */
207
- async #where(filter: AuditFilter): Promise<{ where: string[]; params: unknown[] } | undefined> {
208
- const where: string[] = []
209
- const params: unknown[] = []
213
+ async #where(filter: AuditFilter): Promise<Condition[] | undefined> {
214
+ const where: Condition[] = []
210
215
  if (filter.userKey !== undefined) {
211
216
  if (!UUID.test(filter.userKey)) return undefined
212
- where.push('user_key = ?')
213
- params.push(normaliseUuid(filter.userKey))
217
+ const userKey = normaliseUuid(filter.userKey)
218
+ where.push((eb) => eb('user_key', '=', userKey))
214
219
  }
215
220
  if (filter.entityKey !== undefined) {
216
- where.push('entity_key = ?')
217
- params.push(UUID.test(filter.entityKey) ? normaliseUuid(filter.entityKey) : filter.entityKey)
218
- }
219
- if (filter.category !== undefined) {
220
- where.push('category = ?')
221
- params.push(filter.category)
222
- }
223
- if (filter.action !== undefined) {
224
- where.push('action = ?')
225
- params.push(filter.action)
226
- }
227
- if (filter.since !== undefined) {
228
- where.push('occurred_at >= ?')
229
- params.push(DbDate.toDb(filter.since))
230
- }
231
- if (filter.until !== undefined) {
232
- where.push('occurred_at < ?')
233
- params.push(DbDate.toDb(filter.until))
221
+ const entityKey = UUID.test(filter.entityKey)
222
+ ? normaliseUuid(filter.entityKey)
223
+ : filter.entityKey
224
+ where.push((eb) => eb('entity_key', '=', entityKey))
234
225
  }
226
+ const { category, action, since, until } = filter
227
+ if (category !== undefined) where.push((eb) => eb('category', '=', category))
228
+ if (action !== undefined) where.push((eb) => eb('action', '=', action))
229
+ if (since !== undefined) where.push((eb) => eb('occurred_at', '>=', DbDate.toDb(since)))
230
+ if (until !== undefined) where.push((eb) => eb('occurred_at', '<', DbDate.toDb(until)))
235
231
  const needle = filter.text?.trim().toLowerCase()
236
232
  if (needle) {
237
233
  const like = `%${escapeLike(needle)}%`
238
- where.push(
239
- `(LOWER(entity_name) LIKE ? ESCAPE '\\' OR LOWER(entity_key) LIKE ? ESCAPE '\\' OR LOWER(user_name) LIKE ? ESCAPE '\\')`,
234
+ where.push((eb) =>
235
+ eb.or([
236
+ likeLower('entity_name', like),
237
+ likeLower('entity_key', like),
238
+ likeLower('user_name', like),
239
+ ]),
240
240
  )
241
- params.push(like, like, like)
242
241
  }
243
242
  if (filter.user !== undefined) {
244
243
  const who = filter.user.trim()
245
- const accounts = await this.#db.query<{ key: string }>(
246
- UUID.test(who)
247
- ? 'SELECT key FROM user_account WHERE key = ?'
248
- : 'SELECT key FROM user_account WHERE LOWER(email) = LOWER(?) OR LOWER(login) = LOWER(?) OR LOWER(user_name) = LOWER(?)',
249
- UUID.test(who) ? [normaliseUuid(who)] : [who, who, who],
250
- )
251
- const account = accounts[0]
244
+ const account = await this.#db.q
245
+ .selectFrom('user_account')
246
+ .select('key')
247
+ .$if(UUID.test(who), (q) => q.where('key', '=', normaliseUuid(who)))
248
+ .$if(!UUID.test(who), (q) =>
249
+ q.where((eb) =>
250
+ eb.or([
251
+ eb(eb.fn('lower', ['email']), '=', eb.fn('lower', [eb.val(who)])),
252
+ eb(eb.fn('lower', ['login']), '=', eb.fn('lower', [eb.val(who)])),
253
+ eb(eb.fn('lower', ['user_name']), '=', eb.fn('lower', [eb.val(who)])),
254
+ ]),
255
+ ),
256
+ )
257
+ .executeTakeFirst()
252
258
  if (account) {
253
- where.push('user_key = ?')
254
- params.push(normaliseUuid(String(account.key)))
259
+ const userKey = normaliseUuid(String(account.key))
260
+ where.push((eb) => eb('user_key', '=', userKey))
255
261
  } else if (UUID.test(who)) {
256
- where.push('user_key = ?')
257
- params.push(normaliseUuid(who))
262
+ const userKey = normaliseUuid(who)
263
+ where.push((eb) => eb('user_key', '=', userKey))
258
264
  } else {
259
- where.push('user_key IS NULL AND LOWER(user_name) = LOWER(?)')
260
- params.push(who)
265
+ where.push((eb) =>
266
+ eb.and([
267
+ eb('user_key', 'is', null),
268
+ eb(eb.fn('lower', ['user_name']), '=', eb.fn('lower', [eb.val(who)])),
269
+ ]),
270
+ )
261
271
  }
262
272
  }
263
- return { where, params }
273
+ return where
274
+ }
275
+
276
+ #entries(where: Condition[]) {
277
+ let query = this.#db.q.selectFrom('audit_entry')
278
+ for (const condition of where) query = query.where(condition)
279
+ return query
264
280
  }
265
281
 
266
282
  async query(
267
283
  filter: AuditFilter = {},
268
284
  page: { skip: number; take: number } = { skip: 0, take: 100 },
269
285
  ): Promise<{ total: number; items: AuditEntry[] }> {
270
- const conditions = await this.#where(filter)
271
- if (!conditions) return { total: 0, items: [] }
272
- const { where, params } = conditions
273
- const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''
274
- const counted = await this.#db.query<{ total: number }>(
275
- `SELECT COUNT(*) AS total FROM audit_entry ${clause}`,
276
- params,
277
- )
278
- const order = filter.ascending ? 'ASC' : 'DESC'
279
- const rows = await this.#db.query(
280
- `SELECT * FROM audit_entry ${clause} ORDER BY occurred_at ${order}, id ${order} LIMIT ? OFFSET ?`,
281
- [...params, page.take, page.skip],
282
- )
283
- return { total: Number(counted[0]?.total ?? 0), items: rows.map(toEntry) }
286
+ const where = await this.#where(filter)
287
+ if (!where) return { total: 0, items: [] }
288
+ const counted = await this.#entries(where)
289
+ .select((eb) => eb.fn.countAll().as('total'))
290
+ .executeTakeFirst()
291
+ const order = filter.ascending ? 'asc' : 'desc'
292
+ const rows = await this.#entries(where)
293
+ .selectAll()
294
+ .orderBy('occurred_at', order)
295
+ .orderBy('id', order)
296
+ .limit(page.take)
297
+ .offset(page.skip)
298
+ .execute()
299
+ return { total: Number(counted?.total ?? 0), items: rows.map(toEntry) }
284
300
  }
285
301
 
286
302
  /**
@@ -290,24 +306,17 @@ export class AuditLog {
290
306
  */
291
307
  async page(filter: AuditFilter, cursor: AuditCursor): Promise<AuditPage> {
292
308
  const ascending = cursor.after !== undefined
293
- const conditions = await this.#where(filter)
294
- if (!conditions)
309
+ const where = await this.#where(filter)
310
+ if (!where)
295
311
  return { items: [], next: ascending ? (cursor.after ?? null) : null, truncated: false }
296
- const { where, params } = conditions
297
- if (cursor.after !== undefined) {
298
- where.push('id > ?')
299
- params.push(cursor.after)
300
- }
301
- if (cursor.before !== undefined) {
302
- where.push('id < ?')
303
- params.push(cursor.before)
304
- }
305
- const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''
306
- const order = ascending ? 'ASC' : 'DESC'
307
- const rows = await this.#db.query(
308
- `SELECT * FROM audit_entry ${clause} ORDER BY id ${order} LIMIT ?`,
309
- [...params, cursor.limit],
310
- )
312
+ const { after, before } = cursor
313
+ if (after !== undefined) where.push((eb) => eb('id', '>', after))
314
+ if (before !== undefined) where.push((eb) => eb('id', '<', before))
315
+ const rows = await this.#entries(where)
316
+ .selectAll()
317
+ .orderBy('id', ascending ? 'asc' : 'desc')
318
+ .limit(cursor.limit)
319
+ .execute()
311
320
  const items = rows.map(toEntry)
312
321
  const last = items.at(-1)?.id
313
322
  const next = ascending
@@ -321,13 +330,18 @@ export class AuditLog {
321
330
  /** Whether the entry a cursor names has gone while older ones are kept no longer. */
322
331
  async #pruned(after: number): Promise<boolean> {
323
332
  if (after <= 0) return false
324
- const rows = await this.#db.query<{ oldest: number | null; there: number }>(
325
- 'SELECT MIN(id) AS oldest, SUM(CASE WHEN id = ? THEN 1 ELSE 0 END) AS there FROM audit_entry',
326
- [after],
327
- )
328
- const oldest = rows[0]?.oldest
333
+ const row = await this.#db.q
334
+ .selectFrom('audit_entry')
335
+ .select((eb) => [
336
+ eb.fn.min('id').as('oldest'),
337
+ eb.fn
338
+ .sum<number | string | null>(eb.case().when('id', '=', after).then(1).else(0).end())
339
+ .as('there'),
340
+ ])
341
+ .executeTakeFirst()
342
+ const oldest = row?.oldest
329
343
  return (
330
- Number(rows[0]?.there ?? 0) === 0 &&
344
+ Number(row?.there ?? 0) === 0 &&
331
345
  oldest !== null &&
332
346
  oldest !== undefined &&
333
347
  Number(oldest) > after
@@ -336,12 +350,21 @@ export class AuditLog {
336
350
 
337
351
  /** Everyone the log names, by the name they had most recently. */
338
352
  async users(): Promise<Array<{ key: string; name: string }>> {
339
- const rows = await this.#db.query<{ user_key: string; user_name: string | null }>(
340
- `SELECT e.user_key, e.user_name FROM audit_entry e
341
- JOIN (SELECT user_key, MAX(id) AS id FROM audit_entry WHERE user_key IS NOT NULL GROUP BY user_key) latest
342
- ON latest.id = e.id
343
- ORDER BY e.user_name`,
344
- )
353
+ const rows = await this.#db.q
354
+ .selectFrom('audit_entry as e')
355
+ .innerJoin(
356
+ (eb) =>
357
+ eb
358
+ .selectFrom('audit_entry')
359
+ .select((eb) => ['user_key', eb.fn.max('id').as('id')])
360
+ .where('user_key', 'is not', null)
361
+ .groupBy('user_key')
362
+ .as('latest'),
363
+ (join) => join.onRef('latest.id', '=', 'e.id'),
364
+ )
365
+ .select(['e.user_key', 'e.user_name'])
366
+ .orderBy('e.user_name')
367
+ .execute()
345
368
  return rows.map((row) => ({
346
369
  key: normaliseUuid(String(row.user_key)),
347
370
  name: row.user_name ? String(row.user_name) : '',
@@ -350,23 +373,28 @@ export class AuditLog {
350
373
 
351
374
  /** Deletes entries older than `before`, and returns how many went. */
352
375
  async prune(before: Date): Promise<number> {
353
- const counted = await this.#db.query<{ total: number }>(
354
- 'SELECT COUNT(*) AS total FROM audit_entry WHERE occurred_at < ?',
355
- [DbDate.toDb(before)],
356
- )
357
- const total = Number(counted[0]?.total ?? 0)
376
+ const counted = await this.#db.q
377
+ .selectFrom('audit_entry')
378
+ .select((eb) => eb.fn.countAll().as('total'))
379
+ .where('occurred_at', '<', DbDate.toDb(before))
380
+ .executeTakeFirst()
381
+ const total = Number(counted?.total ?? 0)
358
382
  if (total > 0)
359
- await this.#db.exec('DELETE FROM audit_entry WHERE occurred_at < ?', [DbDate.toDb(before)])
383
+ await this.#db.q
384
+ .deleteFrom('audit_entry')
385
+ .where('occurred_at', '<', DbDate.toDb(before))
386
+ .execute()
360
387
  return total
361
388
  }
362
389
 
363
390
  /** When this database began keeping the log; history before it is in the content versions. */
364
391
  async startedAt(): Promise<Date | undefined> {
365
- const rows = await this.#db.query<{ applied_at: unknown }>(
366
- 'SELECT MIN(applied_at) AS applied_at FROM migration_history WHERE to_state = ?',
367
- [STATE_AUDIT_LOG],
368
- )
369
- return DbDate.fromDb(rows[0]?.applied_at)
392
+ const row = await this.#db.q
393
+ .selectFrom('migration_history')
394
+ .select((eb) => eb.fn.min('applied_at').as('applied_at'))
395
+ .where('to_state', '=', STATE_AUDIT_LOG)
396
+ .executeTakeFirst()
397
+ return DbDate.fromDb(row?.applied_at)
370
398
  }
371
399
 
372
400
  /**
@@ -380,32 +408,34 @@ export class AuditLog {
380
408
  entityName: entityName === null || entityName === undefined ? null : String(entityName),
381
409
  })
382
410
  if (entityType.endsWith('Version') && /^\d+$/.test(key)) {
383
- const rows = await this.#db.query<{ unique_id: string; text: string | null }>(
384
- 'SELECT n.unique_id, n.text FROM content_version cv JOIN node n ON n.id = cv.node_id WHERE cv.id = ?',
385
- [Number(key)],
386
- )
387
- const row = rows[0]
411
+ const row = await this.#db.q
412
+ .selectFrom('content_version as cv')
413
+ .innerJoin('node as n', 'n.id', 'cv.node_id')
414
+ .select(['n.unique_id', 'n.text'])
415
+ .where('cv.id', '=', Number(key))
416
+ .executeTakeFirst()
388
417
  const owner = entityType.slice(0, -'Version'.length)
389
418
  return row ? named(row.text, owner, normaliseUuid(String(row.unique_id))) : named(null)
390
419
  }
391
420
  if (entityType === 'Language') {
392
- const rows = await this.#db.query<{ culture_name: string }>(
393
- 'SELECT culture_name FROM language WHERE iso_code = ?',
394
- [key],
395
- )
396
- return named(rows[0]?.culture_name ?? null)
421
+ const row = await this.#db.q
422
+ .selectFrom('language')
423
+ .select('culture_name')
424
+ .where('iso_code', '=', key)
425
+ .executeTakeFirst()
426
+ return named(row?.culture_name ?? null)
397
427
  }
398
428
  if (!UUID.test(key)) return named(null)
399
429
  const uuid = normaliseUuid(key)
400
- const sql =
401
- entityType === 'User'
402
- ? 'SELECT user_name AS name FROM user_account WHERE key = ?'
403
- : entityType === 'UserGroup'
404
- ? 'SELECT name FROM user_group WHERE key = ?'
405
- : entityType === 'DictionaryItem'
406
- ? 'SELECT item_key AS name FROM dictionary_item WHERE key = ?'
407
- : 'SELECT text AS name FROM node WHERE unique_id = ?'
408
- const rows = await this.#db.query<{ name: string | null }>(sql, [uuid])
409
- return named(rows[0]?.name ?? null, entityType, uuid)
430
+ const q = this.#db.q
431
+ const row = await (entityType === 'User'
432
+ ? q.selectFrom('user_account').select('user_name as name').where('key', '=', uuid)
433
+ : entityType === 'UserGroup'
434
+ ? q.selectFrom('user_group').select('name').where('key', '=', uuid)
435
+ : entityType === 'DictionaryItem'
436
+ ? q.selectFrom('dictionary_item').select('item_key as name').where('key', '=', uuid)
437
+ : q.selectFrom('node').select('text as name').where('unique_id', '=', uuid)
438
+ ).executeTakeFirst()
439
+ return named(row?.name ?? null, entityType, uuid)
410
440
  }
411
441
  }
@@ -91,39 +91,48 @@ export async function writeReport(
91
91
  seen.add(key)
92
92
  const existing = openByIdentity.get(key)
93
93
  if (existing) {
94
- await db.exec(
95
- 'UPDATE change_report SET run_id = ?, kind = ?, subject_name = ?, message = ?, link = ?, last_seen = ? WHERE id = ?',
96
- [runId, finding.kind, finding.subjectName, finding.message, finding.link, now, existing.id],
97
- )
94
+ await db.q
95
+ .updateTable('change_report')
96
+ .set({
97
+ run_id: runId,
98
+ kind: finding.kind,
99
+ subject_name: finding.subjectName,
100
+ message: finding.message,
101
+ link: finding.link,
102
+ last_seen: now,
103
+ })
104
+ .where('id', '=', existing.id)
105
+ .execute()
98
106
  } else {
99
- await db.exec(
100
- `INSERT INTO change_report (run_id, source, scope, kind, code, subject_type, subject_key, subject_name, property_alias, culture, message, link, status, first_seen, last_seen)
101
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)`,
102
- [
103
- runId,
107
+ await db.q
108
+ .insertInto('change_report')
109
+ .values({
110
+ run_id: runId,
104
111
  source,
105
112
  scope,
106
- finding.kind,
107
- finding.code,
108
- finding.subjectType,
109
- finding.subjectKey,
110
- finding.subjectName,
111
- finding.propertyAlias,
112
- finding.culture,
113
- finding.message,
114
- finding.link,
115
- now,
116
- now,
117
- ],
118
- )
113
+ kind: finding.kind,
114
+ code: finding.code,
115
+ subject_type: finding.subjectType,
116
+ subject_key: finding.subjectKey,
117
+ subject_name: finding.subjectName,
118
+ property_alias: finding.propertyAlias,
119
+ culture: finding.culture,
120
+ message: finding.message,
121
+ link: finding.link,
122
+ status: 'open',
123
+ first_seen: now,
124
+ last_seen: now,
125
+ })
126
+ .execute()
119
127
  }
120
128
  }
121
129
  for (const [key, existing] of openByIdentity) {
122
130
  if (seen.has(key)) continue
123
- await db.exec("UPDATE change_report SET status = 'resolved', resolved_at = ? WHERE id = ?", [
124
- now,
125
- existing.id,
126
- ])
131
+ await db.q
132
+ .updateTable('change_report')
133
+ .set({ status: 'resolved', resolved_at: now })
134
+ .where('id', '=', existing.id)
135
+ .execute()
127
136
  }
128
137
  return runId
129
138
  }
@@ -132,24 +141,38 @@ export async function readReport(
132
141
  db: Db,
133
142
  options: ReadReportOptions = {},
134
143
  ): Promise<ReportedFinding[]> {
135
- const where: string[] = []
136
- const params: unknown[] = []
137
- if (!options.includeResolved) where.push("status = 'open'")
138
- if (options.source !== undefined) {
139
- where.push('source = ?')
140
- params.push(options.source)
141
- }
144
+ const { source } = options
142
145
  // `scope` is meaningful when null, so only an explicit key filters.
143
- if ('scope' in options) {
144
- const scope = options.scope ?? null
145
- where.push(scope === null ? 'scope IS NULL' : 'scope = ?')
146
- if (scope !== null) params.push(scope)
147
- }
148
- const rows = await db.query(
149
- `SELECT id, run_id, source, scope, kind, code, subject_type, subject_key, subject_name, property_alias, culture, message, link, status, first_seen, last_seen, resolved_at
150
- FROM change_report ${where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY id`,
151
- params,
152
- )
146
+ const scoped = 'scope' in options
147
+ const scope = options.scope ?? null
148
+ const rows = await db.q
149
+ .selectFrom('change_report')
150
+ .select([
151
+ 'id',
152
+ 'run_id',
153
+ 'source',
154
+ 'scope',
155
+ 'kind',
156
+ 'code',
157
+ 'subject_type',
158
+ 'subject_key',
159
+ 'subject_name',
160
+ 'property_alias',
161
+ 'culture',
162
+ 'message',
163
+ 'link',
164
+ 'status',
165
+ 'first_seen',
166
+ 'last_seen',
167
+ 'resolved_at',
168
+ ])
169
+ .$if(!options.includeResolved, (q) => q.where('status', '=', 'open'))
170
+ .$if(source !== undefined, (q) => q.where('source', '=', source as FindingSource))
171
+ .$if(scoped, (q) =>
172
+ scope === null ? q.where('scope', 'is', null) : q.where('scope', '=', scope),
173
+ )
174
+ .orderBy('id')
175
+ .execute()
153
176
  return rows.map((row) => ({
154
177
  id: Number(row.id),
155
178
  runId: String(row.run_id),