@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
@@ -14,6 +14,7 @@ import {
14
14
  } from '@crombolo/core'
15
15
  import type { Db } from './database.ts'
16
16
  import { DbDate, fromDbBool } from './dialect.ts'
17
+ import { type Expression, sql } from './query.ts'
17
18
  import { escapeLike, searchTerms } from './search-text.ts'
18
19
 
19
20
  export const QUERY_STATES = ['published', 'draft', 'changed', 'trashed'] as const
@@ -288,39 +289,53 @@ export async function queryDocuments(
288
289
  }
289
290
 
290
291
  async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise<QueryResult> {
291
- const bool = (value: boolean) => db.dialect.boolValue(value)
292
- const where: string[] = ['n.node_object_type = ?']
293
- const params: unknown[] = [ObjectTypes.Document]
294
- const joins: string[] = []
295
- const joinParams: unknown[] = []
292
+ const bool = (value: boolean) => db.dialect.boolValue(value) as boolean
296
293
 
297
294
  // ---- culture
298
295
  let languageId: number | undefined
299
296
  if (query.culture) {
300
- const [language] = await db.query<{ id: number }>(
301
- 'SELECT id FROM language WHERE LOWER(iso_code) = LOWER(?)',
302
- [query.culture],
303
- )
297
+ const culture = query.culture
298
+ const language = await db.q
299
+ .selectFrom('language')
300
+ .select('id')
301
+ .where((eb) => eb(eb.fn('lower', ['iso_code']), '=', eb.fn('lower', [eb.val(culture)])))
302
+ .executeTakeFirst()
304
303
  if (!language) throw new ContentQueryRefused(`There is no language "${query.culture}".`)
305
304
  languageId = Number(language.id)
306
- joins.push(
307
- 'LEFT JOIN document_culture_variation dcv ON dcv.node_id = n.id AND dcv.language_id = ?',
308
- )
309
- joinParams.push(languageId)
310
305
  }
311
- const published =
312
- languageId === undefined ? 'd.published' : 'COALESCE(dcv.published, d.published)'
313
- const edited = languageId === undefined ? 'd.edited' : 'COALESCE(dcv.edited, d.edited)'
314
- const nameColumn = languageId === undefined ? 'n.text' : 'COALESCE(dcv.name, n.text)'
306
+ const byCulture = <T>(column: 'published' | 'edited' | 'name', fallback: string) =>
307
+ languageId === undefined
308
+ ? sql.ref<T>(fallback)
309
+ : sql<T>`coalesce(${sql.ref(`dcv.${column}`)}, ${sql.ref(fallback)})`
310
+ const published = byCulture<unknown>('published', 'd.published')
311
+ const edited = byCulture<unknown>('edited', 'd.edited')
312
+ const nameColumn = byCulture<string | null>('name', 'n.text')
313
+
314
+ let q = db.q
315
+ .selectFrom('node as n')
316
+ .innerJoin('content as c', 'c.node_id', 'n.id')
317
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
318
+ .innerJoin('node as tn', 'tn.id', 'ct.node_id')
319
+ .innerJoin('document as d', 'd.node_id', 'n.id')
320
+ .innerJoin('content_version as cv', (join) =>
321
+ join.onRef('cv.node_id', '=', 'n.id').on('cv.current', '=', bool(true)),
322
+ )
323
+ .$if(languageId !== undefined, (qb) =>
324
+ qb.leftJoin('document_culture_variation as dcv', (join) =>
325
+ join.onRef('dcv.node_id', '=', 'n.id').on('dcv.language_id', '=', languageId as number),
326
+ ),
327
+ )
328
+ .where('n.node_object_type', '=', ObjectTypes.Document)
315
329
 
316
330
  // ---- types
317
331
  let typeIds: number[] | undefined
318
332
  if (query.contentTypes?.length) {
319
- const rows = await db.query<{ node_id: number; alias: string; unique_id: string }>(
320
- `SELECT ct.node_id, ct.alias, tn.unique_id FROM content_type ct JOIN node tn ON tn.id = ct.node_id
321
- WHERE tn.node_object_type = ?`,
322
- [ObjectTypes.DocumentType],
323
- )
333
+ const rows = await db.q
334
+ .selectFrom('content_type as ct')
335
+ .innerJoin('node as tn', 'tn.id', 'ct.node_id')
336
+ .select(['ct.node_id', 'ct.alias', 'tn.unique_id'])
337
+ .where('tn.node_object_type', '=', ObjectTypes.DocumentType)
338
+ .execute()
324
339
  typeIds = []
325
340
  for (const wanted of query.contentTypes) {
326
341
  const found = rows.find(
@@ -331,80 +346,81 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
331
346
  if (!found) throw new ContentQueryRefused(`There is no content type "${wanted}".`)
332
347
  typeIds.push(Number(found.node_id))
333
348
  }
334
- where.push(`c.content_type_id IN (${typeIds.map(() => '?').join(', ')})`)
335
- params.push(...typeIds)
349
+ q = q.where('c.content_type_id', 'in', typeIds)
336
350
  }
337
351
 
338
352
  // ---- place
339
353
  const nodeByKey = async (key: string, field: string) => {
340
- const [row] = await db.query<{ id: number; path: string; level: number }>(
341
- 'SELECT id, path, level FROM node WHERE unique_id = ? AND node_object_type = ?',
342
- [key.toLowerCase(), ObjectTypes.Document],
343
- )
354
+ const row = await db.q
355
+ .selectFrom('node')
356
+ .select(['id', 'path', 'level'])
357
+ .where('unique_id', '=', key.toLowerCase())
358
+ .where('node_object_type', '=', ObjectTypes.Document)
359
+ .executeTakeFirst()
344
360
  if (!row) throw new ContentQueryRefused(`"${field}" names no page: ${key}.`)
345
361
  return { id: Number(row.id), path: String(row.path), level: Number(row.level) }
346
362
  }
347
363
  const under = query.under ? await nodeByKey(query.under, 'under') : undefined
348
364
  const parent = query.parent ? await nodeByKey(query.parent, 'parent') : undefined
349
- if (under) {
350
- where.push(`n.path LIKE ? ESCAPE '\\'`)
351
- params.push(`${escapeLike(under.path)},%`)
352
- }
353
- if (parent) {
354
- where.push('n.parent_id = ?')
355
- params.push(parent.id)
356
- }
365
+ if (under) q = q.where(like(sql.ref('n.path'), `${escapeLike(under.path)},%`))
366
+ if (parent) q = q.where('n.parent_id', '=', parent.id)
357
367
  if (query.maxDepth !== undefined) {
358
368
  const from = (under ?? parent) as { level: number }
359
- where.push('n.level <= ?')
360
- params.push(from.level + query.maxDepth)
369
+ q = q.where('n.level', '<=', from.level + query.maxDepth)
361
370
  }
362
371
 
363
372
  // ---- start nodes: the statement itself stays inside them
364
373
  if (!scope.start.root) {
365
374
  if (scope.start.keys.length === 0) return { total: 0, exact: true, items: [] }
366
- const starts = await db.query<{ path: string }>(
367
- `SELECT path FROM node WHERE unique_id IN (${scope.start.keys.map(() => '?').join(', ')})`,
368
- scope.start.keys.map((k) => k.toLowerCase()),
369
- )
375
+ const starts = await db.q
376
+ .selectFrom('node')
377
+ .select('path')
378
+ .where(
379
+ 'unique_id',
380
+ 'in',
381
+ scope.start.keys.map((k) => k.toLowerCase()),
382
+ )
383
+ .execute()
370
384
  if (starts.length === 0) return { total: 0, exact: true, items: [] }
371
- where.push(`(${starts.map(() => `(n.path = ? OR n.path LIKE ? ESCAPE '\\')`).join(' OR ')})`)
372
- for (const s of starts) params.push(String(s.path), `${escapeLike(String(s.path))},%`)
385
+ q = q.where((eb) =>
386
+ eb.or(
387
+ starts.map((s) =>
388
+ eb.or([
389
+ eb('n.path', '=', String(s.path)),
390
+ like(eb.ref('n.path'), `${escapeLike(String(s.path))},%`),
391
+ ]),
392
+ ),
393
+ ),
394
+ )
373
395
  }
374
396
 
375
397
  // ---- state; trashed only when asked for, and never outside root access
376
398
  const states = query.state?.length ? query.state : ['published', 'draft', 'changed']
377
399
  const wantsTrashed = states.includes('trashed') && scope.start.root
378
400
  const live = states.filter((s) => s !== 'trashed')
379
- const stateClauses: string[] = []
380
- if (live.length > 0) {
381
- const liveParts: string[] = []
382
- if (live.includes('published')) liveParts.push(`(${published} = ? AND ${edited} = ?)`)
383
- if (live.includes('changed')) liveParts.push(`(${published} = ? AND ${edited} = ?)`)
384
- if (live.includes('draft')) liveParts.push(`(${published} = ?)`)
385
- stateClauses.push(`(n.trashed = ? AND (${liveParts.join(' OR ')}))`)
386
- params.push(bool(false))
387
- if (live.includes('published')) params.push(bool(true), bool(false))
388
- if (live.includes('changed')) params.push(bool(true), bool(true))
389
- if (live.includes('draft')) params.push(bool(false))
390
- }
391
- if (wantsTrashed) {
392
- stateClauses.push('n.trashed = ?')
393
- params.push(bool(true))
394
- }
395
- if (stateClauses.length === 0) return { total: 0, exact: true, items: [] }
396
- where.push(`(${stateClauses.join(' OR ')})`)
401
+ if (live.length === 0 && !wantsTrashed) return { total: 0, exact: true, items: [] }
402
+ q = q.where((eb) => {
403
+ const clauses: Expression<boolean | 0 | 1>[] = []
404
+ if (live.length > 0) {
405
+ const parts: Expression<boolean | 0 | 1>[] = []
406
+ if (live.includes('published'))
407
+ parts.push(eb.and([eb(published, '=', bool(true)), eb(edited, '=', bool(false))]))
408
+ if (live.includes('changed'))
409
+ parts.push(eb.and([eb(published, '=', bool(true)), eb(edited, '=', bool(true))]))
410
+ if (live.includes('draft')) parts.push(eb(published, '=', bool(false)))
411
+ clauses.push(eb.and([eb('n.trashed', '=', bool(false)), eb.or(parts)]))
412
+ }
413
+ if (wantsTrashed) clauses.push(eb('n.trashed', '=', bool(true)))
414
+ return eb.or(clauses)
415
+ })
397
416
 
398
417
  // ---- dates
399
- const between = (column: string, range: { from?: Date; to?: Date } | undefined) => {
400
- if (range?.from) {
401
- where.push(`${column} >= ?`)
402
- params.push(DbDate.toDb(range.from))
403
- }
404
- if (range?.to) {
405
- where.push(`${column} <= ?`)
406
- params.push(DbDate.toDb(range.to))
407
- }
418
+ const between = (
419
+ column: 'n.create_date' | 'cv.version_date',
420
+ range: { from?: Date; to?: Date } | undefined,
421
+ ) => {
422
+ if (range?.from) q = q.where(column, '>=', DbDate.toDb(range.from))
423
+ if (range?.to) q = q.where(column, '<=', DbDate.toDb(range.to))
408
424
  }
409
425
  between('n.create_date', query.created)
410
426
  between('cv.version_date', query.updated)
@@ -412,112 +428,104 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
412
428
  // ---- name
413
429
  if (query.name) {
414
430
  const value = query.name.value.toLowerCase()
415
- if (query.name.op === 'equals') {
416
- where.push(`LOWER(${nameColumn}) = ?`)
417
- params.push(value)
418
- } else {
419
- where.push(`LOWER(${nameColumn}) LIKE ? ESCAPE '\\'`)
420
- params.push(
421
- query.name.op === 'startsWith' ? `${escapeLike(value)}%` : `%${escapeLike(value)}%`,
431
+ const lowered = sql`lower(${nameColumn})`
432
+ if (query.name.op === 'equals') q = q.where((eb) => eb(lowered, '=', value))
433
+ else
434
+ q = q.where(
435
+ like(
436
+ lowered,
437
+ query.name.op === 'startsWith' ? `${escapeLike(value)}%` : `%${escapeLike(value)}%`,
438
+ ),
422
439
  )
423
- }
424
440
  }
425
441
 
426
442
  // ---- full text, through the existing index
427
443
  if (query.text) {
428
- where.push(`n.id IN (SELECT h.node_id FROM (${db.dialect.fullTextHits}) h)`)
429
- params.push(db.dialect.fullTextQuery(searchTerms(query.text)))
444
+ const hits = db.dialect.fullTextMatches(db.dialect.fullTextQuery(searchTerms(query.text)))
445
+ q = q.where((eb) => eb('n.id', 'in', eb.selectFrom(hits.as('h')).select('h.node_id')))
430
446
  }
431
447
 
432
448
  // ---- properties
433
449
  for (const clause of query.properties ?? []) {
434
450
  const target = await propertyTarget(db, clause.alias, typeIds, scope, clause.op)
435
- const owners = target.ids.map(() => '?').join(', ')
436
- const language =
437
- languageId === undefined ? '' : ' AND (pv.language_id = ? OR pv.language_id IS NULL)'
438
- const row = `SELECT 1 FROM property_value pv WHERE pv.node_id = n.id AND pv.is_current = ?
439
- AND pv.segment IS NULL AND pv.property_type_id IN (${owners})${language}`
440
- const rowParams = [bool(true), ...target.ids, ...(languageId === undefined ? [] : [languageId])]
441
- const col = `pv.${target.column}`
451
+ const col = sql.ref(`pv.${target.column}`)
442
452
  const text = target.storage === 'Ntext' || target.storage === 'Nvarchar'
443
- const hasValue = text ? `${col} IS NOT NULL AND ${col} <> ''` : `${col} IS NOT NULL`
444
- if (clause.op === 'exists' || clause.op === 'empty') {
445
- where.push(`${clause.op === 'empty' ? 'NOT ' : ''}EXISTS (${row} AND ${hasValue})`)
446
- params.push(...rowParams)
447
- continue
448
- }
449
- const value = comparable(clause.value, target.storage, clause.alias)
450
- if (clause.op === 'contains') {
451
- if (!text)
453
+ let value: unknown
454
+ if (clause.op !== 'exists' && clause.op !== 'empty') {
455
+ value = comparable(clause.value, target.storage, clause.alias)
456
+ if (clause.op === 'contains' && !text)
452
457
  throw new ContentQueryRefused(`"contains" compares text; "${clause.alias}" is not text.`)
453
- where.push(`EXISTS (${row} AND LOWER(${col}) LIKE ? ESCAPE '\\')`)
454
- params.push(...rowParams, `%${escapeLike(String(value).toLowerCase())}%`)
455
- continue
456
458
  }
457
- const operator = { eq: '=', ne: '=', gt: '>', gte: '>=', lt: '<', lte: '<=' }[clause.op]
458
- const left = text ? `LOWER(${col})` : col
459
- const right = text ? String(value).toLowerCase() : value
460
- // `ne` is "has no value equal to this", so a page without the value matches too.
461
- where.push(`${clause.op === 'ne' ? 'NOT ' : ''}EXISTS (${row} AND ${left} ${operator} ?)`)
462
- params.push(...rowParams, right)
459
+ q = q.where((eb) => {
460
+ const row = eb
461
+ .selectFrom('property_value as pv')
462
+ .select(eb.lit(1).as('one'))
463
+ .whereRef('pv.node_id', '=', 'n.id')
464
+ .where('pv.is_current', '=', bool(true))
465
+ .where('pv.segment', 'is', null)
466
+ .where('pv.property_type_id', 'in', target.ids)
467
+ .$if(languageId !== undefined, (sub) =>
468
+ sub.where((e) =>
469
+ e.or([e('pv.language_id', '=', languageId as number), e('pv.language_id', 'is', null)]),
470
+ ),
471
+ )
472
+ if (clause.op === 'exists' || clause.op === 'empty') {
473
+ const hasValue = row.where(col, 'is not', null).$if(text, (sub) => sub.where(col, '<>', ''))
474
+ return clause.op === 'empty' ? eb.not(eb.exists(hasValue)) : eb.exists(hasValue)
475
+ }
476
+ if (clause.op === 'contains')
477
+ return eb.exists(
478
+ row.where(like(sql`lower(${col})`, `%${escapeLike(String(value).toLowerCase())}%`)),
479
+ )
480
+ const operator = ({ eq: '=', ne: '=', gt: '>', gte: '>=', lt: '<', lte: '<=' } as const)[
481
+ clause.op
482
+ ]
483
+ const left = text ? sql`lower(${col})` : col
484
+ const right = text ? String(value).toLowerCase() : value
485
+ // `ne` is "has no value equal to this", so a page without the value matches too.
486
+ const matches = eb.exists(row.where(left, operator, right))
487
+ return clause.op === 'ne' ? eb.not(matches) : matches
488
+ })
463
489
  }
464
490
 
465
491
  // ---- sort
466
492
  const by = query.sort?.by ?? 'name'
467
- const dir = query.sort?.dir === 'desc' ? 'DESC' : 'ASC'
493
+ const dir = query.sort?.dir === 'desc' ? 'desc' : 'asc'
468
494
  const sortColumn = {
469
- name: `LOWER(${nameColumn})`,
470
- createDate: 'n.create_date',
471
- updateDate: 'cv.version_date',
472
- path: 'n.path',
473
- sortOrder: 'n.sort_order',
495
+ name: sql`lower(${nameColumn})`,
496
+ createDate: sql.ref('n.create_date'),
497
+ updateDate: sql.ref('cv.version_date'),
498
+ path: sql.ref('n.path'),
499
+ sortOrder: sql.ref('n.sort_order'),
474
500
  }[by]
475
501
 
476
- const from = `node n
477
- JOIN content c ON c.node_id = n.id
478
- JOIN content_type ct ON ct.node_id = c.content_type_id
479
- JOIN node tn ON tn.id = ct.node_id
480
- JOIN document d ON d.node_id = n.id
481
- JOIN content_version cv ON cv.node_id = n.id AND cv.current = ?
482
- ${joins.join('\n')}`
483
- const fromParams = [bool(true), ...joinParams]
484
- const select = `SELECT n.id, n.unique_id, n.path, n.trashed, n.create_date, ${nameColumn} AS name,
485
- ct.alias AS type_alias, tn.unique_id AS type_key, cv.version_date,
486
- ${published} AS published, ${edited} AS edited
487
- FROM ${from} WHERE ${where.join(' AND ')}
488
- ORDER BY ${sortColumn} ${dir}, n.id ${dir}`
489
-
490
- type Row = {
491
- id: number
492
- unique_id: string
493
- path: string
494
- trashed: unknown
495
- create_date: unknown
496
- name: string | null
497
- type_alias: string
498
- type_key: string
499
- version_date: unknown
500
- published: unknown
501
- edited: unknown
502
- }
502
+ const select = q
503
+ .select([
504
+ 'n.id',
505
+ 'n.unique_id',
506
+ 'n.path',
507
+ 'n.trashed',
508
+ 'n.create_date',
509
+ nameColumn.as('name'),
510
+ 'ct.alias as type_alias',
511
+ 'tn.unique_id as type_key',
512
+ 'cv.version_date',
513
+ published.as('published'),
514
+ edited.as('edited'),
515
+ ])
516
+ .orderBy(sortColumn, dir)
517
+ .orderBy('n.id', dir)
518
+
503
519
  let rows: Row[]
504
520
  let total: number
505
521
  let exact = true
506
522
  if (!scope.browses) {
507
- const [count] = await db.query<{ n: number }>(
508
- `SELECT COUNT(*) AS n FROM ${from} WHERE ${where.join(' AND ')}`,
509
- [...fromParams, ...params],
510
- )
523
+ const count = await q.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
511
524
  total = Number(count?.n ?? 0)
512
- rows = await db.query<Row>(`${select} LIMIT ? OFFSET ?`, [
513
- ...fromParams,
514
- ...params,
515
- query.take,
516
- query.skip,
517
- ])
525
+ rows = await select.limit(query.take).offset(query.skip).execute()
518
526
  } else {
519
527
  const limit = scope.window ?? QUERY_WINDOW
520
- const window = await db.query<Row>(`${select} LIMIT ?`, [...fromParams, ...params, limit + 1])
528
+ const window = await select.limit(limit + 1).execute()
521
529
  exact = window.length <= limit
522
530
  const keys = await keysByIds(db, window.slice(0, limit))
523
531
  const visible = window
@@ -529,6 +537,24 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
529
537
  return { total, exact, items: await toItems(db, rows) }
530
538
  }
531
539
 
540
+ type Row = {
541
+ id: number
542
+ unique_id: string
543
+ path: string
544
+ trashed: unknown
545
+ create_date: unknown
546
+ name: string | null
547
+ type_alias: string
548
+ type_key: string
549
+ version_date: unknown
550
+ published: unknown
551
+ edited: unknown
552
+ }
553
+
554
+ /** `left LIKE pattern`, with `\` escaping the pattern's wildcards as `escapeLike` writes them. */
555
+ const like = (left: Expression<unknown>, pattern: string) =>
556
+ sql<boolean>`${left} like ${pattern} escape '\\'`
557
+
532
558
  /** The property types a clause compares, checked for reading and for being comparable. */
533
559
  async function propertyTarget(
534
560
  db: Db,
@@ -538,20 +564,17 @@ async function propertyTarget(
538
564
  op: PropertyOp,
539
565
  ): Promise<PropertyTarget> {
540
566
  const owners = typeIds ? await withCompositions(db, typeIds) : undefined
541
- const rows = await db.query<{
542
- id: number
543
- unique_id: string
544
- db_type: string
545
- editor_alias: string
546
- }>(
547
- `SELECT pt.id, pt.unique_id, dt.db_type, dt.editor_alias FROM property_type pt
548
- JOIN data_type dt ON dt.node_id = pt.data_type_id
549
- JOIN content_type ct ON ct.node_id = pt.content_type_id
550
- JOIN node tn ON tn.id = ct.node_id
551
- WHERE LOWER(pt.alias) = LOWER(?) AND pt.retired_at IS NULL AND tn.node_object_type = ?
552
- ${owners ? `AND pt.content_type_id IN (${owners.map(() => '?').join(', ')})` : ''}`,
553
- [alias, ObjectTypes.DocumentType, ...(owners ?? [])],
554
- )
567
+ const rows = await db.q
568
+ .selectFrom('property_type as pt')
569
+ .innerJoin('data_type as dt', 'dt.node_id', 'pt.data_type_id')
570
+ .innerJoin('content_type as ct', 'ct.node_id', 'pt.content_type_id')
571
+ .innerJoin('node as tn', 'tn.id', 'ct.node_id')
572
+ .select(['pt.id', 'pt.unique_id', 'dt.db_type', 'dt.editor_alias'])
573
+ .where((eb) => eb(eb.fn('lower', ['pt.alias']), '=', eb.fn('lower', [eb.val(alias)])))
574
+ .where('pt.retired_at', 'is', null)
575
+ .where('tn.node_object_type', '=', ObjectTypes.DocumentType)
576
+ .$if(owners !== undefined, (qb) => qb.where('pt.content_type_id', 'in', owners as number[]))
577
+ .execute()
555
578
  if (rows.length === 0)
556
579
  throw new ContentQueryRefused(
557
580
  `There is no property "${alias}"${typeIds ? ' on the content types given' : ''}.`,
@@ -577,9 +600,10 @@ async function propertyTarget(
577
600
 
578
601
  /** The types and every type they are composed of, transitively. */
579
602
  async function withCompositions(db: Db, typeIds: number[]): Promise<number[]> {
580
- const links = await db.query<{ parent: number; child: number }>(
581
- 'SELECT parent_content_type_id AS parent, child_content_type_id AS child FROM content_type_composition',
582
- )
603
+ const links = await db.q
604
+ .selectFrom('content_type_composition')
605
+ .select(['parent_content_type_id as parent', 'child_content_type_id as child'])
606
+ .execute()
583
607
  const found = new Set(typeIds)
584
608
  let grew = true
585
609
  while (grew) {
@@ -629,10 +653,11 @@ async function keysByIds(
629
653
  const all = [...ids]
630
654
  for (let i = 0; i < all.length; i += 500) {
631
655
  const chunk = all.slice(i, i + 500)
632
- const found = await db.query<{ id: number; unique_id: string; text: string | null }>(
633
- `SELECT id, unique_id, text FROM node WHERE id IN (${chunk.map(() => '?').join(', ')})`,
634
- chunk,
635
- )
656
+ const found = await db.q
657
+ .selectFrom('node')
658
+ .select(['id', 'unique_id', 'text'])
659
+ .where('id', 'in', chunk)
660
+ .execute()
636
661
  for (const f of found)
637
662
  map.set(Number(f.id), { key: String(f.unique_id).toLowerCase(), name: String(f.text ?? '') })
638
663
  }
@@ -654,38 +679,18 @@ function chainOf(
654
679
  return [...ancestors.filter(Boolean), String(key).toLowerCase()]
655
680
  }
656
681
 
657
- async function toItems(
658
- db: Db,
659
- rows: ReadonlyArray<{
660
- id: number
661
- unique_id: string
662
- path: string
663
- trashed: unknown
664
- create_date: unknown
665
- name: string | null
666
- type_alias: string
667
- type_key: string
668
- version_date: unknown
669
- published: unknown
670
- edited: unknown
671
- }>,
672
- ): Promise<QueryItem[]> {
682
+ async function toItems(db: Db, rows: readonly Row[]): Promise<QueryItem[]> {
673
683
  if (rows.length === 0) return []
674
684
  const keys = await keysByIds(db, rows)
675
685
  const ids = rows.map((r) => Number(r.id))
676
- const cultures = await db.query<{
677
- node_id: number
678
- iso_code: string
679
- name: string | null
680
- published: unknown
681
- edited: unknown
682
- }>(
683
- `SELECT dcv.node_id, l.iso_code, dcv.name, dcv.published, dcv.edited
684
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
685
- WHERE dcv.available = ? AND dcv.node_id IN (${ids.map(() => '?').join(', ')})
686
- ORDER BY l.iso_code`,
687
- [db.dialect.boolValue(true), ...ids],
688
- )
686
+ const cultures = await db.q
687
+ .selectFrom('document_culture_variation as dcv')
688
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
689
+ .select(['dcv.node_id', 'l.iso_code', 'dcv.name', 'dcv.published', 'dcv.edited'])
690
+ .where('dcv.available', '=', db.dialect.boolValue(true) as boolean)
691
+ .where('dcv.node_id', 'in', ids)
692
+ .orderBy('l.iso_code')
693
+ .execute()
689
694
  const iso = (value: unknown) => (DbDate.fromDb(value) ?? new Date(0)).toISOString()
690
695
  return rows.map((row) => {
691
696
  const trashed = fromDbBool(row.trashed)