@crombolo/data 0.29.1 → 0.30.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.29.1",
3
+ "version": "0.30.2",
4
4
  "description": "SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,6 +28,6 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.29.1"
31
+ "@crombolo/core": "0.30.2"
32
32
  }
33
33
  }
package/src/audit.ts CHANGED
@@ -6,6 +6,7 @@ import { normaliseUuid } from '@crombolo/core'
6
6
  import type { Db } from './database.ts'
7
7
  import { DbDate } from './dialect.ts'
8
8
  import { STATE_AUDIT_LOG } from './schema/audit-log.ts'
9
+ import { escapeLike } from './search-text.ts'
9
10
 
10
11
  export type AuditCategory =
11
12
  | 'content'
@@ -233,7 +234,7 @@ export class AuditLog {
233
234
  }
234
235
  const needle = filter.text?.trim().toLowerCase()
235
236
  if (needle) {
236
- const like = `%${needle.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
237
+ const like = `%${escapeLike(needle)}%`
237
238
  where.push(
238
239
  `(LOWER(entity_name) LIKE ? ESCAPE '\\' OR LOWER(entity_key) LIKE ? ESCAPE '\\' OR LOWER(user_name) LIKE ? ESCAPE '\\')`,
239
240
  )
@@ -0,0 +1,718 @@
1
+ /**
2
+ * Finding documents by their facts (story 183): type, place, dates, state,
3
+ * name, the full-text index and up to five property comparisons, in one SQL
4
+ * statement over the draft. The caller says who is asking: start nodes narrow
5
+ * the statement itself, and a Browse check (when some group can withhold it) is
6
+ * applied to a bounded window. `docs/search.md`, "Finding content by its
7
+ * properties".
8
+ */
9
+ import {
10
+ ObjectTypes,
11
+ STORAGE_COLUMN,
12
+ type StartNodes,
13
+ type ValueStorageTypeName,
14
+ } from '@crombolo/core'
15
+ import type { Db } from './database.ts'
16
+ import { DbDate, fromDbBool } from './dialect.ts'
17
+ import { escapeLike, searchTerms } from './search-text.ts'
18
+
19
+ export const QUERY_STATES = ['published', 'draft', 'changed', 'trashed'] as const
20
+ export type QueryState = (typeof QUERY_STATES)[number]
21
+ export const PROPERTY_OPS = [
22
+ 'eq',
23
+ 'ne',
24
+ 'contains',
25
+ 'gt',
26
+ 'gte',
27
+ 'lt',
28
+ 'lte',
29
+ 'exists',
30
+ 'empty',
31
+ ] as const
32
+ export type PropertyOp = (typeof PROPERTY_OPS)[number]
33
+ export const NAME_OPS = ['contains', 'startsWith', 'equals'] as const
34
+ export const SORT_FIELDS = ['name', 'createDate', 'updateDate', 'path', 'sortOrder'] as const
35
+ export const MAX_PROPERTY_CLAUSES = 5
36
+ export const MAX_TAKE = 100
37
+ export const DEFAULT_TAKE = 25
38
+ /** How many rows a restricted user's query reads before Browse is checked. */
39
+ export const QUERY_WINDOW = 1_000
40
+ /** Postgres stops a query that runs longer than this. */
41
+ export const QUERY_TIMEOUT_MS = 5_000
42
+
43
+ export interface ContentQuery {
44
+ entity: 'document'
45
+ contentTypes?: string[]
46
+ name?: { op: (typeof NAME_OPS)[number]; value: string }
47
+ text?: string
48
+ under?: string
49
+ parent?: string
50
+ maxDepth?: number
51
+ created?: { from?: Date; to?: Date }
52
+ updated?: { from?: Date; to?: Date }
53
+ state?: QueryState[]
54
+ culture?: string
55
+ properties?: Array<{ alias: string; op: PropertyOp; value?: unknown }>
56
+ sort?: { by: (typeof SORT_FIELDS)[number]; dir: 'asc' | 'desc' }
57
+ skip: number
58
+ take: number
59
+ }
60
+
61
+ export type ParsedQuery = { ok: true; query: ContentQuery } | { ok: false; problems: string[] }
62
+
63
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
64
+ typeof value === 'object' && value !== null && !Array.isArray(value)
65
+
66
+ /** A request body checked into a query, or every problem with it, each named. */
67
+ export function parseContentQuery(body: unknown): ParsedQuery {
68
+ const problems: string[] = []
69
+ if (!isRecord(body)) return { ok: false, problems: ['The request must be a JSON object.'] }
70
+ const known = new Set([
71
+ 'entity',
72
+ 'contentTypes',
73
+ 'name',
74
+ 'text',
75
+ 'under',
76
+ 'parent',
77
+ 'maxDepth',
78
+ 'created',
79
+ 'updated',
80
+ 'state',
81
+ 'culture',
82
+ 'properties',
83
+ 'sort',
84
+ 'skip',
85
+ 'take',
86
+ ])
87
+ for (const key of Object.keys(body))
88
+ if (!known.has(key)) problems.push(`"${key}" is not a query field.`)
89
+ if (body.entity !== 'document')
90
+ problems.push('"entity" must be "document"; media is not searchable this way yet.')
91
+
92
+ const strings = (field: string): string[] | undefined => {
93
+ const value = body[field]
94
+ if (value === undefined) return undefined
95
+ if (!Array.isArray(value) || value.some((v) => typeof v !== 'string' || v === '')) {
96
+ problems.push(`"${field}" must be a list of strings.`)
97
+ return undefined
98
+ }
99
+ return value as string[]
100
+ }
101
+ const text = (field: string): string | undefined => {
102
+ const value = body[field]
103
+ if (value === undefined) return undefined
104
+ if (typeof value !== 'string' || value.trim() === '') {
105
+ problems.push(`"${field}" must be a non-empty string.`)
106
+ return undefined
107
+ }
108
+ return value
109
+ }
110
+ const count = (field: string, fallback: number, max = Number.POSITIVE_INFINITY) => {
111
+ const value = body[field]
112
+ if (value === undefined) return fallback
113
+ if (!Number.isInteger(value) || (value as number) < 0 || (value as number) > max) {
114
+ problems.push(
115
+ `"${field}" must be a whole number from 0${max < Infinity ? ` to ${max}` : ''}.`,
116
+ )
117
+ return fallback
118
+ }
119
+ return value as number
120
+ }
121
+ const range = (field: string) => {
122
+ const value = body[field]
123
+ if (value === undefined) return undefined
124
+ if (!isRecord(value)) {
125
+ problems.push(`"${field}" must be { from?, to? }.`)
126
+ return undefined
127
+ }
128
+ const out: { from?: Date; to?: Date } = {}
129
+ for (const end of ['from', 'to'] as const) {
130
+ if (value[end] === undefined) continue
131
+ const date = typeof value[end] === 'string' ? new Date(value[end] as string) : undefined
132
+ if (!date || Number.isNaN(date.getTime())) problems.push(`"${field}.${end}" must be a date.`)
133
+ else out[end] = date
134
+ }
135
+ return out
136
+ }
137
+
138
+ let name: ContentQuery['name']
139
+ if (body.name !== undefined) {
140
+ const n = body.name
141
+ if (
142
+ !isRecord(n) ||
143
+ !NAME_OPS.includes(n.op as never) ||
144
+ typeof n.value !== 'string' ||
145
+ n.value === ''
146
+ )
147
+ problems.push(`"name" must be { op: ${NAME_OPS.join(' | ')}, value }.`)
148
+ else name = { op: n.op as (typeof NAME_OPS)[number], value: n.value }
149
+ }
150
+
151
+ const state = strings('state')
152
+ for (const s of state ?? [])
153
+ if (!QUERY_STATES.includes(s as never))
154
+ problems.push(`"${s}" is not a state; use ${QUERY_STATES.join(', ')}.`)
155
+
156
+ let properties: ContentQuery['properties']
157
+ if (body.properties !== undefined) {
158
+ if (!Array.isArray(body.properties)) problems.push('"properties" must be a list.')
159
+ else if (body.properties.length > MAX_PROPERTY_CLAUSES)
160
+ problems.push(`At most ${MAX_PROPERTY_CLAUSES} property clauses.`)
161
+ else {
162
+ properties = []
163
+ body.properties.forEach((clause, index) => {
164
+ if (
165
+ !isRecord(clause) ||
166
+ typeof clause.alias !== 'string' ||
167
+ !PROPERTY_OPS.includes(clause.op as never)
168
+ ) {
169
+ problems.push(
170
+ `"properties[${index}]" must be { alias, op: ${PROPERTY_OPS.join(' | ')}, value? }.`,
171
+ )
172
+ return
173
+ }
174
+ const op = clause.op as PropertyOp
175
+ const valued = op !== 'exists' && op !== 'empty'
176
+ if (valued && (clause.value === undefined || clause.value === null))
177
+ problems.push(`"properties[${index}]" needs a value for "${op}".`)
178
+ properties?.push({ alias: clause.alias, op, value: clause.value })
179
+ })
180
+ }
181
+ }
182
+
183
+ let sort: ContentQuery['sort']
184
+ if (body.sort !== undefined) {
185
+ const s = body.sort
186
+ if (
187
+ !isRecord(s) ||
188
+ !SORT_FIELDS.includes(s.by as never) ||
189
+ (s.dir !== undefined && s.dir !== 'asc' && s.dir !== 'desc')
190
+ )
191
+ problems.push(`"sort" must be { by: ${SORT_FIELDS.join(' | ')}, dir: asc | desc }.`)
192
+ else
193
+ sort = { by: s.by as (typeof SORT_FIELDS)[number], dir: (s.dir as 'asc' | 'desc') ?? 'asc' }
194
+ }
195
+
196
+ const query: ContentQuery = {
197
+ entity: 'document',
198
+ contentTypes: strings('contentTypes'),
199
+ name,
200
+ text: text('text'),
201
+ under: text('under'),
202
+ parent: text('parent'),
203
+ maxDepth: body.maxDepth === undefined ? undefined : count('maxDepth', 0),
204
+ created: range('created'),
205
+ updated: range('updated'),
206
+ state: state as QueryState[] | undefined,
207
+ culture: text('culture'),
208
+ properties,
209
+ sort,
210
+ skip: count('skip', 0),
211
+ take: count('take', DEFAULT_TAKE, MAX_TAKE),
212
+ }
213
+ if (query.maxDepth !== undefined && !query.under && !query.parent)
214
+ problems.push('"maxDepth" counts from "under"; give one.')
215
+ if (query.text !== undefined && searchTerms(query.text).length === 0)
216
+ problems.push('"text" has no words to search for.')
217
+ return problems.length > 0 ? { ok: false, problems } : { ok: true, query }
218
+ }
219
+
220
+ /** Who is asking: where they may look, and whether Browse must be checked per page. */
221
+ export interface QueryScope {
222
+ start: StartNodes
223
+ /** Undefined when every group can browse everything; else Browse for a key chain. */
224
+ browses?: (chain: readonly string[]) => boolean
225
+ /** Whether the user may read a property type's value, by its key. */
226
+ readsProperty: (propertyTypeKey: string) => boolean
227
+ /** How many rows are read before Browse is checked; `QUERY_WINDOW` unless a test says. */
228
+ window?: number
229
+ }
230
+
231
+ export interface QueryItem {
232
+ id: string
233
+ name: string
234
+ path: Array<{ id: string; name: string }>
235
+ contentType: { id: string; alias: string }
236
+ state: QueryState
237
+ createDate: string
238
+ updateDate: string
239
+ cultures?: Array<{ culture: string; name: string; state: QueryState }>
240
+ }
241
+
242
+ export interface QueryResult {
243
+ total: number
244
+ /** False when a restricted user's window was cut before Browse was checked. */
245
+ exact: boolean
246
+ items: QueryItem[]
247
+ }
248
+
249
+ /** A query the request asked for that cannot be run as asked; a 400 by name. */
250
+ export class ContentQueryRefused extends Error {}
251
+
252
+ /** Editors whose value is JSON or markup: only `exists` and `empty` apply; `text` searches them. */
253
+ const STRUCTURED_EDITORS = new Set([
254
+ 'Umbraco.BlockList',
255
+ 'Umbraco.BlockGrid',
256
+ 'Umbraco.RichText',
257
+ 'Umbraco.MediaPicker3',
258
+ 'Umbraco.MultiUrlPicker',
259
+ 'Umbraco.MultiNodeTreePicker',
260
+ 'Umbraco.ElementPicker',
261
+ 'Umbraco.ImageCropper',
262
+ 'Umbraco.UploadField',
263
+ 'Umbraco.Tags',
264
+ ])
265
+
266
+ const stateOf = (published: boolean, edited: boolean, trashed: boolean): QueryState =>
267
+ trashed ? 'trashed' : published && edited ? 'changed' : published ? 'published' : 'draft'
268
+
269
+ interface PropertyTarget {
270
+ ids: number[]
271
+ column: string
272
+ storage: ValueStorageTypeName
273
+ }
274
+
275
+ /** The documents a query matches, as the scope may see them. */
276
+ export async function queryDocuments(
277
+ db: Db,
278
+ query: ContentQuery,
279
+ scope: QueryScope,
280
+ ): Promise<QueryResult> {
281
+ const run = async (tx: Db) => {
282
+ if (tx.dialect.name === 'postgres')
283
+ await tx.exec(`SET LOCAL statement_timeout = ${QUERY_TIMEOUT_MS}`)
284
+ return runQuery(tx, query, scope)
285
+ }
286
+ // Postgres's timeout is per transaction; SQLite has none, so the window bounds it.
287
+ return db.dialect.name === 'postgres' ? db.transaction(run) : run(db)
288
+ }
289
+
290
+ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise<QueryResult> {
291
+ const bool = (value: boolean) => db.dialect.boolValue(value)
292
+ const where: string[] = ['n.node_object_type = ?']
293
+ const params: unknown[] = [ObjectTypes.Document]
294
+ const joins: string[] = []
295
+ const joinParams: unknown[] = []
296
+
297
+ // ---- culture
298
+ let languageId: number | undefined
299
+ if (query.culture) {
300
+ const [language] = await db.query<{ id: number }>(
301
+ 'SELECT id FROM language WHERE LOWER(iso_code) = LOWER(?)',
302
+ [query.culture],
303
+ )
304
+ if (!language) throw new ContentQueryRefused(`There is no language "${query.culture}".`)
305
+ languageId = Number(language.id)
306
+ joins.push(
307
+ 'LEFT JOIN document_culture_variation dcv ON dcv.node_id = n.id AND dcv.language_id = ?',
308
+ )
309
+ joinParams.push(languageId)
310
+ }
311
+ const published =
312
+ languageId === undefined ? 'd.published' : 'COALESCE(dcv.published, d.published)'
313
+ const edited = languageId === undefined ? 'd.edited' : 'COALESCE(dcv.edited, d.edited)'
314
+ const nameColumn = languageId === undefined ? 'n.text' : 'COALESCE(dcv.name, n.text)'
315
+
316
+ // ---- types
317
+ let typeIds: number[] | undefined
318
+ if (query.contentTypes?.length) {
319
+ const rows = await db.query<{ node_id: number; alias: string; unique_id: string }>(
320
+ `SELECT ct.node_id, ct.alias, tn.unique_id FROM content_type ct JOIN node tn ON tn.id = ct.node_id
321
+ WHERE tn.node_object_type = ?`,
322
+ [ObjectTypes.DocumentType],
323
+ )
324
+ typeIds = []
325
+ for (const wanted of query.contentTypes) {
326
+ const found = rows.find(
327
+ (r) =>
328
+ String(r.alias).toLowerCase() === wanted.toLowerCase() ||
329
+ String(r.unique_id).toLowerCase() === wanted.toLowerCase(),
330
+ )
331
+ if (!found) throw new ContentQueryRefused(`There is no content type "${wanted}".`)
332
+ typeIds.push(Number(found.node_id))
333
+ }
334
+ where.push(`c.content_type_id IN (${typeIds.map(() => '?').join(', ')})`)
335
+ params.push(...typeIds)
336
+ }
337
+
338
+ // ---- place
339
+ const nodeByKey = async (key: string, field: string) => {
340
+ const [row] = await db.query<{ id: number; path: string; level: number }>(
341
+ 'SELECT id, path, level FROM node WHERE unique_id = ? AND node_object_type = ?',
342
+ [key.toLowerCase(), ObjectTypes.Document],
343
+ )
344
+ if (!row) throw new ContentQueryRefused(`"${field}" names no page: ${key}.`)
345
+ return { id: Number(row.id), path: String(row.path), level: Number(row.level) }
346
+ }
347
+ const under = query.under ? await nodeByKey(query.under, 'under') : undefined
348
+ const parent = query.parent ? await nodeByKey(query.parent, 'parent') : undefined
349
+ if (under) {
350
+ where.push(`n.path LIKE ? ESCAPE '\\'`)
351
+ params.push(`${escapeLike(under.path)},%`)
352
+ }
353
+ if (parent) {
354
+ where.push('n.parent_id = ?')
355
+ params.push(parent.id)
356
+ }
357
+ if (query.maxDepth !== undefined) {
358
+ const from = (under ?? parent) as { level: number }
359
+ where.push('n.level <= ?')
360
+ params.push(from.level + query.maxDepth)
361
+ }
362
+
363
+ // ---- start nodes: the statement itself stays inside them
364
+ if (!scope.start.root) {
365
+ if (scope.start.keys.length === 0) return { total: 0, exact: true, items: [] }
366
+ const starts = await db.query<{ path: string }>(
367
+ `SELECT path FROM node WHERE unique_id IN (${scope.start.keys.map(() => '?').join(', ')})`,
368
+ scope.start.keys.map((k) => k.toLowerCase()),
369
+ )
370
+ if (starts.length === 0) return { total: 0, exact: true, items: [] }
371
+ where.push(`(${starts.map(() => `(n.path = ? OR n.path LIKE ? ESCAPE '\\')`).join(' OR ')})`)
372
+ for (const s of starts) params.push(String(s.path), `${escapeLike(String(s.path))},%`)
373
+ }
374
+
375
+ // ---- state; trashed only when asked for, and never outside root access
376
+ const states = query.state?.length ? query.state : ['published', 'draft', 'changed']
377
+ const wantsTrashed = states.includes('trashed') && scope.start.root
378
+ const live = states.filter((s) => s !== 'trashed')
379
+ const stateClauses: string[] = []
380
+ if (live.length > 0) {
381
+ const liveParts: string[] = []
382
+ if (live.includes('published')) liveParts.push(`(${published} = ? AND ${edited} = ?)`)
383
+ if (live.includes('changed')) liveParts.push(`(${published} = ? AND ${edited} = ?)`)
384
+ if (live.includes('draft')) liveParts.push(`(${published} = ?)`)
385
+ stateClauses.push(`(n.trashed = ? AND (${liveParts.join(' OR ')}))`)
386
+ params.push(bool(false))
387
+ if (live.includes('published')) params.push(bool(true), bool(false))
388
+ if (live.includes('changed')) params.push(bool(true), bool(true))
389
+ if (live.includes('draft')) params.push(bool(false))
390
+ }
391
+ if (wantsTrashed) {
392
+ stateClauses.push('n.trashed = ?')
393
+ params.push(bool(true))
394
+ }
395
+ if (stateClauses.length === 0) return { total: 0, exact: true, items: [] }
396
+ where.push(`(${stateClauses.join(' OR ')})`)
397
+
398
+ // ---- dates
399
+ const between = (column: string, range: { from?: Date; to?: Date } | undefined) => {
400
+ if (range?.from) {
401
+ where.push(`${column} >= ?`)
402
+ params.push(DbDate.toDb(range.from))
403
+ }
404
+ if (range?.to) {
405
+ where.push(`${column} <= ?`)
406
+ params.push(DbDate.toDb(range.to))
407
+ }
408
+ }
409
+ between('n.create_date', query.created)
410
+ between('cv.version_date', query.updated)
411
+
412
+ // ---- name
413
+ if (query.name) {
414
+ const value = query.name.value.toLowerCase()
415
+ if (query.name.op === 'equals') {
416
+ where.push(`LOWER(${nameColumn}) = ?`)
417
+ params.push(value)
418
+ } else {
419
+ where.push(`LOWER(${nameColumn}) LIKE ? ESCAPE '\\'`)
420
+ params.push(
421
+ query.name.op === 'startsWith' ? `${escapeLike(value)}%` : `%${escapeLike(value)}%`,
422
+ )
423
+ }
424
+ }
425
+
426
+ // ---- full text, through the existing index
427
+ if (query.text) {
428
+ where.push(`n.id IN (SELECT h.node_id FROM (${db.dialect.fullTextHits}) h)`)
429
+ params.push(db.dialect.fullTextQuery(searchTerms(query.text)))
430
+ }
431
+
432
+ // ---- properties
433
+ for (const clause of query.properties ?? []) {
434
+ const target = await propertyTarget(db, clause.alias, typeIds, scope, clause.op)
435
+ const owners = target.ids.map(() => '?').join(', ')
436
+ const language =
437
+ languageId === undefined ? '' : ' AND (pv.language_id = ? OR pv.language_id IS NULL)'
438
+ const row = `SELECT 1 FROM property_value pv WHERE pv.node_id = n.id AND pv.is_current = ?
439
+ AND pv.segment IS NULL AND pv.property_type_id IN (${owners})${language}`
440
+ const rowParams = [bool(true), ...target.ids, ...(languageId === undefined ? [] : [languageId])]
441
+ const col = `pv.${target.column}`
442
+ const text = target.storage === 'Ntext' || target.storage === 'Nvarchar'
443
+ const hasValue = text ? `${col} IS NOT NULL AND ${col} <> ''` : `${col} IS NOT NULL`
444
+ if (clause.op === 'exists' || clause.op === 'empty') {
445
+ where.push(`${clause.op === 'empty' ? 'NOT ' : ''}EXISTS (${row} AND ${hasValue})`)
446
+ params.push(...rowParams)
447
+ continue
448
+ }
449
+ const value = comparable(clause.value, target.storage, clause.alias)
450
+ if (clause.op === 'contains') {
451
+ if (!text)
452
+ throw new ContentQueryRefused(`"contains" compares text; "${clause.alias}" is not text.`)
453
+ where.push(`EXISTS (${row} AND LOWER(${col}) LIKE ? ESCAPE '\\')`)
454
+ params.push(...rowParams, `%${escapeLike(String(value).toLowerCase())}%`)
455
+ continue
456
+ }
457
+ const operator = { eq: '=', ne: '=', gt: '>', gte: '>=', lt: '<', lte: '<=' }[clause.op]
458
+ const left = text ? `LOWER(${col})` : col
459
+ const right = text ? String(value).toLowerCase() : value
460
+ // `ne` is "has no value equal to this", so a page without the value matches too.
461
+ where.push(`${clause.op === 'ne' ? 'NOT ' : ''}EXISTS (${row} AND ${left} ${operator} ?)`)
462
+ params.push(...rowParams, right)
463
+ }
464
+
465
+ // ---- sort
466
+ const by = query.sort?.by ?? 'name'
467
+ const dir = query.sort?.dir === 'desc' ? 'DESC' : 'ASC'
468
+ const sortColumn = {
469
+ name: `LOWER(${nameColumn})`,
470
+ createDate: 'n.create_date',
471
+ updateDate: 'cv.version_date',
472
+ path: 'n.path',
473
+ sortOrder: 'n.sort_order',
474
+ }[by]
475
+
476
+ const from = `node n
477
+ JOIN content c ON c.node_id = n.id
478
+ JOIN content_type ct ON ct.node_id = c.content_type_id
479
+ JOIN node tn ON tn.id = ct.node_id
480
+ JOIN document d ON d.node_id = n.id
481
+ JOIN content_version cv ON cv.node_id = n.id AND cv.current = ?
482
+ ${joins.join('\n')}`
483
+ const fromParams = [bool(true), ...joinParams]
484
+ const select = `SELECT n.id, n.unique_id, n.path, n.trashed, n.create_date, ${nameColumn} AS name,
485
+ ct.alias AS type_alias, tn.unique_id AS type_key, cv.version_date,
486
+ ${published} AS published, ${edited} AS edited
487
+ FROM ${from} WHERE ${where.join(' AND ')}
488
+ ORDER BY ${sortColumn} ${dir}, n.id ${dir}`
489
+
490
+ type Row = {
491
+ id: number
492
+ unique_id: string
493
+ path: string
494
+ trashed: unknown
495
+ create_date: unknown
496
+ name: string | null
497
+ type_alias: string
498
+ type_key: string
499
+ version_date: unknown
500
+ published: unknown
501
+ edited: unknown
502
+ }
503
+ let rows: Row[]
504
+ let total: number
505
+ let exact = true
506
+ if (!scope.browses) {
507
+ const [count] = await db.query<{ n: number }>(
508
+ `SELECT COUNT(*) AS n FROM ${from} WHERE ${where.join(' AND ')}`,
509
+ [...fromParams, ...params],
510
+ )
511
+ total = Number(count?.n ?? 0)
512
+ rows = await db.query<Row>(`${select} LIMIT ? OFFSET ?`, [
513
+ ...fromParams,
514
+ ...params,
515
+ query.take,
516
+ query.skip,
517
+ ])
518
+ } else {
519
+ const limit = scope.window ?? QUERY_WINDOW
520
+ const window = await db.query<Row>(`${select} LIMIT ?`, [...fromParams, ...params, limit + 1])
521
+ exact = window.length <= limit
522
+ const keys = await keysByIds(db, window.slice(0, limit))
523
+ const visible = window
524
+ .slice(0, limit)
525
+ .filter((row) => scope.browses?.(chainOf(row.path, row.unique_id, keys)) ?? true)
526
+ total = visible.length
527
+ rows = visible.slice(query.skip, query.skip + query.take)
528
+ }
529
+ return { total, exact, items: await toItems(db, rows) }
530
+ }
531
+
532
+ /** The property types a clause compares, checked for reading and for being comparable. */
533
+ async function propertyTarget(
534
+ db: Db,
535
+ alias: string,
536
+ typeIds: number[] | undefined,
537
+ scope: QueryScope,
538
+ op: PropertyOp,
539
+ ): Promise<PropertyTarget> {
540
+ const owners = typeIds ? await withCompositions(db, typeIds) : undefined
541
+ const rows = await db.query<{
542
+ id: number
543
+ unique_id: string
544
+ db_type: string
545
+ editor_alias: string
546
+ }>(
547
+ `SELECT pt.id, pt.unique_id, dt.db_type, dt.editor_alias FROM property_type pt
548
+ JOIN data_type dt ON dt.node_id = pt.data_type_id
549
+ JOIN content_type ct ON ct.node_id = pt.content_type_id
550
+ JOIN node tn ON tn.id = ct.node_id
551
+ WHERE LOWER(pt.alias) = LOWER(?) AND pt.retired_at IS NULL AND tn.node_object_type = ?
552
+ ${owners ? `AND pt.content_type_id IN (${owners.map(() => '?').join(', ')})` : ''}`,
553
+ [alias, ObjectTypes.DocumentType, ...(owners ?? [])],
554
+ )
555
+ if (rows.length === 0)
556
+ throw new ContentQueryRefused(
557
+ `There is no property "${alias}"${typeIds ? ' on the content types given' : ''}.`,
558
+ )
559
+ // A filter on a value the user cannot read would tell them about it.
560
+ if (rows.some((r) => !scope.readsProperty(String(r.unique_id))))
561
+ throw new ContentQueryRefused(`You cannot read the property "${alias}".`)
562
+ const storages = new Set(rows.map((r) => r.db_type))
563
+ if (storages.size > 1)
564
+ throw new ContentQueryRefused(
565
+ `"${alias}" is stored differently on different types; name one content type.`,
566
+ )
567
+ const structured = rows.some((r) => STRUCTURED_EDITORS.has(r.editor_alias))
568
+ if (structured && op !== 'exists' && op !== 'empty')
569
+ throw new ContentQueryRefused(
570
+ `"${alias}" holds structured content; use "exists" or "empty", or "text" to search it.`,
571
+ )
572
+ const storage = rows[0]?.db_type as ValueStorageTypeName
573
+ const column = STORAGE_COLUMN[storage]
574
+ if (!column) throw new ContentQueryRefused(`"${alias}" cannot be compared.`)
575
+ return { ids: rows.map((r) => Number(r.id)), column, storage }
576
+ }
577
+
578
+ /** The types and every type they are composed of, transitively. */
579
+ async function withCompositions(db: Db, typeIds: number[]): Promise<number[]> {
580
+ const links = await db.query<{ parent: number; child: number }>(
581
+ 'SELECT parent_content_type_id AS parent, child_content_type_id AS child FROM content_type_composition',
582
+ )
583
+ const found = new Set(typeIds)
584
+ let grew = true
585
+ while (grew) {
586
+ grew = false
587
+ for (const link of links)
588
+ if (found.has(Number(link.child)) && !found.has(Number(link.parent))) {
589
+ found.add(Number(link.parent))
590
+ grew = true
591
+ }
592
+ }
593
+ return [...found]
594
+ }
595
+
596
+ /** A clause's value as its storage type compares it. */
597
+ function comparable(value: unknown, storage: ValueStorageTypeName, alias: string): unknown {
598
+ if (storage === 'Integer') {
599
+ const n = typeof value === 'boolean' ? (value ? 1 : 0) : Number(value)
600
+ if (!Number.isFinite(n)) throw new ContentQueryRefused(`"${alias}" compares numbers.`)
601
+ return Math.trunc(n)
602
+ }
603
+ if (storage === 'Decimal') {
604
+ const n = Number(value)
605
+ if (!Number.isFinite(n)) throw new ContentQueryRefused(`"${alias}" compares numbers.`)
606
+ return n
607
+ }
608
+ if (storage === 'Date') {
609
+ const date = new Date(String(value))
610
+ if (Number.isNaN(date.getTime())) throw new ContentQueryRefused(`"${alias}" compares dates.`)
611
+ return DbDate.toDb(date)
612
+ }
613
+ if (typeof value === 'object') throw new ContentQueryRefused(`"${alias}" compares text.`)
614
+ return String(value)
615
+ }
616
+
617
+ /** id → key for every node on these rows' paths, for Browse and the path chain. */
618
+ async function keysByIds(
619
+ db: Db,
620
+ rows: ReadonlyArray<{ path: string }>,
621
+ ): Promise<Map<number, { key: string; name: string }>> {
622
+ const ids = new Set<number>()
623
+ for (const row of rows)
624
+ for (const part of String(row.path).split(',')) {
625
+ const id = Number(part)
626
+ if (id > 0) ids.add(id)
627
+ }
628
+ const map = new Map<number, { key: string; name: string }>()
629
+ const all = [...ids]
630
+ for (let i = 0; i < all.length; i += 500) {
631
+ const chunk = all.slice(i, i + 500)
632
+ const found = await db.query<{ id: number; unique_id: string; text: string | null }>(
633
+ `SELECT id, unique_id, text FROM node WHERE id IN (${chunk.map(() => '?').join(', ')})`,
634
+ chunk,
635
+ )
636
+ for (const f of found)
637
+ map.set(Number(f.id), { key: String(f.unique_id).toLowerCase(), name: String(f.text ?? '') })
638
+ }
639
+ return map
640
+ }
641
+
642
+ /** A page's ancestor keys then its own, root first, as the permission rules read them. */
643
+ function chainOf(
644
+ path: string,
645
+ key: string,
646
+ keys: Map<number, { key: string; name: string }>,
647
+ ): string[] {
648
+ const ancestors = String(path)
649
+ .split(',')
650
+ .map(Number)
651
+ .filter((id) => id > 0)
652
+ .slice(0, -1)
653
+ .map((id) => keys.get(id)?.key ?? '')
654
+ return [...ancestors.filter(Boolean), String(key).toLowerCase()]
655
+ }
656
+
657
+ async function toItems(
658
+ db: Db,
659
+ rows: ReadonlyArray<{
660
+ id: number
661
+ unique_id: string
662
+ path: string
663
+ trashed: unknown
664
+ create_date: unknown
665
+ name: string | null
666
+ type_alias: string
667
+ type_key: string
668
+ version_date: unknown
669
+ published: unknown
670
+ edited: unknown
671
+ }>,
672
+ ): Promise<QueryItem[]> {
673
+ if (rows.length === 0) return []
674
+ const keys = await keysByIds(db, rows)
675
+ const ids = rows.map((r) => Number(r.id))
676
+ const cultures = await db.query<{
677
+ node_id: number
678
+ iso_code: string
679
+ name: string | null
680
+ published: unknown
681
+ edited: unknown
682
+ }>(
683
+ `SELECT dcv.node_id, l.iso_code, dcv.name, dcv.published, dcv.edited
684
+ FROM document_culture_variation dcv JOIN language l ON l.id = dcv.language_id
685
+ WHERE dcv.available = ? AND dcv.node_id IN (${ids.map(() => '?').join(', ')})
686
+ ORDER BY l.iso_code`,
687
+ [db.dialect.boolValue(true), ...ids],
688
+ )
689
+ const iso = (value: unknown) => (DbDate.fromDb(value) ?? new Date(0)).toISOString()
690
+ return rows.map((row) => {
691
+ const trashed = fromDbBool(row.trashed)
692
+ const own = cultures.filter((c) => Number(c.node_id) === Number(row.id))
693
+ const path = String(row.path)
694
+ .split(',')
695
+ .map(Number)
696
+ .filter((id) => id > 0 && id !== Number(row.id))
697
+ .map((id) => ({ id: keys.get(id)?.key ?? '', name: keys.get(id)?.name ?? '' }))
698
+ .filter((step) => step.id !== '')
699
+ return {
700
+ id: String(row.unique_id).toLowerCase(),
701
+ name: String(row.name ?? ''),
702
+ path,
703
+ contentType: { id: String(row.type_key).toLowerCase(), alias: String(row.type_alias) },
704
+ state: stateOf(fromDbBool(row.published), fromDbBool(row.edited), trashed),
705
+ createDate: iso(row.create_date),
706
+ updateDate: iso(row.version_date),
707
+ ...(own.length > 0
708
+ ? {
709
+ cultures: own.map((c) => ({
710
+ culture: String(c.iso_code),
711
+ name: String(c.name ?? ''),
712
+ state: stateOf(fromDbBool(c.published), fromDbBool(c.edited), trashed),
713
+ })),
714
+ }
715
+ : {}),
716
+ }
717
+ })
718
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export * from './bundle-tables/index.ts'
4
4
  export * from './busy.ts'
5
5
  export * from './change-report.ts'
6
6
  export * from './cluster.ts'
7
+ export * from './content-query.ts'
7
8
  export * from './database.ts'
8
9
  export * from './dialect.ts'
9
10
  export * from './locks.ts'
@@ -138,3 +138,8 @@ export function valueText(
138
138
  collect(raw, out, unsearchable)
139
139
  return out
140
140
  }
141
+
142
+ /** `%`, `_` and the escape character itself, made literal for `LIKE … ESCAPE '\'`. */
143
+ export function escapeLike(value: string): string {
144
+ return value.replace(/[\\%_]/g, (c) => `\\${c}`)
145
+ }