@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
@@ -7,6 +7,7 @@
7
7
  import { normaliseUuid, ObjectTypes, type Page, SystemNodes } from '@crombolo/core'
8
8
  import type { Db } from '../database.ts'
9
9
  import { DbDate, fromDbBool } from '../dialect.ts'
10
+ import { sql } from '../query.ts'
10
11
  import { searchTerms } from '../search-text.ts'
11
12
 
12
13
  export interface NodeRow {
@@ -37,8 +38,18 @@ export function mapNode(row: Record<string, unknown>): NodeRow {
37
38
  }
38
39
  }
39
40
 
40
- const NODE_COLUMNS =
41
- 'id, unique_id, parent_id, level, path, sort_order, trashed, text, node_object_type, create_date'
41
+ const NODE_COLUMNS = [
42
+ 'id',
43
+ 'unique_id',
44
+ 'parent_id',
45
+ 'level',
46
+ 'path',
47
+ 'sort_order',
48
+ 'trashed',
49
+ 'text',
50
+ 'node_object_type',
51
+ 'create_date',
52
+ ] as const
42
53
 
43
54
  export interface CreateNodeInit {
44
55
  key?: string
@@ -57,24 +68,30 @@ export class NodeRepository {
57
68
  }
58
69
 
59
70
  async byKey(key: string): Promise<NodeRow | undefined> {
60
- const rows = await this.#db.query(`SELECT ${NODE_COLUMNS} FROM node WHERE unique_id = ?`, [
61
- normaliseUuid(key),
62
- ])
71
+ const rows = await this.#db.q
72
+ .selectFrom('node')
73
+ .select(NODE_COLUMNS)
74
+ .where('unique_id', '=', normaliseUuid(key))
75
+ .execute()
63
76
  return rows[0] ? mapNode(rows[0]) : undefined
64
77
  }
65
78
 
66
79
  async byId(id: number): Promise<NodeRow | undefined> {
67
- const rows = await this.#db.query(`SELECT ${NODE_COLUMNS} FROM node WHERE id = ?`, [id])
80
+ const rows = await this.#db.q
81
+ .selectFrom('node')
82
+ .select(NODE_COLUMNS)
83
+ .where('id', '=', id)
84
+ .execute()
68
85
  return rows[0] ? mapNode(rows[0]) : undefined
69
86
  }
70
87
 
71
88
  async byKeys(keys: readonly string[]): Promise<NodeRow[]> {
72
89
  if (keys.length === 0) return []
73
- const placeholders = keys.map(() => '?').join(', ')
74
- const rows = await this.#db.query(
75
- `SELECT ${NODE_COLUMNS} FROM node WHERE unique_id IN (${placeholders})`,
76
- keys.map(normaliseUuid),
77
- )
90
+ const rows = await this.#db.q
91
+ .selectFrom('node')
92
+ .select(NODE_COLUMNS)
93
+ .where('unique_id', 'in', keys.map(normaliseUuid))
94
+ .execute()
78
95
  return rows.map(mapNode)
79
96
  }
80
97
 
@@ -89,37 +106,35 @@ export class NodeRepository {
89
106
  const sortOrder = init.sortOrder ?? (await this.#nextSortOrder(init.parentId, init.objectType))
90
107
  const now = DbDate.toDb(new Date())
91
108
 
92
- await this.#db.exec(
93
- `INSERT INTO node
94
- (unique_id, parent_id, level, path, sort_order, trashed, node_user, text, node_object_type, create_date)
95
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
96
- [
97
- key,
98
- init.parentId,
109
+ await this.#db.q
110
+ .insertInto('node')
111
+ .values({
112
+ unique_id: key,
113
+ parent_id: init.parentId,
99
114
  level,
100
- '',
101
- sortOrder,
102
- this.#db.dialect.boolValue(false),
103
- init.userId ?? null,
104
- init.text,
105
- init.objectType,
106
- now,
107
- ],
108
- )
115
+ path: '',
116
+ sort_order: sortOrder,
117
+ trashed: this.#db.dialect.boolValue(false),
118
+ node_user: init.userId ?? null,
119
+ text: init.text,
120
+ node_object_type: init.objectType,
121
+ create_date: now,
122
+ })
123
+ .execute()
109
124
  const created = await this.byKey(key)
110
125
  if (!created) throw new Error('Node insert did not produce a row.')
111
126
 
112
127
  const path = parent ? `${parent.path},${created.id}` : `${SystemNodes.Root},${created.id}`
113
- await this.#db.exec('UPDATE node SET path = ? WHERE id = ?', [path, created.id])
128
+ await this.#db.q.updateTable('node').set({ path }).where('id', '=', created.id).execute()
114
129
  return { ...created, path }
115
130
  }
116
131
 
117
132
  async rename(id: number, text: string): Promise<void> {
118
- await this.#db.exec('UPDATE node SET text = ? WHERE id = ?', [text, id])
133
+ await this.#db.q.updateTable('node').set({ text }).where('id', '=', id).execute()
119
134
  }
120
135
 
121
136
  async delete(id: number): Promise<void> {
122
- await this.#db.exec('DELETE FROM node WHERE id = ?', [id])
137
+ await this.#db.q.deleteFrom('node').where('id', '=', id).execute()
123
138
  }
124
139
 
125
140
  /** Root-level items of a type, i.e. those parented to the system root. */
@@ -135,28 +150,22 @@ export class NodeRepository {
135
150
  trashed = false,
136
151
  excludeKeys: readonly string[] = [],
137
152
  ): Promise<Page<NodeRow>> {
138
- const where = `parent_id = ? AND node_object_type = ? AND trashed = ?${
139
- excludeKeys.length > 0
140
- ? ` AND unique_id NOT IN (${excludeKeys.map(() => '?').join(', ')})`
141
- : ''
142
- }`
143
- const params = [
144
- parentId,
145
- objectType,
146
- this.#db.dialect.boolValue(trashed),
147
- ...excludeKeys.map(normaliseUuid),
148
- ]
149
- const totals = await this.#db.query<{ n: number }>(
150
- `SELECT COUNT(*) AS n FROM node WHERE ${where}`,
151
- params,
152
- )
153
- const rows = await this.#db.query(
154
- `SELECT ${NODE_COLUMNS} FROM node
155
- WHERE ${where}
156
- ORDER BY sort_order, id
157
- LIMIT ? OFFSET ?`,
158
- [...params, take, skip],
159
- )
153
+ const matching = this.#db.q
154
+ .selectFrom('node')
155
+ .where('parent_id', '=', parentId)
156
+ .where('node_object_type', '=', objectType)
157
+ .where('trashed', '=', this.#db.dialect.boolValue(trashed))
158
+ .$if(excludeKeys.length > 0, (q) =>
159
+ q.where('unique_id', 'not in', excludeKeys.map(normaliseUuid)),
160
+ )
161
+ const totals = await matching.select((eb) => eb.fn.countAll().as('n')).execute()
162
+ const rows = await matching
163
+ .select(NODE_COLUMNS)
164
+ .orderBy('sort_order')
165
+ .orderBy('id')
166
+ .limit(take)
167
+ .offset(skip)
168
+ .execute()
160
169
  return { total: Number(totals[0]?.n ?? 0), items: rows.map(mapNode) }
161
170
  }
162
171
 
@@ -168,19 +177,27 @@ export class NodeRepository {
168
177
  take: number,
169
178
  ): Promise<Page<NodeRow>> {
170
179
  if (objectTypes.length === 0) return { total: 0, items: [] }
171
- const marks = objectTypes.map(() => '?').join(', ')
172
- const f = this.#db.dialect.boolValue(false)
173
- const totals = await this.#db.query<{ n: number }>(
174
- `SELECT COUNT(*) AS n FROM node WHERE parent_id = ? AND node_object_type IN (${marks}) AND trashed = ?`,
175
- [parentId, ...objectTypes, f],
176
- )
177
- const rows = await this.#db.query(
178
- `SELECT ${NODE_COLUMNS} FROM node
179
- WHERE parent_id = ? AND node_object_type IN (${marks}) AND trashed = ?
180
- ORDER BY CASE WHEN node_object_type = ? THEN 0 ELSE 1 END, text, id
181
- LIMIT ? OFFSET ?`,
182
- [parentId, ...objectTypes, f, objectTypes[0], take, skip],
183
- )
180
+ const matching = this.#db.q
181
+ .selectFrom('node')
182
+ .where('parent_id', '=', parentId)
183
+ .where('node_object_type', 'in', objectTypes)
184
+ .where('trashed', '=', this.#db.dialect.boolValue(false))
185
+ const totals = await matching.select((eb) => eb.fn.countAll().as('n')).execute()
186
+ const rows = await matching
187
+ .select(NODE_COLUMNS)
188
+ .orderBy((eb) =>
189
+ eb
190
+ .case()
191
+ .when('node_object_type', '=', objectTypes[0] as string)
192
+ .then(0)
193
+ .else(1)
194
+ .end(),
195
+ )
196
+ .orderBy('text')
197
+ .orderBy('id')
198
+ .limit(take)
199
+ .offset(skip)
200
+ .execute()
184
201
  return { total: Number(totals[0]?.n ?? 0), items: rows.map(mapNode) }
185
202
  }
186
203
 
@@ -193,22 +210,25 @@ export class NodeRepository {
193
210
  const newLevel = parent ? parent.level + 1 : 1
194
211
  const delta = newLevel - node.level
195
212
  const oldPath = node.path
196
- await this.#db.exec('UPDATE node SET parent_id = ?, level = ?, path = ? WHERE id = ?', [
197
- newParentId,
198
- newLevel,
199
- newPath,
200
- node.id,
201
- ])
202
- const descendants = await this.#db.query<{ id: number; path: string; level: number }>(
203
- 'SELECT id, path, level FROM node WHERE path LIKE ?',
204
- [`${oldPath},%`],
205
- )
213
+ await this.#db.q
214
+ .updateTable('node')
215
+ .set({ parent_id: newParentId, level: newLevel, path: newPath })
216
+ .where('id', '=', node.id)
217
+ .execute()
218
+ const descendants = await this.#db.q
219
+ .selectFrom('node')
220
+ .select(['id', 'path', 'level'])
221
+ .where('path', 'like', `${oldPath},%`)
222
+ .execute()
206
223
  for (const d of descendants) {
207
- await this.#db.exec('UPDATE node SET path = ?, level = ? WHERE id = ?', [
208
- `${newPath}${String(d.path).slice(oldPath.length)}`,
209
- Number(d.level) + delta,
210
- Number(d.id),
211
- ])
224
+ await this.#db.q
225
+ .updateTable('node')
226
+ .set({
227
+ path: `${newPath}${String(d.path).slice(oldPath.length)}`,
228
+ level: Number(d.level) + delta,
229
+ })
230
+ .where('id', '=', Number(d.id))
231
+ .execute()
212
232
  }
213
233
  }
214
234
 
@@ -222,21 +242,27 @@ export class NodeRepository {
222
242
  const target = await this.byKey(key)
223
243
  if (!target) return undefined
224
244
  const types = typeof objectType === 'string' ? [objectType] : [...objectType]
225
- const marks = types.map(() => '?').join(', ')
226
- const order =
227
- types.length > 1
228
- ? 'CASE WHEN node_object_type = ? THEN 0 ELSE 1 END, text, id'
229
- : 'sort_order, id'
230
- const all = await this.#db.query(
231
- `SELECT ${NODE_COLUMNS} FROM node WHERE parent_id = ? AND node_object_type IN (${marks}) AND trashed = ?
232
- ORDER BY ${order}`,
233
- [
234
- target.parentId,
235
- ...types,
236
- this.#db.dialect.boolValue(target.trashed),
237
- ...(types.length > 1 ? [types[0]] : []),
238
- ],
239
- )
245
+ const all = await this.#db.q
246
+ .selectFrom('node')
247
+ .select(NODE_COLUMNS)
248
+ .where('parent_id', '=', target.parentId)
249
+ .where('node_object_type', 'in', types)
250
+ .where('trashed', '=', this.#db.dialect.boolValue(target.trashed))
251
+ .$if(types.length > 1, (q) =>
252
+ q
253
+ .orderBy((eb) =>
254
+ eb
255
+ .case()
256
+ .when('node_object_type', '=', types[0] as string)
257
+ .then(0)
258
+ .else(1)
259
+ .end(),
260
+ )
261
+ .orderBy('text'),
262
+ )
263
+ .$if(types.length <= 1, (q) => q.orderBy('sort_order'))
264
+ .orderBy('id')
265
+ .execute()
240
266
  const rows = all.map(mapNode)
241
267
  const index = rows.findIndex((row) => row.id === target.id)
242
268
  const start = Math.max(0, index - before)
@@ -263,47 +289,59 @@ export class NodeRepository {
263
289
  const like = `%${query.toLowerCase().replaceAll('%', '').replaceAll('_', '')}%`
264
290
  const terms = options.fullText ? searchTerms(query) : []
265
291
  const indexed = terms.length > 0
266
- const conditions = [
267
- 'node_object_type = ?',
268
- 'trashed = ?',
269
- indexed ? '(LOWER(text) LIKE ? OR h.node_id IS NOT NULL)' : 'LOWER(text) LIKE ?',
270
- ]
271
- const params: unknown[] = [
272
- ...(indexed ? [this.#db.dialect.fullTextQuery(terms)] : []),
273
- objectType,
274
- this.#db.dialect.boolValue(options.trashed ?? false),
275
- like,
276
- ]
277
- if (options.parentId !== undefined) {
278
- conditions.push('parent_id = ?')
279
- params.push(options.parentId)
280
- }
281
- const from = indexed
282
- ? `node LEFT JOIN (${this.#db.dialect.fullTextHits}) h ON h.node_id = node.id`
283
- : 'node'
284
- const where = conditions.join(' AND ')
285
- const totals = await this.#db.query<{ n: number }>(
286
- `SELECT COUNT(*) AS n FROM ${from} WHERE ${where}`,
287
- params,
288
- )
289
- const order = indexed
290
- ? 'CASE WHEN LOWER(text) LIKE ? THEN 0 ELSE 1 END, COALESCE(h.score, 0) DESC, text, id'
291
- : 'text, id'
292
- const rows = await this.#db.query(
293
- `SELECT ${NODE_COLUMNS} FROM ${from} WHERE ${where} ORDER BY ${order} LIMIT ? OFFSET ?`,
294
- [...params, ...(indexed ? [like] : []), options.take, options.skip],
295
- )
292
+ const dialect = this.#db.dialect
293
+ const hitNode = sql.ref<number | null>('h.node_id')
294
+ const hitScore = sql.ref<number | null>('h.score')
295
+ const { parentId } = options
296
+ const matching = this.#db.q
297
+ .selectFrom('node')
298
+ .$if(
299
+ indexed,
300
+ (q) =>
301
+ q.leftJoin(
302
+ dialect.fullTextMatches(dialect.fullTextQuery(terms)).as('h'),
303
+ 'h.node_id',
304
+ 'node.id',
305
+ ) as unknown as typeof q,
306
+ )
307
+ .where('node_object_type', '=', objectType)
308
+ .where('trashed', '=', dialect.boolValue(options.trashed ?? false))
309
+ .where((eb) => {
310
+ const named = eb(eb.fn('lower', ['text']), 'like', like)
311
+ return indexed ? eb.or([named, eb(hitNode, 'is not', null)]) : named
312
+ })
313
+ .$if(parentId !== undefined, (q) => q.where('parent_id', '=', parentId as number))
314
+ const totals = await matching.select((eb) => eb.fn.countAll().as('n')).execute()
315
+ const rows = await matching
316
+ .select(NODE_COLUMNS)
317
+ .$if(indexed, (q) =>
318
+ q
319
+ .orderBy((eb) =>
320
+ eb
321
+ .case()
322
+ .when(eb(eb.fn('lower', ['text']), 'like', like))
323
+ .then(0)
324
+ .else(1)
325
+ .end(),
326
+ )
327
+ .orderBy(sql`coalesce(${hitScore}, 0)`, 'desc'),
328
+ )
329
+ .orderBy('text')
330
+ .orderBy('id')
331
+ .limit(options.take)
332
+ .offset(options.skip)
333
+ .execute()
296
334
  return { total: Number(totals[0]?.n ?? 0), items: rows.map(mapNode) }
297
335
  }
298
336
 
299
337
  /** The nodes with these ids, in no particular order; one query. */
300
338
  async byIds(ids: readonly number[]): Promise<NodeRow[]> {
301
339
  if (ids.length === 0) return []
302
- const placeholders = ids.map(() => '?').join(', ')
303
- const rows = await this.#db.query(
304
- `SELECT ${NODE_COLUMNS} FROM node WHERE id IN (${placeholders})`,
305
- [...ids],
306
- )
340
+ const rows = await this.#db.q
341
+ .selectFrom('node')
342
+ .select(NODE_COLUMNS)
343
+ .where('id', 'in', [...ids])
344
+ .execute()
307
345
  return rows.map(mapNode)
308
346
  }
309
347
 
@@ -316,11 +354,12 @@ export class NodeRepository {
316
354
  .map((part) => Number(part))
317
355
  .filter((id) => id > 0 && id !== node.id)
318
356
  if (ids.length === 0) return []
319
- const placeholders = ids.map(() => '?').join(', ')
320
- const rows = await this.#db.query(
321
- `SELECT ${NODE_COLUMNS} FROM node WHERE id IN (${placeholders}) ORDER BY level`,
322
- ids,
323
- )
357
+ const rows = await this.#db.q
358
+ .selectFrom('node')
359
+ .select(NODE_COLUMNS)
360
+ .where('id', 'in', ids)
361
+ .orderBy('level')
362
+ .execute()
324
363
  return rows.map(mapNode)
325
364
  }
326
365
 
@@ -334,13 +373,16 @@ export class NodeRepository {
334
373
  */
335
374
  async descendants(node: NodeRow, objectTypes: readonly string[]): Promise<NodeRow[]> {
336
375
  if (objectTypes.length === 0) return []
337
- const marks = objectTypes.map(() => '?').join(', ')
338
- const rows = await this.#db.query(
339
- `SELECT ${NODE_COLUMNS} FROM node
340
- WHERE path LIKE ? AND node_object_type IN (${marks}) AND trashed = ?
341
- ORDER BY level, sort_order, id`,
342
- [`${node.path},%`, ...objectTypes, this.#db.dialect.boolValue(false)],
343
- )
376
+ const rows = await this.#db.q
377
+ .selectFrom('node')
378
+ .select(NODE_COLUMNS)
379
+ .where('path', 'like', `${node.path},%`)
380
+ .where('node_object_type', 'in', objectTypes)
381
+ .where('trashed', '=', this.#db.dialect.boolValue(false))
382
+ .orderBy('level')
383
+ .orderBy('sort_order')
384
+ .orderBy('id')
385
+ .execute()
344
386
  return rows.map(mapNode)
345
387
  }
346
388
 
@@ -351,67 +393,71 @@ export class NodeRepository {
351
393
  name: string,
352
394
  ): Promise<NodeRow[]> {
353
395
  if (objectTypes.length === 0) return []
354
- const marks = objectTypes.map(() => '?').join(', ')
355
- const rows = await this.#db.query(
356
- `SELECT ${NODE_COLUMNS} FROM node
357
- WHERE parent_id = ? AND node_object_type IN (${marks}) AND trashed = ?
358
- AND LOWER(text) = LOWER(?)
359
- ORDER BY sort_order, id`,
360
- [parentId, ...objectTypes, this.#db.dialect.boolValue(false), name],
361
- )
396
+ const rows = await this.#db.q
397
+ .selectFrom('node')
398
+ .select(NODE_COLUMNS)
399
+ .where('parent_id', '=', parentId)
400
+ .where('node_object_type', 'in', objectTypes)
401
+ .where('trashed', '=', this.#db.dialect.boolValue(false))
402
+ .where((eb) => eb(eb.fn('lower', ['text']), '=', eb.fn('lower', [eb.val(name)])))
403
+ .orderBy('sort_order')
404
+ .orderBy('id')
405
+ .execute()
362
406
  return rows.map(mapNode)
363
407
  }
364
408
 
365
409
  /** The names under a node, so a failed path resolution can say what was there. */
366
410
  async childNames(parentId: number, objectTypes: readonly string[]): Promise<string[]> {
367
411
  if (objectTypes.length === 0) return []
368
- const marks = objectTypes.map(() => '?').join(', ')
369
- const rows = await this.#db.query<{ text: string | null }>(
370
- `SELECT text FROM node
371
- WHERE parent_id = ? AND node_object_type IN (${marks}) AND trashed = ?
372
- ORDER BY sort_order, id`,
373
- [parentId, ...objectTypes, this.#db.dialect.boolValue(false)],
374
- )
412
+ const rows = await this.#db.q
413
+ .selectFrom('node')
414
+ .select('text')
415
+ .where('parent_id', '=', parentId)
416
+ .where('node_object_type', 'in', objectTypes)
417
+ .where('trashed', '=', this.#db.dialect.boolValue(false))
418
+ .orderBy('sort_order')
419
+ .orderBy('id')
420
+ .execute()
375
421
  return rows.flatMap((row) => (row.text ? [String(row.text)] : []))
376
422
  }
377
423
 
378
424
  async hasChildren(id: number, objectType: string): Promise<boolean> {
379
- const rows = await this.#db.query<{ n: number }>(
380
- 'SELECT COUNT(*) AS n FROM node WHERE parent_id = ? AND node_object_type = ?',
381
- [id, objectType],
382
- )
425
+ const rows = await this.#db.q
426
+ .selectFrom('node')
427
+ .select((eb) => eb.fn.countAll().as('n'))
428
+ .where('parent_id', '=', id)
429
+ .where('node_object_type', '=', objectType)
430
+ .execute()
383
431
  return Number(rows[0]?.n ?? 0) > 0
384
432
  }
385
433
 
386
434
  /** Bulk `hasChildren`, so a tree page costs one query instead of one per row. */
387
435
  async childCounts(ids: readonly number[], objectType: string): Promise<Map<number, number>> {
388
436
  if (ids.length === 0) return new Map()
389
- const placeholders = ids.map(() => '?').join(', ')
390
- const rows = await this.#db.query<{ parent_id: number; n: number }>(
391
- `SELECT parent_id, COUNT(*) AS n FROM node
392
- WHERE parent_id IN (${placeholders}) AND node_object_type = ?
393
- GROUP BY parent_id`,
394
- [...ids, objectType],
395
- )
437
+ const rows = await this.#db.q
438
+ .selectFrom('node')
439
+ .select((eb) => ['parent_id', eb.fn.countAll().as('n')])
440
+ .where('parent_id', 'in', [...ids])
441
+ .where('node_object_type', '=', objectType)
442
+ .groupBy('parent_id')
443
+ .execute()
396
444
  return new Map(rows.map((row) => [Number(row.parent_id), Number(row.n)]))
397
445
  }
398
446
 
399
447
  async #nextSortOrder(parentId: number, objectType: string): Promise<number> {
400
448
  // One maximum per `trashed`, so each is read off the end of `ix_node_parent_sort`
401
449
  // rather than across every child: a folder may hold a million files (story 197).
402
- const max =
403
- 'SELECT MAX(sort_order) AS m FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ?'
404
- const rows = await this.#db.query<{ next: number | null }>(
405
- `SELECT MAX(m) AS next FROM (${max} UNION ALL ${max}) maxima`,
406
- [
407
- parentId,
408
- objectType,
409
- this.#db.dialect.boolValue(false),
410
- parentId,
411
- objectType,
412
- this.#db.dialect.boolValue(true),
413
- ],
414
- )
450
+ const max = (trashed: boolean) =>
451
+ this.#db.q
452
+ .selectFrom('node')
453
+ .select((eb) => eb.fn.max('sort_order').as('m'))
454
+ .where('parent_id', '=', parentId)
455
+ .where('node_object_type', '=', objectType)
456
+ .where('trashed', '=', this.#db.dialect.boolValue(trashed))
457
+ const rows = await this.#db.q
458
+ .selectFrom(max(false).unionAll(max(true)).as('maxima'))
459
+ .select((eb) => eb.fn.max('m').as('next'))
460
+ .execute()
415
461
  const current = rows[0]?.next
416
462
  return current === null || current === undefined ? 0 : Number(current) + 1
417
463
  }
@@ -28,10 +28,12 @@ export class NotificationRepository {
28
28
  }
29
29
 
30
30
  async subscribed(userId: number, nodeId: number): Promise<string[]> {
31
- const rows = await this.#db.query<{ action: string }>(
32
- 'SELECT action FROM user_notification WHERE user_id = ? AND node_id = ?',
33
- [userId, nodeId],
34
- )
31
+ const rows = await this.#db.q
32
+ .selectFrom('user_notification')
33
+ .select('action')
34
+ .where('user_id', '=', userId)
35
+ .where('node_id', '=', nodeId)
36
+ .execute()
35
37
  return rows.map((row) => String(row.action))
36
38
  }
37
39
 
@@ -39,16 +41,17 @@ export class NotificationRepository {
39
41
  async set(userId: number, nodeId: number, actionIds: readonly string[]): Promise<void> {
40
42
  const known = new Set(NOTIFIABLE_ACTIONS.map((a) => a.actionId))
41
43
  await this.#db.transaction(async (tx) => {
42
- await tx.exec('DELETE FROM user_notification WHERE user_id = ? AND node_id = ?', [
43
- userId,
44
- nodeId,
45
- ])
44
+ await tx.q
45
+ .deleteFrom('user_notification')
46
+ .where('user_id', '=', userId)
47
+ .where('node_id', '=', nodeId)
48
+ .execute()
46
49
  for (const action of new Set(actionIds))
47
50
  if (known.has(action))
48
- await tx.exec(
49
- 'INSERT INTO user_notification (user_id, node_id, action) VALUES (?, ?, ?)',
50
- [userId, nodeId, action],
51
- )
51
+ await tx.q
52
+ .insertInto('user_notification')
53
+ .values({ user_id: userId, node_id: nodeId, action })
54
+ .execute()
52
55
  })
53
56
  }
54
57
 
@@ -58,11 +61,13 @@ export class NotificationRepository {
58
61
  */
59
62
  async subscribersFor(actionId: string, pathNodeIds: readonly number[]): Promise<number[]> {
60
63
  if (pathNodeIds.length === 0) return []
61
- const rows = await this.#db.query<{ user_id: number }>(
62
- `SELECT DISTINCT user_id FROM user_notification
63
- WHERE action = ? AND node_id IN (${pathNodeIds.map(() => '?').join(', ')})`,
64
- [actionId, ...pathNodeIds],
65
- )
64
+ const rows = await this.#db.q
65
+ .selectFrom('user_notification')
66
+ .select('user_id')
67
+ .distinct()
68
+ .where('action', '=', actionId)
69
+ .where('node_id', 'in', pathNodeIds)
70
+ .execute()
66
71
  return rows.map((row) => Number(row.user_id))
67
72
  }
68
73
  }