@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
@@ -9,6 +9,7 @@
9
9
  import type { Db } from './database.ts'
10
10
  import { DbDate } from './dialect.ts'
11
11
  import { parseWritesPaused, WRITES_PAUSED_KEY, type WritesPaused } from './maintenance.ts'
12
+ import { rowLock } from './query.ts'
12
13
 
13
14
  export interface SchemaStateRow {
14
15
  id: number
@@ -78,12 +79,14 @@ export class WritesPausedError extends WriteRejectedError {
78
79
 
79
80
  /** The latest current state. Takes a shared lock where the engine has one, so an upgrade cannot slip between the check and the write. */
80
81
  export async function currentSchemaState(db: Db, lock = false): Promise<SchemaStateRow> {
81
- const suffix = lock ? db.dialect.forShare : ''
82
- const rows = await db.query(
83
- `SELECT id, version, revision, hash, status FROM schema_state
84
- WHERE status = 'current' ORDER BY id DESC LIMIT 1 ${suffix}`,
85
- )
86
- const row = rows[0]
82
+ const row = await db.q
83
+ .selectFrom('schema_state')
84
+ .select(['id', 'version', 'revision', 'hash', 'status'])
85
+ .where('status', '=', 'current')
86
+ .orderBy('id', 'desc')
87
+ .limit(1)
88
+ .$if(lock, (q) => q.$call(rowLock(db, 'share')))
89
+ .executeTakeFirst()
87
90
  if (!row) throw new Error('schema_state has no current row; the database is not installed.')
88
91
  return {
89
92
  id: Number(row.id),
@@ -101,11 +104,12 @@ export async function currentSchemaState(db: Db, lock = false): Promise<SchemaSt
101
104
  export async function assertNodeMayWrite(db: Db, node: NodeSchemaState): Promise<SchemaStateRow> {
102
105
  const current = await currentSchemaState(db, true)
103
106
  if (compareStates(node, current) < 0) throw new WriteRejectedError(node, current)
104
- const rows = await db.query<{ value: string | null }>(
105
- 'SELECT value FROM key_value WHERE key = ?',
106
- [WRITES_PAUSED_KEY],
107
- )
108
- const paused = parseWritesPaused(rows[0]?.value)
107
+ const pausedRow = await db.q
108
+ .selectFrom('key_value')
109
+ .select('value')
110
+ .where('key', '=', WRITES_PAUSED_KEY)
111
+ .executeTakeFirst()
112
+ const paused = parseWritesPaused(pausedRow?.value)
109
113
  if (paused) throw new WritesPausedError(node, current, paused)
110
114
  return current
111
115
  }
@@ -120,25 +124,24 @@ export interface AdvanceOptions {
120
124
 
121
125
  /** Appends a schema state row. Under `FOR UPDATE` on the previous current row, so it serialises against writers. */
122
126
  export async function appendSchemaState(db: Db, options: AdvanceOptions): Promise<SchemaStateRow> {
123
- await db.query(
124
- `SELECT id FROM schema_state WHERE status = 'current' ORDER BY id DESC LIMIT 1 ${db.dialect.forUpdate}`,
125
- )
126
- await db.exec(
127
- `INSERT INTO schema_state (version, revision, hash, status, synced_at, synced_by)
128
- VALUES (?, ?, ?, ?, ?, ?)`,
129
- [
130
- options.version,
131
- options.revision,
132
- options.hash ?? null,
133
- options.status,
134
- DbDate.toDb(new Date()),
135
- options.by ?? null,
136
- ],
137
- )
138
- const rows = await db.query(
139
- 'SELECT id, version, revision, hash, status FROM schema_state ORDER BY id DESC LIMIT 1',
140
- )
141
- const row = rows[0] as Record<string, unknown>
127
+ await lockCurrentState(db)
128
+ await db.q
129
+ .insertInto('schema_state')
130
+ .values({
131
+ version: options.version,
132
+ revision: options.revision,
133
+ hash: options.hash ?? null,
134
+ status: options.status,
135
+ synced_at: DbDate.toDb(new Date()),
136
+ synced_by: options.by ?? null,
137
+ })
138
+ .execute()
139
+ const row = await db.q
140
+ .selectFrom('schema_state')
141
+ .select(['id', 'version', 'revision', 'hash', 'status'])
142
+ .orderBy('id', 'desc')
143
+ .limit(1)
144
+ .executeTakeFirstOrThrow()
142
145
  return {
143
146
  id: Number(row.id),
144
147
  version: String(row.version),
@@ -150,14 +153,16 @@ export async function appendSchemaState(db: Db, options: AdvanceOptions): Promis
150
153
 
151
154
  /** Key write-back changes the files after they were hashed; the state records the files as they now are. */
152
155
  export async function updateSchemaStateHash(db: Db, id: number, hash: string): Promise<void> {
153
- await db.exec('UPDATE schema_state SET hash = ? WHERE id = ?', [hash, id])
156
+ await db.q.updateTable('schema_state').set({ hash }).where('id', '=', id).execute()
154
157
  }
155
158
 
156
159
  /** Every state row, oldest first. The table is small: one row per deployment. */
157
160
  export async function allSchemaStates(db: Db): Promise<SchemaStateRow[]> {
158
- const rows = await db.query(
159
- 'SELECT id, version, revision, hash, status FROM schema_state ORDER BY id',
160
- )
161
+ const rows = await db.q
162
+ .selectFrom('schema_state')
163
+ .select(['id', 'version', 'revision', 'hash', 'status'])
164
+ .orderBy('id')
165
+ .execute()
161
166
  return rows.map((row) => ({
162
167
  id: Number(row.id),
163
168
  version: String(row.version),
@@ -189,8 +194,18 @@ export async function visibleStateIdFor(
189
194
 
190
195
  /** Marks a prepared state current — the cut-over. */
191
196
  export async function makeStateCurrent(db: Db, id: number): Promise<void> {
192
- await db.query(
193
- `SELECT id FROM schema_state WHERE status = 'current' ORDER BY id DESC LIMIT 1 ${db.dialect.forUpdate}`,
194
- )
195
- await db.exec("UPDATE schema_state SET status = 'current' WHERE id = ?", [id])
197
+ await lockCurrentState(db)
198
+ await db.q.updateTable('schema_state').set({ status: 'current' }).where('id', '=', id).execute()
199
+ }
200
+
201
+ /** Locks the current state row where the engine can, so state changes serialise against writers. */
202
+ async function lockCurrentState(db: Db): Promise<void> {
203
+ await db.q
204
+ .selectFrom('schema_state')
205
+ .select('id')
206
+ .where('status', '=', 'current')
207
+ .orderBy('id', 'desc')
208
+ .limit(1)
209
+ .$call(rowLock(db, 'update'))
210
+ .execute()
196
211
  }
package/src/search.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { ObjectTypes } from '@crombolo/core'
7
7
  import type { Db } from './database.ts'
8
8
  import { DbDate, fromDbBool } from './dialect.ts'
9
+ import { type Expression, now, rowLock } from './query.ts'
9
10
  import { searchTerms, searchWords, type UnsearchableProperty, valueText } from './search-text.ts'
10
11
  import { siteEntriesFor, writeSiteEntries } from './site-search.ts'
11
12
 
@@ -35,11 +36,29 @@ const INDEX_TYPE: Record<string, string> = {
35
36
  [ObjectTypes.Member]: 'member',
36
37
  }
37
38
 
38
- const marks = (n: number) => Array.from({ length: n }, () => '?').join(', ')
39
+ /** Queues the rows a select of `node_id, generation, queued_at` answers, bumping any already queued. */
40
+ async function enqueue(db: Db, rows: Expression<unknown>): Promise<void> {
41
+ await db.q
42
+ .insertInto('search_index_queue')
43
+ .columns(['node_id', 'generation', 'queued_at'])
44
+ .expression(rows)
45
+ .onConflict((oc) =>
46
+ oc.column('node_id').doUpdateSet((eb) => ({
47
+ generation: eb('search_index_queue.generation', '+', 1),
48
+ queued_at: eb.ref('excluded.queued_at'),
49
+ })),
50
+ )
51
+ .execute()
52
+ }
39
53
 
40
- const ENQUEUE = `INSERT INTO search_index_queue (node_id, generation, queued_at)`
41
- const ON_CONFLICT = `ON CONFLICT (node_id) DO UPDATE
42
- SET generation = search_index_queue.generation + 1, queued_at = excluded.queued_at`
54
+ /** Every node of these object types, as rows to queue. */
55
+ function nodesOfTypes(db: Db, objectTypes: readonly string[], ids?: readonly number[]) {
56
+ return db.q
57
+ .selectFrom('node')
58
+ .select((eb) => ['id', eb.lit(1).as('generation'), now(db).as('queued_at')])
59
+ .$if(ids !== undefined, (q) => q.where('id', 'in', ids ?? []))
60
+ .where('node_object_type', 'in', objectTypes)
61
+ }
43
62
 
44
63
  /**
45
64
  * Queues items for the indexer. Called inside the write's own transaction, so
@@ -50,13 +69,7 @@ export async function queueForSearch(db: Db, nodeIds: Iterable<number>): Promise
50
69
  const ids = [...new Set(nodeIds)]
51
70
  if (ids.length === 0) return
52
71
  for (let i = 0; i < ids.length; i += 500) {
53
- const chunk = ids.slice(i, i + 500)
54
- await db.exec(
55
- `${ENQUEUE} SELECT id, 1, ${db.dialect.now()} FROM node
56
- WHERE id IN (${marks(chunk.length)}) AND node_object_type IN (${marks(INDEXED_TYPES.length)})
57
- ${ON_CONFLICT}`,
58
- [...chunk, ...INDEXED_TYPES],
59
- )
72
+ await enqueue(db, nodesOfTypes(db, INDEXED_TYPES, ids.slice(i, i + 500)))
60
73
  }
61
74
  }
62
75
 
@@ -68,21 +81,21 @@ export async function queueContentTypesForSearch(
68
81
  const types = new Set(contentTypeNodeIds)
69
82
  let frontier = [...types]
70
83
  while (frontier.length > 0) {
71
- const children = await db.query<{ id: number }>(
72
- `SELECT child_content_type_id AS id FROM content_type_composition
73
- WHERE parent_content_type_id IN (${marks(frontier.length)})`,
74
- frontier,
75
- )
84
+ const children = await db.q
85
+ .selectFrom('content_type_composition')
86
+ .select('child_content_type_id as id')
87
+ .where('parent_content_type_id', 'in', frontier)
88
+ .execute()
76
89
  frontier = children.map((row) => Number(row.id)).filter((id) => !types.has(id))
77
90
  for (const id of frontier) types.add(id)
78
91
  }
79
92
  if (types.size === 0) return
80
- const ids = [...types]
81
- await db.exec(
82
- `${ENQUEUE} SELECT node_id, 1, ${db.dialect.now()} FROM content
83
- WHERE content_type_id IN (${marks(ids.length)})
84
- ${ON_CONFLICT}`,
85
- ids,
93
+ await enqueue(
94
+ db,
95
+ db.q
96
+ .selectFrom('content')
97
+ .select((eb) => ['node_id', eb.lit(1).as('generation'), now(db).as('queued_at')])
98
+ .where('content_type_id', 'in', [...types]),
86
99
  )
87
100
  }
88
101
 
@@ -91,12 +104,7 @@ export async function queueContentTypesForSearch(
91
104
  * read inside blocks wherever they are used, which no query can narrow.
92
105
  */
93
106
  export async function queueEverythingForSearch(db: Db): Promise<void> {
94
- await db.exec(
95
- `${ENQUEUE} SELECT id, 1, ${db.dialect.now()} FROM node
96
- WHERE node_object_type IN (${marks(INDEXED_TYPES.length)})
97
- ${ON_CONFLICT}`,
98
- [...INDEXED_TYPES],
99
- )
107
+ await enqueue(db, nodesOfTypes(db, INDEXED_TYPES))
100
108
  }
101
109
 
102
110
  /** One row of `search_document`: an item in one culture, '' when invariant. */
@@ -142,26 +150,33 @@ export class SearchIndex {
142
150
  * generation, so the row outlives this run and the item is indexed once more.
143
151
  */
144
152
  async indexQueued(limit = 200): Promise<number> {
145
- const queued = await this.#db.query<{ node_id: number; generation: number }>(
146
- 'SELECT node_id, generation FROM search_index_queue ORDER BY queued_at, node_id LIMIT ?',
147
- [limit],
148
- )
153
+ const queued = await this.#db.q
154
+ .selectFrom('search_index_queue')
155
+ .select(['node_id', 'generation'])
156
+ .orderBy('queued_at')
157
+ .orderBy('node_id')
158
+ .limit(limit)
159
+ .execute()
149
160
  let indexed = 0
150
161
  for (const row of queued) {
151
162
  const nodeId = Number(row.node_id)
152
163
  const generation = Number(row.generation)
153
164
  const done = await this.#db.transaction(async (tx) => {
154
- const claimed = await tx.query(
155
- `SELECT node_id FROM search_index_queue WHERE node_id = ? AND generation = ? ${tx.dialect.forUpdateSkipLocked}`,
156
- [nodeId, generation],
157
- )
165
+ const claimed = await tx.q
166
+ .selectFrom('search_index_queue')
167
+ .select('node_id')
168
+ .where('node_id', '=', nodeId)
169
+ .where('generation', '=', generation)
170
+ .$call(rowLock(tx, 'update skip locked'))
171
+ .execute()
158
172
  if (claimed.length === 0) return false
159
173
  await writeEntries(tx, nodeId, await entriesFor(tx, nodeId))
160
174
  await writeSiteEntries(tx, nodeId, await siteEntriesFor(tx, nodeId))
161
- await tx.exec('DELETE FROM search_index_queue WHERE node_id = ? AND generation = ?', [
162
- nodeId,
163
- generation,
164
- ])
175
+ await tx.q
176
+ .deleteFrom('search_index_queue')
177
+ .where('node_id', '=', nodeId)
178
+ .where('generation', '=', generation)
179
+ .execute()
165
180
  return true
166
181
  })
167
182
  if (done) indexed++
@@ -181,27 +196,26 @@ export class SearchIndex {
181
196
 
182
197
  /** Queues every item the index covers; the index keeps answering meanwhile. */
183
198
  async rebuild(index: SearchIndexDefinition): Promise<void> {
184
- await this.#db.exec(
185
- `${ENQUEUE} SELECT id, 1, ${this.#db.dialect.now()} FROM node
186
- WHERE node_object_type IN (${marks(index.objectTypes.length)})
187
- ${ON_CONFLICT}`,
188
- [...index.objectTypes],
189
- )
199
+ await enqueue(this.#db, nodesOfTypes(this.#db, index.objectTypes))
190
200
  }
191
201
 
192
202
  async stats(index: SearchIndexDefinition): Promise<SearchIndexStats> {
193
203
  const types = index.objectTypes
194
- const [documents] = await this.#db.query<{ n: number; fields: number | null }>(
195
- `SELECT COUNT(DISTINCT sd.node_id) AS n, MAX(sd.field_count) AS fields
196
- FROM search_document sd JOIN node n ON n.id = sd.node_id
197
- WHERE n.node_object_type IN (${marks(types.length)})`,
198
- [...types],
199
- )
200
- const [pending] = await this.#db.query<{ n: number }>(
201
- `SELECT COUNT(*) AS n FROM search_index_queue q JOIN node n ON n.id = q.node_id
202
- WHERE n.node_object_type IN (${marks(types.length)})`,
203
- [...types],
204
- )
204
+ const documents = await this.#db.q
205
+ .selectFrom('search_document as sd')
206
+ .innerJoin('node as n', 'n.id', 'sd.node_id')
207
+ .select((eb) => [
208
+ eb.fn.count('sd.node_id').distinct().as('n'),
209
+ eb.fn.max('sd.field_count').as('fields'),
210
+ ])
211
+ .where('n.node_object_type', 'in', types)
212
+ .executeTakeFirst()
213
+ const pending = await this.#db.q
214
+ .selectFrom('search_index_queue as q')
215
+ .innerJoin('node as n', 'n.id', 'q.node_id')
216
+ .select((eb) => eb.fn.countAll().as('n'))
217
+ .where('n.node_object_type', 'in', types)
218
+ .executeTakeFirst()
205
219
  return {
206
220
  documentCount: Number(documents?.n ?? 0),
207
221
  fieldCount: Number(documents?.fields ?? 0),
@@ -218,20 +232,27 @@ export class SearchIndex {
218
232
  const terms = searchTerms(term)
219
233
  if (terms.length === 0) return { total: 0, items: [] }
220
234
  const types = index.objectTypes
221
- const from = `FROM (${this.#db.dialect.fullTextHits}) h JOIN node n ON n.id = h.node_id
222
- WHERE n.node_object_type IN (${marks(types.length)})`
223
- const params = [this.#db.dialect.fullTextQuery(terms), ...types]
224
- const [count] = await this.#db.query<{ n: number }>(`SELECT COUNT(*) AS n ${from}`, params)
225
- const rows = await this.#db.query<{ id: number; key: string; score: number }>(
226
- `SELECT n.id, n.unique_id AS key, h.score ${from} ORDER BY h.score DESC, n.id LIMIT ? OFFSET ?`,
227
- [...params, paging.take, paging.skip],
228
- )
235
+ const dialect = this.#db.dialect
236
+ const hits = this.#db.q
237
+ .selectFrom(dialect.fullTextMatches(dialect.fullTextQuery(terms)).as('h'))
238
+ .innerJoin('node as n', 'n.id', 'h.node_id')
239
+ .where('n.node_object_type', 'in', types)
240
+ const count = await hits.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
241
+ const rows = await hits
242
+ .select(['n.id', 'n.unique_id as key', 'h.score'])
243
+ .orderBy('h.score', 'desc')
244
+ .orderBy('n.id')
245
+ .limit(paging.take)
246
+ .offset(paging.skip)
247
+ .execute()
229
248
  const items: SearchHit[] = []
230
249
  for (const row of rows) {
231
- const stored = await this.#db.query<{ fields: string }>(
232
- 'SELECT fields FROM search_document WHERE node_id = ? ORDER BY culture',
233
- [Number(row.id)],
234
- )
250
+ const stored = await this.#db.q
251
+ .selectFrom('search_document')
252
+ .select('fields')
253
+ .where('node_id', '=', Number(row.id))
254
+ .orderBy('culture')
255
+ .execute()
235
256
  const merged = new Map<string, string[]>()
236
257
  for (const entry of stored)
237
258
  for (const [name, values] of Object.entries(
@@ -249,22 +270,21 @@ export class SearchIndex {
249
270
  }
250
271
 
251
272
  async function writeEntries(tx: Db, nodeId: number, entries: readonly SearchEntry[]) {
252
- await tx.exec('DELETE FROM search_document WHERE node_id = ?', [nodeId])
253
- const now = DbDate.toDb(new Date())
273
+ await tx.q.deleteFrom('search_document').where('node_id', '=', nodeId).execute()
274
+ const indexedAt = DbDate.toDb(new Date())
254
275
  for (const entry of entries)
255
- await tx.exec(
256
- `INSERT INTO search_document (node_id, culture, name, body, fields, field_count, indexed_at)
257
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
258
- [
259
- nodeId,
260
- entry.culture,
261
- entry.name,
262
- entry.body,
263
- JSON.stringify(entry.fields),
264
- Object.keys(entry.fields).length,
265
- now,
266
- ],
267
- )
276
+ await tx.q
277
+ .insertInto('search_document')
278
+ .values({
279
+ node_id: nodeId,
280
+ culture: entry.culture,
281
+ name: entry.name,
282
+ body: entry.body,
283
+ fields: JSON.stringify(entry.fields),
284
+ field_count: Object.keys(entry.fields).length,
285
+ indexed_at: indexedAt,
286
+ })
287
+ .execute()
268
288
  }
269
289
 
270
290
  const folded = (texts: readonly string[]) => texts.flatMap(searchWords).join(' ')
@@ -275,36 +295,43 @@ const folded = (texts: readonly string[]) => texts.flatMap(searchWords).join(' '
275
295
  * counts on every type composing it, which is the key a block carries.
276
296
  */
277
297
  function unsearchableElementProperties(db: Db): Promise<UnsearchableProperty> {
278
- return hiddenElementProperties(db, 'p.searchable = ?', [db.dialect.boolValue(false)])
298
+ return hiddenElementProperties(db, false)
279
299
  }
280
300
 
281
301
  /**
282
- * The properties a condition on `property_type p` picks out, as a test by type
283
- * key and alias: what a block's text is checked against. Shared with site search.
302
+ * The properties marked `searchable = false`, and with `siteSearch` those whose
303
+ * site search is `off` too, as a test by type key and alias: what a block's
304
+ * text is checked against. Shared with site search.
284
305
  */
285
306
  export async function hiddenElementProperties(
286
307
  db: Db,
287
- condition: string,
288
- params: readonly unknown[],
308
+ siteSearch: boolean,
289
309
  ): Promise<UnsearchableProperty> {
290
- const rows = await db.query<{ type_id: number; alias: string }>(
291
- `SELECT p.content_type_id AS type_id, p.alias FROM property_type p
292
- WHERE (${condition}) AND p.retired_at IS NULL`,
293
- [...params],
294
- )
310
+ const rows = await db.q
311
+ .selectFrom('property_type as p')
312
+ .select(['p.content_type_id as type_id', 'p.alias'])
313
+ .where((eb) => {
314
+ const unsearchable = eb('p.searchable', '=', db.dialect.boolValue(false))
315
+ return siteSearch ? eb.or([unsearchable, eb('p.site_search', '=', 'off')]) : unsearchable
316
+ })
317
+ .where('p.retired_at', 'is', null)
318
+ .execute()
295
319
  if (rows.length === 0) return () => false
296
320
  const composedBy = new Map<number, number[]>()
297
- for (const row of await db.query<{ parent: number; child: number }>(
298
- 'SELECT parent_content_type_id AS parent, child_content_type_id AS child FROM content_type_composition',
299
- ))
321
+ for (const row of await db.q
322
+ .selectFrom('content_type_composition')
323
+ .select(['parent_content_type_id as parent', 'child_content_type_id as child'])
324
+ .execute())
300
325
  composedBy.set(Number(row.parent), [
301
326
  ...(composedBy.get(Number(row.parent)) ?? []),
302
327
  Number(row.child),
303
328
  ])
304
329
  const keys = new Map<number, string>()
305
- for (const row of await db.query<{ id: number; unique_id: string }>(
306
- `SELECT n.id, n.unique_id FROM node n JOIN content_type ct ON ct.node_id = n.id`,
307
- ))
330
+ for (const row of await db.q
331
+ .selectFrom('node as n')
332
+ .innerJoin('content_type as ct', 'ct.node_id', 'n.id')
333
+ .select(['n.id', 'n.unique_id'])
334
+ .execute())
308
335
  keys.set(Number(row.id), String(row.unique_id).toLowerCase())
309
336
  const hidden = new Set<string>()
310
337
  for (const row of rows) {
@@ -329,41 +356,60 @@ export async function hiddenElementProperties(
329
356
  * items are kept and filtered when searched, so the recycle bin is searchable.
330
357
  */
331
358
  export async function entriesFor(db: Db, nodeId: number): Promise<SearchEntry[]> {
332
- const [node] = await db.query<Record<string, unknown>>(
333
- `SELECT n.id, n.unique_id, n.text, n.path, n.node_object_type, n.trashed, ct.alias AS type_alias
334
- FROM node n JOIN content c ON c.node_id = n.id JOIN content_type ct ON ct.node_id = c.content_type_id
335
- WHERE n.id = ?`,
336
- [nodeId],
337
- )
359
+ const node = await db.q
360
+ .selectFrom('node as n')
361
+ .innerJoin('content as c', 'c.node_id', 'n.id')
362
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
363
+ .select([
364
+ 'n.id',
365
+ 'n.unique_id',
366
+ 'n.text',
367
+ 'n.path',
368
+ 'n.node_object_type',
369
+ 'n.trashed',
370
+ 'ct.alias as type_alias',
371
+ ])
372
+ .where('n.id', '=', nodeId)
373
+ .executeTakeFirst()
338
374
  if (!node || !INDEXED_TYPES.includes(String(node.node_object_type))) return []
339
375
 
340
- const values = await db.query<Record<string, unknown>>(
341
- `SELECT p.alias, l.iso_code, pv.varchar_value, pv.text_value
342
- FROM property_value pv
343
- JOIN property_type p ON p.id = pv.property_type_id
344
- LEFT JOIN language l ON l.id = pv.language_id
345
- LEFT JOIN member_property_type mpt ON mpt.property_type_id = p.id
346
- WHERE pv.node_id = ? AND pv.is_current = ? AND p.retired_at IS NULL AND p.searchable = ?
347
- AND (mpt.is_sensitive IS NULL OR mpt.is_sensitive = ?)
348
- ORDER BY p.sort_order, p.id`,
349
- [nodeId, db.dialect.boolValue(true), db.dialect.boolValue(true), db.dialect.boolValue(false)],
350
- )
376
+ const values = await db.q
377
+ .selectFrom('property_value as pv')
378
+ .innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
379
+ .leftJoin('language as l', 'l.id', 'pv.language_id')
380
+ .leftJoin('member_property_type as mpt', 'mpt.property_type_id', 'p.id')
381
+ .select(['p.alias', 'l.iso_code', 'pv.varchar_value', 'pv.text_value'])
382
+ .where('pv.node_id', '=', nodeId)
383
+ .where('pv.is_current', '=', db.dialect.boolValue(true) as boolean)
384
+ .where('p.retired_at', 'is', null)
385
+ .where('p.searchable', '=', db.dialect.boolValue(true))
386
+ .where((eb) =>
387
+ eb.or([
388
+ eb('mpt.is_sensitive', 'is', null),
389
+ eb('mpt.is_sensitive', '=', db.dialect.boolValue(false) as boolean),
390
+ ]),
391
+ )
392
+ .orderBy('p.sort_order')
393
+ .orderBy('p.id')
394
+ .execute()
351
395
  const unsearchable = await unsearchableElementProperties(db)
352
- const names = await db.query<{ iso_code: string; name: string }>(
353
- `SELECT l.iso_code, cvcv.name FROM content_version cv
354
- JOIN content_version_culture_variation cvcv ON cvcv.version_id = cv.id
355
- JOIN language l ON l.id = cvcv.language_id
356
- WHERE cv.node_id = ? AND cv.current = ?
357
- ORDER BY l.iso_code`,
358
- [nodeId, db.dialect.boolValue(true)],
359
- )
396
+ const names = await db.q
397
+ .selectFrom('content_version as cv')
398
+ .innerJoin('content_version_culture_variation as cvcv', 'cvcv.version_id', 'cv.id')
399
+ .innerJoin('language as l', 'l.id', 'cvcv.language_id')
400
+ .select(['l.iso_code', 'cvcv.name'])
401
+ .where('cv.node_id', '=', nodeId)
402
+ .where('cv.current', '=', db.dialect.boolValue(true) as boolean)
403
+ .orderBy('l.iso_code')
404
+ .execute()
360
405
  const extraNames: string[] = []
361
406
  const extraFields: Record<string, string[]> = {}
362
407
  if (String(node.node_object_type) === ObjectTypes.Member) {
363
- const [member] = await db.query<{ email: string; login_name: string }>(
364
- 'SELECT email, login_name FROM member WHERE node_id = ?',
365
- [nodeId],
366
- )
408
+ const member = await db.q
409
+ .selectFrom('member')
410
+ .select(['email', 'login_name'])
411
+ .where('node_id', '=', nodeId)
412
+ .executeTakeFirst()
367
413
  if (member) {
368
414
  extraNames.push(String(member.email), String(member.login_name))
369
415
  extraFields.email = [String(member.email)]
package/src/setup.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import type { Db } from './database.ts'
6
6
  import { Locks } from './locks.ts'
7
+ import { now } from './query.ts'
7
8
  import { insertSuperUser, type SeedAdmin, type SeedOptions } from './schema/seed.ts'
8
9
 
9
10
  export const SETUP_STATE_KEY = 'crombolo:setup'
@@ -12,24 +13,27 @@ export const SETUP_STATE_KEY = 'crombolo:setup'
12
13
  export type SetupState = 'pending' | 'complete' | 'none'
13
14
 
14
15
  export async function readSetupState(db: Db): Promise<SetupState> {
15
- const rows = await db.query<{ value: string }>('SELECT value FROM key_value WHERE key = ?', [
16
- SETUP_STATE_KEY,
17
- ])
18
- const value = rows[0]?.value
16
+ const row = await db.q
17
+ .selectFrom('key_value')
18
+ .select('value')
19
+ .where('key', '=', SETUP_STATE_KEY)
20
+ .executeTakeFirst()
21
+ const value = row?.value
19
22
  return value === 'pending' || value === 'complete' ? value : 'none'
20
23
  }
21
24
 
22
25
  async function writeSetupState(db: Db, state: 'pending' | 'complete'): Promise<void> {
23
- const now = db.dialect.now()
24
- const updated = await db.query<{ key: string }>(
25
- `UPDATE key_value SET value = ?, update_date = ${now} WHERE key = ? RETURNING key`,
26
- [state, SETUP_STATE_KEY],
27
- )
26
+ const updated = await db.q
27
+ .updateTable('key_value')
28
+ .set({ value: state, update_date: now(db) })
29
+ .where('key', '=', SETUP_STATE_KEY)
30
+ .returning('key')
31
+ .execute()
28
32
  if (updated.length === 0)
29
- await db.exec(`INSERT INTO key_value (key, value, update_date) VALUES (?, ?, ${now})`, [
30
- SETUP_STATE_KEY,
31
- state,
32
- ])
33
+ await db.q
34
+ .insertInto('key_value')
35
+ .values({ key: SETUP_STATE_KEY, value: state, update_date: now(db) })
36
+ .execute()
33
37
  }
34
38
 
35
39
  /** Opens setup on a database that has just been created with no administrator. */