@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
@@ -4,6 +4,8 @@
4
4
  */
5
5
  import type { Db } from '../database.ts'
6
6
  import { DbDate } from '../dialect.ts'
7
+ import type { Updateable } from '../query.ts'
8
+ import type { CoreTables } from '../tables.gen.ts'
7
9
 
8
10
  export type RemoteJobKind = 'pull' | 'push'
9
11
  export type RemoteJobState =
@@ -90,7 +92,7 @@ export type RemoteJobUpdate = Partial<
90
92
  >
91
93
  >
92
94
 
93
- const COLUMNS: Record<keyof RemoteJobUpdate, string> = {
95
+ const COLUMNS: Record<keyof RemoteJobUpdate, keyof CoreTables['remote_job']> = {
94
96
  state: 'state',
95
97
  stage: 'stage',
96
98
  progress: 'progress',
@@ -123,55 +125,61 @@ export class RemoteJobRepository {
123
125
  expiresAt: Date
124
126
  }): Promise<void> {
125
127
  const now = DbDate.toDb(new Date())
126
- await this.#db.exec(
127
- `INSERT INTO remote_job
128
- (id, kind, environment, requested_by, requested_by_name, options, state, heartbeat_at, expires_at, create_date)
129
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
130
- [
131
- job.id,
132
- job.kind,
133
- job.environment,
134
- job.requestedBy,
135
- job.requestedByName,
136
- JSON.stringify(job.options),
137
- job.state,
138
- now,
139
- DbDate.toDb(job.expiresAt),
140
- now,
141
- ],
142
- )
128
+ await this.#db.q
129
+ .insertInto('remote_job')
130
+ .values({
131
+ id: job.id,
132
+ kind: job.kind,
133
+ environment: job.environment,
134
+ requested_by: job.requestedBy,
135
+ requested_by_name: job.requestedByName,
136
+ options: JSON.stringify(job.options),
137
+ state: job.state,
138
+ heartbeat_at: now,
139
+ expires_at: DbDate.toDb(job.expiresAt),
140
+ create_date: now,
141
+ })
142
+ .execute()
143
143
  }
144
144
 
145
145
  async get(id: string): Promise<RemoteJob | undefined> {
146
- const rows = await this.#db.query('SELECT * FROM remote_job WHERE id = ?', [id])
147
- return rows[0] ? mapJob(rows[0]) : undefined
146
+ const row = await this.#db.q
147
+ .selectFrom('remote_job')
148
+ .selectAll()
149
+ .where('id', '=', id)
150
+ .executeTakeFirst()
151
+ return row ? mapJob(row) : undefined
148
152
  }
149
153
 
150
154
  /** Records progress, and that the node running it is still alive. */
151
155
  async update(id: string, change: RemoteJobUpdate): Promise<void> {
152
- const sets: string[] = ['heartbeat_at = ?']
153
- const values: unknown[] = [DbDate.toDb(new Date())]
156
+ const sets: Record<string, unknown> = { heartbeat_at: DbDate.toDb(new Date()) }
154
157
  for (const [field, value] of Object.entries(change) as [keyof RemoteJobUpdate, unknown][]) {
155
- sets.push(`${COLUMNS[field]} = ?`)
156
- values.push(
158
+ sets[COLUMNS[field]] =
157
159
  field === 'problem'
158
160
  ? value === null
159
161
  ? null
160
162
  : JSON.stringify(value)
161
163
  : value instanceof Date
162
164
  ? DbDate.toDb(value)
163
- : value,
164
- )
165
+ : (value ?? null)
165
166
  }
166
- await this.#db.exec(`UPDATE remote_job SET ${sets.join(', ')} WHERE id = ?`, [...values, id])
167
+ await this.#db.q
168
+ .updateTable('remote_job')
169
+ .set(sets as Updateable<CoreTables['remote_job']>)
170
+ .where('id', '=', id)
171
+ .execute()
167
172
  }
168
173
 
169
174
  /** Moves a job from one state to another only if it is still in the first; true when it moved. */
170
175
  async transition(id: string, from: RemoteJobState, change: RemoteJobUpdate): Promise<boolean> {
171
- const rows = await this.#db.query<{ id: string }>(
172
- 'UPDATE remote_job SET state = ?, heartbeat_at = ? WHERE id = ? AND state = ? RETURNING id',
173
- [change.state ?? from, DbDate.toDb(new Date()), id, from],
174
- )
176
+ const rows = await this.#db.q
177
+ .updateTable('remote_job')
178
+ .set({ state: change.state ?? from, heartbeat_at: DbDate.toDb(new Date()) })
179
+ .where('id', '=', id)
180
+ .where('state', '=', from)
181
+ .returning('id')
182
+ .execute()
175
183
  if (rows.length === 0) return false
176
184
  await this.update(id, change)
177
185
  return true
@@ -179,13 +187,15 @@ export class RemoteJobRepository {
179
187
 
180
188
  /** Jobs past their expiry, whose files are to be swept. */
181
189
  async expired(now = new Date()): Promise<RemoteJob[]> {
182
- const rows = await this.#db.query('SELECT * FROM remote_job WHERE expires_at < ?', [
183
- DbDate.toDb(now),
184
- ])
190
+ const rows = await this.#db.q
191
+ .selectFrom('remote_job')
192
+ .selectAll()
193
+ .where('expires_at', '<', DbDate.toDb(now))
194
+ .execute()
185
195
  return rows.map(mapJob)
186
196
  }
187
197
 
188
198
  async delete(id: string): Promise<void> {
189
- await this.#db.exec('DELETE FROM remote_job WHERE id = ?', [id])
199
+ await this.#db.q.deleteFrom('remote_job').where('id', '=', id).execute()
190
200
  }
191
201
  }
@@ -43,16 +43,17 @@ export class TagRepository {
43
43
  async all(
44
44
  filter: { query?: string; group?: string; culture?: string | null } = {},
45
45
  ): Promise<TagRow[]> {
46
- const rows = await this.#db.query(
47
- `SELECT pv.node_id, pv.text_value, pv.varchar_value, d.config, l.iso_code
48
- FROM property_value pv
49
- JOIN property_type p ON p.id = pv.property_type_id
50
- JOIN data_type d ON d.node_id = p.data_type_id
51
- JOIN node n ON n.id = pv.node_id
52
- LEFT JOIN language l ON l.id = pv.language_id
53
- WHERE pv.is_current = ? AND d.editor_alias = ? AND n.trashed = ?`,
54
- [this.#db.dialect.boolValue(true), 'Umbraco.Tags', this.#db.dialect.boolValue(false)],
55
- )
46
+ const rows = await this.#db.q
47
+ .selectFrom('property_value as pv')
48
+ .innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
49
+ .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
50
+ .innerJoin('node as n', 'n.id', 'pv.node_id')
51
+ .leftJoin('language as l', 'l.id', 'pv.language_id')
52
+ .select(['pv.node_id', 'pv.text_value', 'pv.varchar_value', 'd.config', 'l.iso_code'])
53
+ .where('pv.is_current', '=', this.#db.dialect.boolValue(true))
54
+ .where('d.editor_alias', '=', 'Umbraco.Tags')
55
+ .where('n.trashed', '=', this.#db.dialect.boolValue(false))
56
+ .execute()
56
57
  const tags = new Map<string, TagRow & { nodes: Set<number> }>()
57
58
  for (const row of rows) {
58
59
  let group = 'default'
@@ -34,11 +34,12 @@ export class ComponentRepository {
34
34
  }
35
35
 
36
36
  async byKey(key: string): Promise<ComponentModel | undefined> {
37
- const rows = await this.#db.query(
38
- `SELECT n.unique_id, n.text, t.alias FROM template t
39
- JOIN node n ON n.id = t.node_id WHERE n.unique_id = ?`,
40
- [normaliseUuid(key)],
41
- )
37
+ const rows = await this.#db.q
38
+ .selectFrom('template as t')
39
+ .innerJoin('node as n', 'n.id', 't.node_id')
40
+ .select(['n.unique_id', 'n.text', 't.alias'])
41
+ .where('n.unique_id', '=', normaliseUuid(key))
42
+ .execute()
42
43
  const row = rows[0]
43
44
  if (!row) return undefined
44
45
  const alias = String(row.alias)
@@ -51,10 +52,12 @@ export class ComponentRepository {
51
52
  }
52
53
 
53
54
  async byAlias(alias: string): Promise<ComponentModel | undefined> {
54
- const rows = await this.#db.query<{ unique_id: string }>(
55
- 'SELECT n.unique_id FROM template t JOIN node n ON n.id = t.node_id WHERE t.alias = ?',
56
- [alias],
57
- )
55
+ const rows = await this.#db.q
56
+ .selectFrom('template as t')
57
+ .innerJoin('node as n', 'n.id', 't.node_id')
58
+ .select('n.unique_id')
59
+ .where('t.alias', '=', alias)
60
+ .execute()
58
61
  return rows[0] ? this.byKey(String(rows[0].unique_id)) : undefined
59
62
  }
60
63
 
@@ -78,7 +81,11 @@ export class ComponentRepository {
78
81
  const existing = await repo.nodes.byKey(model.key)
79
82
  if (existing) {
80
83
  await repo.nodes.rename(existing.id, model.name)
81
- await tx.exec('UPDATE template SET alias = ? WHERE node_id = ?', [model.alias, existing.id])
84
+ await tx.q
85
+ .updateTable('template')
86
+ .set({ alias: model.alias })
87
+ .where('node_id', '=', existing.id)
88
+ .execute()
82
89
  } else {
83
90
  const node = await repo.nodes.create({
84
91
  key: model.key,
@@ -87,7 +94,7 @@ export class ComponentRepository {
87
94
  text: model.name,
88
95
  userId,
89
96
  })
90
- await tx.exec('INSERT INTO template (node_id, alias) VALUES (?, ?)', [node.id, model.alias])
97
+ await tx.q.insertInto('template').values({ node_id: node.id, alias: model.alias }).execute()
91
98
  }
92
99
  return model
93
100
  })
@@ -104,9 +111,12 @@ export class ComponentRepository {
104
111
  const node = await this.#nodes.byKey(key)
105
112
  if (!template || !node) return false
106
113
  await this.#db.transaction(async (tx) => {
107
- await tx.exec('DELETE FROM content_type_template WHERE template_node_id = ?', [node.id])
108
- await tx.exec('DELETE FROM template WHERE node_id = ?', [node.id])
109
- await tx.exec('DELETE FROM node WHERE id = ?', [node.id])
114
+ await tx.q
115
+ .deleteFrom('content_type_template')
116
+ .where('template_node_id', '=', node.id)
117
+ .execute()
118
+ await tx.q.deleteFrom('template').where('node_id', '=', node.id).execute()
119
+ await tx.q.deleteFrom('node').where('id', '=', node.id).execute()
110
120
  })
111
121
  await this.#files?.remove(template.alias)
112
122
  return true
@@ -63,51 +63,58 @@ export class TransferAnswerRepository {
63
63
  async recordCheck(pending: PendingTransfer): Promise<void> {
64
64
  const bool = (value: boolean) => this.#db.dialect.boolValue(value)
65
65
  await this.#db.transaction(async (tx) => {
66
- await tx.exec('DELETE FROM transfer_pending WHERE bundle_id = ?', [pending.bundleId])
67
- await tx.exec(
68
- `INSERT INTO transfer_pending
69
- (bundle_id, label, target, target_kind, under_target, publish, allow_missing_blobs, checked_at, checked_by)
70
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
71
- [
72
- pending.bundleId,
73
- pending.label,
74
- pending.target,
75
- pending.targetKind,
76
- pending.under,
77
- bool(pending.publish),
78
- bool(pending.allowMissingBlobs),
79
- DbDate.toDb(pending.checkedAt),
80
- pending.checkedBy,
81
- ],
82
- )
66
+ await tx.q.deleteFrom('transfer_pending').where('bundle_id', '=', pending.bundleId).execute()
67
+ await tx.q
68
+ .insertInto('transfer_pending')
69
+ .values({
70
+ bundle_id: pending.bundleId,
71
+ label: pending.label,
72
+ target: pending.target,
73
+ target_kind: pending.targetKind,
74
+ under_target: pending.under,
75
+ publish: bool(pending.publish),
76
+ allow_missing_blobs: bool(pending.allowMissingBlobs),
77
+ checked_at: DbDate.toDb(pending.checkedAt),
78
+ checked_by: pending.checkedBy,
79
+ })
80
+ .execute()
83
81
  })
84
82
  }
85
83
 
86
84
  async pending(bundleId: string): Promise<PendingTransfer | undefined> {
87
- const rows = await this.#db.query('SELECT * FROM transfer_pending WHERE bundle_id = ?', [
88
- bundleId,
89
- ])
90
- return rows[0] ? pendingFrom(rows[0]) : undefined
85
+ const row = await this.#db.q
86
+ .selectFrom('transfer_pending')
87
+ .selectAll()
88
+ .where('bundle_id', '=', bundleId)
89
+ .executeTakeFirst()
90
+ return row ? pendingFrom(row) : undefined
91
91
  }
92
92
 
93
93
  async allPending(): Promise<PendingTransfer[]> {
94
- return (await this.#db.query('SELECT * FROM transfer_pending ORDER BY checked_at DESC')).map(
95
- pendingFrom,
96
- )
94
+ const rows = await this.#db.q
95
+ .selectFrom('transfer_pending')
96
+ .selectAll()
97
+ .orderBy('checked_at', 'desc')
98
+ .execute()
99
+ return rows.map(pendingFrom)
97
100
  }
98
101
 
99
102
  async setAllowMissingBlobs(bundleId: string, allow: boolean): Promise<void> {
100
- await this.#db.exec('UPDATE transfer_pending SET allow_missing_blobs = ? WHERE bundle_id = ?', [
101
- this.#db.dialect.boolValue(allow),
102
- bundleId,
103
- ])
103
+ await this.#db.q
104
+ .updateTable('transfer_pending')
105
+ .set({ allow_missing_blobs: this.#db.dialect.boolValue(allow) })
106
+ .where('bundle_id', '=', bundleId)
107
+ .execute()
104
108
  }
105
109
 
106
110
  async answers(bundleId: string): Promise<TransferAnswer[]> {
107
- const rows = await this.#db.query(
108
- 'SELECT * FROM transfer_answer WHERE bundle_id = ? ORDER BY node_key, handle',
109
- [bundleId],
110
- )
111
+ const rows = await this.#db.q
112
+ .selectFrom('transfer_answer')
113
+ .selectAll()
114
+ .where('bundle_id', '=', bundleId)
115
+ .orderBy('node_key')
116
+ .orderBy('handle')
117
+ .execute()
111
118
  return rows.map((row) => ({
112
119
  nodeKey: row.node_key as string,
113
120
  handle: row.handle as string,
@@ -123,29 +130,30 @@ export class TransferAnswerRepository {
123
130
  answer: { nodeKey: string; handle: string; resolution: string | null; by: string | null },
124
131
  ): Promise<void> {
125
132
  await this.#db.transaction(async (tx) => {
126
- await tx.exec(
127
- 'DELETE FROM transfer_answer WHERE bundle_id = ? AND node_key = ? AND handle = ?',
128
- [bundleId, answer.nodeKey, answer.handle],
129
- )
133
+ await tx.q
134
+ .deleteFrom('transfer_answer')
135
+ .where('bundle_id', '=', bundleId)
136
+ .where('node_key', '=', answer.nodeKey)
137
+ .where('handle', '=', answer.handle)
138
+ .execute()
130
139
  if (answer.resolution === null) return
131
- await tx.exec(
132
- `INSERT INTO transfer_answer (bundle_id, node_key, handle, resolution, answered_by, answered_at)
133
- VALUES (?, ?, ?, ?, ?, ?)`,
134
- [
135
- bundleId,
136
- answer.nodeKey,
137
- answer.handle,
138
- answer.resolution,
139
- answer.by,
140
- DbDate.toDb(new Date()),
141
- ],
142
- )
140
+ await tx.q
141
+ .insertInto('transfer_answer')
142
+ .values({
143
+ bundle_id: bundleId,
144
+ node_key: answer.nodeKey,
145
+ handle: answer.handle,
146
+ resolution: answer.resolution,
147
+ answered_by: answer.by,
148
+ answered_at: DbDate.toDb(new Date()),
149
+ })
150
+ .execute()
143
151
  })
144
152
  }
145
153
 
146
154
  /** Once the import is applied there is nothing pending, and nothing left to answer. */
147
155
  async clear(bundleId: string): Promise<void> {
148
- await this.#db.exec('DELETE FROM transfer_answer WHERE bundle_id = ?', [bundleId])
149
- await this.#db.exec('DELETE FROM transfer_pending WHERE bundle_id = ?', [bundleId])
156
+ await this.#db.q.deleteFrom('transfer_answer').where('bundle_id', '=', bundleId).execute()
157
+ await this.#db.q.deleteFrom('transfer_pending').where('bundle_id', '=', bundleId).execute()
150
158
  }
151
159
  }
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { Db } from '../database.ts'
9
9
  import { DbDate } from '../dialect.ts'
10
+ import { sql } from '../query.ts'
10
11
 
11
12
  export type TransferDirection = 'import' | 'revert'
12
13
  export type TransferRunStatus = 'applied' | 'reverted' | 'failed'
@@ -58,57 +59,63 @@ export class TransferRunRepository {
58
59
  }
59
60
 
60
61
  async start(run: Omit<TransferRun, 'finishedAt' | 'status'>): Promise<void> {
61
- await this.#db.exec(
62
- `INSERT INTO content_transfer_run
63
- (id, bundle_id, bundle_label, package_name, package_version, direction, reverts_run_id, schema_state_id, started_at, applied_by, node_count, status)
64
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'applied')`,
65
- [
66
- run.id,
67
- run.bundleId,
68
- run.bundleLabel,
69
- run.packageName,
70
- run.packageVersion,
71
- run.direction,
72
- run.revertsRunId,
73
- run.schemaStateId,
74
- DbDate.toDb(run.startedAt),
75
- run.appliedBy,
76
- run.nodeCount,
77
- ],
78
- )
62
+ await this.#db.q
63
+ .insertInto('content_transfer_run')
64
+ .values({
65
+ id: run.id,
66
+ bundle_id: run.bundleId,
67
+ bundle_label: run.bundleLabel,
68
+ package_name: run.packageName,
69
+ package_version: run.packageVersion,
70
+ direction: run.direction,
71
+ reverts_run_id: run.revertsRunId,
72
+ schema_state_id: run.schemaStateId,
73
+ started_at: DbDate.toDb(run.startedAt),
74
+ applied_by: run.appliedBy,
75
+ node_count: run.nodeCount,
76
+ status: 'applied',
77
+ })
78
+ .execute()
79
79
  }
80
80
 
81
81
  async finish(id: string, nodeCount: number): Promise<void> {
82
- await this.#db.exec(
83
- 'UPDATE content_transfer_run SET finished_at = ?, node_count = ? WHERE id = ?',
84
- [DbDate.toDb(new Date()), nodeCount, id],
85
- )
82
+ await this.#db.q
83
+ .updateTable('content_transfer_run')
84
+ .set({ finished_at: DbDate.toDb(new Date()), node_count: nodeCount })
85
+ .where('id', '=', id)
86
+ .execute()
86
87
  }
87
88
 
88
89
  async setStatus(id: string, status: TransferRunStatus): Promise<void> {
89
- await this.#db.exec('UPDATE content_transfer_run SET status = ? WHERE id = ?', [status, id])
90
+ await this.#db.q
91
+ .updateTable('content_transfer_run')
92
+ .set({ status })
93
+ .where('id', '=', id)
94
+ .execute()
90
95
  }
91
96
 
92
97
  async record(change: Omit<TransferChange, 'id'>): Promise<void> {
93
- await this.#db.exec(
94
- `INSERT INTO content_transfer_change
95
- (run_id, node_key, kind, action, before_event_id, before_published_event_id, event_id)
96
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
97
- [
98
- change.runId,
99
- change.nodeKey,
100
- change.kind,
101
- change.action,
102
- change.beforeEventId,
103
- change.beforePublishedEventId,
104
- change.eventId,
105
- ],
106
- )
98
+ await this.#db.q
99
+ .insertInto('content_transfer_change')
100
+ .values({
101
+ run_id: change.runId,
102
+ node_key: change.nodeKey,
103
+ kind: change.kind,
104
+ action: change.action,
105
+ before_event_id: change.beforeEventId,
106
+ before_published_event_id: change.beforePublishedEventId,
107
+ event_id: change.eventId,
108
+ })
109
+ .execute()
107
110
  }
108
111
 
109
112
  async byId(id: string): Promise<TransferRun | undefined> {
110
- const rows = await this.#db.query('SELECT * FROM content_transfer_run WHERE id = ?', [id])
111
- return rows[0] ? mapRun(rows[0]) : undefined
113
+ const row = await this.#db.q
114
+ .selectFrom('content_transfer_run')
115
+ .selectAll()
116
+ .where('id', '=', id)
117
+ .executeTakeFirst()
118
+ return row ? mapRun(row) : undefined
112
119
  }
113
120
 
114
121
  /**
@@ -117,45 +124,56 @@ export class TransferRunRepository {
117
124
  * is the right answer. This is what makes `start --bundle` import once.
118
125
  */
119
126
  async appliedFor(bundleId: string): Promise<TransferRun | undefined> {
120
- const rows = await this.#db.query(
121
- `SELECT * FROM content_transfer_run
122
- WHERE bundle_id = ? AND direction = 'import' AND status = 'applied'
123
- ORDER BY started_at DESC, id DESC LIMIT 1`,
124
- [bundleId],
125
- )
126
- return rows[0] ? mapRun(rows[0]) : undefined
127
+ const row = await this.#standing().where('bundle_id', '=', bundleId).executeTakeFirst()
128
+ return row ? mapRun(row) : undefined
127
129
  }
128
130
 
129
131
  /** The latest standing import of a package's content, whichever version brought it. */
130
132
  async appliedForPackage(packageName: string): Promise<TransferRun | undefined> {
131
- const rows = await this.#db.query(
132
- `SELECT * FROM content_transfer_run
133
- WHERE package_name = ? AND direction = 'import' AND status = 'applied'
134
- ORDER BY started_at DESC, id DESC LIMIT 1`,
135
- [packageName],
136
- )
137
- return rows[0] ? mapRun(rows[0]) : undefined
133
+ const row = await this.#standing().where('package_name', '=', packageName).executeTakeFirst()
134
+ return row ? mapRun(row) : undefined
135
+ }
136
+
137
+ /** The latest standing import, narrowed by the caller. */
138
+ #standing() {
139
+ return this.#db.q
140
+ .selectFrom('content_transfer_run')
141
+ .selectAll()
142
+ .where('direction', '=', 'import')
143
+ .where('status', '=', 'applied')
144
+ .orderBy('started_at', 'desc')
145
+ .orderBy('id', 'desc')
146
+ .limit(1)
138
147
  }
139
148
 
140
149
  /** Runs, newest first. */
141
150
  async recent(limit = 20, offset = 0): Promise<TransferRun[]> {
142
- const rows = await this.#db.query(
143
- 'SELECT * FROM content_transfer_run ORDER BY started_at DESC, id DESC LIMIT ? OFFSET ?',
144
- [limit, offset],
145
- )
151
+ const rows = await this.#db.q
152
+ .selectFrom('content_transfer_run')
153
+ .selectAll()
154
+ .orderBy('started_at', 'desc')
155
+ .orderBy('id', 'desc')
156
+ .limit(limit)
157
+ .offset(offset)
158
+ .execute()
146
159
  return rows.map(mapRun)
147
160
  }
148
161
 
149
162
  async count(): Promise<number> {
150
- const rows = await this.#db.query('SELECT COUNT(*) AS n FROM content_transfer_run')
151
- return Number(rows[0]?.n ?? 0)
163
+ const row = await this.#db.q
164
+ .selectFrom('content_transfer_run')
165
+ .select(sql<number>`count(*)`.as('n'))
166
+ .executeTakeFirst()
167
+ return Number(row?.n ?? 0)
152
168
  }
153
169
 
154
170
  async changes(runId: string): Promise<TransferChange[]> {
155
- const rows = await this.#db.query(
156
- 'SELECT * FROM content_transfer_change WHERE run_id = ? ORDER BY id',
157
- [runId],
158
- )
171
+ const rows = await this.#db.q
172
+ .selectFrom('content_transfer_change')
173
+ .selectAll()
174
+ .where('run_id', '=', runId)
175
+ .orderBy('id')
176
+ .execute()
159
177
  return rows.map(mapChange)
160
178
  }
161
179
 
@@ -164,18 +182,18 @@ export class TransferRunRepository {
164
182
  * of these stands would quietly undo its work too, so revert refuses.
165
183
  */
166
184
  async laterRunsTouching(runId: string): Promise<string[]> {
167
- const rows = await this.#db.query<{ id: string }>(
168
- `SELECT DISTINCT later.id
169
- FROM content_transfer_change mine
170
- JOIN content_transfer_change theirs ON theirs.node_key = mine.node_key
171
- JOIN content_transfer_run later ON later.id = theirs.run_id
172
- JOIN content_transfer_run self ON self.id = mine.run_id
173
- WHERE mine.run_id = ?
174
- AND theirs.run_id <> mine.run_id
175
- AND later.started_at >= self.started_at
176
- AND later.status = 'applied'`,
177
- [runId],
178
- )
185
+ const rows = await this.#db.q
186
+ .selectFrom('content_transfer_change as mine')
187
+ .innerJoin('content_transfer_change as theirs', 'theirs.node_key', 'mine.node_key')
188
+ .innerJoin('content_transfer_run as later', 'later.id', 'theirs.run_id')
189
+ .innerJoin('content_transfer_run as self', 'self.id', 'mine.run_id')
190
+ .select('later.id')
191
+ .distinct()
192
+ .where('mine.run_id', '=', runId)
193
+ .whereRef('theirs.run_id', '<>', 'mine.run_id')
194
+ .whereRef('later.started_at', '>=', 'self.started_at')
195
+ .where('later.status', '=', 'applied')
196
+ .execute()
179
197
  return rows.map((row) => String(row.id))
180
198
  }
181
199
  }