@crombolo/data 0.37.0 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +3 -2
  2. package/src/audit.ts +163 -133
  3. package/src/change-report.ts +66 -43
  4. package/src/cluster.ts +119 -59
  5. package/src/content-query.ts +205 -200
  6. package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
  7. package/src/custom-tables/chain.ts +150 -0
  8. package/src/custom-tables/ddl.ts +159 -0
  9. package/src/custom-tables/handle.ts +141 -0
  10. package/src/{bundle-tables → custom-tables}/index.ts +3 -2
  11. package/src/custom-tables/names.ts +94 -0
  12. package/src/custom-tables/owners.ts +299 -0
  13. package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
  14. package/src/custom-tables/values.ts +181 -0
  15. package/src/database.ts +40 -5
  16. package/src/dialect.ts +43 -16
  17. package/src/index.ts +8 -1
  18. package/src/migrations.ts +130 -88
  19. package/src/query.ts +158 -0
  20. package/src/relations.ts +49 -28
  21. package/src/repositories/approvals.ts +130 -89
  22. package/src/repositories/bundle-grants.ts +74 -0
  23. package/src/repositories/bundles.ts +85 -76
  24. package/src/repositories/content-applied.ts +47 -28
  25. package/src/repositories/content-events.ts +114 -67
  26. package/src/repositories/content-notifications.ts +102 -74
  27. package/src/repositories/content-types.ts +449 -320
  28. package/src/repositories/data-types.ts +105 -56
  29. package/src/repositories/delivery-member-tokens.ts +37 -28
  30. package/src/repositories/dictionary.ts +77 -58
  31. package/src/repositories/documents.ts +956 -580
  32. package/src/repositories/domains.ts +28 -16
  33. package/src/repositories/dynamic-roots.ts +32 -17
  34. package/src/repositories/external-logins.ts +38 -24
  35. package/src/repositories/folders.ts +7 -4
  36. package/src/repositories/form-entries.ts +120 -103
  37. package/src/repositories/form-workflows.ts +87 -62
  38. package/src/repositories/jobs.ts +296 -0
  39. package/src/repositories/languages.ts +51 -38
  40. package/src/repositories/log-searches.ts +7 -5
  41. package/src/repositories/media-access.ts +173 -123
  42. package/src/repositories/media-listing.ts +155 -92
  43. package/src/repositories/members.ts +189 -162
  44. package/src/repositories/nodes.ts +227 -181
  45. package/src/repositories/notifications.ts +22 -17
  46. package/src/repositories/public-access.ts +77 -61
  47. package/src/repositories/redirects.ts +113 -70
  48. package/src/repositories/references.ts +55 -44
  49. package/src/repositories/remote-jobs.ts +45 -35
  50. package/src/repositories/tags.ts +11 -10
  51. package/src/repositories/templates.ts +24 -14
  52. package/src/repositories/transfer-answers.ts +58 -50
  53. package/src/repositories/transfer-runs.ts +93 -75
  54. package/src/repositories/two-factor.ts +74 -55
  55. package/src/repositories/user-data.ts +54 -36
  56. package/src/repositories/users.ts +345 -300
  57. package/src/repositories/webhooks.ts +196 -137
  58. package/src/schema/bundle-grants.ts +32 -0
  59. package/src/schema/jobs.ts +56 -0
  60. package/src/schema/plan.ts +4 -0
  61. package/src/schema-ops.ts +15 -12
  62. package/src/schema-state.ts +53 -38
  63. package/src/search.ts +175 -129
  64. package/src/setup.ts +17 -13
  65. package/src/site-search.ts +134 -83
  66. package/src/table-types.ts +152 -0
  67. package/src/tables.gen.ts +859 -0
  68. package/src/tree-invariants.ts +21 -12
  69. package/src/url-options.ts +17 -13
  70. package/src/workflow-store.ts +17 -13
  71. package/src/bundle-tables/capability.ts +0 -377
  72. package/src/bundle-tables/chain.ts +0 -105
  73. package/src/bundle-tables/ddl.ts +0 -124
  74. package/src/bundle-tables/guard.ts +0 -116
  75. package/src/bundle-tables/names.ts +0 -58
@@ -40,12 +40,21 @@ export class DataTypeRepository {
40
40
  }
41
41
 
42
42
  async byKey(key: string): Promise<DataTypeModel | undefined> {
43
- const rows = await this.#db.query(
44
- `SELECT n.unique_id, n.text, n.parent_id, d.alias, d.editor_alias, d.editor_ui_alias, d.db_type, d.config
45
- FROM data_type d JOIN node n ON n.id = d.node_id
46
- WHERE n.unique_id = ?`,
47
- [normaliseUuid(key)],
48
- )
43
+ const rows = await this.#db.q
44
+ .selectFrom('data_type as d')
45
+ .innerJoin('node as n', 'n.id', 'd.node_id')
46
+ .select([
47
+ 'n.unique_id',
48
+ 'n.text',
49
+ 'n.parent_id',
50
+ 'd.alias',
51
+ 'd.editor_alias',
52
+ 'd.editor_ui_alias',
53
+ 'd.db_type',
54
+ 'd.config',
55
+ ])
56
+ .where('n.unique_id', '=', normaliseUuid(key))
57
+ .execute()
49
58
  const row = rows[0]
50
59
  if (!row) return undefined
51
60
  const parent =
@@ -63,10 +72,12 @@ export class DataTypeRepository {
63
72
  }
64
73
 
65
74
  async byAlias(alias: string): Promise<DataTypeModel | undefined> {
66
- const rows = await this.#db.query<{ unique_id: string }>(
67
- 'SELECT n.unique_id FROM data_type d JOIN node n ON n.id = d.node_id WHERE d.alias = ?',
68
- [alias],
69
- )
75
+ const rows = await this.#db.q
76
+ .selectFrom('data_type as d')
77
+ .innerJoin('node as n', 'n.id', 'd.node_id')
78
+ .select('n.unique_id')
79
+ .where('d.alias', '=', alias)
80
+ .execute()
70
81
  return rows[0] ? this.byKey(String(rows[0].unique_id)) : undefined
71
82
  }
72
83
 
@@ -81,11 +92,12 @@ export class DataTypeRepository {
81
92
 
82
93
  /** The storage type, which decides which `property_data` column a value uses. */
83
94
  async storageTypeByPropertyTypeId(propertyTypeId: number): Promise<string | undefined> {
84
- const rows = await this.#db.query<{ db_type: string }>(
85
- `SELECT d.db_type FROM property_type p JOIN data_type d ON d.node_id = p.data_type_id
86
- WHERE p.id = ?`,
87
- [propertyTypeId],
88
- )
95
+ const rows = await this.#db.q
96
+ .selectFrom('property_type as p')
97
+ .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
98
+ .select('d.db_type')
99
+ .where('p.id', '=', propertyTypeId)
100
+ .execute()
89
101
  return rows[0] ? String(rows[0].db_type) : undefined
90
102
  }
91
103
 
@@ -100,9 +112,12 @@ export class DataTypeRepository {
100
112
  }
101
113
 
102
114
  async all(): Promise<DataTypeModel[]> {
103
- const rows = await this.#db.query<{ unique_id: string }>(
104
- 'SELECT n.unique_id FROM data_type d JOIN node n ON n.id = d.node_id ORDER BY n.text',
105
- )
115
+ const rows = await this.#db.q
116
+ .selectFrom('data_type as d')
117
+ .innerJoin('node as n', 'n.id', 'd.node_id')
118
+ .select('n.unique_id')
119
+ .orderBy('n.text')
120
+ .execute()
106
121
  return this.byKeys(rows.map((r) => String(r.unique_id)))
107
122
  }
108
123
 
@@ -125,7 +140,7 @@ export class DataTypeRepository {
125
140
  async isUsed(key: string): Promise<boolean | undefined> {
126
141
  const node = await this.#nodes.byKey(key)
127
142
  if (!node || node.objectType !== ObjectTypes.DataType) return undefined
128
- return this.#hasValues('p.data_type_id = ?', [node.id])
143
+ return this.#hasValues('p.data_type_id', node.id)
129
144
  }
130
145
 
131
146
  /**
@@ -133,29 +148,39 @@ export class DataTypeRepository {
133
148
  * undefined when the type or the property does not exist.
134
149
  */
135
150
  async isPropertyUsed(contentTypeKey: string, alias: string): Promise<boolean | undefined> {
136
- const rows = await this.#db.query<{ id: number }>(
137
- `SELECT p.id FROM property_type p
138
- JOIN node ctn ON ctn.id = p.content_type_id
139
- WHERE ctn.unique_id = ? AND p.alias = ? AND p.retired_at IS NULL`,
140
- [normaliseUuid(contentTypeKey), alias],
141
- )
151
+ const rows = await this.#db.q
152
+ .selectFrom('property_type as p')
153
+ .innerJoin('node as ctn', 'ctn.id', 'p.content_type_id')
154
+ .select('p.id')
155
+ .where('ctn.unique_id', '=', normaliseUuid(contentTypeKey))
156
+ .where('p.alias', '=', alias)
157
+ .where('p.retired_at', 'is', null)
158
+ .execute()
142
159
  const property = rows[0]
143
160
  if (!property) return undefined
144
- return this.#hasValues('p.id = ?', [Number(property.id)])
161
+ return this.#hasValues('p.id', Number(property.id))
145
162
  }
146
163
 
147
164
  /** A current value that holds something: an empty string or an all-null row is not a use. */
148
- async #hasValues(where: string, params: unknown[]): Promise<boolean> {
149
- const rows = await this.#db.query(
150
- `SELECT 1 AS used FROM property_value v
151
- JOIN property_type p ON p.id = v.property_type_id
152
- WHERE ${where} AND v.is_current = ? AND p.retired_at IS NULL
153
- AND (v.int_value IS NOT NULL OR v.decimal_value IS NOT NULL OR v.date_value IS NOT NULL
154
- OR (v.varchar_value IS NOT NULL AND v.varchar_value <> '')
155
- OR (v.text_value IS NOT NULL AND v.text_value <> ''))
156
- LIMIT 1`,
157
- [...params, this.#db.dialect.boolValue(true)],
158
- )
165
+ async #hasValues(column: 'p.data_type_id' | 'p.id', id: number): Promise<boolean> {
166
+ const rows = await this.#db.q
167
+ .selectFrom('property_value as v')
168
+ .innerJoin('property_type as p', 'p.id', 'v.property_type_id')
169
+ .select((eb) => eb.lit(1).as('used'))
170
+ .where(column, '=', id)
171
+ .where('v.is_current', '=', this.#db.dialect.boolValue(true))
172
+ .where('p.retired_at', 'is', null)
173
+ .where((eb) =>
174
+ eb.or([
175
+ eb('v.int_value', 'is not', null),
176
+ eb('v.decimal_value', 'is not', null),
177
+ eb('v.date_value', 'is not', null),
178
+ eb.and([eb('v.varchar_value', 'is not', null), eb('v.varchar_value', '<>', '')]),
179
+ eb.and([eb('v.text_value', 'is not', null), eb('v.text_value', '<>', '')]),
180
+ ]),
181
+ )
182
+ .limit(1)
183
+ .execute()
159
184
  return rows.length > 0
160
185
  }
161
186
 
@@ -170,15 +195,25 @@ export class DataTypeRepository {
170
195
  > {
171
196
  const node = await this.#nodes.byKey(key)
172
197
  if (!node) return []
173
- const rows = await this.#db.query(
174
- `SELECT p.unique_id, p.alias, p.name, ctn.unique_id AS type_key, ct.alias AS type_alias, ctn.text AS type_name, ct.icon
175
- FROM property_type p
176
- JOIN content_type ct ON ct.node_id = p.content_type_id
177
- JOIN node ctn ON ctn.id = ct.node_id
178
- WHERE p.data_type_id = ? AND p.retired_at IS NULL AND ct.retired_at IS NULL
179
- ORDER BY ctn.text, p.sort_order`,
180
- [node.id],
181
- )
198
+ const rows = await this.#db.q
199
+ .selectFrom('property_type as p')
200
+ .innerJoin('content_type as ct', 'ct.node_id', 'p.content_type_id')
201
+ .innerJoin('node as ctn', 'ctn.id', 'ct.node_id')
202
+ .select([
203
+ 'p.unique_id',
204
+ 'p.alias',
205
+ 'p.name',
206
+ 'ctn.unique_id as type_key',
207
+ 'ct.alias as type_alias',
208
+ 'ctn.text as type_name',
209
+ 'ct.icon',
210
+ ])
211
+ .where('p.data_type_id', '=', node.id)
212
+ .where('p.retired_at', 'is', null)
213
+ .where('ct.retired_at', 'is', null)
214
+ .orderBy('ctn.text')
215
+ .orderBy('p.sort_order')
216
+ .execute()
182
217
  return rows.map((row) => ({
183
218
  propertyKey: normaliseUuid(String(row.unique_id)),
184
219
  alias: String(row.alias),
@@ -222,10 +257,17 @@ export class DataTypeRepository {
222
257
  )
223
258
  if (existing) {
224
259
  await repo.nodes.rename(existing.id, model.name)
225
- await tx.exec(
226
- 'UPDATE data_type SET alias = ?, editor_alias = ?, editor_ui_alias = ?, db_type = ?, config = ? WHERE node_id = ?',
227
- [model.alias, model.editorAlias, model.editorUiAlias, model.dbType, config, existing.id],
228
- )
260
+ await tx.q
261
+ .updateTable('data_type')
262
+ .set({
263
+ alias: model.alias ?? null,
264
+ editor_alias: model.editorAlias,
265
+ editor_ui_alias: model.editorUiAlias ?? null,
266
+ db_type: model.dbType,
267
+ config,
268
+ })
269
+ .where('node_id', '=', existing.id)
270
+ .execute()
229
271
  } else {
230
272
  const parentId = model.parentKey
231
273
  ? ((await repo.nodes.byKey(model.parentKey))?.id ?? SystemNodes.Root)
@@ -237,10 +279,17 @@ export class DataTypeRepository {
237
279
  text: model.name,
238
280
  userId,
239
281
  })
240
- await tx.exec(
241
- 'INSERT INTO data_type (node_id, alias, editor_alias, editor_ui_alias, db_type, config) VALUES (?, ?, ?, ?, ?, ?)',
242
- [node.id, model.alias, model.editorAlias, model.editorUiAlias, model.dbType, config],
243
- )
282
+ await tx.q
283
+ .insertInto('data_type')
284
+ .values({
285
+ node_id: node.id,
286
+ alias: model.alias ?? null,
287
+ editor_alias: model.editorAlias,
288
+ editor_ui_alias: model.editorUiAlias ?? null,
289
+ db_type: model.dbType,
290
+ config,
291
+ })
292
+ .execute()
244
293
  }
245
294
  const saved = await repo.byKey(model.key)
246
295
  if (!saved) throw new Error('Data type could not be read back after saving.')
@@ -252,8 +301,8 @@ export class DataTypeRepository {
252
301
  const node = await this.#nodes.byKey(key)
253
302
  if (!node || node.objectType !== ObjectTypes.DataType) return false
254
303
  return this.#db.transaction(async (tx) => {
255
- await tx.exec('DELETE FROM data_type WHERE node_id = ?', [node.id])
256
- await tx.exec('DELETE FROM node WHERE id = ?', [node.id])
304
+ await tx.q.deleteFrom('data_type').where('node_id', '=', node.id).execute()
305
+ await tx.q.deleteFrom('node').where('id', '=', node.id).execute()
257
306
  return true
258
307
  })
259
308
  }
@@ -43,31 +43,30 @@ export class DeliveryMemberTokenRepository {
43
43
  const { token: value, hash } = newToken()
44
44
  const now = new Date()
45
45
  const expiresAt = new Date(now.getTime() + token.lifetimeMs)
46
- await this.#db.exec(
47
- `INSERT INTO delivery_member_token
48
- (hash, kind, member_key, client_id, scopes, redirect_uri, code_challenge, expires_at, create_date)
49
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
50
- [
46
+ await this.#db.q
47
+ .insertInto('delivery_member_token')
48
+ .values({
51
49
  hash,
52
- token.kind,
53
- token.memberKey,
54
- token.clientId,
55
- token.scopes.join(' '),
56
- token.redirectUri,
57
- token.codeChallenge,
58
- DbDate.toDb(expiresAt),
59
- DbDate.toDb(now),
60
- ],
61
- )
50
+ kind: token.kind,
51
+ member_key: token.memberKey,
52
+ client_id: token.clientId,
53
+ scopes: token.scopes.join(' '),
54
+ redirect_uri: token.redirectUri,
55
+ code_challenge: token.codeChallenge,
56
+ expires_at: DbDate.toDb(expiresAt),
57
+ create_date: DbDate.toDb(now),
58
+ })
59
+ .execute()
62
60
  return { token: value, expiresAt }
63
61
  }
64
62
 
65
63
  /** The token a client presents, whatever its state; the caller judges it. */
66
64
  async find(token: string): Promise<MemberToken | undefined> {
67
- const rows = await this.#db.query('SELECT * FROM delivery_member_token WHERE hash = ?', [
68
- hashToken(token),
69
- ])
70
- const row = rows[0]
65
+ const row = await this.#db.q
66
+ .selectFrom('delivery_member_token')
67
+ .selectAll()
68
+ .where('hash', '=', hashToken(token))
69
+ .executeTakeFirst()
71
70
  if (!row) return undefined
72
71
  return {
73
72
  kind: String(row.kind) as MemberTokenKind,
@@ -85,26 +84,36 @@ export class DeliveryMemberTokenRepository {
85
84
 
86
85
  /** Marks a code or refresh token used; false when it already was, so only one redemption wins. */
87
86
  async redeem(token: string): Promise<boolean> {
88
- const rows = await this.#db.query<{ hash: string }>(
89
- 'UPDATE delivery_member_token SET redeemed_at = ? WHERE hash = ? AND redeemed_at IS NULL RETURNING hash',
90
- [DbDate.toDb(new Date()), hashToken(token)],
91
- )
87
+ const rows = await this.#db.q
88
+ .updateTable('delivery_member_token')
89
+ .set({ redeemed_at: DbDate.toDb(new Date()) })
90
+ .where('hash', '=', hashToken(token))
91
+ .where('redeemed_at', 'is', null)
92
+ .returning('hash')
93
+ .execute()
92
94
  return rows.length > 0
93
95
  }
94
96
 
95
97
  async revoke(token: string): Promise<void> {
96
- await this.#db.exec('DELETE FROM delivery_member_token WHERE hash = ?', [hashToken(token)])
98
+ await this.#db.q
99
+ .deleteFrom('delivery_member_token')
100
+ .where('hash', '=', hashToken(token))
101
+ .execute()
97
102
  }
98
103
 
99
104
  /** Every token a member holds, as signing out ends them. */
100
105
  async revokeMember(memberKey: string): Promise<void> {
101
- await this.#db.exec('DELETE FROM delivery_member_token WHERE member_key = ?', [memberKey])
106
+ await this.#db.q
107
+ .deleteFrom('delivery_member_token')
108
+ .where('member_key', '=', memberKey)
109
+ .execute()
102
110
  }
103
111
 
104
112
  /** Expired tokens, which nothing will accept again. */
105
113
  async purgeExpired(): Promise<void> {
106
- await this.#db.exec('DELETE FROM delivery_member_token WHERE expires_at < ?', [
107
- DbDate.toDb(new Date()),
108
- ])
114
+ await this.#db.q
115
+ .deleteFrom('delivery_member_token')
116
+ .where('expires_at', '<', DbDate.toDb(new Date()))
117
+ .execute()
109
118
  }
110
119
  }
@@ -29,6 +29,15 @@ interface Row {
29
29
  parent_key: string | null
30
30
  }
31
31
 
32
+ function items(db: Db) {
33
+ return db.q
34
+ .selectFrom('dictionary_item')
35
+ .select(['key', 'item_key', 'parent_key'])
36
+ .orderBy('item_key')
37
+ }
38
+
39
+ type Items = ReturnType<typeof items>
40
+
32
41
  export class DictionaryRepository {
33
42
  #db: Db
34
43
 
@@ -36,23 +45,20 @@ export class DictionaryRepository {
36
45
  this.#db = db
37
46
  }
38
47
 
39
- async #rows(where = '', params: unknown[] = []): Promise<Row[]> {
40
- return this.#db.query<Row>(
41
- `SELECT key, item_key, parent_key FROM dictionary_item ${where} ORDER BY item_key`,
42
- params,
43
- )
48
+ async #rows(narrow: (query: Items) => Items = (q) => q): Promise<Row[]> {
49
+ return narrow(items(this.#db)).execute()
44
50
  }
45
51
 
46
52
  async #withTranslations(rows: Row[]): Promise<DictionaryItem[]> {
47
53
  if (rows.length === 0) return []
48
54
  const keys = rows.map((r) => normaliseUuid(String(r.key)))
49
- const texts = await this.#db.query<{ dictionary_key: string; iso_code: string; value: string }>(
50
- `SELECT t.dictionary_key, l.iso_code, t.value FROM dictionary_text t
51
- JOIN language l ON l.id = t.language_id
52
- WHERE t.dictionary_key IN (${keys.map(() => '?').join(', ')})
53
- ORDER BY l.iso_code`,
54
- keys,
55
- )
55
+ const texts = await this.#db.q
56
+ .selectFrom('dictionary_text as t')
57
+ .innerJoin('language as l', 'l.id', 't.language_id')
58
+ .select(['t.dictionary_key', 'l.iso_code', 't.value'])
59
+ .where('t.dictionary_key', 'in', keys)
60
+ .orderBy('l.iso_code')
61
+ .execute()
56
62
  return rows.map((row) => {
57
63
  const key = normaliseUuid(String(row.key))
58
64
  return {
@@ -68,26 +74,28 @@ export class DictionaryRepository {
68
74
 
69
75
  async get(key: string): Promise<DictionaryItem | undefined> {
70
76
  return (
71
- await this.#withTranslations(await this.#rows('WHERE key = ?', [normaliseUuid(key)]))
77
+ await this.#withTranslations(await this.#rows((q) => q.where('key', '=', normaliseUuid(key))))
72
78
  )[0]
73
79
  }
74
80
 
75
81
  async byName(name: string): Promise<DictionaryItem | undefined> {
76
- return (await this.#withTranslations(await this.#rows('WHERE item_key = ?', [name])))[0]
82
+ return (
83
+ await this.#withTranslations(await this.#rows((q) => q.where('item_key', '=', name)))
84
+ )[0]
77
85
  }
78
86
 
79
87
  async many(keys: readonly string[]): Promise<DictionaryItem[]> {
80
88
  const wanted = keys.filter((k) => /^[0-9a-f-]{32,36}$/i.test(k)).map(normaliseUuid)
81
89
  if (wanted.length === 0) return []
82
- return this.#withTranslations(
83
- await this.#rows(`WHERE key IN (${wanted.map(() => '?').join(', ')})`, wanted),
84
- )
90
+ return this.#withTranslations(await this.#rows((q) => q.where('key', 'in', wanted)))
85
91
  }
86
92
 
87
93
  /** Every item, or those whose key contains `filter`, in tree order by key. */
88
94
  async all(filter?: string): Promise<DictionaryItem[]> {
89
95
  const rows = filter
90
- ? await this.#rows('WHERE LOWER(item_key) LIKE ?', [`%${filter.toLowerCase()}%`])
96
+ ? await this.#rows((q) =>
97
+ q.where((eb) => eb(eb.fn('lower', ['item_key']), 'like', `%${filter.toLowerCase()}%`)),
98
+ )
91
99
  : await this.#rows()
92
100
  return this.#withTranslations(rows)
93
101
  }
@@ -96,13 +104,16 @@ export class DictionaryRepository {
96
104
  parentKey: string | null,
97
105
  ): Promise<Array<{ key: string; name: string; parentKey: string | null; hasChildren: boolean }>> {
98
106
  const rows = parentKey
99
- ? await this.#rows('WHERE parent_key = ?', [normaliseUuid(parentKey)])
100
- : await this.#rows('WHERE parent_key IS NULL')
107
+ ? await this.#rows((q) => q.where('parent_key', '=', normaliseUuid(parentKey)))
108
+ : await this.#rows((q) => q.where('parent_key', 'is', null))
101
109
  const parents = new Set(
102
110
  (
103
- await this.#db.query<{ parent_key: string }>(
104
- 'SELECT DISTINCT parent_key FROM dictionary_item WHERE parent_key IS NOT NULL',
105
- )
111
+ await this.#db.q
112
+ .selectFrom('dictionary_item')
113
+ .select('parent_key')
114
+ .distinct()
115
+ .where('parent_key', 'is not', null)
116
+ .execute()
106
117
  ).map((r) => normaliseUuid(String(r.parent_key))),
107
118
  )
108
119
  return rows.map((row) => {
@@ -132,7 +143,7 @@ export class DictionaryRepository {
132
143
  const queue = [normaliseUuid(key)]
133
144
  while (queue.length > 0) {
134
145
  const next = queue.shift() as string
135
- for (const child of await this.#rows('WHERE parent_key = ?', [next])) {
146
+ for (const child of await this.#rows((q) => q.where('parent_key', '=', next))) {
136
147
  const childKey = normaliseUuid(String(child.key))
137
148
  out.push(childKey)
138
149
  queue.push(childKey)
@@ -144,9 +155,7 @@ export class DictionaryRepository {
144
155
  async #languageIds(
145
156
  translations: readonly DictionaryTranslation[],
146
157
  ): Promise<Map<string, number> | undefined> {
147
- const languages = await this.#db.query<{ id: number; iso_code: string }>(
148
- 'SELECT id, iso_code FROM language',
149
- )
158
+ const languages = await this.#db.q.selectFrom('language').select(['id', 'iso_code']).execute()
150
159
  const byIso = new Map(languages.map((l) => [String(l.iso_code).toLowerCase(), Number(l.id)]))
151
160
  const ids = new Map<string, number>()
152
161
  for (const t of translations) {
@@ -162,12 +171,16 @@ export class DictionaryRepository {
162
171
  translations: readonly DictionaryTranslation[],
163
172
  ids: Map<string, number>,
164
173
  ): Promise<void> {
165
- await this.#db.exec('DELETE FROM dictionary_text WHERE dictionary_key = ?', [key])
174
+ await this.#db.q.deleteFrom('dictionary_text').where('dictionary_key', '=', key).execute()
166
175
  for (const t of translations)
167
- await this.#db.exec(
168
- 'INSERT INTO dictionary_text (dictionary_key, language_id, value) VALUES (?, ?, ?)',
169
- [key, ids.get(t.isoCode), t.translation],
170
- )
176
+ await this.#db.q
177
+ .insertInto('dictionary_text')
178
+ .values({
179
+ dictionary_key: key,
180
+ language_id: ids.get(t.isoCode) as number,
181
+ value: t.translation,
182
+ })
183
+ .execute()
171
184
  }
172
185
 
173
186
  async create(item: DictionaryItem): Promise<DictionaryWriteResult> {
@@ -179,11 +192,14 @@ export class DictionaryRepository {
179
192
  if (item.parentKey && !(await repo.get(item.parentKey))) return 'ParentNotFound'
180
193
  const ids = await repo.#languageIds(item.translations)
181
194
  if (!ids) return 'InvalidLanguage'
182
- await tx.exec('INSERT INTO dictionary_item (key, parent_key, item_key) VALUES (?, ?, ?)', [
183
- key,
184
- item.parentKey ? normaliseUuid(item.parentKey) : null,
185
- item.name,
186
- ])
195
+ await tx.q
196
+ .insertInto('dictionary_item')
197
+ .values({
198
+ key,
199
+ parent_key: item.parentKey ? normaliseUuid(item.parentKey) : null,
200
+ item_key: item.name,
201
+ })
202
+ .execute()
187
203
  await repo.#writeTranslations(key, item.translations, ids)
188
204
  return 'Success'
189
205
  })
@@ -201,7 +217,11 @@ export class DictionaryRepository {
201
217
  if (clash && clash.key !== k) return 'DuplicateItemKey'
202
218
  const ids = await repo.#languageIds(change.translations)
203
219
  if (!ids) return 'InvalidLanguage'
204
- await tx.exec('UPDATE dictionary_item SET item_key = ? WHERE key = ?', [change.name, k])
220
+ await tx.q
221
+ .updateTable('dictionary_item')
222
+ .set({ item_key: change.name })
223
+ .where('key', '=', k)
224
+ .execute()
205
225
  await repo.#writeTranslations(k, change.translations, ids)
206
226
  return 'Success'
207
227
  })
@@ -217,10 +237,11 @@ export class DictionaryRepository {
217
237
  if (!(await repo.get(parent))) return 'ParentNotFound'
218
238
  if (parent === k || (await repo.#descendantKeys(k)).includes(parent)) return 'InvalidParent'
219
239
  }
220
- await tx.exec('UPDATE dictionary_item SET parent_key = ? WHERE key = ?', [
221
- parentKey ? normaliseUuid(parentKey) : null,
222
- k,
223
- ])
240
+ await tx.q
241
+ .updateTable('dictionary_item')
242
+ .set({ parent_key: parentKey ? normaliseUuid(parentKey) : null })
243
+ .where('key', '=', k)
244
+ .execute()
224
245
  return 'Success'
225
246
  })
226
247
  }
@@ -233,8 +254,8 @@ export class DictionaryRepository {
233
254
  if (!(await repo.get(k))) return 'NotFound'
234
255
  const doomed = [...(await repo.#descendantKeys(k)).reverse(), k]
235
256
  for (const d of doomed) {
236
- await tx.exec('DELETE FROM dictionary_text WHERE dictionary_key = ?', [d])
237
- await tx.exec('DELETE FROM dictionary_item WHERE key = ?', [d])
257
+ await tx.q.deleteFrom('dictionary_text').where('dictionary_key', '=', d).execute()
258
+ await tx.q.deleteFrom('dictionary_item').where('key', '=', d).execute()
238
259
  }
239
260
  return 'Success'
240
261
  })
@@ -242,15 +263,12 @@ export class DictionaryRepository {
242
263
 
243
264
  /** Every item's key, name and parent's name, for a choice list drawn from the dictionary. */
244
265
  async outline(): Promise<Array<{ key: string; name: string; parentName: string | null }>> {
245
- const rows = await this.#db.query<{
246
- key: string
247
- item_key: string
248
- parent_name: string | null
249
- }>(
250
- `SELECT d.key, d.item_key, p.item_key AS parent_name FROM dictionary_item d
251
- LEFT JOIN dictionary_item p ON p.key = d.parent_key
252
- ORDER BY d.item_key`,
253
- )
266
+ const rows = await this.#db.q
267
+ .selectFrom('dictionary_item as d')
268
+ .leftJoin('dictionary_item as p', 'p.key', 'd.parent_key')
269
+ .select(['d.key', 'd.item_key', 'p.item_key as parent_name'])
270
+ .orderBy('d.item_key')
271
+ .execute()
254
272
  return rows.map((row) => ({
255
273
  key: normaliseUuid(String(row.key)),
256
274
  name: String(row.item_key),
@@ -260,11 +278,12 @@ export class DictionaryRepository {
260
278
 
261
279
  /** Every translation, keyed by item name then iso code, for rendering. */
262
280
  async translations(): Promise<Map<string, Map<string, string>>> {
263
- const rows = await this.#db.query<{ item_key: string; iso_code: string; value: string }>(
264
- `SELECT d.item_key, l.iso_code, t.value FROM dictionary_item d
265
- JOIN dictionary_text t ON t.dictionary_key = d.key
266
- JOIN language l ON l.id = t.language_id`,
267
- )
281
+ const rows = await this.#db.q
282
+ .selectFrom('dictionary_item as d')
283
+ .innerJoin('dictionary_text as t', 't.dictionary_key', 'd.key')
284
+ .innerJoin('language as l', 'l.id', 't.language_id')
285
+ .select(['d.item_key', 'l.iso_code', 't.value'])
286
+ .execute()
268
287
  const out = new Map<string, Map<string, string>>()
269
288
  for (const row of rows) {
270
289
  const name = String(row.item_key)