@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
@@ -44,10 +44,14 @@ export class DomainRepository {
44
44
  }
45
45
 
46
46
  async all(): Promise<DomainRow[]> {
47
- const rows = await this.#db.query(
48
- `SELECT d.node_id, d.domain_name, d.sort_order, l.iso_code FROM domain d
49
- LEFT JOIN language l ON l.id = d.language_id ORDER BY d.node_id, d.sort_order, d.id`,
50
- )
47
+ const rows = await this.#db.q
48
+ .selectFrom('domain as d')
49
+ .leftJoin('language as l', 'l.id', 'd.language_id')
50
+ .select(['d.node_id', 'd.domain_name', 'd.sort_order', 'l.iso_code'])
51
+ .orderBy('d.node_id')
52
+ .orderBy('d.sort_order')
53
+ .orderBy('d.id')
54
+ .execute()
51
55
  return rows.map((row) => ({
52
56
  nodeId: Number(row.node_id),
53
57
  domainName: String(row.domain_name),
@@ -69,9 +73,7 @@ export class DomainRepository {
69
73
 
70
74
  /** Replaces a node's domains. Names are unique across the site, and each culture must exist. */
71
75
  async setForNode(nodeId: number, assignment: DomainAssignment): Promise<SetDomainsResult> {
72
- const languages = await this.#db.query<{ id: number; iso_code: string }>(
73
- 'SELECT id, iso_code FROM language',
74
- )
76
+ const languages = await this.#db.q.selectFrom('language').select(['id', 'iso_code']).execute()
75
77
  const languageId = (iso: string) =>
76
78
  languages.find((l) => String(l.iso_code).toLowerCase() === iso.toLowerCase())?.id
77
79
  if (assignment.defaultIsoCode && languageId(assignment.defaultIsoCode) === undefined)
@@ -91,17 +93,27 @@ export class DomainRepository {
91
93
  if (taken[0]) return { status: 'conflict', domainName: taken[0].domainName }
92
94
 
93
95
  await this.#db.transaction(async (tx) => {
94
- await tx.exec('DELETE FROM domain WHERE node_id = ?', [nodeId])
96
+ await tx.q.deleteFrom('domain').where('node_id', '=', nodeId).execute()
95
97
  if (assignment.defaultIsoCode)
96
- await tx.exec(
97
- 'INSERT INTO domain (node_id, language_id, domain_name, sort_order) VALUES (?, ?, ?, ?)',
98
- [nodeId, languageId(assignment.defaultIsoCode), `*${nodeId}`, 0],
99
- )
98
+ await tx.q
99
+ .insertInto('domain')
100
+ .values({
101
+ node_id: nodeId,
102
+ language_id: languageId(assignment.defaultIsoCode),
103
+ domain_name: `*${nodeId}`,
104
+ sort_order: 0,
105
+ })
106
+ .execute()
100
107
  for (const [index, domain] of assignment.domains.entries())
101
- await tx.exec(
102
- 'INSERT INTO domain (node_id, language_id, domain_name, sort_order) VALUES (?, ?, ?, ?)',
103
- [nodeId, languageId(domain.isoCode), names[index], index],
104
- )
108
+ await tx.q
109
+ .insertInto('domain')
110
+ .values({
111
+ node_id: nodeId,
112
+ language_id: languageId(domain.isoCode),
113
+ domain_name: names[index] as string,
114
+ sort_order: index,
115
+ })
116
+ .execute()
105
117
  })
106
118
  return { status: 'ok' }
107
119
  }
@@ -25,10 +25,19 @@ interface Node {
25
25
  /** The virtual root above the tree: ContentRoot's origin, which descendant steps start from. */
26
26
  const CONTENT_ROOT: Node = { id: -1, key: '', level: 0, path: '-1', typeKey: '' }
27
27
 
28
- const SELECT = `SELECT n.id, n.unique_id, n.level, n.path, t.unique_id AS type_key
29
- FROM node n
30
- JOIN content c ON c.node_id = n.id
31
- JOIN node t ON t.id = c.content_type_id`
28
+ function documents(db: Db) {
29
+ return db.q
30
+ .selectFrom('node as n')
31
+ .innerJoin('content as c', 'c.node_id', 'n.id')
32
+ .innerJoin('node as t', 't.id', 'c.content_type_id')
33
+ .select(['n.id', 'n.unique_id', 'n.level', 'n.path', 't.unique_id as type_key'])
34
+ .where('n.node_object_type', '=', ObjectTypes.Document)
35
+ .where('n.trashed', '=', db.dialect.boolValue(false))
36
+ .orderBy('n.level')
37
+ .orderBy('n.sort_order')
38
+ }
39
+
40
+ type Documents = ReturnType<typeof documents>
32
41
 
33
42
  export class DynamicRootRepository {
34
43
  #db: Db
@@ -96,11 +105,8 @@ export class DynamicRootRepository {
96
105
  }
97
106
  }
98
107
 
99
- async #query(where: string, params: unknown[]): Promise<Node[]> {
100
- const rows = await this.#db.query(
101
- `${SELECT} WHERE n.node_object_type = ? AND n.trashed = ? AND ${where} ORDER BY n.level, n.sort_order`,
102
- [ObjectTypes.Document, this.#db.dialect.boolValue(false), ...params],
103
- )
108
+ async #query(narrow: (query: Documents) => Documents): Promise<Node[]> {
109
+ const rows = await narrow(documents(this.#db)).execute()
104
110
  return rows.map((row) => ({
105
111
  id: Number(row.id),
106
112
  key: normaliseUuid(String(row.unique_id)),
@@ -111,7 +117,7 @@ export class DynamicRootRepository {
111
117
  }
112
118
 
113
119
  async #byKey(key: string): Promise<Node | undefined> {
114
- return (await this.#query('n.unique_id = ?', [normaliseUuid(key)]))[0]
120
+ return (await this.#query((q) => q.where('n.unique_id', '=', normaliseUuid(key))))[0]
115
121
  }
116
122
 
117
123
  /** Top of the tree first, `node` last. */
@@ -122,12 +128,14 @@ export class DynamicRootRepository {
122
128
  .map(Number)
123
129
  .filter((id) => id > 0)
124
130
  if (ids.length === 0) return []
125
- return this.#query(`n.id IN (${ids.map(() => '?').join(', ')})`, ids)
131
+ return this.#query((q) => q.where('n.id', 'in', ids))
126
132
  }
127
133
 
128
134
  async #descendantsOrSelf(node: Node): Promise<Node[]> {
129
- if (node.id === CONTENT_ROOT.id) return this.#query('n.level >= 1', [])
130
- return this.#query('(n.id = ? OR n.path LIKE ?)', [node.id, `${node.path},%`])
135
+ if (node.id === CONTENT_ROOT.id) return this.#query((q) => q.where('n.level', '>=', 1))
136
+ return this.#query((q) =>
137
+ q.where((eb) => eb.or([eb('n.id', '=', node.id), eb('n.path', 'like', `${node.path},%`)])),
138
+ )
131
139
  }
132
140
 
133
141
  async #root(key: string): Promise<Node | undefined> {
@@ -141,10 +149,17 @@ export class DynamicRootRepository {
141
149
  if (!node) return undefined
142
150
  const line = await this.#ancestorsOrSelf(node)
143
151
  if (line.length === 0) return undefined
144
- const rows = await this.#db.query<{ node_id: number }>(
145
- `SELECT DISTINCT node_id FROM domain WHERE domain_name NOT LIKE '*%' AND node_id IN (${line.map(() => '?').join(', ')})`,
146
- line.map((candidate) => candidate.id),
147
- )
152
+ const rows = await this.#db.q
153
+ .selectFrom('domain')
154
+ .select('node_id')
155
+ .distinct()
156
+ .where('domain_name', 'not like', '*%')
157
+ .where(
158
+ 'node_id',
159
+ 'in',
160
+ line.map((candidate) => candidate.id),
161
+ )
162
+ .execute()
148
163
  const sites = new Set(rows.map((row) => Number(row.node_id)))
149
164
  return line.filter((candidate) => sites.has(candidate.id)).at(-1)
150
165
  }
@@ -41,19 +41,23 @@ export class ExternalLoginRepository {
41
41
 
42
42
  /** Who an account at a provider is linked to, if anyone. */
43
43
  async find(loginProvider: string, providerKey: string): Promise<ExternalLogin | undefined> {
44
- const rows = await this.#db.query(
45
- 'SELECT * FROM external_login WHERE login_provider = ? AND provider_key = ?',
46
- [loginProvider, providerKey],
47
- )
48
- return rows[0] ? toLogin(rows[0]) : undefined
44
+ const row = await this.#db.q
45
+ .selectFrom('external_login')
46
+ .selectAll()
47
+ .where('login_provider', '=', loginProvider)
48
+ .where('provider_key', '=', providerKey)
49
+ .executeTakeFirst()
50
+ return row ? toLogin(row) : undefined
49
51
  }
50
52
 
51
53
  /** Every provider account linked to a member or user. */
52
54
  async forOwner(ownerKey: string): Promise<ExternalLogin[]> {
53
- const rows = await this.#db.query(
54
- 'SELECT * FROM external_login WHERE user_or_member_key = ? ORDER BY login_provider',
55
- [normaliseUuid(ownerKey)],
56
- )
55
+ const rows = await this.#db.q
56
+ .selectFrom('external_login')
57
+ .selectAll()
58
+ .where('user_or_member_key', '=', normaliseUuid(ownerKey))
59
+ .orderBy('login_provider')
60
+ .execute()
57
61
  return rows.map(toLogin)
58
62
  }
59
63
 
@@ -61,11 +65,15 @@ export class ExternalLoginRepository {
61
65
  async link(ownerKey: string, loginProvider: string, providerKey: string): Promise<void> {
62
66
  await this.#db.transaction(async (tx) => {
63
67
  await removeLink(tx, ownerKey, loginProvider)
64
- await tx.exec(
65
- `INSERT INTO external_login (user_or_member_key, login_provider, provider_key, create_date)
66
- VALUES (?, ?, ?, ?)`,
67
- [normaliseUuid(ownerKey), loginProvider, providerKey, DbDate.toDb(new Date())],
68
- )
68
+ await tx.q
69
+ .insertInto('external_login')
70
+ .values({
71
+ user_or_member_key: normaliseUuid(ownerKey),
72
+ login_provider: loginProvider,
73
+ provider_key: providerKey,
74
+ create_date: DbDate.toDb(new Date()),
75
+ })
76
+ .execute()
69
77
  })
70
78
  }
71
79
 
@@ -76,14 +84,20 @@ export class ExternalLoginRepository {
76
84
 
77
85
  /** A link and the tokens kept for it, which reference it. */
78
86
  async function removeLink(tx: Db, ownerKey: string, loginProvider: string): Promise<void> {
79
- const params = [loginProvider, normaliseUuid(ownerKey)]
80
- await tx.exec(
81
- `DELETE FROM external_login_token WHERE external_login_id IN
82
- (SELECT id FROM external_login WHERE login_provider = ? AND user_or_member_key = ?)`,
83
- params,
84
- )
85
- await tx.exec(
86
- 'DELETE FROM external_login WHERE login_provider = ? AND user_or_member_key = ?',
87
- params,
88
- )
87
+ const owner = normaliseUuid(ownerKey)
88
+ await tx.q
89
+ .deleteFrom('external_login_token')
90
+ .where('external_login_id', 'in', (eb) =>
91
+ eb
92
+ .selectFrom('external_login')
93
+ .select('id')
94
+ .where('login_provider', '=', loginProvider)
95
+ .where('user_or_member_key', '=', owner),
96
+ )
97
+ .execute()
98
+ await tx.q
99
+ .deleteFrom('external_login')
100
+ .where('login_provider', '=', loginProvider)
101
+ .where('user_or_member_key', '=', owner)
102
+ .execute()
89
103
  }
@@ -82,10 +82,13 @@ export class FolderRepository {
82
82
  let parentId: number = SystemNodes.Root
83
83
  let key: string | null = null
84
84
  for (const name of names) {
85
- const found = await this.#db.query<{ unique_id: string; id: number }>(
86
- 'SELECT unique_id, id FROM node WHERE parent_id = ? AND node_object_type = ? AND text = ?',
87
- [parentId, this.#objectType, name],
88
- )
85
+ const found = await this.#db.q
86
+ .selectFrom('node')
87
+ .select(['unique_id', 'id'])
88
+ .where('parent_id', '=', parentId)
89
+ .where('node_object_type', '=', this.#objectType)
90
+ .where('text', '=', name)
91
+ .execute()
89
92
  if (found[0]) {
90
93
  parentId = Number(found[0].id)
91
94
  key = String(found[0].unique_id).toLowerCase()
@@ -13,6 +13,7 @@
13
13
  import { randomUUID } from 'node:crypto'
14
14
  import type { Db } from '../database.ts'
15
15
  import { DbDate, fromDbBool } from '../dialect.ts'
16
+ import { sql } from '../query.ts'
16
17
 
17
18
  /** Where an entry is in its life: approval is the only transition. */
18
19
  export type FormEntryState = 'submitted' | 'approved' | 'rejected'
@@ -91,9 +92,19 @@ interface ValueRow {
91
92
  label: string | null
92
93
  }
93
94
 
94
- const SELECT = `SELECT id, form_key, form_alias, state, culture, page_key, ip_hash,
95
- user_agent, spam, create_date, update_date
96
- FROM form_entry`
95
+ const COLUMNS = [
96
+ 'id',
97
+ 'form_key',
98
+ 'form_alias',
99
+ 'state',
100
+ 'culture',
101
+ 'page_key',
102
+ 'ip_hash',
103
+ 'user_agent',
104
+ 'spam',
105
+ 'create_date',
106
+ 'update_date',
107
+ ] as const
97
108
 
98
109
  const state = (value: string): FormEntryState =>
99
110
  FORM_ENTRY_STATES.includes(value as FormEntryState) ? (value as FormEntryState) : 'submitted'
@@ -146,104 +157,98 @@ export class FormEntryRepository {
146
157
  /** The values for a page of entries, in one query rather than one each. */
147
158
  async #valuesFor(ids: readonly string[]): Promise<Map<string, FormEntryValue[]>> {
148
159
  if (ids.length === 0) return new Map()
149
- const placeholders = ids.map(() => '?').join(', ')
150
- const rows = await this.#db.query<ValueRow>(
151
- `SELECT entry_id, field_alias, sort_order, value, label
152
- FROM form_entry_value
153
- WHERE entry_id IN (${placeholders})
154
- ORDER BY field_alias, sort_order`,
155
- [...ids],
156
- )
160
+ const rows = await this.#db.q
161
+ .selectFrom('form_entry_value')
162
+ .select(['entry_id', 'field_alias', 'sort_order', 'value', 'label'])
163
+ .where('entry_id', 'in', [...ids])
164
+ .orderBy('field_alias')
165
+ .orderBy('sort_order')
166
+ .execute()
157
167
  return group(rows)
158
168
  }
159
169
 
160
170
  async byId(id: string): Promise<FormEntry | undefined> {
161
- const rows = await this.#db.query<EntryRow>(`${SELECT} WHERE id = ?`, [id])
162
- const row = rows[0]
171
+ const row = await this.#db.q
172
+ .selectFrom('form_entry')
173
+ .select(COLUMNS)
174
+ .where('id', '=', id)
175
+ .executeTakeFirst()
163
176
  if (!row) return undefined
164
177
  return hydrate(row, (await this.#valuesFor([id])).get(id) ?? [])
165
178
  }
166
179
 
167
180
  async list(query: FormEntryQuery): Promise<{ total: number; items: FormEntry[] }> {
168
- const where: string[] = ['form_key = ?']
169
- const params: unknown[] = [query.formKey]
170
- if (query.state) {
171
- where.push('state = ?')
172
- params.push(query.state)
173
- }
174
- if (query.from) {
175
- where.push('create_date >= ?')
176
- params.push(DbDate.toDb(query.from))
177
- }
178
- if (query.to) {
179
- where.push('create_date <= ?')
180
- params.push(DbDate.toDb(query.to))
181
- }
182
- // Spam is stored and flagged rather than dropped — a false positive that
183
- // silently discarded an enquiry is worse than one to review — so it is
184
- // hidden from the list by default rather than absent from the table.
185
- if (!query.includeSpam) {
186
- where.push('spam = ?')
187
- params.push(this.#db.dialect.boolValue(false))
188
- }
189
- if (query.search) {
190
- where.push(
191
- `id IN (SELECT entry_id FROM form_entry_value WHERE LOWER(value) LIKE ? OR LOWER(label) LIKE ?)`,
181
+ const search = query.search ? `%${query.search.toLowerCase()}%` : undefined
182
+ const matching = this.#db.q
183
+ .selectFrom('form_entry')
184
+ .where('form_key', '=', query.formKey)
185
+ .$if(Boolean(query.state), (q) => q.where('state', '=', query.state as FormEntryState))
186
+ .$if(Boolean(query.from), (q) =>
187
+ q.where('create_date', '>=', DbDate.toDb(query.from as Date)),
188
+ )
189
+ .$if(Boolean(query.to), (q) => q.where('create_date', '<=', DbDate.toDb(query.to as Date)))
190
+ // Spam is stored and flagged rather than dropped — a false positive that
191
+ // silently discarded an enquiry is worse than one to review — so it is
192
+ // hidden from the list by default rather than absent from the table.
193
+ .$if(!query.includeSpam, (q) => q.where('spam', '=', this.#db.dialect.boolValue(false)))
194
+ .$if(search !== undefined, (q) =>
195
+ q.where('id', 'in', (eb) =>
196
+ eb
197
+ .selectFrom('form_entry_value')
198
+ .select('entry_id')
199
+ .where((v) =>
200
+ v.or([
201
+ v(v.fn('lower', ['value']), 'like', search as string),
202
+ v(v.fn('lower', ['label']), 'like', search as string),
203
+ ]),
204
+ ),
205
+ ),
192
206
  )
193
- params.push(`%${query.search.toLowerCase()}%`, `%${query.search.toLowerCase()}%`)
194
- }
195
- const clause = `WHERE ${where.join(' AND ')}`
196
207
 
197
- const counted = await this.#db.query<{ total: number }>(
198
- `SELECT COUNT(*) AS total FROM form_entry ${clause}`,
199
- params,
200
- )
201
- const rows = await this.#db.query<EntryRow>(
202
- `${SELECT} ${clause} ORDER BY create_date DESC, id LIMIT ? OFFSET ?`,
203
- [...params, query.take ?? 100, query.skip ?? 0],
204
- )
208
+ const counted = await matching.select(sql<number>`count(*)`.as('total')).executeTakeFirst()
209
+ const rows = await matching
210
+ .select(COLUMNS)
211
+ .orderBy('create_date', 'desc')
212
+ .orderBy('id')
213
+ .limit(query.take ?? 100)
214
+ .offset(query.skip ?? 0)
215
+ .execute()
205
216
  const values = await this.#valuesFor(rows.map((row) => row.id))
206
217
  return {
207
- total: Number(counted[0]?.total ?? 0),
218
+ total: Number(counted?.total ?? 0),
208
219
  items: rows.map((row) => hydrate(row, values.get(row.id) ?? [])),
209
220
  }
210
221
  }
211
222
 
212
223
  /** How many entries a form has, for a form with a hard cap. */
213
224
  async count(formKey: string, options: { includeSpam?: boolean } = {}): Promise<number> {
214
- const rows = options.includeSpam
215
- ? await this.#db.query<{ total: number }>(
216
- 'SELECT COUNT(*) AS total FROM form_entry WHERE form_key = ?',
217
- [formKey],
218
- )
219
- : await this.#db.query<{ total: number }>(
220
- 'SELECT COUNT(*) AS total FROM form_entry WHERE form_key = ? AND spam = ?',
221
- [formKey, this.#db.dialect.boolValue(false)],
222
- )
223
- return Number(rows[0]?.total ?? 0)
225
+ const row = await this.#db.q
226
+ .selectFrom('form_entry')
227
+ .select(sql<number>`count(*)`.as('total'))
228
+ .where('form_key', '=', formKey)
229
+ .$if(!options.includeSpam, (q) => q.where('spam', '=', this.#db.dialect.boolValue(false)))
230
+ .executeTakeFirst()
231
+ return Number(row?.total ?? 0)
224
232
  }
225
233
 
226
234
  async create(input: FormEntryInput, id: string = randomUUID()): Promise<FormEntry> {
227
235
  const now = new Date()
228
- await this.#db.exec(
229
- `INSERT INTO form_entry
230
- (id, form_key, form_alias, state, culture, page_key, ip_hash, user_agent,
231
- spam, create_date, update_date)
232
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
233
- [
236
+ await this.#db.q
237
+ .insertInto('form_entry')
238
+ .values({
234
239
  id,
235
- input.formKey,
236
- input.formAlias,
237
- input.state ?? 'submitted',
238
- input.culture,
239
- input.pageKey,
240
- input.ipHash,
241
- input.userAgent,
242
- this.#db.dialect.boolValue(input.spam ?? false),
243
- DbDate.toDb(now),
244
- DbDate.toDb(now),
245
- ],
246
- )
240
+ form_key: input.formKey,
241
+ form_alias: input.formAlias,
242
+ state: input.state ?? 'submitted',
243
+ culture: input.culture,
244
+ page_key: input.pageKey,
245
+ ip_hash: input.ipHash,
246
+ user_agent: input.userAgent,
247
+ spam: this.#db.dialect.boolValue(input.spam ?? false),
248
+ create_date: DbDate.toDb(now),
249
+ update_date: DbDate.toDb(now),
250
+ })
251
+ .execute()
247
252
  await this.#writeValues(id, input.values)
248
253
  return (await this.byId(id)) as FormEntry
249
254
  }
@@ -254,11 +259,16 @@ export class FormEntryRepository {
254
259
  // is different from the field being absent; one empty row records it.
255
260
  const list = value.values.length === 0 ? [''] : value.values
256
261
  for (const [sort, text] of list.entries())
257
- await this.#db.exec(
258
- `INSERT INTO form_entry_value (entry_id, field_alias, sort_order, value, label)
259
- VALUES (?, ?, ?, ?, ?)`,
260
- [id, value.fieldAlias, sort, text, value.labels?.[sort] ?? null],
261
- )
262
+ await this.#db.q
263
+ .insertInto('form_entry_value')
264
+ .values({
265
+ entry_id: id,
266
+ field_alias: value.fieldAlias,
267
+ sort_order: sort,
268
+ value: text,
269
+ label: value.labels?.[sort] ?? null,
270
+ })
271
+ .execute()
262
272
  }
263
273
  }
264
274
 
@@ -269,11 +279,11 @@ export class FormEntryRepository {
269
279
  async setState(id: string, next: FormEntryState): Promise<FormEntry | undefined> {
270
280
  const existing = await this.byId(id)
271
281
  if (!existing) return undefined
272
- await this.#db.exec('UPDATE form_entry SET state = ?, update_date = ? WHERE id = ?', [
273
- next,
274
- DbDate.toDb(new Date()),
275
- id,
276
- ])
282
+ await this.#db.q
283
+ .updateTable('form_entry')
284
+ .set({ state: next, update_date: DbDate.toDb(new Date()) })
285
+ .where('id', '=', id)
286
+ .execute()
277
287
  return this.byId(id)
278
288
  }
279
289
 
@@ -281,11 +291,11 @@ export class FormEntryRepository {
281
291
  async setSpam(id: string, spam: boolean): Promise<FormEntry | undefined> {
282
292
  const existing = await this.byId(id)
283
293
  if (!existing) return undefined
284
- await this.#db.exec('UPDATE form_entry SET spam = ?, update_date = ? WHERE id = ?', [
285
- this.#db.dialect.boolValue(spam),
286
- DbDate.toDb(new Date()),
287
- id,
288
- ])
294
+ await this.#db.q
295
+ .updateTable('form_entry')
296
+ .set({ spam: this.#db.dialect.boolValue(spam), update_date: DbDate.toDb(new Date()) })
297
+ .where('id', '=', id)
298
+ .execute()
289
299
  return this.byId(id)
290
300
  }
291
301
 
@@ -301,12 +311,13 @@ export class FormEntryRepository {
301
311
  const labels = value.values.map((v) => old.labels?.[old.values.indexOf(v)] ?? v)
302
312
  return { ...value, labels }
303
313
  })
304
- await this.#db.exec('DELETE FROM form_entry_value WHERE entry_id = ?', [id])
314
+ await this.#db.q.deleteFrom('form_entry_value').where('entry_id', '=', id).execute()
305
315
  await this.#writeValues(id, kept)
306
- await this.#db.exec('UPDATE form_entry SET update_date = ? WHERE id = ?', [
307
- DbDate.toDb(new Date()),
308
- id,
309
- ])
316
+ await this.#db.q
317
+ .updateTable('form_entry')
318
+ .set({ update_date: DbDate.toDb(new Date()) })
319
+ .where('id', '=', id)
320
+ .execute()
310
321
  return this.byId(id)
311
322
  }
312
323
 
@@ -315,17 +326,23 @@ export class FormEntryRepository {
315
326
  if (!existing) return false
316
327
  // Explicit rather than relying on the cascade: SQLite enforces foreign keys
317
328
  // only when the pragma is on, and this must not depend on that.
318
- await this.#db.exec('DELETE FROM form_entry_value WHERE entry_id = ?', [id])
319
- await this.#db.exec('DELETE FROM form_entry WHERE id = ?', [id])
329
+ await this.#db.q.deleteFrom('form_entry_value').where('entry_id', '=', id).execute()
330
+ await this.#db.q.deleteFrom('form_entry').where('id', '=', id).execute()
320
331
  return true
321
332
  }
322
333
 
323
334
  /** Every form that has entries, with how many — including orphaned ones. */
324
335
  async forms(): Promise<{ formKey: string; formAlias: string; total: number }[]> {
325
- const rows = await this.#db.query<{ form_key: string; form_alias: string; total: number }>(
326
- `SELECT form_key, MAX(form_alias) AS form_alias, COUNT(*) AS total
327
- FROM form_entry GROUP BY form_key ORDER BY MAX(form_alias)`,
328
- )
336
+ const rows = await this.#db.q
337
+ .selectFrom('form_entry')
338
+ .select((eb) => [
339
+ 'form_key',
340
+ eb.fn.max('form_alias').as('form_alias'),
341
+ sql<number>`count(*)`.as('total'),
342
+ ])
343
+ .groupBy('form_key')
344
+ .orderBy((eb) => eb.fn.max('form_alias'))
345
+ .execute()
329
346
  return rows.map((row) => ({
330
347
  formKey: row.form_key,
331
348
  formAlias: row.form_alias,