@crombolo/data 0.37.0 → 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
@@ -11,7 +11,10 @@ import {
11
11
  normaliseUuid,
12
12
  ObjectTypes,
13
13
  } from '@crombolo/core'
14
+ import type { ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'
14
15
  import type { Db } from '../database.ts'
16
+ import { type Expression, sql } from '../query.ts'
17
+ import type { CoreTables } from '../tables.gen.ts'
15
18
 
16
19
  export type MediaSortField = 'createDate' | 'updateDate' | 'name' | 'sortOrder'
17
20
 
@@ -31,29 +34,35 @@ export interface MediaListingQuery {
31
34
  readable?: { rules: ReadonlyMap<number, MediaRule>; member: MediaMember | undefined }
32
35
  }
33
36
 
34
- const NAME = 'COALESCE(head.text, n.text)'
35
- const FROM = `FROM node n
36
- JOIN content c ON c.node_id = n.id
37
- JOIN content_type ct ON ct.node_id = c.content_type_id
38
- LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?`
37
+ type Listed = {
38
+ n: CoreTables['node']
39
+ c: CoreTables['content']
40
+ ct: CoreTables['content_type']
41
+ head: CoreTables['content_version']
42
+ }
43
+ type Aliases = keyof Listed
44
+ type Eb = ExpressionBuilder<CoreTables & Listed, Aliases>
45
+
46
+ const nameOf = (eb: Eb) => eb.fn.coalesce('head.text', 'n.text')
39
47
 
40
- const SORT_COLUMNS: Record<MediaSortField, string> = {
41
- createDate: 'n.create_date',
42
- updateDate: 'COALESCE(head.version_date, n.create_date)',
43
- name: `LOWER(${NAME})`,
44
- sortOrder: 'n.sort_order',
48
+ const SORT_COLUMNS: Record<MediaSortField, (eb: Eb) => Expression<unknown>> = {
49
+ createDate: (eb) => eb.ref('n.create_date'),
50
+ updateDate: (eb) => eb.fn.coalesce('head.version_date', 'n.create_date'),
51
+ name: (eb) => eb.fn('lower', [nameOf(eb)]),
52
+ sortOrder: (eb) => eb.ref('n.sort_order'),
45
53
  }
46
54
 
47
55
  const likeEscape = (value: string) => value.replace(/[\\%_]/g, (c) => `\\${c}`)
48
56
 
49
57
  /**
50
- * Who may read a child, as SQL, under one rule: `memberMay('read', …)` with
51
- * everything but the item's own columns worked out here. Pure.
58
+ * Who may read a child, as a condition, under one rule: `memberMay('read', …)`
59
+ * with everything but the item's own columns worked out here. Pure.
52
60
  */
53
61
  function readableUnder(
62
+ eb: Eb,
54
63
  rule: MediaRule | undefined,
55
64
  member: MediaMember | undefined,
56
- ): { sql: string; params: unknown[] } {
65
+ ): Expression<SqlBool> {
57
66
  const held = new Set(member?.groups.map((g) => g.toLowerCase()) ?? [])
58
67
  const inGroups = (names: readonly string[]) => names.some((n) => held.has(n.toLowerCase()))
59
68
  const groups =
@@ -62,16 +71,20 @@ function readableUnder(
62
71
  member && rule?.readMembers?.some((key) => key.toLowerCase() === member.key.toLowerCase()),
63
72
  )
64
73
  const inherited = !rule || rule.publicRead || groups
65
- const parts = ["c.read_policy = 'public'"]
66
- const params: unknown[] = []
67
- if (groups) parts.push("c.read_policy = 'groups'")
74
+ const parts: Expression<SqlBool>[] = [eb('c.read_policy', '=', 'public')]
75
+ if (groups) parts.push(eb('c.read_policy', '=', 'groups'))
68
76
  if (member) {
69
- parts.push("c.read_policy = 'members'")
70
- parts.push("(c.read_policy = 'creator' AND c.creator_member_key = ?)")
71
- params.push(normaliseUuid(member.key))
77
+ parts.push(eb('c.read_policy', '=', 'members'))
78
+ parts.push(
79
+ eb.and([
80
+ eb('c.read_policy', '=', 'creator'),
81
+ eb('c.creator_member_key', '=', normaliseUuid(member.key)),
82
+ ]),
83
+ )
72
84
  }
73
- if (inherited) parts.push("(c.read_policy IS NULL OR c.read_policy = 'inherit')")
74
- return { sql: `(${parts.join(' OR ')})`, params }
85
+ if (inherited)
86
+ parts.push(eb.or([eb('c.read_policy', 'is', null), eb('c.read_policy', '=', 'inherit')]))
87
+ return eb.or(parts)
75
88
  }
76
89
 
77
90
  export class MediaListingRepository {
@@ -90,60 +103,87 @@ export class MediaListingRepository {
90
103
  const mediaTypes = query.mediaTypes ?? []
91
104
  const names = query.names ?? []
92
105
  const sortsByHead = query.sort?.field === 'name' || query.sort?.field === 'updateDate'
93
- const joins: string[] = []
94
- const joinParams: unknown[] = []
95
- if (query.readable || mediaTypes.length > 0) joins.push('JOIN content c ON c.node_id = n.id')
96
- if (mediaTypes.length > 0) joins.push('JOIN content_type ct ON ct.node_id = c.content_type_id')
97
- const head = 'LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?'
98
- const where = ['n.parent_id = ?', 'n.node_object_type = ?', 'n.trashed = ?']
99
- const params: unknown[] = [query.parentId, ObjectTypes.Media, this.#db.dialect.boolValue(false)]
100
- for (const alias of mediaTypes) {
101
- where.push('ct.alias = ?')
102
- params.push(alias)
103
- }
104
- for (const part of names) {
105
- where.push(`LOWER(${NAME}) LIKE ? ESCAPE '\\'`)
106
- params.push(`%${likeEscape(part.toLowerCase())}%`)
107
- }
108
- if (query.readable) {
109
- // The children share the rule above them, except one with a rule of its own.
110
- const { rules, member } = query.readable
111
- const own = [...rules.values()]
112
- const above = readableUnder(nearestMediaRule(query.parentPath, rules), member)
113
- const clauses: string[] = []
114
- if (own.length === 0) clauses.push(above.sql)
115
- else
116
- clauses.push(
117
- `(n.id NOT IN (${own.map(() => '?').join(', ')}) AND ${above.sql})`,
118
- ...own.map((rule) => `(n.id = ? AND ${readableUnder(rule, member).sql})`),
106
+ const db = this.#db
107
+ const listing = (withHead: boolean) =>
108
+ (
109
+ db.q.selectFrom('node as n') as unknown as SelectQueryBuilder<
110
+ CoreTables & Listed,
111
+ Aliases,
112
+ object
113
+ >
114
+ )
115
+ .$if(Boolean(query.readable) || mediaTypes.length > 0, (q) =>
116
+ q.innerJoin('content as c', 'c.node_id', 'n.id'),
117
+ )
118
+ .$if(mediaTypes.length > 0, (q) =>
119
+ q.innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id'),
120
+ )
121
+ .$if(withHead, (q) =>
122
+ q.leftJoin('content_version as head', (join) =>
123
+ join
124
+ .onRef('head.node_id', '=', 'n.id')
125
+ .on('head.current', '=', db.dialect.boolValue(true)),
126
+ ),
127
+ )
128
+ .where('n.parent_id', '=', query.parentId)
129
+ .where('n.node_object_type', '=', ObjectTypes.Media)
130
+ .where('n.trashed', '=', db.dialect.boolValue(false))
131
+ .$call((q) => mediaTypes.reduce((acc, alias) => acc.where('ct.alias', '=', alias), q))
132
+ .$call((q) =>
133
+ names.reduce(
134
+ (acc, part) =>
135
+ acc.where(
136
+ (eb) =>
137
+ sql<SqlBool>`${eb.fn('lower', [nameOf(eb)])} like ${`%${likeEscape(part.toLowerCase())}%`} escape '\\'`,
138
+ ),
139
+ q,
140
+ ),
141
+ )
142
+ .$if(Boolean(query.readable), (q) =>
143
+ q.where((eb) => {
144
+ // The children share the rule above them, except one with a rule of its own.
145
+ const { rules, member } = query.readable as NonNullable<MediaListingQuery['readable']>
146
+ const own = [...rules.values()]
147
+ const above = readableUnder(eb, nearestMediaRule(query.parentPath, rules), member)
148
+ if (own.length === 0) return eb.or([above])
149
+ return eb.or([
150
+ eb.and([
151
+ eb(
152
+ 'n.id',
153
+ 'not in',
154
+ own.map((rule) => rule.nodeId),
155
+ ),
156
+ above,
157
+ ]),
158
+ ...own.map((rule) =>
159
+ eb.and([eb('n.id', '=', rule.nodeId), readableUnder(eb, rule, member)]),
160
+ ),
161
+ ])
162
+ }),
119
163
  )
120
- where.push(`(${clauses.join(' OR ')})`)
121
- if (own.length > 0) params.push(...own.map((rule) => rule.nodeId))
122
- params.push(...above.params)
123
- for (const rule of own) params.push(rule.nodeId, ...readableUnder(rule, member).params)
124
- }
125
- const from = (withHead: boolean) =>
126
- `FROM node n ${[...joins, ...(withHead ? [head] : [])].join(' ')} WHERE ${where.join(' AND ')}`
127
- const headParams = (withHead: boolean) =>
128
- withHead ? [...joinParams, this.#db.dialect.boolValue(true)] : joinParams
129
164
  const countHead = names.length > 0
130
- const counted = await this.#db.query<{ n: unknown }>(
131
- `SELECT COUNT(*) AS n ${from(countHead)}`,
132
- [...headParams(countHead), ...params],
133
- )
165
+ const counted = await listing(countHead)
166
+ .select(sql<number>`count(*)`.as('n'))
167
+ .executeTakeFirst()
134
168
  const pageHead = countHead || sortsByHead
135
- const order = query.sort
136
- ? `${SORT_COLUMNS[query.sort.field]} ${query.sort.ascending ? 'ASC' : 'DESC'}, n.sort_order, n.id`
137
- : 'n.sort_order, n.id'
169
+ const sort = query.sort
138
170
  const rows =
139
171
  query.take <= 0
140
172
  ? []
141
- : await this.#db.query<{ unique_id: string }>(
142
- `SELECT n.unique_id ${from(pageHead)} ORDER BY ${order} LIMIT ? OFFSET ?`,
143
- [...headParams(pageHead), ...params, query.take, Math.max(0, query.skip)],
144
- )
173
+ : await listing(pageHead)
174
+ .select('n.unique_id')
175
+ .$call((q) =>
176
+ sort
177
+ ? q.orderBy((eb) => SORT_COLUMNS[sort.field](eb), sort.ascending ? 'asc' : 'desc')
178
+ : q,
179
+ )
180
+ .orderBy('n.sort_order')
181
+ .orderBy('n.id')
182
+ .limit(query.take)
183
+ .offset(Math.max(0, query.skip))
184
+ .execute()
145
185
  return {
146
- total: Number(counted[0]?.n ?? 0),
186
+ total: Number(counted?.n ?? 0),
147
187
  keys: rows.map((row) => normaliseUuid(String(row.unique_id))),
148
188
  }
149
189
  }
@@ -162,11 +202,13 @@ export class MediaListingRepository {
162
202
 
163
203
  /** A node's id and path, by key; undefined for anything not media or in the bin. */
164
204
  async byKey(key: string): Promise<{ id: number; key: string; path: string } | undefined> {
165
- const rows = await this.#db.query<{ id: number; unique_id: string; path: string }>(
166
- 'SELECT id, unique_id, path FROM node WHERE unique_id = ? AND node_object_type = ? AND trashed = ?',
167
- [normaliseUuid(key), ObjectTypes.Media, this.#db.dialect.boolValue(false)],
168
- )
169
- const row = rows[0]
205
+ const row = await this.#db.q
206
+ .selectFrom('node')
207
+ .select(['id', 'unique_id', 'path'])
208
+ .where('unique_id', '=', normaliseUuid(key))
209
+ .where('node_object_type', '=', ObjectTypes.Media)
210
+ .where('trashed', '=', this.#db.dialect.boolValue(false))
211
+ .executeTakeFirst()
170
212
  return row
171
213
  ? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }
172
214
  : undefined
@@ -174,23 +216,35 @@ export class MediaListingRepository {
174
216
 
175
217
  async #childNamed(parentId: number, name: string) {
176
218
  const lowered = name.toLowerCase()
177
- const query = (extra: string, params: unknown[], limit = '') =>
178
- this.#db.query<{ id: number; unique_id: string; path: string; name: string }>(
179
- `SELECT n.id, n.unique_id, n.path, ${NAME} AS name ${FROM}
180
- WHERE n.parent_id = ? AND n.node_object_type = ? AND n.trashed = ? ${extra}
181
- ORDER BY n.sort_order, n.id ${limit}`,
182
- [
183
- this.#db.dialect.boolValue(true),
184
- parentId,
185
- ObjectTypes.Media,
186
- this.#db.dialect.boolValue(false),
187
- ...params,
188
- ],
219
+ const db = this.#db
220
+ const query = (exact: boolean) =>
221
+ (
222
+ db.q.selectFrom('node as n') as unknown as SelectQueryBuilder<
223
+ CoreTables & Listed,
224
+ Aliases,
225
+ object
226
+ >
189
227
  )
190
- let rows = await query(`AND LOWER(${NAME}) = ?`, [lowered], 'LIMIT 1')
228
+ .innerJoin('content as c', 'c.node_id', 'n.id')
229
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
230
+ .leftJoin('content_version as head', (join) =>
231
+ join
232
+ .onRef('head.node_id', '=', 'n.id')
233
+ .on('head.current', '=', db.dialect.boolValue(true)),
234
+ )
235
+ .select((eb) => ['n.id', 'n.unique_id', 'n.path', nameOf(eb).as('name')])
236
+ .where('n.parent_id', '=', parentId)
237
+ .where('n.node_object_type', '=', ObjectTypes.Media)
238
+ .where('n.trashed', '=', db.dialect.boolValue(false))
239
+ .$if(exact, (q) => q.where((eb) => eb(eb.fn('lower', [nameOf(eb)]), '=', lowered)))
240
+ .orderBy('n.sort_order')
241
+ .orderBy('n.id')
242
+ .$if(exact, (q) => q.limit(1))
243
+ .execute()
244
+ let rows = await query(true)
191
245
  // SQLite lowers only ASCII, so a name with other letters is matched here.
192
246
  if (rows.length === 0 && this.#db.dialect.name === 'sqlite' && /[^ -~]/.test(name))
193
- rows = (await query('', [])).filter((row) => String(row.name).toLowerCase() === lowered)
247
+ rows = (await query(false)).filter((row) => String(row.name).toLowerCase() === lowered)
194
248
  const row = rows[0]
195
249
  return row
196
250
  ? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }
@@ -203,12 +257,21 @@ export class MediaListingRepository {
203
257
  const out = new Map<number, string>()
204
258
  for (let at = 0; at < wanted.length; at += 500) {
205
259
  const slice = wanted.slice(at, at + 500)
206
- const rows = await this.#db.query<{ id: number; name: string }>(
207
- `SELECT n.id, ${NAME} AS name FROM node n
208
- LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?
209
- WHERE n.id IN (${slice.map(() => '?').join(', ')})`,
210
- [this.#db.dialect.boolValue(true), ...slice],
260
+ const rows = await (
261
+ this.#db.q.selectFrom('node as n') as unknown as SelectQueryBuilder<
262
+ CoreTables & Listed,
263
+ 'n',
264
+ object
265
+ >
211
266
  )
267
+ .leftJoin('content_version as head', (join) =>
268
+ join
269
+ .onRef('head.node_id', '=', 'n.id')
270
+ .on('head.current', '=', this.#db.dialect.boolValue(true)),
271
+ )
272
+ .select((eb) => ['n.id', eb.fn.coalesce('head.text', 'n.text').as('name')])
273
+ .where('n.id', 'in', slice)
274
+ .execute()
212
275
  for (const row of rows) out.set(Number(row.id), String(row.name ?? ''))
213
276
  }
214
277
  return out