@crombolo/data 0.36.2 → 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
@@ -31,6 +31,7 @@ import type { Db } from '../database.ts'
31
31
  import { DbDate, fromDbBool } from '../dialect.ts'
32
32
  import { type LockId, Locks } from '../locks.ts'
33
33
  import { isPending } from '../pending.ts'
34
+ import { type Insertable, sql } from '../query.ts'
34
35
  import {
35
36
  assertNodeMayWrite,
36
37
  BASELINE_NODE_STATE,
@@ -39,6 +40,7 @@ import {
39
40
  visibleStateIdFor,
40
41
  } from '../schema-state.ts'
41
42
  import { queueForSearch } from '../search.ts'
43
+ import type { CoreTables } from '../tables.gen.ts'
42
44
  import { recordFiles } from './media-access.ts'
43
45
  import { NodeRepository, type NodeRow } from './nodes.ts'
44
46
 
@@ -338,6 +340,9 @@ export interface CurrentNodeRow {
338
340
  }
339
341
 
340
342
  /** Ids in slices small enough for either dialect's parameter limit. */
343
+ /** A turn for whatever else is waiting: a request, while a long read runs. */
344
+ const giveWay = () => new Promise<void>((resolve) => setImmediate(resolve))
345
+
341
346
  const slices = <T>(items: readonly T[], size = 500): T[][] =>
342
347
  Array.from({ length: Math.ceil(items.length / size) }, (_, n) =>
343
348
  items.slice(n * size, (n + 1) * size),
@@ -452,15 +457,22 @@ export class DocumentRepository {
452
457
  async versions(key: string): Promise<DocumentVersionSummary[]> {
453
458
  const node = await this.#nodes.byKey(key)
454
459
  if (!node) return []
455
- const rows = await this.#db.query(
456
- `SELECT cv.id, cv.kind, cv.version_date, cv.current, cv.prevent_cleanup, dv.published, u.key AS user_key
457
- FROM content_version cv
458
- JOIN document_version dv ON dv.id = cv.id
459
- LEFT JOIN user_account u ON u.id = cv.user_id
460
- WHERE cv.node_id = ?
461
- ORDER BY cv.id DESC`,
462
- [node.id],
463
- )
460
+ const rows = await this.#db.q
461
+ .selectFrom('content_version as cv')
462
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
463
+ .leftJoin('user_account as u', 'u.id', 'cv.user_id')
464
+ .select([
465
+ 'cv.id',
466
+ 'cv.kind',
467
+ 'cv.version_date',
468
+ 'cv.current',
469
+ 'cv.prevent_cleanup',
470
+ 'dv.published',
471
+ 'u.key as user_key',
472
+ ])
473
+ .where('cv.node_id', '=', node.id)
474
+ .orderBy('cv.id', 'desc')
475
+ .execute()
464
476
  return rows.map((row) => ({
465
477
  id: String(row.id),
466
478
  documentKey: node.key,
@@ -481,23 +493,40 @@ export class DocumentRepository {
481
493
  */
482
494
  /** Every published node of this kind, for the published cache. Elements too. */
483
495
  async loadPublished(asOfSchemaStateId?: number): Promise<PublishedNodeRow[]> {
484
- const t = this.#db.dialect.boolValue(true)
485
- const f = this.#db.dialect.boolValue(false)
486
- const rows = await this.#db.query(
487
- `SELECT n.id, n.unique_id, n.parent_id, n.level, n.path, n.sort_order, n.create_date,
488
- cv.id AS event_id, cv.text AS name, cv.version_date,
489
- ct.alias AS content_type_alias, c.content_type_id, tpl.alias AS template_alias
490
- FROM node n
491
- JOIN content c ON c.node_id = n.id
492
- JOIN content_type ct ON ct.node_id = c.content_type_id
493
- JOIN document d ON d.node_id = n.id
494
- JOIN content_version cv ON cv.node_id = n.id
495
- JOIN document_version dv ON dv.id = cv.id AND dv.published = ?
496
- LEFT JOIN template tpl ON tpl.node_id = dv.template_id
497
- WHERE d.published = ? AND n.trashed = ? AND n.node_object_type = ?
498
- ORDER BY n.level, n.sort_order, n.id`,
499
- [t, t, f, this.objectType],
500
- )
496
+ const t = this.#db.dialect.boolValue(true) as boolean
497
+ const f = this.#db.dialect.boolValue(false) as boolean
498
+ const rows = await this.#db.q
499
+ .selectFrom('node as n')
500
+ .innerJoin('content as c', 'c.node_id', 'n.id')
501
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
502
+ .innerJoin('document as d', 'd.node_id', 'n.id')
503
+ .innerJoin('content_version as cv', 'cv.node_id', 'n.id')
504
+ .innerJoin('document_version as dv', (join) =>
505
+ join.onRef('dv.id', '=', 'cv.id').on('dv.published', '=', t),
506
+ )
507
+ .leftJoin('template as tpl', 'tpl.node_id', 'dv.template_id')
508
+ .select([
509
+ 'n.id',
510
+ 'n.unique_id',
511
+ 'n.parent_id',
512
+ 'n.level',
513
+ 'n.path',
514
+ 'n.sort_order',
515
+ 'n.create_date',
516
+ 'cv.id as event_id',
517
+ 'cv.text as name',
518
+ 'cv.version_date',
519
+ 'ct.alias as content_type_alias',
520
+ 'c.content_type_id',
521
+ 'tpl.alias as template_alias',
522
+ ])
523
+ .where('d.published', '=', t)
524
+ .where('n.trashed', '=', f)
525
+ .where('n.node_object_type', '=', this.objectType)
526
+ .orderBy('n.level')
527
+ .orderBy('n.sort_order')
528
+ .orderBy('n.id')
529
+ .execute()
501
530
  const languages = await this.#languages()
502
531
  // Read in slices rather than per node: a large site is tens of thousands
503
532
  // of nodes, and a query each is most of a rebuild's time.
@@ -505,13 +534,16 @@ export class DocumentRepository {
505
534
  const culturesById = new Map<number, PublishedCulture[]>()
506
535
  const historyById = new Map<number, ValueRow[]>()
507
536
  for (const slice of slices(rows.map((row) => Number(row.id)))) {
537
+ // SQLite reads without giving the thread up: let waiting requests in.
538
+ await giveWay()
508
539
  for (const [id, cultures] of await this.#publishedCultureEventsFor(slice))
509
540
  culturesById.set(id, cultures)
510
541
  for (const [id, history] of await this.#valueHistoryFor(slice, asOfSchemaStateId))
511
542
  historyById.set(id, history)
512
543
  }
513
544
  const published: PublishedNodeRow[] = []
514
- for (const row of rows) {
545
+ for (const [index, row] of rows.entries()) {
546
+ if (index % 250 === 0) await giveWay()
515
547
  const typeId = Number(row.content_type_id)
516
548
  if (!typesById.has(typeId))
517
549
  // A pending property is never rendered, even if a template asks for it.
@@ -555,19 +587,36 @@ export class DocumentRepository {
555
587
  * id or (media) file address — through indexed lookups, in the order asked.
556
588
  */
557
589
  async loadCurrent(filter?: CurrentFilter): Promise<CurrentNodeRow[]> {
558
- const t = this.#db.dialect.boolValue(true)
559
- const select = `SELECT n.id, n.unique_id, n.text, n.parent_id, n.path, n.sort_order, n.create_date,
560
- head.text AS draft_name, head.version_date,
561
- ct.alias AS content_type_alias, c.content_type_id,
562
- c.read_policy, c.write_policy, c.creator_member_key, c.file_url
563
- FROM node n
564
- JOIN content c ON c.node_id = n.id
565
- JOIN content_type ct ON ct.node_id = c.content_type_id
566
- JOIN content_version head ON head.node_id = n.id AND head.current = ?
567
- WHERE n.node_object_type = ? AND n.trashed = ?`
568
- const base = [t, this.objectType, this.#db.dialect.boolValue(false)]
569
- let rows: Record<string, unknown>[]
570
- if (!filter) rows = await this.#db.query(`${select} ORDER BY n.level, n.sort_order, n.id`, base)
590
+ const t = this.#db.dialect.boolValue(true) as boolean
591
+ const select = this.#db.q
592
+ .selectFrom('node as n')
593
+ .innerJoin('content as c', 'c.node_id', 'n.id')
594
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
595
+ .innerJoin('content_version as head', (join) =>
596
+ join.onRef('head.node_id', '=', 'n.id').on('head.current', '=', t),
597
+ )
598
+ .select([
599
+ 'n.id',
600
+ 'n.unique_id',
601
+ 'n.text',
602
+ 'n.parent_id',
603
+ 'n.path',
604
+ 'n.sort_order',
605
+ 'n.create_date',
606
+ 'head.text as draft_name',
607
+ 'head.version_date',
608
+ 'ct.alias as content_type_alias',
609
+ 'c.content_type_id',
610
+ 'c.read_policy',
611
+ 'c.write_policy',
612
+ 'c.creator_member_key',
613
+ 'c.file_url',
614
+ ])
615
+ .where('n.node_object_type', '=', this.objectType)
616
+ .where('n.trashed', '=', this.#db.dialect.boolValue(false) as boolean)
617
+ let rows: Awaited<ReturnType<typeof select.execute>>
618
+ if (!filter)
619
+ rows = await select.orderBy('n.level').orderBy('n.sort_order').orderBy('n.id').execute()
571
620
  else {
572
621
  const [column, wanted] =
573
622
  filter.keys !== undefined
@@ -577,14 +626,9 @@ export class DocumentRepository {
577
626
  : ['c.file_url', [...new Set(filter.urls ?? [])]]
578
627
  rows = []
579
628
  for (const slice of slices<string | number>(wanted))
580
- rows.push(
581
- ...(await this.#db.query(
582
- `${select} AND ${column} IN (${slice.map(() => '?').join(', ')})`,
583
- [...base, ...slice],
584
- )),
585
- )
629
+ rows.push(...(await select.where(sql.ref(column), 'in', slice).execute()))
586
630
  const order = new Map(wanted.map((value, index) => [String(value), index]))
587
- const at = (row: Record<string, unknown>) =>
631
+ const at = (row: (typeof rows)[number]) =>
588
632
  order.get(
589
633
  column === 'n.unique_id'
590
634
  ? normaliseUuid(String(row.unique_id))
@@ -634,17 +678,29 @@ export class DocumentRepository {
634
678
  * reading an older schema state, the latest at or before it. Read in slices.
635
679
  */
636
680
  async #currentValueRowsFor(ids: number[]): Promise<Map<number, ValueRow[]>> {
637
- const t = this.#db.dialect.boolValue(true)
681
+ const t = this.#db.dialect.boolValue(true) as boolean
638
682
  const stateId = await visibleStateIdFor(this.#db, this.#nodeState)
639
683
  const rowsById = new Map<number, ValueRow[]>()
640
684
  for (const slice of slices(ids)) {
641
685
  if (stateId === undefined) {
642
- const current = await this.#db.query(
643
- `SELECT id, node_id, event_id, property_type_id, language_id, segment,
644
- int_value, decimal_value, date_value, varchar_value, text_value
645
- FROM property_value WHERE node_id IN (${slice.map(() => '?').join(', ')}) AND is_current = ?`,
646
- [...slice, t],
647
- )
686
+ const current = await this.#db.q
687
+ .selectFrom('property_value')
688
+ .select([
689
+ 'id',
690
+ 'node_id',
691
+ 'event_id',
692
+ 'property_type_id',
693
+ 'language_id',
694
+ 'segment',
695
+ 'int_value',
696
+ 'decimal_value',
697
+ 'date_value',
698
+ 'varchar_value',
699
+ 'text_value',
700
+ ])
701
+ .where('node_id', 'in', slice)
702
+ .where('is_current', '=', t)
703
+ .execute()
648
704
  for (const row of current) {
649
705
  const id = Number(row.node_id)
650
706
  rowsById.set(id, [...(rowsById.get(id) ?? []), this.#toValueRow(row)])
@@ -668,32 +724,49 @@ export class DocumentRepository {
668
724
  * (story 053). A culture is there once it has a name.
669
725
  */
670
726
  async loadDrafts(): Promise<PublishedNodeRow[]> {
671
- const t = this.#db.dialect.boolValue(true)
672
- const rows = await this.#db.query(
673
- `SELECT n.id, n.unique_id, n.parent_id, n.level, n.path, n.sort_order, n.create_date, n.text,
674
- head.text AS draft_name, head.version_date,
675
- ct.alias AS content_type_alias, c.content_type_id, tpl.alias AS template_alias
676
- FROM node n
677
- JOIN content c ON c.node_id = n.id
678
- JOIN content_type ct ON ct.node_id = c.content_type_id
679
- JOIN content_version head ON head.node_id = n.id AND head.current = ?
680
- JOIN document_version hv ON hv.id = head.id
681
- LEFT JOIN template tpl ON tpl.node_id = hv.template_id
682
- WHERE n.node_object_type = ? AND n.trashed = ?
683
- ORDER BY n.level, n.sort_order, n.id`,
684
- [t, this.objectType, this.#db.dialect.boolValue(false)],
685
- )
727
+ const t = this.#db.dialect.boolValue(true) as boolean
728
+ const rows = await this.#db.q
729
+ .selectFrom('node as n')
730
+ .innerJoin('content as c', 'c.node_id', 'n.id')
731
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
732
+ .innerJoin('content_version as head', (join) =>
733
+ join.onRef('head.node_id', '=', 'n.id').on('head.current', '=', t),
734
+ )
735
+ .innerJoin('document_version as hv', 'hv.id', 'head.id')
736
+ .leftJoin('template as tpl', 'tpl.node_id', 'hv.template_id')
737
+ .select([
738
+ 'n.id',
739
+ 'n.unique_id',
740
+ 'n.parent_id',
741
+ 'n.level',
742
+ 'n.path',
743
+ 'n.sort_order',
744
+ 'n.create_date',
745
+ 'n.text',
746
+ 'head.text as draft_name',
747
+ 'head.version_date',
748
+ 'ct.alias as content_type_alias',
749
+ 'c.content_type_id',
750
+ 'tpl.alias as template_alias',
751
+ ])
752
+ .where('n.node_object_type', '=', this.objectType)
753
+ .where('n.trashed', '=', this.#db.dialect.boolValue(false) as boolean)
754
+ .orderBy('n.level')
755
+ .orderBy('n.sort_order')
756
+ .orderBy('n.id')
757
+ .execute()
686
758
  const ids = rows.map((row) => Number(row.id))
687
759
  const languages = await this.#languages()
688
760
  const valuesById = await this.#currentValueRowsFor(ids)
689
761
  const culturesById = new Map<number, Array<{ isoCode: string; name: string }>>()
690
762
  for (const slice of slices(ids)) {
691
- const cultureRows = await this.#db.query(
692
- `SELECT dcv.node_id, dcv.name, l.iso_code
693
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
694
- WHERE dcv.node_id IN (${slice.map(() => '?').join(', ')}) AND dcv.available = ?`,
695
- [...slice, t],
696
- )
763
+ const cultureRows = await this.#db.q
764
+ .selectFrom('document_culture_variation as dcv')
765
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
766
+ .select(['dcv.node_id', 'dcv.name', 'l.iso_code'])
767
+ .where('dcv.node_id', 'in', slice)
768
+ .where('dcv.available', '=', t)
769
+ .execute()
697
770
  for (const row of cultureRows) {
698
771
  const id = Number(row.node_id)
699
772
  culturesById.set(id, [
@@ -762,15 +835,18 @@ export class DocumentRepository {
762
835
  userId: input.userId,
763
836
  })
764
837
 
765
- await tx.exec('INSERT INTO content (node_id, content_type_id) VALUES (?, ?)', [
766
- node.id,
767
- contentTypeNode.id,
768
- ])
769
- await tx.exec('INSERT INTO document (node_id, published, edited) VALUES (?, ?, ?)', [
770
- node.id,
771
- tx.dialect.boolValue(false),
772
- tx.dialect.boolValue(true),
773
- ])
838
+ await tx.q
839
+ .insertInto('content')
840
+ .values({ node_id: node.id, content_type_id: contentTypeNode.id })
841
+ .execute()
842
+ await tx.q
843
+ .insertInto('document')
844
+ .values({
845
+ node_id: node.id,
846
+ published: tx.dialect.boolValue(false) as boolean,
847
+ edited: tx.dialect.boolValue(true) as boolean,
848
+ })
849
+ .execute()
774
850
 
775
851
  const templateId = input.componentKey
776
852
  ? ((await repo.nodes.byKey(input.componentKey))?.id ?? null)
@@ -805,13 +881,15 @@ export class DocumentRepository {
805
881
  }>
806
882
  > {
807
883
  if (contentTypeNodeIds.length === 0) return []
808
- const rows = await this.#db.query(
809
- `SELECT n.id, n.unique_id, n.text, c.content_type_id, d.published FROM content c
810
- JOIN node n ON n.id = c.node_id JOIN document d ON d.node_id = n.id
811
- WHERE c.content_type_id IN (${contentTypeNodeIds.map(() => '?').join(', ')}) AND n.trashed = ?
812
- ORDER BY n.path`,
813
- [...contentTypeNodeIds, this.#db.dialect.boolValue(false)],
814
- )
884
+ const rows = await this.#db.q
885
+ .selectFrom('content as c')
886
+ .innerJoin('node as n', 'n.id', 'c.node_id')
887
+ .innerJoin('document as d', 'd.node_id', 'n.id')
888
+ .select(['n.id', 'n.unique_id', 'n.text', 'c.content_type_id', 'd.published'])
889
+ .where('c.content_type_id', 'in', contentTypeNodeIds)
890
+ .where('n.trashed', '=', this.#db.dialect.boolValue(false) as boolean)
891
+ .orderBy('n.path')
892
+ .execute()
815
893
  return rows.map((row) => ({
816
894
  key: normaliseUuid(String(row.unique_id)),
817
895
  nodeId: Number(row.id),
@@ -830,15 +908,28 @@ export class DocumentRepository {
830
908
  if (aliases.length === 0) return []
831
909
  const languages = await this.#languages()
832
910
  const isoById = new Map(languages.map((l) => [l.id, l.isoCode]))
833
- const rows = await this.#db.query(
834
- `SELECT pv.id, pv.event_id, pv.schema_state_id, pv.language_id, pv.segment, pv.int_value, pv.decimal_value,
835
- pv.date_value, pv.varchar_value, pv.text_value, p.alias, d.db_type
836
- FROM property_value pv
837
- JOIN property_type p ON p.id = pv.property_type_id
838
- JOIN data_type d ON d.node_id = p.data_type_id
839
- WHERE pv.node_id = ? AND pv.is_current = ? AND p.alias IN (${aliases.map(() => '?').join(', ')})`,
840
- [nodeId, this.#db.dialect.boolValue(true), ...aliases],
841
- )
911
+ const rows = await this.#db.q
912
+ .selectFrom('property_value as pv')
913
+ .innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
914
+ .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
915
+ .select([
916
+ 'pv.id',
917
+ 'pv.event_id',
918
+ 'pv.schema_state_id',
919
+ 'pv.language_id',
920
+ 'pv.segment',
921
+ 'pv.int_value',
922
+ 'pv.decimal_value',
923
+ 'pv.date_value',
924
+ 'pv.varchar_value',
925
+ 'pv.text_value',
926
+ 'p.alias',
927
+ 'd.db_type',
928
+ ])
929
+ .where('pv.node_id', '=', nodeId)
930
+ .where('pv.is_current', '=', this.#db.dialect.boolValue(true) as boolean)
931
+ .where('p.alias', 'in', aliases)
932
+ .execute()
842
933
  const out: CurrentValue[] = []
843
934
  for (const row of rows) {
844
935
  const storage = String(row.db_type) as ValueStorageTypeName
@@ -895,10 +986,18 @@ export class DocumentRepository {
895
986
  ]),
896
987
  )
897
988
  const head = await repo.#headEvent(node.id)
898
- const published = await tx.query<{ id: number }>(
899
- 'SELECT cv.id FROM content_version cv JOIN document_version dv ON dv.id = cv.id AND dv.published = ? WHERE cv.node_id = ? ORDER BY cv.id DESC LIMIT 1',
900
- [tx.dialect.boolValue(true), node.id],
901
- )
989
+ const published = await tx.q
990
+ .selectFrom('content_version as cv')
991
+ .innerJoin('document_version as dv', (join) =>
992
+ join
993
+ .onRef('dv.id', '=', 'cv.id')
994
+ .on('dv.published', '=', tx.dialect.boolValue(true) as boolean),
995
+ )
996
+ .select('cv.id')
997
+ .where('cv.node_id', '=', node.id)
998
+ .orderBy('cv.id', 'desc')
999
+ .limit(1)
1000
+ .execute()
902
1001
  const fallbackEvent = Number(published[0]?.id ?? head?.id ?? 0)
903
1002
  let written = false
904
1003
  for (const value of values) {
@@ -1030,12 +1129,15 @@ export class DocumentRepository {
1030
1129
  await repo.#assertMandatoryFilled(node, targets)
1031
1130
 
1032
1131
  const head = await repo.#headEvent(node.id)
1033
- const t = tx.dialect.boolValue(true)
1034
- const f = tx.dialect.boolValue(false)
1035
- await tx.exec(
1036
- 'UPDATE document_version SET published = ? WHERE id IN (SELECT id FROM content_version WHERE node_id = ?)',
1037
- [f, node.id],
1038
- )
1132
+ const t = tx.dialect.boolValue(true) as boolean
1133
+ const f = tx.dialect.boolValue(false) as boolean
1134
+ await tx.q
1135
+ .updateTable('document_version')
1136
+ .set({ published: f })
1137
+ .where('id', 'in', (eb) =>
1138
+ eb.selectFrom('content_version').select('id').where('node_id', '=', node.id),
1139
+ )
1140
+ .execute()
1039
1141
  const eventId = await repo.#insertEvent(
1040
1142
  node.id,
1041
1143
  'publish',
@@ -1044,7 +1146,11 @@ export class DocumentRepository {
1044
1146
  head?.templateId ?? null,
1045
1147
  true,
1046
1148
  )
1047
- await tx.exec('UPDATE document SET published = ? WHERE node_id = ?', [t, node.id])
1149
+ await tx.q
1150
+ .updateTable('document')
1151
+ .set({ published: t })
1152
+ .where('node_id', '=', node.id)
1153
+ .execute()
1048
1154
  for (const iso of targets ?? []) await repo.#setCulturePublished(node.id, iso, eventId)
1049
1155
  await repo.#recomputeEdited(node.id)
1050
1156
  await repo.#instructContent(node.key)
@@ -1134,15 +1240,21 @@ export class DocumentRepository {
1134
1240
  for (const iso of isoCodes) await repo.#setCulturePublished(node.id, iso, null)
1135
1241
  if (everything || !(await repo.#anyCulturePublished(node.id))) {
1136
1242
  // Events survive an unpublish; only the flags change.
1137
- await tx.exec(
1138
- 'UPDATE document_version SET published = ? WHERE id IN (SELECT id FROM content_version WHERE node_id = ?)',
1139
- [tx.dialect.boolValue(false), node.id],
1140
- )
1141
- await tx.exec('UPDATE document SET published = ?, edited = ? WHERE node_id = ?', [
1142
- tx.dialect.boolValue(false),
1143
- tx.dialect.boolValue(true),
1144
- node.id,
1145
- ])
1243
+ await tx.q
1244
+ .updateTable('document_version')
1245
+ .set({ published: tx.dialect.boolValue(false) as boolean })
1246
+ .where('id', 'in', (eb) =>
1247
+ eb.selectFrom('content_version').select('id').where('node_id', '=', node.id),
1248
+ )
1249
+ .execute()
1250
+ await tx.q
1251
+ .updateTable('document')
1252
+ .set({
1253
+ published: tx.dialect.boolValue(false) as boolean,
1254
+ edited: tx.dialect.boolValue(true) as boolean,
1255
+ })
1256
+ .where('node_id', '=', node.id)
1257
+ .execute()
1146
1258
  }
1147
1259
  // Site search holds published values only; what this took offline leaves it.
1148
1260
  await queueForSearch(tx, [node.id])
@@ -1186,11 +1298,20 @@ export class DocumentRepository {
1186
1298
  }
1187
1299
 
1188
1300
  async #revision(nodeId: number): Promise<string> {
1189
- const rows = await this.#db.query<{ head: number | null; value: number | null }>(
1190
- `SELECT (SELECT MAX(id) FROM content_version WHERE node_id = ?) AS head,
1191
- (SELECT MAX(id) FROM property_value WHERE node_id = ?) AS value`,
1192
- [nodeId, nodeId],
1193
- )
1301
+ const rows = await this.#db.q
1302
+ .selectNoFrom((eb) => [
1303
+ eb
1304
+ .selectFrom('content_version')
1305
+ .select((e) => e.fn.max('id').as('id'))
1306
+ .where('node_id', '=', nodeId)
1307
+ .as('head'),
1308
+ eb
1309
+ .selectFrom('property_value')
1310
+ .select((e) => e.fn.max('id').as('id'))
1311
+ .where('node_id', '=', nodeId)
1312
+ .as('value'),
1313
+ ])
1314
+ .execute()
1194
1315
  return revisionString(rows[0]?.head, rows[0]?.value)
1195
1316
  }
1196
1317
 
@@ -1208,10 +1329,11 @@ export class DocumentRepository {
1208
1329
  const repo = this.#child(tx)
1209
1330
  const state = await assertNodeMayWrite(tx, this.#nodeState)
1210
1331
  const targetId = Number(versionId)
1211
- const rows = await tx.query<{ node_id: number; text: string | null; user_id: number | null }>(
1212
- 'SELECT node_id, text, user_id FROM content_version WHERE id = ?',
1213
- [targetId],
1214
- )
1332
+ const rows = await tx.q
1333
+ .selectFrom('content_version')
1334
+ .select(['node_id', 'text', 'user_id'])
1335
+ .where('id', '=', targetId)
1336
+ .execute()
1215
1337
  const target = rows[0]
1216
1338
  if (!target) return undefined
1217
1339
  const node = await repo.nodes.byId(Number(target.node_id))
@@ -1220,10 +1342,11 @@ export class DocumentRepository {
1220
1342
  const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
1221
1343
  if (!contentTypeNodeId) return undefined
1222
1344
 
1223
- const templateRows = await tx.query<{ template_id: number | null }>(
1224
- 'SELECT template_id FROM document_version WHERE id = ?',
1225
- [targetId],
1226
- )
1345
+ const templateRows = await tx.q
1346
+ .selectFrom('document_version')
1347
+ .select('template_id')
1348
+ .where('id', '=', targetId)
1349
+ .execute()
1227
1350
  const name = String(target.text ?? node.text ?? '')
1228
1351
  const eventId = await repo.#insertEvent(
1229
1352
  node.id,
@@ -1247,15 +1370,17 @@ export class DocumentRepository {
1247
1370
  }
1248
1371
 
1249
1372
  async setPreventCleanup(versionId: string, prevent: boolean): Promise<boolean> {
1250
- const rows = await this.#db.query<{ id: number }>(
1251
- 'SELECT id FROM content_version WHERE id = ?',
1252
- [Number(versionId)],
1253
- )
1373
+ const rows = await this.#db.q
1374
+ .selectFrom('content_version')
1375
+ .select('id')
1376
+ .where('id', '=', Number(versionId))
1377
+ .execute()
1254
1378
  if (!rows[0]) return false
1255
- await this.#db.exec('UPDATE content_version SET prevent_cleanup = ? WHERE id = ?', [
1256
- this.#db.dialect.boolValue(prevent),
1257
- Number(versionId),
1258
- ])
1379
+ await this.#db.q
1380
+ .updateTable('content_version')
1381
+ .set({ prevent_cleanup: this.#db.dialect.boolValue(prevent) as boolean })
1382
+ .where('id', '=', Number(versionId))
1383
+ .execute()
1259
1384
  return true
1260
1385
  }
1261
1386
 
@@ -1275,36 +1400,44 @@ export class DocumentRepository {
1275
1400
  if (node.parentId === bin) return true
1276
1401
  // Read before the move, while the branch's paths are still under the node's own.
1277
1402
  const branch = (
1278
- await tx.query<{ id: number }>('SELECT id FROM node WHERE id = ? OR path LIKE ?', [
1279
- node.id,
1280
- `${node.path},%`,
1281
- ])
1403
+ await tx.q
1404
+ .selectFrom('node')
1405
+ .select('id')
1406
+ .where((eb) => eb.or([eb('id', '=', node.id), eb('path', 'like', `${node.path},%`)]))
1407
+ .execute()
1282
1408
  ).map((row) => Number(row.id))
1283
- const t = tx.dialect.boolValue(true)
1284
- const f = tx.dialect.boolValue(false)
1285
- await tx.exec(
1286
- 'UPDATE document SET original_parent_id = ?, trashed_date = ? WHERE node_id = ?',
1287
- [
1288
- node.parentId === SystemNodes.Root ? null : node.parentId,
1289
- DbDate.toDb(new Date()),
1290
- node.id,
1291
- ],
1292
- )
1409
+ const t = tx.dialect.boolValue(true) as boolean
1410
+ const f = tx.dialect.boolValue(false) as boolean
1411
+ await tx.q
1412
+ .updateTable('document')
1413
+ .set({
1414
+ original_parent_id: node.parentId === SystemNodes.Root ? null : node.parentId,
1415
+ trashed_date: DbDate.toDb(new Date()),
1416
+ })
1417
+ .where('node_id', '=', node.id)
1418
+ .execute()
1293
1419
  // The whole branch goes with it, and stays unpublished while trashed.
1294
- await tx.exec('UPDATE node SET trashed = ? WHERE id = ? OR path LIKE ?', [
1295
- t,
1296
- node.id,
1297
- `${node.path},%`,
1298
- ])
1299
- await tx.exec(
1300
- `UPDATE document SET published = ?, edited = ? WHERE node_id IN (SELECT id FROM node WHERE id = ? OR path LIKE ?)`,
1301
- [f, t, node.id, `${node.path},%`],
1302
- )
1420
+ await tx.q
1421
+ .updateTable('node')
1422
+ .set({ trashed: t })
1423
+ .where((eb) => eb.or([eb('id', '=', node.id), eb('path', 'like', `${node.path},%`)]))
1424
+ .execute()
1425
+ await tx.q
1426
+ .updateTable('document')
1427
+ .set({ published: f, edited: t })
1428
+ .where('node_id', 'in', (eb) =>
1429
+ eb
1430
+ .selectFrom('node')
1431
+ .select('id')
1432
+ .where((w) => w.or([w('id', '=', node.id), w('path', 'like', `${node.path},%`)])),
1433
+ )
1434
+ .execute()
1303
1435
  await repo.nodes.move(node.id, bin)
1304
- await tx.exec('UPDATE node SET sort_order = ? WHERE id = ?', [
1305
- await repo.#nextSortOrder(bin, node.id),
1306
- node.id,
1307
- ])
1436
+ await tx.q
1437
+ .updateTable('node')
1438
+ .set({ sort_order: await repo.#nextSortOrder(bin, node.id) })
1439
+ .where('id', '=', node.id)
1440
+ .execute()
1308
1441
  // The branch is no longer published: other nodes drop it, and so does site search.
1309
1442
  await queueForSearch(tx, branch)
1310
1443
  await repo.#instructContent(node.key)
@@ -1321,34 +1454,35 @@ export class DocumentRepository {
1321
1454
  return this.#db.transaction(async (tx) => {
1322
1455
  const node = await new NodeRepository(tx).byKey(key)
1323
1456
  if (!node) return false
1324
- const ids = await tx.query<{ id: number }>(
1325
- 'SELECT id FROM node WHERE id = ? OR path LIKE ?',
1326
- [node.id, `${node.path},%`],
1327
- )
1457
+ const ids = await tx.q
1458
+ .selectFrom('node')
1459
+ .select('id')
1460
+ .where((eb) => eb.or([eb('id', '=', node.id), eb('path', 'like', `${node.path},%`)]))
1461
+ .execute()
1328
1462
  for (const row of ids.map((r) => Number(r.id)).reverse()) {
1329
- await tx.exec('DELETE FROM property_value WHERE node_id = ?', [row])
1330
- await tx.exec('DELETE FROM content_schedule WHERE node_id = ?', [row])
1331
- await tx.exec('DELETE FROM user_notification WHERE node_id = ?', [row])
1332
- await tx.exec('DELETE FROM domain WHERE node_id = ?', [row])
1333
- await tx.exec(
1334
- 'DELETE FROM media_access_rule WHERE media_access_id IN (SELECT id FROM media_access WHERE node_id = ?)',
1335
- [row],
1336
- )
1337
- await tx.exec('DELETE FROM media_access WHERE node_id = ?', [row])
1338
- await tx.exec('DELETE FROM node_file WHERE node_id = ?', [row])
1339
- await tx.exec(
1340
- 'DELETE FROM content_version_culture_variation WHERE version_id IN (SELECT id FROM content_version WHERE node_id = ?)',
1341
- [row],
1342
- )
1343
- await tx.exec('DELETE FROM document_culture_variation WHERE node_id = ?', [row])
1344
- await tx.exec(
1345
- 'DELETE FROM document_version WHERE id IN (SELECT id FROM content_version WHERE node_id = ?)',
1346
- [row],
1347
- )
1348
- await tx.exec('DELETE FROM content_version WHERE node_id = ?', [row])
1349
- await tx.exec('DELETE FROM document WHERE node_id = ?', [row])
1350
- await tx.exec('DELETE FROM content WHERE node_id = ?', [row])
1351
- await tx.exec('DELETE FROM node WHERE id = ?', [row])
1463
+ const versions = tx.q.selectFrom('content_version').select('id').where('node_id', '=', row)
1464
+ await tx.q.deleteFrom('property_value').where('node_id', '=', row).execute()
1465
+ await tx.q.deleteFrom('content_schedule').where('node_id', '=', row).execute()
1466
+ await tx.q.deleteFrom('user_notification').where('node_id', '=', row).execute()
1467
+ await tx.q.deleteFrom('domain').where('node_id', '=', row).execute()
1468
+ await tx.q
1469
+ .deleteFrom('media_access_rule')
1470
+ .where('media_access_id', 'in', (eb) =>
1471
+ eb.selectFrom('media_access').select('id').where('node_id', '=', row),
1472
+ )
1473
+ .execute()
1474
+ await tx.q.deleteFrom('media_access').where('node_id', '=', row).execute()
1475
+ await tx.q.deleteFrom('node_file').where('node_id', '=', row).execute()
1476
+ await tx.q
1477
+ .deleteFrom('content_version_culture_variation')
1478
+ .where('version_id', 'in', versions)
1479
+ .execute()
1480
+ await tx.q.deleteFrom('document_culture_variation').where('node_id', '=', row).execute()
1481
+ await tx.q.deleteFrom('document_version').where('id', 'in', versions).execute()
1482
+ await tx.q.deleteFrom('content_version').where('node_id', '=', row).execute()
1483
+ await tx.q.deleteFrom('document').where('node_id', '=', row).execute()
1484
+ await tx.q.deleteFrom('content').where('node_id', '=', row).execute()
1485
+ await tx.q.deleteFrom('node').where('id', '=', row).execute()
1352
1486
  }
1353
1487
  // A page deleted from the bin was never served, but an item deleted
1354
1488
  // directly may have been: every node is told (story 174).
@@ -1381,21 +1515,23 @@ export class DocumentRepository {
1381
1515
  const parentId = target?.id ?? SystemNodes.Root
1382
1516
  // Out of the bin is a restore, as Umbraco's Move treats it.
1383
1517
  if (node.trashed) {
1384
- await tx.exec('UPDATE node SET trashed = ? WHERE id = ? OR path LIKE ?', [
1385
- tx.dialect.boolValue(false),
1386
- node.id,
1387
- `${node.path},%`,
1388
- ])
1389
- await tx.exec(
1390
- 'UPDATE document SET original_parent_id = NULL, trashed_date = NULL WHERE node_id = ?',
1391
- [node.id],
1392
- )
1518
+ await tx.q
1519
+ .updateTable('node')
1520
+ .set({ trashed: tx.dialect.boolValue(false) as boolean })
1521
+ .where((eb) => eb.or([eb('id', '=', node.id), eb('path', 'like', `${node.path},%`)]))
1522
+ .execute()
1523
+ await tx.q
1524
+ .updateTable('document')
1525
+ .set({ original_parent_id: null, trashed_date: null })
1526
+ .where('node_id', '=', node.id)
1527
+ .execute()
1393
1528
  }
1394
1529
  await repo.nodes.move(node.id, parentId)
1395
- await tx.exec('UPDATE node SET sort_order = ? WHERE id = ?', [
1396
- await repo.#nextSortOrder(parentId, node.id),
1397
- node.id,
1398
- ])
1530
+ await tx.q
1531
+ .updateTable('node')
1532
+ .set({ sort_order: await repo.#nextSortOrder(parentId, node.id) })
1533
+ .where('id', '=', node.id)
1534
+ .execute()
1399
1535
  await repo.#instructContent(node.key)
1400
1536
  return 'moved'
1401
1537
  }),
@@ -1470,7 +1606,11 @@ export class DocumentRepository {
1470
1606
  }
1471
1607
  for (const item of sorting) {
1472
1608
  const node = byKey.get(normaliseUuid(item.key)) as NodeRow
1473
- await tx.exec('UPDATE node SET sort_order = ? WHERE id = ?', [item.sortOrder, node.id])
1609
+ await tx.q
1610
+ .updateTable('node')
1611
+ .set({ sort_order: item.sortOrder })
1612
+ .where('id', '=', node.id)
1613
+ .execute()
1474
1614
  await this.#child(tx).#instructContent(node.key)
1475
1615
  }
1476
1616
  return 'sorted'
@@ -1528,20 +1668,22 @@ export class DocumentRepository {
1528
1668
  if (parentKey && (!parent || parent.trashed)) return 'invalid'
1529
1669
  await assertNodeMayWrite(tx, this.#nodeState)
1530
1670
  const parentId = parent?.id ?? SystemNodes.Root
1531
- await tx.exec('UPDATE node SET trashed = ? WHERE id = ? OR path LIKE ?', [
1532
- tx.dialect.boolValue(false),
1533
- node.id,
1534
- `${node.path},%`,
1535
- ])
1671
+ await tx.q
1672
+ .updateTable('node')
1673
+ .set({ trashed: tx.dialect.boolValue(false) as boolean })
1674
+ .where((eb) => eb.or([eb('id', '=', node.id), eb('path', 'like', `${node.path},%`)]))
1675
+ .execute()
1536
1676
  await repo.nodes.move(node.id, parentId)
1537
- await tx.exec('UPDATE node SET sort_order = ? WHERE id = ?', [
1538
- await repo.#nextSortOrder(parentId, node.id),
1539
- node.id,
1540
- ])
1541
- await tx.exec(
1542
- 'UPDATE document SET original_parent_id = NULL, trashed_date = NULL WHERE node_id = ?',
1543
- [node.id],
1544
- )
1677
+ await tx.q
1678
+ .updateTable('node')
1679
+ .set({ sort_order: await repo.#nextSortOrder(parentId, node.id) })
1680
+ .where('id', '=', node.id)
1681
+ .execute()
1682
+ await tx.q
1683
+ .updateTable('document')
1684
+ .set({ original_parent_id: null, trashed_date: null })
1685
+ .where('node_id', '=', node.id)
1686
+ .execute()
1545
1687
  // Nothing published comes back, but a preview's drafts do.
1546
1688
  await repo.#instructContent(node.key)
1547
1689
  return 'restored' as const
@@ -1579,12 +1721,17 @@ export class DocumentRepository {
1579
1721
  if (!(error instanceof PublishBlockedError)) throw error
1580
1722
  return { published, failed: [{ key: root.key, reason: error.message }] }
1581
1723
  }
1582
- const rows = await this.#db.query(
1583
- `SELECT n.id, n.unique_id, n.path, d.published FROM node n JOIN document d ON d.node_id = n.id
1584
- WHERE n.path LIKE ? AND n.node_object_type = ? AND n.trashed = ?
1585
- ORDER BY n.level, n.sort_order, n.id`,
1586
- [`${root.path},%`, this.objectType, this.#db.dialect.boolValue(false)],
1587
- )
1724
+ const rows = await this.#db.q
1725
+ .selectFrom('node as n')
1726
+ .innerJoin('document as d', 'd.node_id', 'n.id')
1727
+ .select(['n.id', 'n.unique_id', 'n.path', 'd.published'])
1728
+ .where('n.path', 'like', `${root.path},%`)
1729
+ .where('n.node_object_type', '=', this.objectType)
1730
+ .where('n.trashed', '=', this.#db.dialect.boolValue(false) as boolean)
1731
+ .orderBy('n.level')
1732
+ .orderBy('n.sort_order')
1733
+ .orderBy('n.id')
1734
+ .execute()
1588
1735
  const skipped: string[] = []
1589
1736
  for (const row of rows) {
1590
1737
  const path = String(row.path)
@@ -1612,10 +1759,11 @@ export class DocumentRepository {
1612
1759
  ): Promise<{ versionId: string; document: DocumentAggregate } | undefined> {
1613
1760
  const id = Number(versionId)
1614
1761
  if (!Number.isInteger(id)) return undefined
1615
- const rows = await this.#db.query<{ node_id: number; text: string | null }>(
1616
- 'SELECT node_id, text FROM content_version WHERE id = ?',
1617
- [id],
1618
- )
1762
+ const rows = await this.#db.q
1763
+ .selectFrom('content_version')
1764
+ .select(['node_id', 'text'])
1765
+ .where('id', '=', id)
1766
+ .execute()
1619
1767
  const row = rows[0]
1620
1768
  if (!row) return undefined
1621
1769
  const node = await this.#nodes.byId(Number(row.node_id))
@@ -1670,16 +1818,17 @@ export class DocumentRepository {
1670
1818
  ? (languages.find((l) => l.isoCode.toLowerCase() === entry.culture?.toLowerCase())?.id ??
1671
1819
  null)
1672
1820
  : null
1673
- await tx.exec(
1674
- `DELETE FROM content_schedule WHERE node_id = ? AND ${languageId === null ? 'language_id IS NULL' : 'language_id = ?'}`,
1675
- languageId === null ? [node.id] : [node.id, languageId],
1676
- )
1821
+ await tx.q
1822
+ .deleteFrom('content_schedule')
1823
+ .where('node_id', '=', node.id)
1824
+ .where('language_id', languageId === null ? 'is' : '=', languageId)
1825
+ .execute()
1677
1826
  const add = async (action: 'Release' | 'Expire', date: Date | null) => {
1678
1827
  if (!date) return
1679
- await tx.exec(
1680
- 'INSERT INTO content_schedule (node_id, language_id, action, date) VALUES (?, ?, ?, ?)',
1681
- [node.id, languageId, action, DbDate.toDb(date)],
1682
- )
1828
+ await tx.q
1829
+ .insertInto('content_schedule')
1830
+ .values({ node_id: node.id, language_id: languageId, action, date: DbDate.toDb(date) })
1831
+ .execute()
1683
1832
  }
1684
1833
  await add('Release', entry.publishTime)
1685
1834
  await add('Expire', entry.unpublishTime)
@@ -1695,11 +1844,13 @@ export class DocumentRepository {
1695
1844
  > {
1696
1845
  const node = await this.#nodes.byKey(key)
1697
1846
  if (!node) return []
1698
- const rows = await this.#db.query(
1699
- `SELECT s.id, s.action, s.date, l.iso_code FROM content_schedule s
1700
- LEFT JOIN language l ON l.id = s.language_id WHERE s.node_id = ? ORDER BY s.date`,
1701
- [node.id],
1702
- )
1847
+ const rows = await this.#db.q
1848
+ .selectFrom('content_schedule as s')
1849
+ .leftJoin('language as l', 'l.id', 's.language_id')
1850
+ .select(['s.id', 's.action', 's.date', 'l.iso_code'])
1851
+ .where('s.node_id', '=', node.id)
1852
+ .orderBy('s.date')
1853
+ .execute()
1703
1854
  return rows.map((row) => ({
1704
1855
  id: Number(row.id),
1705
1856
  culture: (row.iso_code as string | null) ?? null,
@@ -1714,12 +1865,16 @@ export class DocumentRepository {
1714
1865
  ): Promise<
1715
1866
  Array<{ id: number; key: string; culture: string | null; action: 'Release' | 'Expire' }>
1716
1867
  > {
1717
- const rows = await this.#db.query(
1718
- `SELECT s.id, s.action, n.unique_id, l.iso_code FROM content_schedule s
1719
- JOIN node n ON n.id = s.node_id LEFT JOIN language l ON l.id = s.language_id
1720
- WHERE s.date <= ? AND n.node_object_type = ? ORDER BY s.date, s.id`,
1721
- [DbDate.toDb(now), this.objectType],
1722
- )
1868
+ const rows = await this.#db.q
1869
+ .selectFrom('content_schedule as s')
1870
+ .innerJoin('node as n', 'n.id', 's.node_id')
1871
+ .leftJoin('language as l', 'l.id', 's.language_id')
1872
+ .select(['s.id', 's.action', 'n.unique_id', 'l.iso_code'])
1873
+ .where('s.date', '<=', DbDate.toDb(now))
1874
+ .where('n.node_object_type', '=', this.objectType)
1875
+ .orderBy('s.date')
1876
+ .orderBy('s.id')
1877
+ .execute()
1723
1878
  return rows.map((row) => ({
1724
1879
  id: Number(row.id),
1725
1880
  key: normaliseUuid(String(row.unique_id)),
@@ -1730,9 +1885,11 @@ export class DocumentRepository {
1730
1885
 
1731
1886
  /** Takes a due schedule for this process; false when another node already did. */
1732
1887
  async claimSchedule(id: number): Promise<boolean> {
1733
- const rows = await this.#db.query('DELETE FROM content_schedule WHERE id = ? RETURNING id', [
1734
- id,
1735
- ])
1888
+ const rows = await this.#db.q
1889
+ .deleteFrom('content_schedule')
1890
+ .where('id', '=', id)
1891
+ .returning('id')
1892
+ .execute()
1736
1893
  return rows.length > 0
1737
1894
  }
1738
1895
 
@@ -1751,13 +1908,18 @@ export class DocumentRepository {
1751
1908
  now: Date,
1752
1909
  global: { keepAllVersionsNewerThanDays: number; keepLatestVersionPerDayForDays: number },
1753
1910
  ): Promise<{ nodes: number; versionsDeleted: number }> {
1754
- const types = await this.#db.query(
1755
- `SELECT c.node_id, ct.prevent_cleanup, ct.keep_all_versions_newer_than_days AS keep_all,
1756
- ct.keep_latest_version_per_day_for_days AS keep_latest
1757
- FROM content c JOIN content_type ct ON ct.node_id = c.content_type_id
1758
- JOIN node n ON n.id = c.node_id WHERE n.node_object_type = ?`,
1759
- [this.objectType],
1760
- )
1911
+ const types = await this.#db.q
1912
+ .selectFrom('content as c')
1913
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
1914
+ .innerJoin('node as n', 'n.id', 'c.node_id')
1915
+ .select([
1916
+ 'c.node_id',
1917
+ 'ct.prevent_cleanup',
1918
+ 'ct.keep_all_versions_newer_than_days as keep_all',
1919
+ 'ct.keep_latest_version_per_day_for_days as keep_latest',
1920
+ ])
1921
+ .where('n.node_object_type', '=', this.objectType)
1922
+ .execute()
1761
1923
  const day = 24 * 60 * 60 * 1000
1762
1924
  let nodes = 0
1763
1925
  let versionsDeleted = 0
@@ -1790,12 +1952,13 @@ export class DocumentRepository {
1790
1952
  keepLatestAfter: number,
1791
1953
  ): Promise<number> {
1792
1954
  const events = (
1793
- await this.#db.query(
1794
- `SELECT cv.id, cv.version_date, cv.current, cv.prevent_cleanup, dv.published
1795
- FROM content_version cv JOIN document_version dv ON dv.id = cv.id
1796
- WHERE cv.node_id = ? ORDER BY cv.id`,
1797
- [nodeId],
1798
- )
1955
+ await this.#db.q
1956
+ .selectFrom('content_version as cv')
1957
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
1958
+ .select(['cv.id', 'cv.version_date', 'cv.current', 'cv.prevent_cleanup', 'dv.published'])
1959
+ .where('cv.node_id', '=', nodeId)
1960
+ .orderBy('cv.id')
1961
+ .execute()
1799
1962
  ).map((row) => ({
1800
1963
  id: Number(row.id),
1801
1964
  date: (DbDate.fromDb(row.version_date) ?? new Date(0)).getTime(),
@@ -1817,17 +1980,13 @@ export class DocumentRepository {
1817
1980
  const keptAscending = [...kept].sort((a, b) => a - b)
1818
1981
  const prunedSet = new Set(pruned)
1819
1982
 
1820
- const rows = await this.#db.query<{
1821
- id: number
1822
- property_type_id: number
1823
- language_id: number | null
1824
- segment: string | null
1825
- event_id: number
1826
- }>(
1827
- `SELECT id, property_type_id, language_id, segment, event_id FROM property_value
1828
- WHERE node_id = ? ORDER BY event_id, id`,
1829
- [nodeId],
1830
- )
1983
+ const rows = await this.#db.q
1984
+ .selectFrom('property_value')
1985
+ .select(['id', 'property_type_id', 'language_id', 'segment', 'event_id'])
1986
+ .where('node_id', '=', nodeId)
1987
+ .orderBy('event_id')
1988
+ .orderBy('id')
1989
+ .execute()
1831
1990
  // Per key, the distinct events that wrote it, ascending.
1832
1991
  const eventsByKey = new Map<string, number[]>()
1833
1992
  for (const row of rows) {
@@ -1852,19 +2011,19 @@ export class DocumentRepository {
1852
2011
  const next = written[written.indexOf(eventId) + 1] ?? Number.POSITIVE_INFINITY
1853
2012
  const reader = keptAscending.find((k) => k >= eventId)
1854
2013
  if (reader !== undefined && reader < next)
1855
- await this.#db.exec('UPDATE property_value SET event_id = ? WHERE id = ?', [
1856
- reader,
1857
- Number(row.id),
1858
- ])
1859
- else await this.#db.exec('DELETE FROM property_value WHERE id = ?', [Number(row.id)])
2014
+ await this.#db.q
2015
+ .updateTable('property_value')
2016
+ .set({ event_id: reader })
2017
+ .where('id', '=', Number(row.id))
2018
+ .execute()
2019
+ else await this.#db.q.deleteFrom('property_value').where('id', '=', Number(row.id)).execute()
1860
2020
  }
1861
- const marks = pruned.map(() => '?').join(', ')
1862
- await this.#db.exec(
1863
- `DELETE FROM content_version_culture_variation WHERE version_id IN (${marks})`,
1864
- pruned,
1865
- )
1866
- await this.#db.exec(`DELETE FROM document_version WHERE id IN (${marks})`, pruned)
1867
- await this.#db.exec(`DELETE FROM content_version WHERE id IN (${marks})`, pruned)
2021
+ await this.#db.q
2022
+ .deleteFrom('content_version_culture_variation')
2023
+ .where('version_id', 'in', pruned)
2024
+ .execute()
2025
+ await this.#db.q.deleteFrom('document_version').where('id', 'in', pruned).execute()
2026
+ await this.#db.q.deleteFrom('content_version').where('id', 'in', pruned).execute()
1868
2027
  return pruned.length
1869
2028
  }
1870
2029
 
@@ -1876,10 +2035,12 @@ export class DocumentRepository {
1876
2035
  /** When each item went into the recycle bin; absent for one trashed before that was recorded. */
1877
2036
  async trashedDates(nodeIds: readonly number[]): Promise<Map<number, Date>> {
1878
2037
  if (nodeIds.length === 0) return new Map()
1879
- const rows = await this.#db.query<{ node_id: number; trashed_date: unknown }>(
1880
- `SELECT node_id, trashed_date FROM document WHERE trashed_date IS NOT NULL AND node_id IN (${nodeIds.map(() => '?').join(', ')})`,
1881
- [...nodeIds],
1882
- )
2038
+ const rows = await this.#db.q
2039
+ .selectFrom('document')
2040
+ .select(['node_id', 'trashed_date'])
2041
+ .where('trashed_date', 'is not', null)
2042
+ .where('node_id', 'in', nodeIds)
2043
+ .execute()
1883
2044
  const out = new Map<number, Date>()
1884
2045
  for (const row of rows) {
1885
2046
  const date = DbDate.fromDb(row.trashed_date)
@@ -1889,10 +2050,13 @@ export class DocumentRepository {
1889
2050
  }
1890
2051
 
1891
2052
  async #nextSortOrder(parentId: number, excludingId: number): Promise<number> {
1892
- const rows = await this.#db.query<{ next: number | null }>(
1893
- 'SELECT MAX(sort_order) AS next FROM node WHERE parent_id = ? AND node_object_type = ? AND id <> ?',
1894
- [parentId, this.objectType, excludingId],
1895
- )
2053
+ const rows = await this.#db.q
2054
+ .selectFrom('node')
2055
+ .select((eb) => eb.fn.max('sort_order').as('next'))
2056
+ .where('parent_id', '=', parentId)
2057
+ .where('node_object_type', '=', this.objectType)
2058
+ .where('id', '<>', excludingId)
2059
+ .execute()
1896
2060
  const current = rows[0]?.next
1897
2061
  return current === null || current === undefined ? 0 : Number(current) + 1
1898
2062
  }
@@ -1905,31 +2069,55 @@ export class DocumentRepository {
1905
2069
  // ------------------------------------------------------------ internals
1906
2070
 
1907
2071
  async #load(node: NodeRow): Promise<DocumentAggregate | undefined> {
1908
- const t = this.#db.dialect.boolValue(true)
1909
- const rows = await this.#db.query(
1910
- `SELECT c.content_type_id, ct.alias AS content_type_alias, ct.icon AS content_type_icon,
1911
- ct.list_view AS content_type_collection,
1912
- ctn.unique_id AS content_type_key, d.published, d.edited,
1913
- head.text AS draft_name, head.version_date AS draft_date,
1914
- hv.template_id, tn.unique_id AS template_key,
1915
- pub.version_date AS published_date,
1916
- (SELECT MAX(cvm.id) FROM content_version cvm WHERE cvm.node_id = n.id) AS head_id,
1917
- (SELECT MAX(pvm.id) FROM property_value pvm WHERE pvm.node_id = n.id) AS last_value_id
1918
- FROM node n
1919
- JOIN content c ON c.node_id = n.id
1920
- JOIN content_type ct ON ct.node_id = c.content_type_id
1921
- JOIN node ctn ON ctn.id = ct.node_id
1922
- JOIN document d ON d.node_id = n.id
1923
- JOIN content_version head ON head.node_id = n.id AND head.current = ?
1924
- JOIN document_version hv ON hv.id = head.id
1925
- LEFT JOIN node tn ON tn.id = hv.template_id
1926
- LEFT JOIN (
1927
- SELECT pc.node_id, pc.version_date FROM content_version pc
1928
- JOIN document_version pd ON pd.id = pc.id AND pd.published = ?
1929
- ) pub ON pub.node_id = n.id
1930
- WHERE n.id = ?`,
1931
- [t, t, node.id],
1932
- )
2072
+ const t = this.#db.dialect.boolValue(true) as boolean
2073
+ const rows = await this.#db.q
2074
+ .selectFrom('node as n')
2075
+ .innerJoin('content as c', 'c.node_id', 'n.id')
2076
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
2077
+ .innerJoin('node as ctn', 'ctn.id', 'ct.node_id')
2078
+ .innerJoin('document as d', 'd.node_id', 'n.id')
2079
+ .innerJoin('content_version as head', (join) =>
2080
+ join.onRef('head.node_id', '=', 'n.id').on('head.current', '=', t),
2081
+ )
2082
+ .innerJoin('document_version as hv', 'hv.id', 'head.id')
2083
+ .leftJoin('node as tn', 'tn.id', 'hv.template_id')
2084
+ .leftJoin(
2085
+ (eb) =>
2086
+ eb
2087
+ .selectFrom('content_version as pc')
2088
+ .innerJoin('document_version as pd', (join) =>
2089
+ join.onRef('pd.id', '=', 'pc.id').on('pd.published', '=', t),
2090
+ )
2091
+ .select(['pc.node_id', 'pc.version_date'])
2092
+ .as('pub'),
2093
+ (join) => join.onRef('pub.node_id', '=', 'n.id'),
2094
+ )
2095
+ .select((eb) => [
2096
+ 'c.content_type_id',
2097
+ 'ct.alias as content_type_alias',
2098
+ 'ct.icon as content_type_icon',
2099
+ 'ct.list_view as content_type_collection',
2100
+ 'ctn.unique_id as content_type_key',
2101
+ 'd.published',
2102
+ 'd.edited',
2103
+ 'head.text as draft_name',
2104
+ 'head.version_date as draft_date',
2105
+ 'hv.template_id',
2106
+ 'tn.unique_id as template_key',
2107
+ 'pub.version_date as published_date',
2108
+ eb
2109
+ .selectFrom('content_version as cvm')
2110
+ .select((e) => e.fn.max('cvm.id').as('id'))
2111
+ .whereRef('cvm.node_id', '=', 'n.id')
2112
+ .as('head_id'),
2113
+ eb
2114
+ .selectFrom('property_value as pvm')
2115
+ .select((e) => e.fn.max('pvm.id').as('id'))
2116
+ .whereRef('pvm.node_id', '=', 'n.id')
2117
+ .as('last_value_id'),
2118
+ ])
2119
+ .where('n.id', '=', node.id)
2120
+ .execute()
1933
2121
  const row = rows[0]
1934
2122
  if (!row) return undefined
1935
2123
 
@@ -1960,15 +2148,19 @@ export class DocumentRepository {
1960
2148
  }
1961
2149
 
1962
2150
  async #contentTypeNodeId(nodeId: number): Promise<number | undefined> {
1963
- const rows = await this.#db.query<{ content_type_id: number }>(
1964
- 'SELECT content_type_id FROM content WHERE node_id = ?',
1965
- [nodeId],
1966
- )
2151
+ const rows = await this.#db.q
2152
+ .selectFrom('content')
2153
+ .select('content_type_id')
2154
+ .where('node_id', '=', nodeId)
2155
+ .execute()
1967
2156
  return rows[0] ? Number(rows[0].content_type_id) : undefined
1968
2157
  }
1969
2158
 
1970
2159
  async #languages(): Promise<LanguageRow[]> {
1971
- const rows = await this.#db.query('SELECT id, iso_code, is_default, is_mandatory FROM language')
2160
+ const rows = await this.#db.q
2161
+ .selectFrom('language')
2162
+ .select(['id', 'iso_code', 'is_default', 'is_mandatory'])
2163
+ .execute()
1972
2164
  return rows.map((row) => ({
1973
2165
  id: Number(row.id),
1974
2166
  isoCode: String(row.iso_code),
@@ -1994,16 +2186,12 @@ export class DocumentRepository {
1994
2186
  if (!node) return undefined
1995
2187
  const contentTypeNodeId = await this.#contentTypeNodeId(node.id)
1996
2188
  if (!contentTypeNodeId) return undefined
1997
- const rows = await this.#db.query<{ alias: string; unique_id: string; name: string }>(
1998
- `WITH RECURSIVE ancestry(id) AS (
1999
- SELECT ?
2000
- UNION
2001
- SELECT c.parent_content_type_id FROM content_type_composition c JOIN ancestry a ON a.id = c.child_content_type_id
2002
- )
2003
- SELECT p.alias, p.unique_id, p.name FROM property_type p
2004
- WHERE p.content_type_id IN (SELECT id FROM ancestry) AND p.retired_at IS NULL`,
2005
- [contentTypeNodeId],
2006
- )
2189
+ const rows = await this.#withAncestry(contentTypeNodeId)
2190
+ .selectFrom('property_type as p')
2191
+ .select(['p.alias', 'p.unique_id', 'p.name'])
2192
+ .where('p.content_type_id', 'in', (eb) => eb.selectFrom('ancestry').select('id'))
2193
+ .where('p.retired_at', 'is', null)
2194
+ .execute()
2007
2195
  return rows.map((row) => ({
2008
2196
  alias: String(row.alias),
2009
2197
  key: normaliseUuid(String(row.unique_id)),
@@ -2011,23 +2199,47 @@ export class DocumentRepository {
2011
2199
  }))
2012
2200
  }
2013
2201
 
2202
+ /** A content type and every type it composes, transitively, as the CTE `ancestry(id)`. */
2203
+ #withAncestry(contentTypeNodeId: number) {
2204
+ return this.#db.q.withRecursive('ancestry(id)', (db) =>
2205
+ db
2206
+ .selectNoFrom((eb) => eb.val(contentTypeNodeId).as('id'))
2207
+ .union(
2208
+ db
2209
+ .selectFrom('content_type_composition as c')
2210
+ .innerJoin('ancestry as a', 'a.id', 'c.child_content_type_id')
2211
+ .select('c.parent_content_type_id as id'),
2212
+ ),
2213
+ )
2214
+ }
2215
+
2014
2216
  /** Property types of a content type, including everything it composes; retired ones excluded. */
2015
2217
  async #propertyTypes(contentTypeNodeId: number): Promise<PropertyTypeRow[]> {
2016
- const rows = await this.#db.query(
2017
- `WITH RECURSIVE ancestry(id) AS (
2018
- SELECT ?
2019
- UNION
2020
- SELECT c.parent_content_type_id FROM content_type_composition c JOIN ancestry a ON a.id = c.child_content_type_id
2021
- )
2022
- SELECT p.id, p.alias, p.name, p.variations, p.mandatory, p.mandatory_message,
2023
- p.validation_reg_exp, p.validation_reg_exp_message, d.db_type, d.editor_alias, d.config,
2024
- p.since_version, ss.version AS since_v, ss.revision AS since_r
2025
- FROM property_type p JOIN data_type d ON d.node_id = p.data_type_id
2026
- LEFT JOIN schema_state ss ON ss.id = p.since_state_id
2027
- WHERE p.content_type_id IN (SELECT id FROM ancestry) AND p.retired_at IS NULL
2028
- ORDER BY p.sort_order, p.id`,
2029
- [contentTypeNodeId],
2030
- )
2218
+ const rows = await this.#withAncestry(contentTypeNodeId)
2219
+ .selectFrom('property_type as p')
2220
+ .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
2221
+ .leftJoin('schema_state as ss', 'ss.id', 'p.since_state_id')
2222
+ .select([
2223
+ 'p.id',
2224
+ 'p.alias',
2225
+ 'p.name',
2226
+ 'p.variations',
2227
+ 'p.mandatory',
2228
+ 'p.mandatory_message',
2229
+ 'p.validation_reg_exp',
2230
+ 'p.validation_reg_exp_message',
2231
+ 'd.db_type',
2232
+ 'd.editor_alias',
2233
+ 'd.config',
2234
+ 'p.since_version',
2235
+ 'ss.version as since_v',
2236
+ 'ss.revision as since_r',
2237
+ ])
2238
+ .where('p.content_type_id', 'in', (eb) => eb.selectFrom('ancestry').select('id'))
2239
+ .where('p.retired_at', 'is', null)
2240
+ .orderBy('p.sort_order')
2241
+ .orderBy('p.id')
2242
+ .execute()
2031
2243
  return rows.map((row) => ({
2032
2244
  id: Number(row.id),
2033
2245
  alias: String(row.alias),
@@ -2066,11 +2278,23 @@ export class DocumentRepository {
2066
2278
  }
2067
2279
 
2068
2280
  async #currentValueRows(nodeId: number): Promise<ValueRow[]> {
2069
- const rows = await this.#db.query(
2070
- `SELECT id, event_id, property_type_id, language_id, segment, int_value, decimal_value, date_value, varchar_value, text_value
2071
- FROM property_value WHERE node_id = ? AND is_current = ?`,
2072
- [nodeId, this.#db.dialect.boolValue(true)],
2073
- )
2281
+ const rows = await this.#db.q
2282
+ .selectFrom('property_value')
2283
+ .select([
2284
+ 'id',
2285
+ 'event_id',
2286
+ 'property_type_id',
2287
+ 'language_id',
2288
+ 'segment',
2289
+ 'int_value',
2290
+ 'decimal_value',
2291
+ 'date_value',
2292
+ 'varchar_value',
2293
+ 'text_value',
2294
+ ])
2295
+ .where('node_id', '=', nodeId)
2296
+ .where('is_current', '=', this.#db.dialect.boolValue(true) as boolean)
2297
+ .execute()
2074
2298
  return rows.map((row) => this.#toValueRow(row))
2075
2299
  }
2076
2300
 
@@ -2079,27 +2303,36 @@ export class DocumentRepository {
2079
2303
  nodeId: number,
2080
2304
  asOf: { eventId?: number; schemaStateId?: number },
2081
2305
  ): Promise<ValueRow[]> {
2082
- const conditions = ['node_id = ?']
2083
- const params: unknown[] = [nodeId]
2084
- if (asOf.eventId !== undefined) {
2085
- conditions.push('event_id <= ?')
2086
- params.push(asOf.eventId)
2087
- }
2088
- if (asOf.schemaStateId !== undefined) {
2089
- conditions.push('schema_state_id <= ?')
2090
- params.push(asOf.schemaStateId)
2091
- }
2092
- const rows = await this.#db.query(
2093
- `SELECT pv.id, pv.event_id, pv.property_type_id, pv.language_id, pv.segment,
2094
- pv.int_value, pv.decimal_value, pv.date_value, pv.varchar_value, pv.text_value
2095
- FROM property_value pv
2096
- JOIN (
2097
- SELECT property_type_id, language_id, segment, MAX(id) AS id
2098
- FROM property_value WHERE ${conditions.join(' AND ')}
2099
- GROUP BY property_type_id, language_id, segment
2100
- ) latest ON latest.id = pv.id`,
2101
- params,
2102
- )
2306
+ const { eventId, schemaStateId } = asOf
2307
+ const rows = await this.#db.q
2308
+ .selectFrom('property_value as pv')
2309
+ .innerJoin(
2310
+ (eb) =>
2311
+ eb
2312
+ .selectFrom('property_value')
2313
+ .select((e) => ['property_type_id', 'language_id', 'segment', e.fn.max('id').as('id')])
2314
+ .where('node_id', '=', nodeId)
2315
+ .$if(eventId !== undefined, (q) => q.where('event_id', '<=', eventId as number))
2316
+ .$if(schemaStateId !== undefined, (q) =>
2317
+ q.where('schema_state_id', '<=', schemaStateId as number),
2318
+ )
2319
+ .groupBy(['property_type_id', 'language_id', 'segment'])
2320
+ .as('latest'),
2321
+ (join) => join.onRef('latest.id', '=', 'pv.id'),
2322
+ )
2323
+ .select([
2324
+ 'pv.id',
2325
+ 'pv.event_id',
2326
+ 'pv.property_type_id',
2327
+ 'pv.language_id',
2328
+ 'pv.segment',
2329
+ 'pv.int_value',
2330
+ 'pv.decimal_value',
2331
+ 'pv.date_value',
2332
+ 'pv.varchar_value',
2333
+ 'pv.text_value',
2334
+ ])
2335
+ .execute()
2103
2336
  return rows.map((row) => this.#toValueRow(row))
2104
2337
  }
2105
2338
 
@@ -2289,10 +2522,12 @@ export class DocumentRepository {
2289
2522
  const types = new Map<number, PropertyTypeRow>()
2290
2523
  for (const row of [...target, ...current]) {
2291
2524
  if (types.has(row.propertyTypeId)) continue
2292
- const found = await this.#db.query(
2293
- 'SELECT p.id, p.alias, p.variations, d.db_type, d.editor_alias FROM property_type p JOIN data_type d ON d.node_id = p.data_type_id WHERE p.id = ?',
2294
- [row.propertyTypeId],
2295
- )
2525
+ const found = await this.#db.q
2526
+ .selectFrom('property_type as p')
2527
+ .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
2528
+ .select(['p.id', 'p.alias', 'p.variations', 'd.db_type', 'd.editor_alias'])
2529
+ .where('p.id', '=', row.propertyTypeId)
2530
+ .execute()
2296
2531
  const r = found[0]
2297
2532
  if (r)
2298
2533
  types.set(row.propertyTypeId, {
@@ -2375,26 +2610,26 @@ export class DocumentRepository {
2375
2610
  ): Promise<void> {
2376
2611
  const column = STORAGE_COLUMN[propertyType.storage]
2377
2612
  if (supersedes !== undefined) {
2378
- await this.#db.exec('UPDATE property_value SET is_current = ? WHERE id = ?', [
2379
- this.#db.dialect.boolValue(false),
2380
- supersedes,
2381
- ])
2613
+ await this.#db.q
2614
+ .updateTable('property_value')
2615
+ .set({ is_current: this.#db.dialect.boolValue(false) as boolean })
2616
+ .where('id', '=', supersedes)
2617
+ .execute()
2382
2618
  }
2383
- await this.#db.exec(
2384
- `INSERT INTO property_value (node_id, property_type_id, language_id, segment, event_id, schema_state_id, is_current, ${column}, sortable_value)
2385
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2386
- [
2387
- nodeId,
2388
- propertyType.id,
2389
- languageId,
2619
+ await this.#db.q
2620
+ .insertInto('property_value')
2621
+ .values({
2622
+ node_id: nodeId,
2623
+ property_type_id: propertyType.id,
2624
+ language_id: languageId,
2390
2625
  segment,
2391
- eventId,
2392
- schemaStateId,
2393
- this.#db.dialect.boolValue(true),
2394
- this.#toStorage(value, propertyType.storage),
2395
- typeof value === 'string' ? value.slice(0, 512) : null,
2396
- ],
2397
- )
2626
+ event_id: eventId,
2627
+ schema_state_id: schemaStateId,
2628
+ is_current: this.#db.dialect.boolValue(true) as boolean,
2629
+ [column]: this.#toStorage(value, propertyType.storage),
2630
+ sortable_value: typeof value === 'string' ? value.slice(0, 512) : null,
2631
+ } as Insertable<CoreTables['property_value']>)
2632
+ .execute()
2398
2633
  }
2399
2634
 
2400
2635
  /**
@@ -2493,10 +2728,18 @@ export class DocumentRepository {
2493
2728
  if (!node) return undefined
2494
2729
  const draft = await this.#load(node)
2495
2730
  if (!draft?.published) return undefined
2496
- const published = await this.#db.query<{ id: number }>(
2497
- 'SELECT cv.id FROM content_version cv JOIN document_version dv ON dv.id = cv.id AND dv.published = ? WHERE cv.node_id = ? ORDER BY cv.id DESC LIMIT 1',
2498
- [this.#db.dialect.boolValue(true), node.id],
2499
- )
2731
+ const published = await this.#db.q
2732
+ .selectFrom('content_version as cv')
2733
+ .innerJoin('document_version as dv', (join) =>
2734
+ join
2735
+ .onRef('dv.id', '=', 'cv.id')
2736
+ .on('dv.published', '=', this.#db.dialect.boolValue(true) as boolean),
2737
+ )
2738
+ .select('cv.id')
2739
+ .where('cv.node_id', '=', node.id)
2740
+ .orderBy('cv.id', 'desc')
2741
+ .limit(1)
2742
+ .execute()
2500
2743
  const eventId = Number(published[0]?.id)
2501
2744
  const contentTypeNodeId = await this.#contentTypeNodeId(node.id)
2502
2745
  if (!contentTypeNodeId || !eventId) return undefined
@@ -2519,29 +2762,44 @@ export class DocumentRepository {
2519
2762
  async treeItems(rows: readonly NodeRow[]): Promise<DocumentTreeItem[]> {
2520
2763
  if (rows.length === 0) return []
2521
2764
  const ids = rows.map((row) => row.id)
2522
- const placeholders = ids.map(() => '?').join(', ')
2523
2765
  const counts = await this.#nodes.childCounts(ids, this.objectType)
2524
- const facts = await this.#db.query(
2525
- `SELECT n.id, ctn.unique_id AS content_type_key, ct.icon AS content_type_icon,
2526
- ct.list_view AS content_type_collection, d.published, d.edited,
2527
- head.text AS draft_name
2528
- FROM node n
2529
- JOIN content c ON c.node_id = n.id
2530
- JOIN content_type ct ON ct.node_id = c.content_type_id
2531
- JOIN node ctn ON ctn.id = ct.node_id
2532
- JOIN document d ON d.node_id = n.id
2533
- JOIN content_version head ON head.node_id = n.id AND head.current = ?
2534
- WHERE n.id IN (${placeholders})`,
2535
- [this.#db.dialect.boolValue(true), ...ids],
2536
- )
2766
+ const facts = await this.#db.q
2767
+ .selectFrom('node as n')
2768
+ .innerJoin('content as c', 'c.node_id', 'n.id')
2769
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
2770
+ .innerJoin('node as ctn', 'ctn.id', 'ct.node_id')
2771
+ .innerJoin('document as d', 'd.node_id', 'n.id')
2772
+ .innerJoin('content_version as head', (join) =>
2773
+ join
2774
+ .onRef('head.node_id', '=', 'n.id')
2775
+ .on('head.current', '=', this.#db.dialect.boolValue(true) as boolean),
2776
+ )
2777
+ .select([
2778
+ 'n.id',
2779
+ 'ctn.unique_id as content_type_key',
2780
+ 'ct.icon as content_type_icon',
2781
+ 'ct.list_view as content_type_collection',
2782
+ 'd.published',
2783
+ 'd.edited',
2784
+ 'head.text as draft_name',
2785
+ ])
2786
+ .where('n.id', 'in', ids)
2787
+ .execute()
2537
2788
  const factsById = new Map(facts.map((row) => [Number(row.id), row]))
2538
- const cultures = await this.#db.query(
2539
- `SELECT dcv.node_id, dcv.name, dcv.published, dcv.edited, dcv.available, l.iso_code
2540
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
2541
- WHERE dcv.node_id IN (${placeholders})`,
2542
- ids,
2543
- )
2544
- const culturesById = new Map<number, Record<string, unknown>[]>()
2789
+ const cultures = await this.#db.q
2790
+ .selectFrom('document_culture_variation as dcv')
2791
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
2792
+ .select([
2793
+ 'dcv.node_id',
2794
+ 'dcv.name',
2795
+ 'dcv.published',
2796
+ 'dcv.edited',
2797
+ 'dcv.available',
2798
+ 'l.iso_code',
2799
+ ])
2800
+ .where('dcv.node_id', 'in', ids)
2801
+ .execute()
2802
+ const culturesById = new Map<number, typeof cultures>()
2545
2803
  for (const row of cultures)
2546
2804
  culturesById.set(Number(row.node_id), [...(culturesById.get(Number(row.node_id)) ?? []), row])
2547
2805
  // Every ancestor the page's paths name, parents included, in one read.
@@ -2604,10 +2862,11 @@ export class DocumentRepository {
2604
2862
  async originalParent(key: string): Promise<string | null | undefined> {
2605
2863
  const node = await this.#nodes.byKey(key)
2606
2864
  if (!node) return undefined
2607
- const rows = await this.#db.query<{ original_parent_id: number | null }>(
2608
- 'SELECT original_parent_id FROM document WHERE node_id = ?',
2609
- [node.id],
2610
- )
2865
+ const rows = await this.#db.q
2866
+ .selectFrom('document')
2867
+ .select('original_parent_id')
2868
+ .where('node_id', '=', node.id)
2869
+ .execute()
2611
2870
  const parentId = rows[0]?.original_parent_id
2612
2871
  if (parentId === null || parentId === undefined) return null
2613
2872
  return (await this.#nodes.byId(Number(parentId)))?.key ?? null
@@ -2630,22 +2889,39 @@ export class DocumentRepository {
2630
2889
  templateId: number | null,
2631
2890
  published: boolean,
2632
2891
  ): Promise<number> {
2633
- const t = this.#db.dialect.boolValue(true)
2634
- const f = this.#db.dialect.boolValue(false)
2635
- await this.#db.exec('UPDATE content_version SET current = ? WHERE node_id = ?', [f, nodeId])
2636
- await this.#db.exec(
2637
- `INSERT INTO content_version (node_id, kind, version_date, user_id, current, text, prevent_cleanup) VALUES (?, ?, ?, ?, ?, ?, ?)`,
2638
- [nodeId, kind, DbDate.toDb(new Date()), userId ?? null, t, name, f],
2639
- )
2640
- const rows = await this.#db.query<{ id: number }>(
2641
- 'SELECT MAX(id) AS id FROM content_version WHERE node_id = ?',
2642
- [nodeId],
2643
- )
2892
+ const t = this.#db.dialect.boolValue(true) as boolean
2893
+ const f = this.#db.dialect.boolValue(false) as boolean
2894
+ await this.#db.q
2895
+ .updateTable('content_version')
2896
+ .set({ current: f })
2897
+ .where('node_id', '=', nodeId)
2898
+ .execute()
2899
+ await this.#db.q
2900
+ .insertInto('content_version')
2901
+ .values({
2902
+ node_id: nodeId,
2903
+ kind,
2904
+ version_date: DbDate.toDb(new Date()),
2905
+ user_id: userId ?? null,
2906
+ current: t,
2907
+ text: name,
2908
+ prevent_cleanup: f,
2909
+ })
2910
+ .execute()
2911
+ const rows = await this.#db.q
2912
+ .selectFrom('content_version')
2913
+ .select((eb) => eb.fn.max('id').as('id'))
2914
+ .where('node_id', '=', nodeId)
2915
+ .execute()
2644
2916
  const eventId = Number(rows[0]?.id)
2645
- await this.#db.exec(
2646
- 'INSERT INTO document_version (id, template_id, published) VALUES (?, ?, ?)',
2647
- [eventId, templateId, this.#db.dialect.boolValue(published)],
2648
- )
2917
+ await this.#db.q
2918
+ .insertInto('document_version')
2919
+ .values({
2920
+ id: eventId,
2921
+ template_id: templateId,
2922
+ published: this.#db.dialect.boolValue(published) as boolean,
2923
+ })
2924
+ .execute()
2649
2925
  // Every change to what an item says is an event, so this is where the search index hears of it.
2650
2926
  await queueForSearch(this.#db, [nodeId])
2651
2927
  return eventId
@@ -2656,11 +2932,14 @@ export class DocumentRepository {
2656
2932
  ): Promise<
2657
2933
  { id: number; name: string; userId: number | undefined; templateId: number | null } | undefined
2658
2934
  > {
2659
- const rows = await this.#db.query(
2660
- `SELECT cv.id, cv.text, cv.user_id, dv.template_id FROM content_version cv JOIN document_version dv ON dv.id = cv.id
2661
- WHERE cv.node_id = ? ORDER BY cv.id DESC LIMIT 1`,
2662
- [nodeId],
2663
- )
2935
+ const rows = await this.#db.q
2936
+ .selectFrom('content_version as cv')
2937
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
2938
+ .select(['cv.id', 'cv.text', 'cv.user_id', 'dv.template_id'])
2939
+ .where('cv.node_id', '=', nodeId)
2940
+ .orderBy('cv.id', 'desc')
2941
+ .limit(1)
2942
+ .execute()
2664
2943
  const row = rows[0]
2665
2944
  if (!row) return undefined
2666
2945
  return {
@@ -2673,10 +2952,13 @@ export class DocumentRepository {
2673
2952
  }
2674
2953
 
2675
2954
  async #publishedEventId(nodeId: number): Promise<number | undefined> {
2676
- const rows = await this.#db.query<{ id: number }>(
2677
- 'SELECT cv.id FROM content_version cv JOIN document_version dv ON dv.id = cv.id WHERE cv.node_id = ? AND dv.published = ?',
2678
- [nodeId, this.#db.dialect.boolValue(true)],
2679
- )
2955
+ const rows = await this.#db.q
2956
+ .selectFrom('content_version as cv')
2957
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
2958
+ .select('cv.id')
2959
+ .where('cv.node_id', '=', nodeId)
2960
+ .where('dv.published', '=', this.#db.dialect.boolValue(true) as boolean)
2961
+ .execute()
2680
2962
  return rows[0] ? Number(rows[0].id) : undefined
2681
2963
  }
2682
2964
 
@@ -2685,38 +2967,56 @@ export class DocumentRepository {
2685
2967
  const publishedId = await this.#publishedEventId(nodeId)
2686
2968
  let edited = true
2687
2969
  if (publishedId !== undefined) {
2688
- const newer = await this.#db.query<{ n: number }>(
2689
- 'SELECT COUNT(*) AS n FROM property_value WHERE node_id = ? AND event_id > ?',
2690
- [nodeId, publishedId],
2691
- )
2692
- const names = await this.#db.query<{ head: string | null; pub: string | null }>(
2693
- `SELECT (SELECT text FROM content_version WHERE node_id = ? ORDER BY id DESC LIMIT 1) AS head,
2694
- (SELECT text FROM content_version WHERE id = ?) AS pub`,
2695
- [nodeId, publishedId],
2696
- )
2970
+ const newer = await this.#db.q
2971
+ .selectFrom('property_value')
2972
+ .select((eb) => eb.fn.countAll().as('n'))
2973
+ .where('node_id', '=', nodeId)
2974
+ .where('event_id', '>', publishedId)
2975
+ .execute()
2976
+ const names = await this.#db.q
2977
+ .selectNoFrom((eb) => [
2978
+ eb
2979
+ .selectFrom('content_version')
2980
+ .select('text')
2981
+ .where('node_id', '=', nodeId)
2982
+ .orderBy('id', 'desc')
2983
+ .limit(1)
2984
+ .as('head'),
2985
+ eb.selectFrom('content_version').select('text').where('id', '=', publishedId).as('pub'),
2986
+ ])
2987
+ .execute()
2697
2988
  edited = Number(newer[0]?.n ?? 0) > 0 || (names[0]?.head ?? '') !== (names[0]?.pub ?? '')
2698
2989
  }
2699
- await this.#db.exec('UPDATE document SET edited = ? WHERE node_id = ?', [
2700
- this.#db.dialect.boolValue(edited),
2701
- nodeId,
2702
- ])
2990
+ await this.#db.q
2991
+ .updateTable('document')
2992
+ .set({ edited: this.#db.dialect.boolValue(edited) as boolean })
2993
+ .where('node_id', '=', nodeId)
2994
+ .execute()
2703
2995
  // A published culture is edited when its values, the invariant ones, or its name moved on
2704
2996
  for (const culture of await this.#publishedCultureEvents(nodeId)) {
2705
- const newer = await this.#db.query<{ n: number }>(
2706
- `SELECT COUNT(*) AS n FROM property_value
2707
- WHERE node_id = ? AND event_id > ? AND (language_id = ? OR language_id IS NULL)`,
2708
- [nodeId, culture.eventId, culture.languageId],
2709
- )
2710
- const names = await this.#db.query<{ name: string | null; published_name: string | null }>(
2711
- 'SELECT name, published_name FROM document_culture_variation WHERE node_id = ? AND language_id = ?',
2712
- [nodeId, culture.languageId],
2713
- )
2997
+ const newer = await this.#db.q
2998
+ .selectFrom('property_value')
2999
+ .select((eb) => eb.fn.countAll().as('n'))
3000
+ .where('node_id', '=', nodeId)
3001
+ .where('event_id', '>', culture.eventId)
3002
+ .where((eb) =>
3003
+ eb.or([eb('language_id', '=', culture.languageId), eb('language_id', 'is', null)]),
3004
+ )
3005
+ .execute()
3006
+ const names = await this.#db.q
3007
+ .selectFrom('document_culture_variation')
3008
+ .select(['name', 'published_name'])
3009
+ .where('node_id', '=', nodeId)
3010
+ .where('language_id', '=', culture.languageId)
3011
+ .execute()
2714
3012
  const cultureEdited =
2715
3013
  Number(newer[0]?.n ?? 0) > 0 || (names[0]?.name ?? '') !== (names[0]?.published_name ?? '')
2716
- await this.#db.exec(
2717
- 'UPDATE document_culture_variation SET edited = ? WHERE node_id = ? AND language_id = ?',
2718
- [this.#db.dialect.boolValue(cultureEdited), nodeId, culture.languageId],
2719
- )
3014
+ await this.#db.q
3015
+ .updateTable('document_culture_variation')
3016
+ .set({ edited: this.#db.dialect.boolValue(cultureEdited) as boolean })
3017
+ .where('node_id', '=', nodeId)
3018
+ .where('language_id', '=', culture.languageId)
3019
+ .execute()
2720
3020
  }
2721
3021
  }
2722
3022
 
@@ -2745,11 +3045,12 @@ export class DocumentRepository {
2745
3045
  const createDate = node.createDate ?? new Date()
2746
3046
  const updateDate = DbDate.fromDb(row.draft_date) ?? createDate
2747
3047
  const publishDate = DbDate.fromDb(row.published_date) ?? null
2748
- const cultureRows = await this.#db.query(
2749
- `SELECT dcv.name, dcv.published, dcv.edited, dcv.available, l.iso_code
2750
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id WHERE dcv.node_id = ?`,
2751
- [node.id],
2752
- )
3048
+ const cultureRows = await this.#db.q
3049
+ .selectFrom('document_culture_variation as dcv')
3050
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
3051
+ .select(['dcv.name', 'dcv.published', 'dcv.edited', 'dcv.available', 'l.iso_code'])
3052
+ .where('dcv.node_id', '=', node.id)
3053
+ .execute()
2753
3054
  if (cultureRows.length === 0) {
2754
3055
  return [
2755
3056
  {
@@ -2789,54 +3090,81 @@ export class DocumentRepository {
2789
3090
  const languages = await this.#languages()
2790
3091
  const idByIso = new Map(languages.map((l) => [l.isoCode.toLowerCase(), l.id]))
2791
3092
  const now = DbDate.toDb(new Date())
2792
- const t = this.#db.dialect.boolValue(true)
2793
- const f = this.#db.dialect.boolValue(false)
3093
+ const t = this.#db.dialect.boolValue(true) as boolean
3094
+ const f = this.#db.dialect.boolValue(false) as boolean
2794
3095
  for (const variant of cultured) {
2795
3096
  const languageId = idByIso.get(String(variant.culture).toLowerCase())
2796
3097
  if (!languageId) continue
2797
- await this.#db.exec(
2798
- 'INSERT INTO content_version_culture_variation (version_id, language_id, name, date) VALUES (?, ?, ?, ?)',
2799
- [eventId, languageId, variant.name, now],
2800
- )
2801
- const existing = await this.#db.query<{ id: number }>(
2802
- 'SELECT id FROM document_culture_variation WHERE node_id = ? AND language_id = ?',
2803
- [nodeId, languageId],
2804
- )
3098
+ await this.#db.q
3099
+ .insertInto('content_version_culture_variation')
3100
+ .values({ version_id: eventId, language_id: languageId, name: variant.name, date: now })
3101
+ .execute()
3102
+ const existing = await this.#db.q
3103
+ .selectFrom('document_culture_variation')
3104
+ .select('id')
3105
+ .where('node_id', '=', nodeId)
3106
+ .where('language_id', '=', languageId)
3107
+ .execute()
2805
3108
  if (existing[0]) {
2806
- await this.#db.exec(
2807
- 'UPDATE document_culture_variation SET name = ?, available = ?, edited = ? WHERE id = ?',
2808
- [variant.name, t, t, Number(existing[0].id)],
2809
- )
3109
+ await this.#db.q
3110
+ .updateTable('document_culture_variation')
3111
+ .set({ name: variant.name, available: t, edited: t })
3112
+ .where('id', '=', Number(existing[0].id))
3113
+ .execute()
2810
3114
  } else {
2811
- await this.#db.exec(
2812
- 'INSERT INTO document_culture_variation (node_id, language_id, edited, available, published, name) VALUES (?, ?, ?, ?, ?, ?)',
2813
- [nodeId, languageId, t, t, f, variant.name],
2814
- )
3115
+ await this.#db.q
3116
+ .insertInto('document_culture_variation')
3117
+ .values({
3118
+ node_id: nodeId,
3119
+ language_id: languageId,
3120
+ edited: t,
3121
+ available: t,
3122
+ published: f,
3123
+ name: variant.name,
3124
+ })
3125
+ .execute()
2815
3126
  }
2816
3127
  }
2817
3128
  }
2818
3129
 
2819
3130
  async #copyCultureVariations(fromEventId: number, toEventId: number): Promise<void> {
2820
- await this.#db.exec(
2821
- `INSERT INTO content_version_culture_variation (version_id, language_id, name, date, available_user_id)
2822
- SELECT ?, language_id, name, date, available_user_id FROM content_version_culture_variation WHERE version_id = ?`,
2823
- [toEventId, fromEventId],
2824
- )
3131
+ await this.#db.q
3132
+ .insertInto('content_version_culture_variation')
3133
+ .columns(['version_id', 'language_id', 'name', 'date', 'available_user_id'])
3134
+ .expression((eb) =>
3135
+ eb
3136
+ .selectFrom('content_version_culture_variation')
3137
+ .select([
3138
+ eb.val(toEventId).as('version_id'),
3139
+ 'language_id',
3140
+ 'name',
3141
+ 'date',
3142
+ 'available_user_id',
3143
+ ])
3144
+ .where('version_id', '=', fromEventId),
3145
+ )
3146
+ .execute()
2825
3147
  }
2826
3148
 
2827
3149
  async #availableCultures(nodeId: number): Promise<string[]> {
2828
- const rows = await this.#db.query<{ iso_code: string }>(
2829
- 'SELECT l.iso_code FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id WHERE dcv.node_id = ? AND dcv.available = ?',
2830
- [nodeId, this.#db.dialect.boolValue(true)],
2831
- )
3150
+ const rows = await this.#db.q
3151
+ .selectFrom('document_culture_variation as dcv')
3152
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
3153
+ .select('l.iso_code')
3154
+ .where('dcv.node_id', '=', nodeId)
3155
+ .where('dcv.available', '=', this.#db.dialect.boolValue(true) as boolean)
3156
+ .execute()
2832
3157
  return rows.map((row) => String(row.iso_code))
2833
3158
  }
2834
3159
 
2835
3160
  async #publishedCultures(nodeId: number): Promise<string[]> {
2836
- const rows = await this.#db.query<{ iso_code: string }>(
2837
- 'SELECT l.iso_code FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id WHERE dcv.node_id = ? AND dcv.published = ?',
2838
- [nodeId, this.#db.dialect.boolValue(true)],
2839
- )
3161
+ const rows = await this.#db.q
3162
+ .selectFrom('document_culture_variation as dcv')
3163
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
3164
+ .select('l.iso_code')
3165
+ .where('dcv.node_id', '=', nodeId)
3166
+ .where('dcv.published', '=', this.#db.dialect.boolValue(true) as boolean)
3167
+ .execute()
2840
3168
  return rows.map((row) => String(row.iso_code))
2841
3169
  }
2842
3170
 
@@ -2846,22 +3174,27 @@ export class DocumentRepository {
2846
3174
  const languageId = languages.find((l) => l.isoCode.toLowerCase() === iso.toLowerCase())?.id
2847
3175
  if (!languageId) return
2848
3176
  if (eventId === null)
2849
- await this.#db.exec(
2850
- 'UPDATE document_culture_variation SET published = ?, edited = ? WHERE node_id = ? AND language_id = ?',
2851
- [this.#db.dialect.boolValue(false), this.#db.dialect.boolValue(true), nodeId, languageId],
2852
- )
3177
+ await this.#db.q
3178
+ .updateTable('document_culture_variation')
3179
+ .set({
3180
+ published: this.#db.dialect.boolValue(false) as boolean,
3181
+ edited: this.#db.dialect.boolValue(true) as boolean,
3182
+ })
3183
+ .where('node_id', '=', nodeId)
3184
+ .where('language_id', '=', languageId)
3185
+ .execute()
2853
3186
  else
2854
- await this.#db.exec(
2855
- `UPDATE document_culture_variation SET published = ?, edited = ?, published_event_id = ?,
2856
- published_name = name WHERE node_id = ? AND language_id = ?`,
2857
- [
2858
- this.#db.dialect.boolValue(true),
2859
- this.#db.dialect.boolValue(false),
2860
- eventId,
2861
- nodeId,
2862
- languageId,
2863
- ],
2864
- )
3187
+ await this.#db.q
3188
+ .updateTable('document_culture_variation')
3189
+ .set((eb) => ({
3190
+ published: this.#db.dialect.boolValue(true) as boolean,
3191
+ edited: this.#db.dialect.boolValue(false) as boolean,
3192
+ published_event_id: eventId,
3193
+ published_name: eb.ref('name'),
3194
+ }))
3195
+ .where('node_id', '=', nodeId)
3196
+ .where('language_id', '=', languageId)
3197
+ .execute()
2865
3198
  }
2866
3199
 
2867
3200
  /** Each published culture: its language, the event it was published at, and its published name. */
@@ -2870,12 +3203,20 @@ export class DocumentRepository {
2870
3203
  ): Promise<Map<number, PublishedCulture[]>> {
2871
3204
  const out = new Map<number, PublishedCulture[]>()
2872
3205
  if (ids.length === 0) return out
2873
- const rows = await this.#db.query(
2874
- `SELECT dcv.node_id, dcv.language_id, l.iso_code, dcv.published_event_id, dcv.published_name, dcv.name
2875
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
2876
- WHERE dcv.node_id IN (${ids.map(() => '?').join(', ')}) AND dcv.published = ?`,
2877
- [...ids, this.#db.dialect.boolValue(true)],
2878
- )
3206
+ const rows = await this.#db.q
3207
+ .selectFrom('document_culture_variation as dcv')
3208
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
3209
+ .select([
3210
+ 'dcv.node_id',
3211
+ 'dcv.language_id',
3212
+ 'l.iso_code',
3213
+ 'dcv.published_event_id',
3214
+ 'dcv.published_name',
3215
+ 'dcv.name',
3216
+ ])
3217
+ .where('dcv.node_id', 'in', ids)
3218
+ .where('dcv.published', '=', this.#db.dialect.boolValue(true) as boolean)
3219
+ .execute()
2879
3220
  for (const row of rows) {
2880
3221
  const id = Number(row.node_id)
2881
3222
  out.set(id, [
@@ -2898,18 +3239,28 @@ export class DocumentRepository {
2898
3239
  ): Promise<Map<number, ValueRow[]>> {
2899
3240
  const out = new Map<number, ValueRow[]>()
2900
3241
  if (ids.length === 0) return out
2901
- const params: unknown[] = [...ids]
2902
- let where = `node_id IN (${ids.map(() => '?').join(', ')})`
2903
- if (schemaStateId !== undefined) {
2904
- where += ' AND schema_state_id <= ?'
2905
- params.push(schemaStateId)
2906
- }
2907
- const rows = await this.#db.query(
2908
- `SELECT id, node_id, event_id, property_type_id, language_id, segment,
2909
- int_value, decimal_value, date_value, varchar_value, text_value
2910
- FROM property_value WHERE ${where} ORDER BY node_id, id`,
2911
- params,
2912
- )
3242
+ const rows = await this.#db.q
3243
+ .selectFrom('property_value')
3244
+ .select([
3245
+ 'id',
3246
+ 'node_id',
3247
+ 'event_id',
3248
+ 'property_type_id',
3249
+ 'language_id',
3250
+ 'segment',
3251
+ 'int_value',
3252
+ 'decimal_value',
3253
+ 'date_value',
3254
+ 'varchar_value',
3255
+ 'text_value',
3256
+ ])
3257
+ .where('node_id', 'in', ids)
3258
+ .$if(schemaStateId !== undefined, (q) =>
3259
+ q.where('schema_state_id', '<=', schemaStateId as number),
3260
+ )
3261
+ .orderBy('node_id')
3262
+ .orderBy('id')
3263
+ .execute()
2913
3264
  for (const row of rows) {
2914
3265
  const id = Number(row.node_id)
2915
3266
  const list = out.get(id)
@@ -2920,12 +3271,19 @@ export class DocumentRepository {
2920
3271
  }
2921
3272
 
2922
3273
  async #publishedCultureEvents(nodeId: number): Promise<PublishedCulture[]> {
2923
- const rows = await this.#db.query(
2924
- `SELECT dcv.language_id, l.iso_code, dcv.published_event_id, dcv.published_name, dcv.name
2925
- FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
2926
- WHERE dcv.node_id = ? AND dcv.published = ?`,
2927
- [nodeId, this.#db.dialect.boolValue(true)],
2928
- )
3274
+ const rows = await this.#db.q
3275
+ .selectFrom('document_culture_variation as dcv')
3276
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
3277
+ .select([
3278
+ 'dcv.language_id',
3279
+ 'l.iso_code',
3280
+ 'dcv.published_event_id',
3281
+ 'dcv.published_name',
3282
+ 'dcv.name',
3283
+ ])
3284
+ .where('dcv.node_id', '=', nodeId)
3285
+ .where('dcv.published', '=', this.#db.dialect.boolValue(true) as boolean)
3286
+ .execute()
2929
3287
  return rows.map((row) => ({
2930
3288
  languageId: Number(row.language_id),
2931
3289
  isoCode: String(row.iso_code),
@@ -2935,10 +3293,12 @@ export class DocumentRepository {
2935
3293
  }
2936
3294
 
2937
3295
  async #variesByCulture(nodeId: number): Promise<boolean> {
2938
- const rows = await this.#db.query<{ variations: number }>(
2939
- 'SELECT ct.variations FROM content c JOIN content_type ct ON ct.node_id = c.content_type_id WHERE c.node_id = ?',
2940
- [nodeId],
2941
- )
3296
+ const rows = await this.#db.q
3297
+ .selectFrom('content as c')
3298
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
3299
+ .select('ct.variations')
3300
+ .where('c.node_id', '=', nodeId)
3301
+ .execute()
2942
3302
  return flagVariesByCulture(Number(rows[0]?.variations ?? 0))
2943
3303
  }
2944
3304
 
@@ -2955,19 +3315,28 @@ export class DocumentRepository {
2955
3315
  schemaStateId?: number,
2956
3316
  ): Promise<DocumentValue[]> {
2957
3317
  const latest = Math.max(invariantEventId, ...cultures.map((c) => c.eventId))
2958
- const conditions = ['node_id = ?', 'event_id <= ?']
2959
- const params: unknown[] = [nodeId, latest]
2960
- if (schemaStateId !== undefined) {
2961
- conditions.push('schema_state_id <= ?')
2962
- params.push(schemaStateId)
2963
- }
2964
3318
  const all = (
2965
- await this.#db.query(
2966
- `SELECT id, event_id, property_type_id, language_id, segment,
2967
- int_value, decimal_value, date_value, varchar_value, text_value
2968
- FROM property_value WHERE ${conditions.join(' AND ')} ORDER BY id`,
2969
- params,
2970
- )
3319
+ await this.#db.q
3320
+ .selectFrom('property_value')
3321
+ .select([
3322
+ 'id',
3323
+ 'event_id',
3324
+ 'property_type_id',
3325
+ 'language_id',
3326
+ 'segment',
3327
+ 'int_value',
3328
+ 'decimal_value',
3329
+ 'date_value',
3330
+ 'varchar_value',
3331
+ 'text_value',
3332
+ ])
3333
+ .where('node_id', '=', nodeId)
3334
+ .where('event_id', '<=', latest)
3335
+ .$if(schemaStateId !== undefined, (q) =>
3336
+ q.where('schema_state_id', '<=', schemaStateId as number),
3337
+ )
3338
+ .orderBy('id')
3339
+ .execute()
2971
3340
  ).map((row) => this.#toValueRow(row))
2972
3341
  return this.#valuesFromRows(
2973
3342
  publishedValueRows(all, invariantEventId, cultures),
@@ -2977,10 +3346,12 @@ export class DocumentRepository {
2977
3346
  }
2978
3347
 
2979
3348
  async #anyCulturePublished(nodeId: number): Promise<boolean> {
2980
- const rows = await this.#db.query<{ n: number }>(
2981
- 'SELECT COUNT(*) AS n FROM document_culture_variation WHERE node_id = ? AND published = ?',
2982
- [nodeId, this.#db.dialect.boolValue(true)],
2983
- )
3349
+ const rows = await this.#db.q
3350
+ .selectFrom('document_culture_variation')
3351
+ .select((eb) => eb.fn.countAll().as('n'))
3352
+ .where('node_id', '=', nodeId)
3353
+ .where('published', '=', this.#db.dialect.boolValue(true) as boolean)
3354
+ .execute()
2984
3355
  return Number(rows[0]?.n ?? 0) > 0
2985
3356
  }
2986
3357
 
@@ -2993,10 +3364,12 @@ export class DocumentRepository {
2993
3364
  .map(Number)
2994
3365
  .filter((id) => id > 0 && id !== node.id && !alsoPublishing.has(id))
2995
3366
  if (ids.length === 0) return true
2996
- const rows = await this.#db.query<{ n: number }>(
2997
- `SELECT COUNT(*) AS n FROM document WHERE node_id IN (${ids.map(() => '?').join(', ')}) AND published = ?`,
2998
- [...ids, this.#db.dialect.boolValue(false)],
2999
- )
3367
+ const rows = await this.#db.q
3368
+ .selectFrom('document')
3369
+ .select((eb) => eb.fn.countAll().as('n'))
3370
+ .where('node_id', 'in', ids)
3371
+ .where('published', '=', this.#db.dialect.boolValue(false) as boolean)
3372
+ .execute()
3000
3373
  return Number(rows[0]?.n ?? 0) === 0
3001
3374
  }
3002
3375
  }
@@ -3037,6 +3410,9 @@ function parseConfig(raw: unknown): Record<string, unknown> {
3037
3410
  * draft cache knows it is stale when the save happened on another node.
3038
3411
  */
3039
3412
  export async function latestContentVersionId(db: Db): Promise<number> {
3040
- const rows = await db.query<{ n: number | null }>('SELECT MAX(id) AS n FROM content_version')
3413
+ const rows = await db.q
3414
+ .selectFrom('content_version')
3415
+ .select((eb) => eb.fn.max('id').as('n'))
3416
+ .execute()
3041
3417
  return Number(rows[0]?.n ?? 0)
3042
3418
  }