@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
@@ -42,12 +42,19 @@ interface EntryRow {
42
42
  error_key: string
43
43
  }
44
44
 
45
- const SELECT = `SELECT a.id, a.key,
46
- n.unique_id AS node_key, l.unique_id AS login_key, e.unique_id AS error_key
47
- FROM public_access a
48
- JOIN node n ON n.id = a.node_id
49
- JOIN node l ON l.id = a.login_node_id
50
- JOIN node e ON e.id = a.error_node_id`
45
+ const entries = (db: Db) =>
46
+ db.q
47
+ .selectFrom('public_access as a')
48
+ .innerJoin('node as n', 'n.id', 'a.node_id')
49
+ .innerJoin('node as l', 'l.id', 'a.login_node_id')
50
+ .innerJoin('node as e', 'e.id', 'a.error_node_id')
51
+ .select([
52
+ 'a.id',
53
+ 'a.key',
54
+ 'n.unique_id as node_key',
55
+ 'l.unique_id as login_key',
56
+ 'e.unique_id as error_key',
57
+ ])
51
58
 
52
59
  export class PublicAccessRepository {
53
60
  #db: Db
@@ -59,10 +66,12 @@ export class PublicAccessRepository {
59
66
  }
60
67
 
61
68
  async #rules(id: number): Promise<{ groups: string[]; users: string[] }> {
62
- const rows = await this.#db.query<{ rule_type: string; rule_value: string }>(
63
- 'SELECT rule_type, rule_value FROM public_access_rule WHERE public_access_id = ? ORDER BY rule_value',
64
- [id],
65
- )
69
+ const rows = await this.#db.q
70
+ .selectFrom('public_access_rule')
71
+ .select(['rule_type', 'rule_value'])
72
+ .where('public_access_id', '=', id)
73
+ .orderBy('rule_value')
74
+ .execute()
66
75
  return {
67
76
  groups: rows
68
77
  .filter((r) => r.rule_type === MEMBER_GROUP_RULE)
@@ -92,16 +101,13 @@ export class PublicAccessRepository {
92
101
  async allRules(): Promise<
93
102
  Array<{ nodeId: number; memberGroupNames: string[]; memberUserNames: string[] }>
94
103
  > {
95
- const entries = await this.#db.query<{ id: number; node_id: number }>(
96
- 'SELECT id, node_id FROM public_access',
97
- )
98
- if (entries.length === 0) return []
99
- const rules = await this.#db.query<{
100
- public_access_id: number
101
- rule_type: string
102
- rule_value: string
103
- }>('SELECT public_access_id, rule_type, rule_value FROM public_access_rule')
104
- return entries.map((entry) => {
104
+ const all = await this.#db.q.selectFrom('public_access').select(['id', 'node_id']).execute()
105
+ if (all.length === 0) return []
106
+ const rules = await this.#db.q
107
+ .selectFrom('public_access_rule')
108
+ .select(['public_access_id', 'rule_type', 'rule_value'])
109
+ .execute()
110
+ return all.map((entry) => {
105
111
  const own = rules.filter((r) => Number(r.public_access_id) === Number(entry.id))
106
112
  return {
107
113
  nodeId: Number(entry.node_id),
@@ -117,10 +123,10 @@ export class PublicAccessRepository {
117
123
 
118
124
  /** The entry protecting this page itself, if any. */
119
125
  async byNodeKey(nodeKey: string): Promise<PublicAccessEntry | undefined> {
120
- const rows = await this.#db.query<EntryRow>(`${SELECT} WHERE n.unique_id = ?`, [
121
- normaliseUuid(nodeKey),
122
- ])
123
- return rows[0] ? this.#hydrate(rows[0]) : undefined
126
+ const row = await entries(this.#db)
127
+ .where('n.unique_id', '=', normaliseUuid(nodeKey))
128
+ .executeTakeFirst()
129
+ return row ? this.#hydrate(row) : undefined
124
130
  }
125
131
 
126
132
  /**
@@ -137,12 +143,12 @@ export class PublicAccessRepository {
137
143
  .map((part) => Number(part))
138
144
  .filter((id) => Number.isFinite(id))
139
145
  if (ids.length === 0) return undefined
140
- const holes = ids.map(() => '?').join(', ')
141
- const rows = await this.#db.query<EntryRow>(
142
- `${SELECT} WHERE a.node_id IN (${holes}) ORDER BY n.level DESC LIMIT 1`,
143
- [...ids],
144
- )
145
- return rows[0] ? this.#hydrate(rows[0]) : undefined
146
+ const row = await entries(this.#db)
147
+ .where('a.node_id', 'in', ids)
148
+ .orderBy('n.level', 'desc')
149
+ .limit(1)
150
+ .executeTakeFirst()
151
+ return row ? this.#hydrate(row) : undefined
146
152
  }
147
153
 
148
154
  /** Whether an ancestor above this page is protected, which the editor shows. */
@@ -162,39 +168,48 @@ export class PublicAccessRepository {
162
168
  if (!node || !login || !error) return undefined
163
169
  const now = DbDate.toDb(new Date())
164
170
  await this.#db.transaction(async (tx) => {
165
- const existing = await tx.query<{ id: number }>(
166
- 'SELECT id FROM public_access WHERE node_id = ?',
167
- [node.id],
168
- )
169
- let id = existing[0] ? Number(existing[0].id) : undefined
171
+ const existing = await tx.q
172
+ .selectFrom('public_access')
173
+ .select('id')
174
+ .where('node_id', '=', node.id)
175
+ .executeTakeFirst()
176
+ let id = existing ? Number(existing.id) : undefined
170
177
  if (id === undefined) {
171
178
  const key = crypto.randomUUID()
172
- await tx.exec(
173
- `INSERT INTO public_access (key, node_id, login_node_id, error_node_id, create_date, update_date)
174
- VALUES (?, ?, ?, ?, ?, ?)`,
175
- [key, node.id, login.id, error.id, now, now],
176
- )
177
- const created = await tx.query<{ id: number }>(
178
- 'SELECT id FROM public_access WHERE node_id = ?',
179
- [node.id],
180
- )
181
- id = Number(created[0]?.id)
179
+ await tx.q
180
+ .insertInto('public_access')
181
+ .values({
182
+ key,
183
+ node_id: node.id,
184
+ login_node_id: login.id,
185
+ error_node_id: error.id,
186
+ create_date: now,
187
+ update_date: now,
188
+ })
189
+ .execute()
190
+ const created = await tx.q
191
+ .selectFrom('public_access')
192
+ .select('id')
193
+ .where('node_id', '=', node.id)
194
+ .executeTakeFirst()
195
+ id = Number(created?.id)
182
196
  } else {
183
- await tx.exec(
184
- 'UPDATE public_access SET login_node_id = ?, error_node_id = ?, update_date = ? WHERE id = ?',
185
- [login.id, error.id, now, id],
186
- )
187
- await tx.exec('DELETE FROM public_access_rule WHERE public_access_id = ?', [id])
197
+ await tx.q
198
+ .updateTable('public_access')
199
+ .set({ login_node_id: login.id, error_node_id: error.id, update_date: now })
200
+ .where('id', '=', id)
201
+ .execute()
202
+ await tx.q.deleteFrom('public_access_rule').where('public_access_id', '=', id).execute()
188
203
  }
189
204
  for (const [type, names] of [
190
205
  [MEMBER_GROUP_RULE, input.memberGroupNames],
191
206
  [MEMBER_USERNAME_RULE, input.memberUserNames],
192
207
  ] as const) {
193
208
  for (const name of new Set(names.filter((value) => value.trim() !== ''))) {
194
- await tx.exec(
195
- 'INSERT INTO public_access_rule (public_access_id, rule_type, rule_value, create_date) VALUES (?, ?, ?, ?)',
196
- [id, type, name, now],
197
- )
209
+ await tx.q
210
+ .insertInto('public_access_rule')
211
+ .values({ public_access_id: id, rule_type: type, rule_value: name, create_date: now })
212
+ .execute()
198
213
  }
199
214
  }
200
215
  })
@@ -204,14 +219,15 @@ export class PublicAccessRepository {
204
219
  async remove(nodeKey: string): Promise<boolean> {
205
220
  const node = await this.#nodes.byKey(nodeKey)
206
221
  if (!node) return false
207
- const rows = await this.#db.query<{ id: number }>(
208
- 'SELECT id FROM public_access WHERE node_id = ?',
209
- [node.id],
210
- )
211
- const id = rows[0]?.id
222
+ const row = await this.#db.q
223
+ .selectFrom('public_access')
224
+ .select('id')
225
+ .where('node_id', '=', node.id)
226
+ .executeTakeFirst()
227
+ const id = row?.id
212
228
  if (id === undefined) return false
213
- await this.#db.exec('DELETE FROM public_access_rule WHERE public_access_id = ?', [id])
214
- await this.#db.exec('DELETE FROM public_access WHERE id = ?', [id])
229
+ await this.#db.q.deleteFrom('public_access_rule').where('public_access_id', '=', id).execute()
230
+ await this.#db.q.deleteFrom('public_access').where('id', '=', id).execute()
215
231
  return true
216
232
  }
217
233
  }
@@ -14,8 +14,11 @@
14
14
  * ends up behaving without the duplicates.
15
15
  */
16
16
  import { normaliseUuid } from '@crombolo/core'
17
+ import type { SelectQueryBuilder } from 'kysely'
17
18
  import type { Db } from '../database.ts'
18
19
  import { DbDate } from '../dialect.ts'
20
+ import { sql } from '../query.ts'
21
+ import type { CoreTables } from '../tables.gen.ts'
19
22
 
20
23
  export type RedirectMatchKind = 'exact' | 'prefix' | 'regex'
21
24
  export type RedirectTargetKind = 'document' | 'path' | 'url'
@@ -59,12 +62,30 @@ interface Row {
59
62
  create_date: unknown
60
63
  }
61
64
 
62
- const SELECT = `SELECT key, source, match_kind, pattern, root_key, culture,
63
- target_kind, target, status_code, sort_order, create_date
64
- FROM redirect_url`
65
+ const COLUMNS = [
66
+ 'key',
67
+ 'source',
68
+ 'match_kind',
69
+ 'pattern',
70
+ 'root_key',
71
+ 'culture',
72
+ 'target_kind',
73
+ 'target',
74
+ 'status_code',
75
+ 'sort_order',
76
+ 'create_date',
77
+ ] as const
78
+
79
+ const selectRules = (db: Db) => db.q.selectFrom('redirect_url').select(COLUMNS)
65
80
 
66
81
  /** By source — see `RedirectSource` — then by the rule's own order, newest first. */
67
- const ORDER = 'ORDER BY source, sort_order, create_date DESC, id DESC'
82
+ // biome-ignore lint/suspicious/noExplicitAny: any select over redirect_url
83
+ const ordered = <Q extends SelectQueryBuilder<CoreTables, 'redirect_url', any>>(query: Q): Q =>
84
+ query
85
+ .orderBy('source')
86
+ .orderBy('sort_order')
87
+ .orderBy('create_date', 'desc')
88
+ .orderBy('id', 'desc') as Q
68
89
 
69
90
  const hydrate = (row: Row): RedirectRow => ({
70
91
  key: normaliseUuid(String(row.key)),
@@ -107,13 +128,13 @@ export class RedirectRepository {
107
128
 
108
129
  /** Every rule, in the order they are matched. */
109
130
  async all(): Promise<RedirectRow[]> {
110
- const rows = await this.#db.query<Row>(`${SELECT} ${ORDER}`)
131
+ const rows = await selectRules(this.#db).$call(ordered).execute()
111
132
  return rows.map(hydrate)
112
133
  }
113
134
 
114
135
  async byKey(key: string): Promise<RedirectRow | undefined> {
115
- const rows = await this.#db.query<Row>(`${SELECT} WHERE key = ?`, [normaliseUuid(key)])
116
- return rows[0] ? hydrate(rows[0]) : undefined
136
+ const row = await selectRules(this.#db).where('key', '=', normaliseUuid(key)).executeTakeFirst()
137
+ return row ? hydrate(row) : undefined
117
138
  }
118
139
 
119
140
  /**
@@ -127,18 +148,29 @@ export class RedirectRepository {
127
148
  items: RedirectRow[]
128
149
  }> {
129
150
  const filter = options.filter?.trim().toLowerCase()
130
- const where = filter ? 'WHERE LOWER(pattern) LIKE ? OR LOWER(target) LIKE ?' : ''
131
- const params = filter ? [`%${filter}%`, `%${filter}%`] : []
132
- const counted = await this.#db.query<{ total: number }>(
133
- `SELECT COUNT(*) AS total FROM redirect_url ${where}`,
134
- params,
135
- )
136
- const rows = await this.#db.query<Row>(`${SELECT} ${where} ${ORDER} LIMIT ? OFFSET ?`, [
137
- ...params,
138
- options.take ?? 100,
139
- options.skip ?? 0,
140
- ])
141
- return { total: Number(counted[0]?.total ?? 0), items: rows.map(hydrate) }
151
+ const matching = <Q extends SelectQueryBuilder<CoreTables, 'redirect_url', object>>(
152
+ query: Q,
153
+ ): Q =>
154
+ filter
155
+ ? (query.where((eb) =>
156
+ eb.or([
157
+ eb(eb.fn('lower', ['pattern']), 'like', `%${filter}%`),
158
+ eb(eb.fn('lower', ['target']), 'like', `%${filter}%`),
159
+ ]),
160
+ ) as Q)
161
+ : query
162
+ const counted = await this.#db.q
163
+ .selectFrom('redirect_url')
164
+ .select(sql<number>`count(*)`.as('total'))
165
+ .$call(matching)
166
+ .executeTakeFirst()
167
+ const rows = await selectRules(this.#db)
168
+ .$call(matching)
169
+ .$call(ordered)
170
+ .limit(options.take ?? 100)
171
+ .offset(options.skip ?? 0)
172
+ .execute()
173
+ return { total: Number(counted?.total ?? 0), items: rows.map(hydrate) }
142
174
  }
143
175
 
144
176
  /** The rules pointing at one document, newest first. */
@@ -147,17 +179,24 @@ export class RedirectRepository {
147
179
  options: { skip?: number; take?: number } = {},
148
180
  ): Promise<{ total: number; items: RedirectRow[] }> {
149
181
  const target = normaliseUuid(documentKey)
150
- const where = "WHERE target_kind = 'document' AND LOWER(target) = ?"
151
- const counted = await this.#db.query<{ total: number }>(
152
- `SELECT COUNT(*) AS total FROM redirect_url ${where}`,
153
- [target],
154
- )
155
- const rows = await this.#db.query<Row>(`${SELECT} ${where} ${ORDER} LIMIT ? OFFSET ?`, [
156
- target,
157
- options.take ?? 100,
158
- options.skip ?? 0,
159
- ])
160
- return { total: Number(counted[0]?.total ?? 0), items: rows.map(hydrate) }
182
+ const pointing = <Q extends SelectQueryBuilder<CoreTables, 'redirect_url', object>>(
183
+ query: Q,
184
+ ): Q =>
185
+ query
186
+ .where('target_kind', '=', 'document')
187
+ .where((eb) => eb(eb.fn('lower', ['target']), '=', target)) as Q
188
+ const counted = await this.#db.q
189
+ .selectFrom('redirect_url')
190
+ .select(sql<number>`count(*)`.as('total'))
191
+ .$call(pointing)
192
+ .executeTakeFirst()
193
+ const rows = await selectRules(this.#db)
194
+ .$call(pointing)
195
+ .$call(ordered)
196
+ .limit(options.take ?? 100)
197
+ .offset(options.skip ?? 0)
198
+ .execute()
199
+ return { total: Number(counted?.total ?? 0), items: rows.map(hydrate) }
161
200
  }
162
201
 
163
202
  /**
@@ -171,39 +210,41 @@ export class RedirectRepository {
171
210
  async save(input: RedirectInput): Promise<RedirectRow> {
172
211
  const hash = matchHash(input)
173
212
  const now = new Date()
174
- const rows = await this.#db.query<{ key: string }>(
175
- `INSERT INTO redirect_url
176
- (key, source, match_kind, pattern, root_key, culture,
177
- target_kind, target, status_code, sort_order, match_hash, create_date)
178
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
179
- ON CONFLICT (match_hash) DO UPDATE SET
180
- target_kind = excluded.target_kind, target = excluded.target,
181
- status_code = excluded.status_code, sort_order = excluded.sort_order,
182
- create_date = excluded.create_date
183
- RETURNING key`,
184
- [
185
- crypto.randomUUID(),
186
- input.source,
187
- input.matchKind,
188
- input.pattern,
189
- input.rootKey,
190
- input.culture,
191
- input.targetKind,
192
- input.target,
193
- input.statusCode,
194
- input.sortOrder,
195
- hash,
196
- DbDate.toDb(now),
197
- ],
198
- )
199
- return { ...input, key: normaliseUuid(String(rows[0]?.key)), createDate: now }
213
+ const row = await this.#db.q
214
+ .insertInto('redirect_url')
215
+ .values({
216
+ key: crypto.randomUUID(),
217
+ source: input.source,
218
+ match_kind: input.matchKind,
219
+ pattern: input.pattern,
220
+ root_key: input.rootKey,
221
+ culture: input.culture,
222
+ target_kind: input.targetKind,
223
+ target: input.target,
224
+ status_code: input.statusCode,
225
+ sort_order: input.sortOrder,
226
+ match_hash: hash,
227
+ create_date: DbDate.toDb(now),
228
+ })
229
+ .onConflict((oc) =>
230
+ oc.column('match_hash').doUpdateSet((eb) => ({
231
+ target_kind: eb.ref('excluded.target_kind'),
232
+ target: eb.ref('excluded.target'),
233
+ status_code: eb.ref('excluded.status_code'),
234
+ sort_order: eb.ref('excluded.sort_order'),
235
+ create_date: eb.ref('excluded.create_date'),
236
+ })),
237
+ )
238
+ .returning('key')
239
+ .executeTakeFirst()
240
+ return { ...input, key: normaliseUuid(String(row?.key)), createDate: now }
200
241
  }
201
242
 
202
243
  /** Deletes one rule. `false` means there was nothing with that key. */
203
244
  async delete(key: string): Promise<boolean> {
204
245
  const found = await this.byKey(key)
205
246
  if (!found) return false
206
- await this.#db.exec('DELETE FROM redirect_url WHERE key = ?', [normaliseUuid(key)])
247
+ await this.#db.q.deleteFrom('redirect_url').where('key', '=', normaliseUuid(key)).execute()
207
248
  return true
208
249
  }
209
250
 
@@ -217,15 +258,15 @@ export class RedirectRepository {
217
258
  rootKey: string | null,
218
259
  path: string,
219
260
  ): Promise<void> {
220
- await this.#db.exec(
221
- `DELETE FROM redirect_url
222
- WHERE source = 'tracked' AND target_kind = 'document'
223
- AND LOWER(target) = ? AND match_kind = 'exact' AND LOWER(pattern) = ?
224
- AND ${rootKey === null ? 'root_key IS NULL' : 'root_key = ?'}`,
225
- rootKey === null
226
- ? [normaliseUuid(documentKey), path.toLowerCase()]
227
- : [normaliseUuid(documentKey), path.toLowerCase(), rootKey],
228
- )
261
+ await this.#db.q
262
+ .deleteFrom('redirect_url')
263
+ .where('source', '=', 'tracked')
264
+ .where('target_kind', '=', 'document')
265
+ .where((eb) => eb(eb.fn('lower', ['target']), '=', normaliseUuid(documentKey)))
266
+ .where('match_kind', '=', 'exact')
267
+ .where((eb) => eb(eb.fn('lower', ['pattern']), '=', path.toLowerCase()))
268
+ .where('root_key', rootKey === null ? 'is' : '=', rootKey)
269
+ .execute()
229
270
  }
230
271
 
231
272
  /**
@@ -244,14 +285,16 @@ export class RedirectRepository {
244
285
  kept.add(matchHash(rule))
245
286
  await this.save(rule)
246
287
  }
247
- const stale = await this.#db.query<{ match_hash: string }>(
248
- "SELECT match_hash FROM redirect_url WHERE source = 'config'",
249
- )
288
+ const stale = await this.#db.q
289
+ .selectFrom('redirect_url')
290
+ .select('match_hash')
291
+ .where('source', '=', 'config')
292
+ .execute()
250
293
  let removed = 0
251
294
  for (const row of stale) {
252
295
  const hash = String(row.match_hash)
253
296
  if (kept.has(hash)) continue
254
- await this.#db.exec('DELETE FROM redirect_url WHERE match_hash = ?', [hash])
297
+ await this.#db.q.deleteFrom('redirect_url').where('match_hash', '=', hash).execute()
255
298
  removed += 1
256
299
  }
257
300
  return { stored: kept.size, removed }
@@ -42,14 +42,22 @@ export class ReferenceRepository {
42
42
  const found = new Map<string, number[]>()
43
43
  for (const key of keys) {
44
44
  const [dashed, plain] = patterns(key)
45
- const rows = await this.#db.query<{ id: number }>(
46
- `SELECT DISTINCT pv.node_id AS id
47
- FROM property_value pv
48
- WHERE pv.is_current = ?
49
- AND ( LOWER(pv.varchar_value) LIKE ? OR LOWER(pv.text_value) LIKE ?
50
- OR LOWER(pv.varchar_value) LIKE ? OR LOWER(pv.text_value) LIKE ? )`,
51
- [this.#db.dialect.boolValue(true), dashed, dashed, plain, plain],
52
- )
45
+ const rows = await this.#db.q
46
+ .selectFrom('property_value as pv')
47
+ .select('pv.node_id as id')
48
+ .distinct()
49
+ .where('pv.is_current', '=', this.#db.dialect.boolValue(true))
50
+ .where((eb) => {
51
+ const varchar = eb.fn<string>('lower', ['pv.varchar_value'])
52
+ const text = eb.fn<string>('lower', ['pv.text_value'])
53
+ return eb.or([
54
+ eb(varchar, 'like', dashed),
55
+ eb(text, 'like', dashed),
56
+ eb(varchar, 'like', plain),
57
+ eb(text, 'like', plain),
58
+ ])
59
+ })
60
+ .execute()
53
61
  found.set(
54
62
  normaliseUuid(key),
55
63
  rows.map((row) => Number(row.id)),
@@ -60,28 +68,24 @@ export class ReferenceRepository {
60
68
 
61
69
  async #describe(ids: readonly number[]): Promise<ReferencingNode[]> {
62
70
  if (ids.length === 0) return []
63
- const holes = ids.map(() => '?').join(', ')
64
- const rows = await this.#db.query<{
65
- unique_id: string
66
- text: string | null
67
- node_object_type: string | null
68
- published: unknown
69
- type_key: string | null
70
- type_alias: string | null
71
- type_icon: string | null
72
- }>(
73
- `SELECT n.unique_id, n.text, n.node_object_type,
74
- d.published AS published,
75
- tn.unique_id AS type_key, ct.alias AS type_alias, ct.icon AS type_icon
76
- FROM node n
77
- LEFT JOIN content c ON c.node_id = n.id
78
- LEFT JOIN content_type ct ON ct.node_id = c.content_type_id
79
- LEFT JOIN node tn ON tn.id = ct.node_id
80
- LEFT JOIN document d ON d.node_id = n.id
81
- WHERE n.id IN (${holes})
82
- ORDER BY n.text`,
83
- [...ids],
84
- )
71
+ const rows = await this.#db.q
72
+ .selectFrom('node as n')
73
+ .leftJoin('content as c', 'c.node_id', 'n.id')
74
+ .leftJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
75
+ .leftJoin('node as tn', 'tn.id', 'ct.node_id')
76
+ .leftJoin('document as d', 'd.node_id', 'n.id')
77
+ .select([
78
+ 'n.unique_id',
79
+ 'n.text',
80
+ 'n.node_object_type',
81
+ 'd.published as published',
82
+ 'tn.unique_id as type_key',
83
+ 'ct.alias as type_alias',
84
+ 'ct.icon as type_icon',
85
+ ])
86
+ .where('n.id', 'in', [...ids])
87
+ .orderBy('n.text')
88
+ .execute()
85
89
  return rows.map((row) => ({
86
90
  key: String(row.unique_id),
87
91
  name: row.text,
@@ -99,9 +103,11 @@ export class ReferenceRepository {
99
103
  skip: number,
100
104
  take: number,
101
105
  ): Promise<{ total: number; items: ReferencingNode[] }> {
102
- const self = await this.#db.query<{ id: number }>('SELECT id FROM node WHERE unique_id = ?', [
103
- normaliseUuid(key),
104
- ])
106
+ const self = await this.#db.q
107
+ .selectFrom('node')
108
+ .select('id')
109
+ .where('unique_id', '=', normaliseUuid(key))
110
+ .execute()
105
111
  const selfId = self[0]?.id
106
112
  const ids = (await this.#referencingIds([key])).get(normaliseUuid(key)) ?? []
107
113
  const others = ids.filter((id) => id !== Number(selfId))
@@ -117,16 +123,19 @@ export class ReferenceRepository {
117
123
  skip: number,
118
124
  take: number,
119
125
  ): Promise<{ total: number; items: string[] }> {
120
- const self = await this.#db.query<{ id: number; path: string }>(
121
- 'SELECT id, path FROM node WHERE unique_id = ?',
122
- [normaliseUuid(key)],
123
- )
126
+ const self = await this.#db.q
127
+ .selectFrom('node')
128
+ .select(['id', 'path'])
129
+ .where('unique_id', '=', normaliseUuid(key))
130
+ .execute()
124
131
  const node = self[0]
125
132
  if (!node) return { total: 0, items: [] }
126
- const descendants = await this.#db.query<{ id: number; unique_id: string }>(
127
- 'SELECT id, unique_id FROM node WHERE path LIKE ? AND id <> ?',
128
- [`${node.path},%`, node.id],
129
- )
133
+ const descendants = await this.#db.q
134
+ .selectFrom('node')
135
+ .select(['id', 'unique_id'])
136
+ .where('path', 'like', `${node.path},%`)
137
+ .where('id', '<>', node.id)
138
+ .execute()
130
139
  const referenced: string[] = []
131
140
  for (const descendant of descendants) {
132
141
  const ids = (await this.#referencingIds([String(descendant.unique_id)])).values().next()
@@ -150,9 +159,11 @@ export class ReferenceRepository {
150
159
  const found = await this.#referencingIds(wanted)
151
160
  const selfIds = new Map<string, number>()
152
161
  for (const key of wanted) {
153
- const rows = await this.#db.query<{ id: number }>('SELECT id FROM node WHERE unique_id = ?', [
154
- key,
155
- ])
162
+ const rows = await this.#db.q
163
+ .selectFrom('node')
164
+ .select('id')
165
+ .where('unique_id', '=', key)
166
+ .execute()
156
167
  if (rows[0]) selfIds.set(key, Number(rows[0].id))
157
168
  }
158
169
  const referenced = wanted.filter((key) =>