@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.
- package/package.json +3 -2
- package/src/audit.ts +163 -133
- package/src/change-report.ts +66 -43
- package/src/cluster.ts +119 -59
- package/src/content-query.ts +205 -200
- package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
- package/src/custom-tables/chain.ts +150 -0
- package/src/custom-tables/ddl.ts +159 -0
- package/src/custom-tables/handle.ts +141 -0
- package/src/{bundle-tables → custom-tables}/index.ts +3 -2
- package/src/custom-tables/names.ts +94 -0
- package/src/custom-tables/owners.ts +299 -0
- package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
- package/src/custom-tables/values.ts +181 -0
- package/src/database.ts +40 -5
- package/src/dialect.ts +43 -16
- package/src/index.ts +8 -1
- package/src/migrations.ts +130 -88
- package/src/query.ts +158 -0
- package/src/relations.ts +49 -28
- package/src/repositories/approvals.ts +130 -89
- package/src/repositories/bundle-grants.ts +74 -0
- package/src/repositories/bundles.ts +85 -76
- package/src/repositories/content-applied.ts +47 -28
- package/src/repositories/content-events.ts +114 -67
- package/src/repositories/content-notifications.ts +102 -74
- package/src/repositories/content-types.ts +449 -320
- package/src/repositories/data-types.ts +105 -56
- package/src/repositories/delivery-member-tokens.ts +37 -28
- package/src/repositories/dictionary.ts +77 -58
- package/src/repositories/documents.ts +956 -580
- package/src/repositories/domains.ts +28 -16
- package/src/repositories/dynamic-roots.ts +32 -17
- package/src/repositories/external-logins.ts +38 -24
- package/src/repositories/folders.ts +7 -4
- package/src/repositories/form-entries.ts +120 -103
- package/src/repositories/form-workflows.ts +87 -62
- package/src/repositories/jobs.ts +296 -0
- package/src/repositories/languages.ts +51 -38
- package/src/repositories/log-searches.ts +7 -5
- package/src/repositories/media-access.ts +173 -123
- package/src/repositories/media-listing.ts +155 -92
- package/src/repositories/members.ts +189 -162
- package/src/repositories/nodes.ts +227 -181
- package/src/repositories/notifications.ts +22 -17
- package/src/repositories/public-access.ts +77 -61
- package/src/repositories/redirects.ts +113 -70
- package/src/repositories/references.ts +55 -44
- package/src/repositories/remote-jobs.ts +45 -35
- package/src/repositories/tags.ts +11 -10
- package/src/repositories/templates.ts +24 -14
- package/src/repositories/transfer-answers.ts +58 -50
- package/src/repositories/transfer-runs.ts +93 -75
- package/src/repositories/two-factor.ts +74 -55
- package/src/repositories/user-data.ts +54 -36
- package/src/repositories/users.ts +345 -300
- package/src/repositories/webhooks.ts +196 -137
- package/src/schema/bundle-grants.ts +32 -0
- package/src/schema/jobs.ts +56 -0
- package/src/schema/plan.ts +4 -0
- package/src/schema-ops.ts +15 -12
- package/src/schema-state.ts +53 -38
- package/src/search.ts +175 -129
- package/src/setup.ts +17 -13
- package/src/site-search.ts +134 -83
- package/src/table-types.ts +152 -0
- package/src/tables.gen.ts +859 -0
- package/src/tree-invariants.ts +21 -12
- package/src/url-options.ts +17 -13
- package/src/workflow-store.ts +17 -13
- package/src/bundle-tables/capability.ts +0 -377
- package/src/bundle-tables/chain.ts +0 -105
- package/src/bundle-tables/ddl.ts +0 -124
- package/src/bundle-tables/guard.ts +0 -116
- package/src/bundle-tables/names.ts +0 -58
package/src/migrations.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type { Db } from './database.ts'
|
|
|
11
11
|
import type { Dialect } from './dialect.ts'
|
|
12
12
|
import type { LockManager } from './locks.ts'
|
|
13
13
|
import { Locks } from './locks.ts'
|
|
14
|
+
import { now, type Query, queryFor, sql } from './query.ts'
|
|
14
15
|
|
|
15
16
|
export const MIGRATION_STATE_KEY = 'Crombolo.Core.Upgrader.State'
|
|
16
17
|
export const INITIAL_STATE = '{00000000-0000-0000-0000-000000000000}'
|
|
@@ -47,6 +48,11 @@ export interface ChainOptions {
|
|
|
47
48
|
initialState?: string
|
|
48
49
|
/** A bundle's id, for a bundle's chain; absent for core's. */
|
|
49
50
|
bundle?: string
|
|
51
|
+
/**
|
|
52
|
+
* Runs a step's `up` and `backfill` somewhere other than the transaction it
|
|
53
|
+
* is ledgered in: custom tables run on their owner's connection (story 189).
|
|
54
|
+
*/
|
|
55
|
+
runStep?: (tx: Db, step: (db: Db) => Promise<void>) => Promise<void>
|
|
50
56
|
}
|
|
51
57
|
|
|
52
58
|
function compareRelease(a: string, b: string): number {
|
|
@@ -101,12 +107,14 @@ export class MigrationPlan {
|
|
|
101
107
|
readonly stateKey: string
|
|
102
108
|
readonly initialState: string
|
|
103
109
|
readonly bundle: string | undefined
|
|
110
|
+
readonly runStep: ChainOptions['runStep']
|
|
104
111
|
|
|
105
112
|
constructor(migrations: readonly Migration[], options: ChainOptions = {}) {
|
|
106
113
|
this.migrations = migrations
|
|
107
114
|
this.stateKey = options.stateKey ?? MIGRATION_STATE_KEY
|
|
108
115
|
this.initialState = options.initialState ?? INITIAL_STATE
|
|
109
116
|
this.bundle = options.bundle
|
|
117
|
+
this.runStep = options.runStep
|
|
110
118
|
let expected = this.initialState
|
|
111
119
|
const seen = new Map<string, Migration>()
|
|
112
120
|
for (const migration of migrations) {
|
|
@@ -169,44 +177,42 @@ const ensured = new WeakSet<Db>()
|
|
|
169
177
|
async function ensureTables(db: Db): Promise<void> {
|
|
170
178
|
if (ensured.has(db)) return
|
|
171
179
|
const t = db.dialect.types
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
180
|
+
const type = (definition: string) => sql.raw(definition)
|
|
181
|
+
await db.q.schema
|
|
182
|
+
.createTable('key_value')
|
|
183
|
+
.ifNotExists()
|
|
184
|
+
.addColumn('key', type(t.text), (c) => c.primaryKey())
|
|
185
|
+
.addColumn('value', type(t.text))
|
|
186
|
+
.addColumn('update_date', type(t.timestamp), (c) => c.notNull())
|
|
187
|
+
.execute()
|
|
188
|
+
await db.q.schema
|
|
189
|
+
.createTable('migration_history')
|
|
190
|
+
.ifNotExists()
|
|
191
|
+
.addColumn('id', type(t.identity))
|
|
192
|
+
.addColumn('name', type(t.varchar(255)), (c) => c.notNull())
|
|
193
|
+
.addColumn('kind', type(t.varchar(20)), (c) => c.notNull())
|
|
194
|
+
.addColumn('from_state', type(t.varchar(255)))
|
|
195
|
+
.addColumn('to_state', type(t.varchar(255)))
|
|
196
|
+
.addColumn('applied_at', type(t.timestamp), (c) => c.notNull())
|
|
197
|
+
.addColumn('duration_ms', type(t.integer), (c) => c.notNull())
|
|
198
|
+
.addColumn('checksum', type(t.varchar(64)))
|
|
199
|
+
.addColumn('applied_by', type(t.varchar(255)))
|
|
200
|
+
.addColumn('note', type(t.text))
|
|
201
|
+
.addColumn('bundle', type(t.varchar(64)))
|
|
202
|
+
.execute()
|
|
194
203
|
// A ledger from before bundles could own tables has no `bundle` column. It is
|
|
195
204
|
// added here, where the table is, rather than by a core migration: the ledger
|
|
196
205
|
// has to be able to record a bundle's step whatever state core is at.
|
|
197
206
|
if (!(await hasColumn(db, 'migration_history', 'bundle')))
|
|
198
|
-
await db.
|
|
207
|
+
await db.q.schema
|
|
208
|
+
.alterTable('migration_history')
|
|
209
|
+
.addColumn('bundle', type(t.varchar(64)))
|
|
210
|
+
.execute()
|
|
199
211
|
ensured.add(db)
|
|
200
212
|
}
|
|
201
213
|
|
|
202
214
|
async function hasColumn(db: Db, table: string, column: string): Promise<boolean> {
|
|
203
|
-
const rows =
|
|
204
|
-
db.dialect.name === 'sqlite'
|
|
205
|
-
? await db.query<{ name: string }>(`SELECT name FROM pragma_table_info('${table}')`)
|
|
206
|
-
: await db.query<{ name: string }>(
|
|
207
|
-
'SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ?',
|
|
208
|
-
[table],
|
|
209
|
-
)
|
|
215
|
+
const rows = await db.query<{ name: string }>(db.dialect.columnsOf, [table])
|
|
210
216
|
return rows.some((row) => row.name === column)
|
|
211
217
|
}
|
|
212
218
|
|
|
@@ -219,28 +225,41 @@ export async function readState(
|
|
|
219
225
|
},
|
|
220
226
|
): Promise<string> {
|
|
221
227
|
await ensureTables(db)
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
228
|
+
const row = await db.q
|
|
229
|
+
.selectFrom('key_value')
|
|
230
|
+
.select('value')
|
|
231
|
+
.where('key', '=', chain.stateKey)
|
|
232
|
+
.executeTakeFirst()
|
|
233
|
+
return row?.value ?? chain.initialState
|
|
226
234
|
}
|
|
227
235
|
|
|
228
236
|
async function writeState(db: Db, state: string, key = MIGRATION_STATE_KEY): Promise<void> {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
)
|
|
237
|
-
|
|
237
|
+
await upsertKeyValue(db, key, state)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Updates a setting, then inserts it if the update found no row: two statements, as ever. */
|
|
241
|
+
async function upsertKeyValue(db: Db, key: string, value: string): Promise<void> {
|
|
242
|
+
await db.q
|
|
243
|
+
.updateTable('key_value')
|
|
244
|
+
.set({ value, update_date: now(db) })
|
|
245
|
+
.where('key', '=', key)
|
|
246
|
+
.execute()
|
|
247
|
+
const row = await db.q
|
|
248
|
+
.selectFrom('key_value')
|
|
249
|
+
.select('value')
|
|
250
|
+
.where('key', '=', key)
|
|
251
|
+
.executeTakeFirst()
|
|
252
|
+
if (!row)
|
|
253
|
+
await db.q
|
|
254
|
+
.insertInto('key_value')
|
|
255
|
+
.values({ key, value, update_date: now(db) })
|
|
256
|
+
.execute()
|
|
238
257
|
}
|
|
239
258
|
|
|
240
259
|
/** Forgets a setting entirely, as a purged bundle's state is forgotten. */
|
|
241
260
|
export async function deleteKeyValue(db: Db, key: string): Promise<void> {
|
|
242
261
|
await ensureTables(db)
|
|
243
|
-
await db.
|
|
262
|
+
await db.q.deleteFrom('key_value').where('key', '=', key).execute()
|
|
244
263
|
}
|
|
245
264
|
|
|
246
265
|
export interface LedgerEntry {
|
|
@@ -264,23 +283,17 @@ export interface LedgerEntry {
|
|
|
264
283
|
*/
|
|
265
284
|
export async function readKeyValue(db: Db, key: string): Promise<string | undefined> {
|
|
266
285
|
await ensureTables(db)
|
|
267
|
-
const
|
|
268
|
-
'
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
286
|
+
const row = await db.q
|
|
287
|
+
.selectFrom('key_value')
|
|
288
|
+
.select('value')
|
|
289
|
+
.where('key', '=', key)
|
|
290
|
+
.executeTakeFirst()
|
|
291
|
+
return row?.value ?? undefined
|
|
272
292
|
}
|
|
273
293
|
|
|
274
294
|
export async function writeKeyValue(db: Db, key: string, value: string): Promise<void> {
|
|
275
295
|
await ensureTables(db)
|
|
276
|
-
|
|
277
|
-
await db.exec(`UPDATE key_value SET value = ?, update_date = ${now} WHERE key = ?`, [value, key])
|
|
278
|
-
const rows = await db.query('SELECT value FROM key_value WHERE key = ?', [key])
|
|
279
|
-
if (rows.length === 0)
|
|
280
|
-
await db.exec(`INSERT INTO key_value (key, value, update_date) VALUES (?, ?, ${now})`, [
|
|
281
|
-
key,
|
|
282
|
-
value,
|
|
283
|
-
])
|
|
296
|
+
await upsertKeyValue(db, key, value)
|
|
284
297
|
}
|
|
285
298
|
|
|
286
299
|
/**
|
|
@@ -297,28 +310,31 @@ export async function ensureKeyValue(db: Db, key: string, create: () => string):
|
|
|
297
310
|
/** Appends a row to `migration_history`. */
|
|
298
311
|
export async function recordInLedger(db: Db, entry: LedgerEntry): Promise<void> {
|
|
299
312
|
await ensureTables(db)
|
|
300
|
-
await db.
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
entry.
|
|
305
|
-
entry.
|
|
306
|
-
entry.
|
|
307
|
-
|
|
308
|
-
entry.durationMs,
|
|
309
|
-
entry.checksum ?? null,
|
|
310
|
-
entry.appliedBy ?? null,
|
|
311
|
-
entry.note ?? null,
|
|
312
|
-
entry.bundle ?? null,
|
|
313
|
-
|
|
314
|
-
|
|
313
|
+
await db.q
|
|
314
|
+
.insertInto('migration_history')
|
|
315
|
+
.values({
|
|
316
|
+
name: entry.name,
|
|
317
|
+
kind: entry.kind,
|
|
318
|
+
from_state: entry.fromState ?? null,
|
|
319
|
+
to_state: entry.toState ?? null,
|
|
320
|
+
applied_at: now(db),
|
|
321
|
+
duration_ms: entry.durationMs,
|
|
322
|
+
checksum: entry.checksum ?? null,
|
|
323
|
+
applied_by: entry.appliedBy ?? null,
|
|
324
|
+
note: entry.note ?? null,
|
|
325
|
+
bundle: entry.bundle ?? null,
|
|
326
|
+
})
|
|
327
|
+
.execute()
|
|
315
328
|
}
|
|
316
329
|
|
|
317
330
|
/** The newest ledger row's id, so a node can later ask what was ledgered after it booted. */
|
|
318
331
|
export async function latestLedgerId(db: Db): Promise<number> {
|
|
319
332
|
await ensureTables(db)
|
|
320
|
-
const
|
|
321
|
-
|
|
333
|
+
const row = await db.q
|
|
334
|
+
.selectFrom('migration_history')
|
|
335
|
+
.select((eb) => eb.fn.max('id').as('n'))
|
|
336
|
+
.executeTakeFirst()
|
|
337
|
+
return Number(row?.n ?? 0)
|
|
322
338
|
}
|
|
323
339
|
|
|
324
340
|
/**
|
|
@@ -327,11 +343,14 @@ export async function latestLedgerId(db: Db): Promise<number> {
|
|
|
327
343
|
* bundle's own tables, which no read of core's depends on.
|
|
328
344
|
*/
|
|
329
345
|
export async function contractsLedgeredAfter(db: Db, afterId: number): Promise<number> {
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
346
|
+
const row = await db.q
|
|
347
|
+
.selectFrom('migration_history')
|
|
348
|
+
.select((eb) => eb.fn.countAll().as('n'))
|
|
349
|
+
.where('id', '>', afterId)
|
|
350
|
+
.where('kind', '=', 'contract')
|
|
351
|
+
.where('bundle', 'is', null)
|
|
352
|
+
.executeTakeFirst()
|
|
353
|
+
return Number(row?.n ?? 0)
|
|
335
354
|
}
|
|
336
355
|
|
|
337
356
|
export interface LedgerRow extends LedgerEntry {
|
|
@@ -341,9 +360,23 @@ export interface LedgerRow extends LedgerEntry {
|
|
|
341
360
|
|
|
342
361
|
export async function readLedger(db: Db): Promise<LedgerRow[]> {
|
|
343
362
|
await ensureTables(db)
|
|
344
|
-
const rows = await db.
|
|
345
|
-
'
|
|
346
|
-
|
|
363
|
+
const rows = await db.q
|
|
364
|
+
.selectFrom('migration_history')
|
|
365
|
+
.select([
|
|
366
|
+
'id',
|
|
367
|
+
'name',
|
|
368
|
+
'kind',
|
|
369
|
+
'from_state',
|
|
370
|
+
'to_state',
|
|
371
|
+
'applied_at',
|
|
372
|
+
'duration_ms',
|
|
373
|
+
'checksum',
|
|
374
|
+
'applied_by',
|
|
375
|
+
'note',
|
|
376
|
+
'bundle',
|
|
377
|
+
])
|
|
378
|
+
.orderBy('id')
|
|
379
|
+
.execute()
|
|
347
380
|
return rows.map((row) => ({
|
|
348
381
|
id: Number(row.id),
|
|
349
382
|
name: String(row.name),
|
|
@@ -426,10 +459,12 @@ async function verifyApplied(db: Db, plan: MigrationPlan, state: string): Promis
|
|
|
426
459
|
if (!plan.bundle) return
|
|
427
460
|
const applied = plan.appliedAt(state) ?? []
|
|
428
461
|
if (applied.length === 0) return
|
|
429
|
-
const rows = await db.
|
|
430
|
-
'
|
|
431
|
-
[
|
|
432
|
-
|
|
462
|
+
const rows = await db.q
|
|
463
|
+
.selectFrom('migration_history')
|
|
464
|
+
.select(['name', 'kind', 'checksum'])
|
|
465
|
+
.where('bundle', '=', plan.bundle)
|
|
466
|
+
.orderBy('id')
|
|
467
|
+
.execute()
|
|
433
468
|
const purged = rows.map((row) => row.kind).lastIndexOf('purge')
|
|
434
469
|
const ran = new Map(
|
|
435
470
|
rows
|
|
@@ -474,8 +509,11 @@ export async function migrate(
|
|
|
474
509
|
// run resumes at the first step that did not land and never repeats one.
|
|
475
510
|
await db
|
|
476
511
|
.transaction(async (tx) => {
|
|
477
|
-
|
|
478
|
-
|
|
512
|
+
const step = async (db: Db) => {
|
|
513
|
+
await next.up(db)
|
|
514
|
+
await next.backfill?.(db)
|
|
515
|
+
}
|
|
516
|
+
await (plan.runStep ? plan.runStep(tx, step) : step(tx))
|
|
479
517
|
await writeState(tx, next.to, plan.stateKey)
|
|
480
518
|
await recordInLedger(tx, {
|
|
481
519
|
name: next.name,
|
|
@@ -520,6 +558,10 @@ class RecordingDb implements Db {
|
|
|
520
558
|
readonly locks: LockManager
|
|
521
559
|
readonly statements: string[]
|
|
522
560
|
|
|
561
|
+
get q(): Query {
|
|
562
|
+
return queryFor(this)
|
|
563
|
+
}
|
|
564
|
+
|
|
523
565
|
constructor(dialect: Dialect, locks: LockManager, statements: string[] = []) {
|
|
524
566
|
this.dialect = dialect
|
|
525
567
|
this.locks = locks
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kysely as the query builder over a `Db` (story 221): Kysely compiles, and the
|
|
3
|
+
* `Db` runs what it compiles, so transactions, locks, snapshots and the dialect
|
|
4
|
+
* seam stay exactly as they are. docs/data-model.md, "Building queries".
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
type CompiledQuery,
|
|
8
|
+
type DatabaseConnection,
|
|
9
|
+
type DatabaseIntrospector,
|
|
10
|
+
type Driver,
|
|
11
|
+
Kysely,
|
|
12
|
+
type Dialect as KyselyDialect,
|
|
13
|
+
PostgresAdapter,
|
|
14
|
+
PostgresIntrospector,
|
|
15
|
+
PostgresQueryCompiler,
|
|
16
|
+
type QueryResult,
|
|
17
|
+
type RawBuilder,
|
|
18
|
+
type SelectQueryBuilder,
|
|
19
|
+
SqliteAdapter,
|
|
20
|
+
SqliteIntrospector,
|
|
21
|
+
SqliteQueryCompiler,
|
|
22
|
+
sql,
|
|
23
|
+
} from 'kysely'
|
|
24
|
+
import type { Db } from './database.ts'
|
|
25
|
+
import type { Dialect as DbDialect } from './dialect.ts'
|
|
26
|
+
import type { CoreTables } from './tables.gen.ts'
|
|
27
|
+
|
|
28
|
+
export type { Expression, Insertable, Selectable, Updateable } from 'kysely'
|
|
29
|
+
export { sql }
|
|
30
|
+
|
|
31
|
+
export type Query<Tables = CoreTables> = Kysely<Tables>
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Placeholders stay `?` on Postgres too: the `Db` renders them, as it does for
|
|
35
|
+
* every statement, so a wrapped or recording `Db` sees Kysely's SQL as it would
|
|
36
|
+
* any other.
|
|
37
|
+
*/
|
|
38
|
+
export class PlaceholderCompiler extends PostgresQueryCompiler {
|
|
39
|
+
protected override getCurrentParameterPlaceholder(): string {
|
|
40
|
+
return '?'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const READS = /^\s*(select|with|values|pragma|explain|show)\b/i
|
|
45
|
+
const RETURNS = /\breturning\b/i
|
|
46
|
+
|
|
47
|
+
/** Whether a statement answers with rows, so it runs as a query rather than an exec. */
|
|
48
|
+
export function readsRows(compiled: CompiledQuery): boolean {
|
|
49
|
+
const kind = compiled.query.kind
|
|
50
|
+
if (kind === 'SelectQueryNode') return true
|
|
51
|
+
if (kind === 'InsertQueryNode' || kind === 'UpdateQueryNode' || kind === 'DeleteQueryNode')
|
|
52
|
+
return 'returning' in compiled.query && compiled.query.returning !== undefined
|
|
53
|
+
return READS.test(compiled.sql) || RETURNS.test(compiled.sql)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class DbConnection implements DatabaseConnection {
|
|
57
|
+
constructor(readonly db: Db) {}
|
|
58
|
+
|
|
59
|
+
async executeQuery<R>(compiled: CompiledQuery): Promise<QueryResult<R>> {
|
|
60
|
+
const params = compiled.parameters as unknown[]
|
|
61
|
+
if (readsRows(compiled)) return { rows: await this.db.query<R>(compiled.sql, params) }
|
|
62
|
+
await this.db.exec(compiled.sql, params)
|
|
63
|
+
return { rows: [] }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// biome-ignore lint/correctness/useYield: refuses before streaming anything
|
|
67
|
+
async *streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
|
|
68
|
+
throw new Error('Streaming is not supported; page with limit and offset instead.')
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class TransactionRefused extends Error {
|
|
73
|
+
constructor() {
|
|
74
|
+
super('Open transactions with db.transaction(async (tx) => …) and build with tx.q.')
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
class DbDriver implements Driver {
|
|
79
|
+
readonly #connection: DbConnection
|
|
80
|
+
constructor(db: Db) {
|
|
81
|
+
this.#connection = new DbConnection(db)
|
|
82
|
+
}
|
|
83
|
+
async init(): Promise<void> {}
|
|
84
|
+
async acquireConnection(): Promise<DatabaseConnection> {
|
|
85
|
+
return this.#connection
|
|
86
|
+
}
|
|
87
|
+
async beginTransaction(): Promise<void> {
|
|
88
|
+
throw new TransactionRefused()
|
|
89
|
+
}
|
|
90
|
+
async commitTransaction(): Promise<void> {
|
|
91
|
+
throw new TransactionRefused()
|
|
92
|
+
}
|
|
93
|
+
async rollbackTransaction(): Promise<void> {
|
|
94
|
+
throw new TransactionRefused()
|
|
95
|
+
}
|
|
96
|
+
async releaseConnection(): Promise<void> {}
|
|
97
|
+
async destroy(): Promise<void> {}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function kyselyDialect(db: Db): KyselyDialect {
|
|
101
|
+
const postgres = db.dialect.name === 'postgres'
|
|
102
|
+
return {
|
|
103
|
+
createAdapter: () => (postgres ? new PostgresAdapter() : new SqliteAdapter()),
|
|
104
|
+
createDriver: () => new DbDriver(db),
|
|
105
|
+
createQueryCompiler: () => (postgres ? new PlaceholderCompiler() : new SqliteQueryCompiler()),
|
|
106
|
+
createIntrospector: (k: Kysely<unknown>): DatabaseIntrospector =>
|
|
107
|
+
postgres ? new PostgresIntrospector(k) : new SqliteIntrospector(k),
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const built = new WeakMap<Db, Kysely<unknown>>()
|
|
112
|
+
|
|
113
|
+
/** The query builder over `db`, made once per `Db`; what `db.q` returns. */
|
|
114
|
+
export function queryFor<Tables = CoreTables>(db: Db): Kysely<Tables> {
|
|
115
|
+
let k = built.get(db)
|
|
116
|
+
if (!k) {
|
|
117
|
+
k = new Kysely<unknown>({ dialect: kyselyDialect(db) })
|
|
118
|
+
built.set(db, k)
|
|
119
|
+
}
|
|
120
|
+
return k as Kysely<Tables>
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The database's clock, as the dialect writes it: what `dialect.now()` was spliced in as. */
|
|
124
|
+
export function now(db: Db): RawBuilder<string> {
|
|
125
|
+
return sql<string>`${sql.raw(db.dialect.now())}`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type RowLock = 'update' | 'share' | 'update skip locked'
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Locks the rows a select reads, where the engine can: Postgres. SQLite has a
|
|
132
|
+
* single writer, so its select is left alone. Use as `.$call(rowLock(db, 'update'))`.
|
|
133
|
+
*/
|
|
134
|
+
// biome-ignore lint/suspicious/noExplicitAny: any select, whatever its tables and output
|
|
135
|
+
export function rowLock<Q extends SelectQueryBuilder<any, any, any>>(db: Db, mode: RowLock) {
|
|
136
|
+
return (query: Q): Q => {
|
|
137
|
+
if (db.dialect.name !== 'postgres') return query
|
|
138
|
+
if (mode === 'share') return query.forShare() as Q
|
|
139
|
+
if (mode === 'update') return query.forUpdate() as Q
|
|
140
|
+
return query.forUpdate().skipLocked() as Q
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const compilers = new Map<string, Kysely<unknown>>()
|
|
145
|
+
|
|
146
|
+
/** A builder that only compiles, for statements rendered before there is a connection to run them. */
|
|
147
|
+
export function compilerFor<Tables = CoreTables>(dialect: DbDialect): Kysely<Tables> {
|
|
148
|
+
let k = compilers.get(dialect.name)
|
|
149
|
+
if (!k) {
|
|
150
|
+
const refuse = async (): Promise<never> => {
|
|
151
|
+
throw new Error('This builder only compiles; run what it compiles on a Db.')
|
|
152
|
+
}
|
|
153
|
+
const stub = { dialect, query: refuse, exec: refuse } as unknown as Db
|
|
154
|
+
k = new Kysely<unknown>({ dialect: kyselyDialect(stub) })
|
|
155
|
+
compilers.set(dialect.name, k)
|
|
156
|
+
}
|
|
157
|
+
return k as Kysely<Tables>
|
|
158
|
+
}
|
package/src/relations.ts
CHANGED
|
@@ -198,12 +198,19 @@ export function deriveReferences(
|
|
|
198
198
|
|
|
199
199
|
/** Every reference the current values make. A scan, which is the price of never going stale. */
|
|
200
200
|
export async function loadReferences(db: Db): Promise<ReferenceEdge[]> {
|
|
201
|
-
const values = await db.
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
201
|
+
const values = await db.q
|
|
202
|
+
.selectFrom('property_value')
|
|
203
|
+
.select(['node_id', 'varchar_value as v', 'text_value as t'])
|
|
204
|
+
.where('is_current', '=', db.dialect.boolValue(true))
|
|
205
|
+
.where((eb) =>
|
|
206
|
+
eb.or([
|
|
207
|
+
eb('varchar_value', 'like', '%-%-%-%-%'),
|
|
208
|
+
eb('text_value', 'like', '%-%-%-%-%'),
|
|
209
|
+
eb('varchar_value', 'like', '%umb://%'),
|
|
210
|
+
eb('text_value', 'like', '%umb://%'),
|
|
211
|
+
]),
|
|
212
|
+
)
|
|
213
|
+
.execute()
|
|
207
214
|
const texts: ValueText[] = []
|
|
208
215
|
for (const row of values) {
|
|
209
216
|
const text = `${row.v ?? ''} ${row.t ?? ''}`
|
|
@@ -211,9 +218,10 @@ export async function loadReferences(db: Db): Promise<ReferenceEdge[]> {
|
|
|
211
218
|
}
|
|
212
219
|
const wanted = new Set(texts.flatMap((value) => referencedKeysIn(value.text)))
|
|
213
220
|
if (wanted.size === 0) return []
|
|
214
|
-
const nodes = await db.
|
|
215
|
-
'
|
|
216
|
-
|
|
221
|
+
const nodes = await db.q
|
|
222
|
+
.selectFrom('node')
|
|
223
|
+
.select(['id', 'unique_id', 'node_object_type'])
|
|
224
|
+
.execute()
|
|
217
225
|
const byKey = new Map<string, KnownNode>()
|
|
218
226
|
for (const node of nodes) {
|
|
219
227
|
const key = normaliseUuid(String(node.unique_id))
|
|
@@ -244,13 +252,24 @@ interface NodeFacts {
|
|
|
244
252
|
async function describeNodes(db: Db, ids: readonly number[]): Promise<Map<number, NodeFacts>> {
|
|
245
253
|
const facts = new Map<number, NodeFacts>()
|
|
246
254
|
if (ids.length === 0) return facts
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
255
|
+
const rows = await db.q
|
|
256
|
+
.selectFrom('node as n')
|
|
257
|
+
.select((eb) => [
|
|
258
|
+
'n.id',
|
|
259
|
+
'n.unique_id',
|
|
260
|
+
'n.text',
|
|
261
|
+
eb.fn
|
|
262
|
+
.coalesce(
|
|
263
|
+
eb
|
|
264
|
+
.selectFrom('content_version as cv')
|
|
265
|
+
.select((sub) => sub.fn.max('cv.version_date').as('latest'))
|
|
266
|
+
.whereRef('cv.node_id', '=', 'n.id'),
|
|
267
|
+
'n.create_date',
|
|
268
|
+
)
|
|
269
|
+
.as('d'),
|
|
270
|
+
])
|
|
271
|
+
.where('n.id', 'in', [...ids])
|
|
272
|
+
.execute()
|
|
254
273
|
for (const row of rows)
|
|
255
274
|
facts.set(Number(row.id), {
|
|
256
275
|
key: normaliseUuid(String(row.unique_id)),
|
|
@@ -306,14 +325,14 @@ export class RelationRepository {
|
|
|
306
325
|
.filter((edge) => edge.toObjectType === type.target)
|
|
307
326
|
.map((edge) => [edge.fromId, edge.toId])
|
|
308
327
|
if (type.derivation === 'original-parent') {
|
|
309
|
-
const rows = await this.#db.
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
328
|
+
const rows = await this.#db.q
|
|
329
|
+
.selectFrom('node as n')
|
|
330
|
+
.innerJoin('document as d', 'd.node_id', 'n.id')
|
|
331
|
+
.innerJoin('node as p', 'p.id', 'd.original_parent_id')
|
|
332
|
+
.select(['n.id', 'd.original_parent_id as parent', 'p.node_object_type as parent_type'])
|
|
333
|
+
.where('n.trashed', '=', this.#db.dialect.boolValue(true))
|
|
334
|
+
.where('n.node_object_type', '=', type.target)
|
|
335
|
+
.execute()
|
|
317
336
|
return rows
|
|
318
337
|
.filter(
|
|
319
338
|
(row) =>
|
|
@@ -329,10 +348,12 @@ export class RelationRepository {
|
|
|
329
348
|
async referencingRecycleBin(objectType: string): Promise<number[]> {
|
|
330
349
|
const trashed = new Set(
|
|
331
350
|
(
|
|
332
|
-
await this.#db.
|
|
333
|
-
'
|
|
334
|
-
[
|
|
335
|
-
|
|
351
|
+
await this.#db.q
|
|
352
|
+
.selectFrom('node')
|
|
353
|
+
.select(['id', 'trashed'])
|
|
354
|
+
.where('node_object_type', '=', objectType)
|
|
355
|
+
.where('trashed', '=', this.#db.dialect.boolValue(true))
|
|
356
|
+
.execute()
|
|
336
357
|
)
|
|
337
358
|
.filter((row) => fromDbBool(row.trashed))
|
|
338
359
|
.map((row) => Number(row.id)),
|