@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
@@ -8,6 +8,7 @@
8
8
  import { randomUUID } from 'node:crypto'
9
9
  import type { Db } from '../database.ts'
10
10
  import { DbDate } from '../dialect.ts'
11
+ import { sql } from '../query.ts'
11
12
 
12
13
  export type FormWorkflowState = 'pending' | 'running' | 'done' | 'failed'
13
14
 
@@ -52,10 +53,22 @@ interface Row {
52
53
  update_date: unknown
53
54
  }
54
55
 
55
- const SELECT = `SELECT id, form_key, form_alias, workflow_name, workflow_type, run_on,
56
- entry_id, payload, state, attempts, last_error, run_after,
57
- create_date, update_date
58
- FROM form_workflow_run`
56
+ const COLUMNS = [
57
+ 'id',
58
+ 'form_key',
59
+ 'form_alias',
60
+ 'workflow_name',
61
+ 'workflow_type',
62
+ 'run_on',
63
+ 'entry_id',
64
+ 'payload',
65
+ 'state',
66
+ 'attempts',
67
+ 'last_error',
68
+ 'run_after',
69
+ 'create_date',
70
+ 'update_date',
71
+ ] as const
59
72
 
60
73
  const STATES: readonly FormWorkflowState[] = ['pending', 'running', 'done', 'failed']
61
74
 
@@ -99,28 +112,25 @@ export class FormWorkflowRepository {
99
112
  const ids: string[] = []
100
113
  for (const run of runs) {
101
114
  const id = randomUUID()
102
- await this.#db.exec(
103
- `INSERT INTO form_workflow_run
104
- (id, form_key, form_alias, workflow_name, workflow_type, run_on, entry_id,
105
- payload, state, attempts, last_error, run_after, create_date, update_date)
106
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
107
- [
115
+ await this.#db.q
116
+ .insertInto('form_workflow_run')
117
+ .values({
108
118
  id,
109
- run.formKey,
110
- run.formAlias,
111
- run.workflowName,
112
- run.workflowType,
113
- run.runOn,
114
- run.entryId,
115
- JSON.stringify(run.payload),
116
- 'pending',
117
- 0,
118
- null,
119
- DbDate.toDb(now),
120
- DbDate.toDb(now),
121
- DbDate.toDb(now),
122
- ],
123
- )
119
+ form_key: run.formKey,
120
+ form_alias: run.formAlias,
121
+ workflow_name: run.workflowName,
122
+ workflow_type: run.workflowType,
123
+ run_on: run.runOn,
124
+ entry_id: run.entryId,
125
+ payload: JSON.stringify(run.payload),
126
+ state: 'pending',
127
+ attempts: 0,
128
+ last_error: null,
129
+ run_after: DbDate.toDb(now),
130
+ create_date: DbDate.toDb(now),
131
+ update_date: DbDate.toDb(now),
132
+ })
133
+ .execute()
124
134
  ids.push(id)
125
135
  }
126
136
  return ids
@@ -128,10 +138,15 @@ export class FormWorkflowRepository {
128
138
 
129
139
  /** What is ready to run, oldest first so a backlog drains in order. */
130
140
  async due(now = new Date(), limit = 25): Promise<FormWorkflowRun[]> {
131
- const rows = await this.#db.query<Row>(
132
- `${SELECT} WHERE state = ? AND run_after <= ? ORDER BY run_after, create_date LIMIT ?`,
133
- ['pending', DbDate.toDb(now), limit],
134
- )
141
+ const rows = await this.#db.q
142
+ .selectFrom('form_workflow_run')
143
+ .select(COLUMNS)
144
+ .where('state', '=', 'pending')
145
+ .where('run_after', '<=', DbDate.toDb(now))
146
+ .orderBy('run_after')
147
+ .orderBy('create_date')
148
+ .limit(limit)
149
+ .execute()
135
150
  return rows.map(hydrate)
136
151
  }
137
152
 
@@ -142,24 +157,26 @@ export class FormWorkflowRepository {
142
157
  * the same UPDATE, and only the first one changes a row.
143
158
  */
144
159
  async claim(id: string): Promise<FormWorkflowRun | undefined> {
145
- const rows = await this.#db.query<Row>(
146
- `UPDATE form_workflow_run
147
- SET state = ?, attempts = attempts + 1, update_date = ?
148
- WHERE id = ? AND state = ?
149
- RETURNING id, form_key, form_alias, workflow_name, workflow_type, run_on,
150
- entry_id, payload, state, attempts, last_error, run_after,
151
- create_date, update_date`,
152
- ['running', DbDate.toDb(new Date()), id, 'pending'],
153
- )
154
- const row = rows[0]
160
+ const row = await this.#db.q
161
+ .updateTable('form_workflow_run')
162
+ .set((eb) => ({
163
+ state: 'running',
164
+ attempts: eb('attempts', '+', 1),
165
+ update_date: DbDate.toDb(new Date()),
166
+ }))
167
+ .where('id', '=', id)
168
+ .where('state', '=', 'pending')
169
+ .returning(COLUMNS)
170
+ .executeTakeFirst()
155
171
  return row ? hydrate(row) : undefined
156
172
  }
157
173
 
158
174
  async succeed(id: string): Promise<void> {
159
- await this.#db.exec(
160
- 'UPDATE form_workflow_run SET state = ?, last_error = NULL, update_date = ? WHERE id = ?',
161
- ['done', DbDate.toDb(new Date()), id],
162
- )
175
+ await this.#db.q
176
+ .updateTable('form_workflow_run')
177
+ .set({ state: 'done', last_error: null, update_date: DbDate.toDb(new Date()) })
178
+ .where('id', '=', id)
179
+ .execute()
163
180
  }
164
181
 
165
182
  /**
@@ -167,38 +184,46 @@ export class FormWorkflowRepository {
167
184
  * finished and a person has to look.
168
185
  */
169
186
  async fail(id: string, error: string, retryAt?: Date): Promise<void> {
170
- await this.#db.exec(
171
- 'UPDATE form_workflow_run SET state = ?, last_error = ?, run_after = ?, update_date = ? WHERE id = ?',
172
- [
173
- retryAt ? 'pending' : 'failed',
174
- error.slice(0, 2000),
175
- DbDate.toDb(retryAt ?? new Date()),
176
- DbDate.toDb(new Date()),
177
- id,
178
- ],
179
- )
187
+ await this.#db.q
188
+ .updateTable('form_workflow_run')
189
+ .set({
190
+ state: retryAt ? 'pending' : 'failed',
191
+ last_error: error.slice(0, 2000),
192
+ run_after: DbDate.toDb(retryAt ?? new Date()),
193
+ update_date: DbDate.toDb(new Date()),
194
+ })
195
+ .where('id', '=', id)
196
+ .execute()
180
197
  }
181
198
 
182
199
  async byId(id: string): Promise<FormWorkflowRun | undefined> {
183
- const rows = await this.#db.query<Row>(`${SELECT} WHERE id = ?`, [id])
184
- const row = rows[0]
200
+ const row = await this.#db.q
201
+ .selectFrom('form_workflow_run')
202
+ .select(COLUMNS)
203
+ .where('id', '=', id)
204
+ .executeTakeFirst()
185
205
  return row ? hydrate(row) : undefined
186
206
  }
187
207
 
188
208
  /** Every run for a form, newest first; what the backoffice would show. */
189
209
  async forForm(formKey: string, limit = 100): Promise<FormWorkflowRun[]> {
190
- const rows = await this.#db.query<Row>(
191
- `${SELECT} WHERE form_key = ? ORDER BY create_date DESC LIMIT ?`,
192
- [formKey, limit],
193
- )
210
+ const rows = await this.#db.q
211
+ .selectFrom('form_workflow_run')
212
+ .select(COLUMNS)
213
+ .where('form_key', '=', formKey)
214
+ .orderBy('create_date', 'desc')
215
+ .limit(limit)
216
+ .execute()
194
217
  return rows.map(hydrate)
195
218
  }
196
219
 
197
220
  /** How many runs sit in each state, for a status line. */
198
221
  async counts(): Promise<Record<FormWorkflowState, number>> {
199
- const rows = await this.#db.query<{ state: string; n: number }>(
200
- 'SELECT state, COUNT(*) AS n FROM form_workflow_run GROUP BY state',
201
- )
222
+ const rows = await this.#db.q
223
+ .selectFrom('form_workflow_run')
224
+ .select(['state', sql<number>`count(*)`.as('n')])
225
+ .groupBy('state')
226
+ .execute()
202
227
  const out: Record<FormWorkflowState, number> = {
203
228
  pending: 0,
204
229
  running: 0,
@@ -0,0 +1,296 @@
1
+ /**
2
+ * The background job queue (story 187): every owner's jobs in one table,
3
+ * claimed by one node at a time, and each schedule's last occurrence.
4
+ * docs/rendering.md, "Background jobs".
5
+ */
6
+ import { randomUUID } from 'node:crypto'
7
+ import type { Db } from '../database.ts'
8
+ import { DbDate } from '../dialect.ts'
9
+
10
+ export type JobState = 'queued' | 'running' | 'succeeded' | 'failed'
11
+
12
+ export interface JobProgress {
13
+ done: number
14
+ total?: number
15
+ note?: string
16
+ }
17
+
18
+ export interface JobRow {
19
+ id: string
20
+ /** `site`, or the bundle's id. */
21
+ owner: string
22
+ name: string
23
+ payload: unknown
24
+ state: JobState
25
+ attempts: number
26
+ maxAttempts: number
27
+ nextAttemptAt: Date
28
+ claimedBy: string | null
29
+ claimedAt: Date | null
30
+ progress: JobProgress | null
31
+ lastError: string | null
32
+ queuedBy: string | null
33
+ createdAt: Date
34
+ finishedAt: Date | null
35
+ }
36
+
37
+ const date = (value: unknown): Date | null => DbDate.fromDb(value) ?? null
38
+
39
+ const parse = <T>(value: unknown): T | null => {
40
+ if (value === null || value === undefined) return null
41
+ try {
42
+ return JSON.parse(String(value)) as T
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ // biome-ignore lint/suspicious/noExplicitAny: a row as the driver hands it back
49
+ function rowOf(row: any): JobRow {
50
+ return {
51
+ id: String(row.id).toLowerCase(),
52
+ owner: row.owner,
53
+ name: row.name,
54
+ payload: parse(row.payload),
55
+ state: row.state as JobState,
56
+ attempts: Number(row.attempts),
57
+ maxAttempts: Number(row.max_attempts),
58
+ nextAttemptAt: date(row.next_attempt_at) ?? new Date(0),
59
+ claimedBy: row.claimed_by ?? null,
60
+ claimedAt: date(row.claimed_at),
61
+ progress: parse<JobProgress>(row.progress),
62
+ lastError: row.last_error ?? null,
63
+ queuedBy: row.queued_by ?? null,
64
+ createdAt: date(row.created_at) ?? new Date(0),
65
+ finishedAt: date(row.finished_at),
66
+ }
67
+ }
68
+
69
+ export class JobRepository {
70
+ constructor(private readonly db: Db) {}
71
+
72
+ async enqueue(job: {
73
+ owner: string
74
+ name: string
75
+ payload: string
76
+ maxAttempts: number
77
+ queuedBy: string | null
78
+ runAt?: Date
79
+ }): Promise<string> {
80
+ const id = randomUUID()
81
+ const now = DbDate.toDb(new Date())
82
+ await this.db.q
83
+ .insertInto('job')
84
+ .values({
85
+ id,
86
+ owner: job.owner,
87
+ name: job.name,
88
+ payload: job.payload,
89
+ state: 'queued',
90
+ attempts: 0,
91
+ max_attempts: job.maxAttempts,
92
+ next_attempt_at: DbDate.toDb(job.runAt ?? new Date()),
93
+ claimed_by: null,
94
+ claimed_at: null,
95
+ progress: null,
96
+ last_error: null,
97
+ queued_by: job.queuedBy,
98
+ created_at: now,
99
+ finished_at: null,
100
+ })
101
+ .execute()
102
+ return id
103
+ }
104
+
105
+ async get(id: string): Promise<JobRow | undefined> {
106
+ const row = await this.db.q
107
+ .selectFrom('job')
108
+ .selectAll()
109
+ .where('id', '=', id.toLowerCase())
110
+ .executeTakeFirst()
111
+ return row ? rowOf(row) : undefined
112
+ }
113
+
114
+ /** The newest first, for the administrators' view; `owner` and `state` narrow it. */
115
+ async list(
116
+ options: { owner?: string; state?: JobState; skip?: number; take?: number } = {},
117
+ ): Promise<{ total: number; items: JobRow[] }> {
118
+ let query = this.db.q.selectFrom('job')
119
+ if (options.owner) query = query.where('owner', '=', options.owner)
120
+ if (options.state) query = query.where('state', '=', options.state)
121
+ const counted = await query.select((eb) => eb.fn.countAll<number>().as('n')).executeTakeFirst()
122
+ const rows = await query
123
+ .selectAll()
124
+ .orderBy('created_at', 'desc')
125
+ .orderBy('id')
126
+ .limit(options.take ?? 50)
127
+ .offset(options.skip ?? 0)
128
+ .execute()
129
+ return { total: Number(counted?.n ?? 0), items: rows.map(rowOf) }
130
+ }
131
+
132
+ /**
133
+ * Claims the job due soonest, or none. Two nodes asking at once take
134
+ * different jobs: the claim is an update that only lands while it is queued.
135
+ */
136
+ async claimNext(
137
+ nodeId: string,
138
+ now = new Date(),
139
+ owners?: readonly string[],
140
+ ): Promise<JobRow | undefined> {
141
+ if (owners && owners.length === 0) return undefined
142
+ for (let tries = 0; tries < 5; tries++) {
143
+ let candidates = this.db.q.selectFrom('job').select('id').where('state', '=', 'queued')
144
+ if (owners) candidates = candidates.where('owner', 'in', [...owners])
145
+ const due = await candidates
146
+ .where('next_attempt_at', '<=', DbDate.toDb(now))
147
+ .orderBy('next_attempt_at')
148
+ .orderBy('created_at')
149
+ .limit(1)
150
+ .executeTakeFirst()
151
+ if (!due) return undefined
152
+ const claimed = await this.db.q
153
+ .updateTable('job')
154
+ .set((eb) => ({
155
+ state: 'running',
156
+ attempts: eb('attempts', '+', 1),
157
+ claimed_by: nodeId,
158
+ claimed_at: DbDate.toDb(now),
159
+ }))
160
+ .where('id', '=', due.id)
161
+ .where('state', '=', 'queued')
162
+ .returning('id')
163
+ .execute()
164
+ if (claimed.length > 0) return this.get(due.id)
165
+ }
166
+ return undefined
167
+ }
168
+
169
+ /** A running job says it is still alive, so it is not taken for one a dead node left. */
170
+ async heartbeat(id: string, progress?: JobProgress): Promise<void> {
171
+ await this.db.q
172
+ .updateTable('job')
173
+ .set({
174
+ claimed_at: DbDate.toDb(new Date()),
175
+ ...(progress ? { progress: JSON.stringify(progress) } : {}),
176
+ })
177
+ .where('id', '=', id)
178
+ .where('state', '=', 'running')
179
+ .execute()
180
+ }
181
+
182
+ async succeed(id: string): Promise<void> {
183
+ await this.db.q
184
+ .updateTable('job')
185
+ .set({
186
+ state: 'succeeded',
187
+ claimed_by: null,
188
+ claimed_at: null,
189
+ finished_at: DbDate.toDb(new Date()),
190
+ })
191
+ .where('id', '=', id)
192
+ .execute()
193
+ }
194
+
195
+ /** A failed attempt: queued again at `retryAt`, or failed for good without one. */
196
+ async fail(id: string, error: string, retryAt: Date | undefined): Promise<void> {
197
+ await this.db.q
198
+ .updateTable('job')
199
+ .set({
200
+ state: retryAt ? 'queued' : 'failed',
201
+ last_error: error,
202
+ claimed_by: null,
203
+ claimed_at: null,
204
+ ...(retryAt
205
+ ? { next_attempt_at: DbDate.toDb(retryAt) }
206
+ : { finished_at: DbDate.toDb(new Date()) }),
207
+ })
208
+ .where('id', '=', id)
209
+ .execute()
210
+ }
211
+
212
+ /** Back in the queue without counting the attempt: its node stopped before it could finish. */
213
+ async release(id: string): Promise<void> {
214
+ await this.db.q
215
+ .updateTable('job')
216
+ .set((eb) => ({
217
+ state: 'queued',
218
+ attempts: eb('attempts', '-', 1),
219
+ claimed_by: null,
220
+ claimed_at: null,
221
+ next_attempt_at: DbDate.toDb(new Date()),
222
+ }))
223
+ .where('id', '=', id)
224
+ .where('state', '=', 'running')
225
+ .execute()
226
+ }
227
+
228
+ /** Jobs whose node stopped answering go back in the queue; returns how many. */
229
+ async releaseStale(before: Date): Promise<number> {
230
+ const rows = await this.db.q
231
+ .updateTable('job')
232
+ .set({ state: 'queued', claimed_by: null, claimed_at: null })
233
+ .where('state', '=', 'running')
234
+ .where('claimed_at', '<', DbDate.toDb(before))
235
+ .returning('id')
236
+ .execute()
237
+ return rows.length
238
+ }
239
+
240
+ /** An administrator runs a failed job again, from its first attempt. */
241
+ async retry(id: string): Promise<boolean> {
242
+ const rows = await this.db.q
243
+ .updateTable('job')
244
+ .set({
245
+ state: 'queued',
246
+ attempts: 0,
247
+ last_error: null,
248
+ finished_at: null,
249
+ next_attempt_at: DbDate.toDb(new Date()),
250
+ })
251
+ .where('id', '=', id.toLowerCase())
252
+ .where('state', '=', 'failed')
253
+ .returning('id')
254
+ .execute()
255
+ return rows.length > 0
256
+ }
257
+
258
+ /** Drops finished jobs older than `before`; failed ones stay until retried or cleared. */
259
+ async pruneSucceeded(before: Date): Promise<void> {
260
+ await this.db.q
261
+ .deleteFrom('job')
262
+ .where('state', '=', 'succeeded')
263
+ .where('finished_at', '<', DbDate.toDb(before))
264
+ .execute()
265
+ }
266
+
267
+ /** When a schedule last ran, made now when it is new, so a new schedule has nothing to catch up. */
268
+ async scheduleSince(key: string, now: Date): Promise<Date> {
269
+ await this.db.q
270
+ .insertInto('job_schedule')
271
+ .values({ schedule_key: key, last_occurrence: DbDate.toDb(now) })
272
+ .onConflict((oc) => oc.column('schedule_key').doNothing())
273
+ .execute()
274
+ const row = await this.db.q
275
+ .selectFrom('job_schedule')
276
+ .select('last_occurrence')
277
+ .where('schedule_key', '=', key)
278
+ .executeTakeFirst()
279
+ return date(row?.last_occurrence) ?? now
280
+ }
281
+
282
+ /**
283
+ * Moves a schedule on from `from` to `to`, only if it is still at `from`: of
284
+ * the nodes that saw the same occurrence due, exactly one gets true.
285
+ */
286
+ async advanceSchedule(key: string, from: Date, to: Date): Promise<boolean> {
287
+ const rows = await this.db.q
288
+ .updateTable('job_schedule')
289
+ .set({ last_occurrence: DbDate.toDb(to) })
290
+ .where('schedule_key', '=', key)
291
+ .where('last_occurrence', '=', DbDate.toDb(from))
292
+ .returning('schedule_key')
293
+ .execute()
294
+ return rows.length > 0
295
+ }
296
+ }
@@ -17,10 +17,18 @@ export class LanguageRepository {
17
17
  }
18
18
 
19
19
  async all(): Promise<LanguageModel[]> {
20
- const rows = await this.#db.query(
21
- `SELECT l.iso_code, l.culture_name, l.is_default, l.is_mandatory, f.iso_code AS fallback
22
- FROM language l LEFT JOIN language f ON f.id = l.fallback_language_id ORDER BY l.id`,
23
- )
20
+ const rows = await this.#db.q
21
+ .selectFrom('language as l')
22
+ .leftJoin('language as f', 'f.id', 'l.fallback_language_id')
23
+ .select([
24
+ 'l.iso_code',
25
+ 'l.culture_name',
26
+ 'l.is_default',
27
+ 'l.is_mandatory',
28
+ 'f.iso_code as fallback',
29
+ ])
30
+ .orderBy('l.id')
31
+ .execute()
24
32
  return rows.map((row) => ({
25
33
  isoCode: String(row.iso_code),
26
34
  cultureName: String(row.culture_name),
@@ -38,10 +46,11 @@ export class LanguageRepository {
38
46
  async save(language: LanguageModel): Promise<LanguageModel> {
39
47
  const bool = (v: boolean) => this.#db.dialect.boolValue(v)
40
48
  if (language.isDefault)
41
- await this.#db.exec('UPDATE language SET is_default = ? WHERE iso_code <> ?', [
42
- bool(false),
43
- language.isoCode,
44
- ])
49
+ await this.#db.q
50
+ .updateTable('language')
51
+ .set({ is_default: bool(false) })
52
+ .where('iso_code', '<>', language.isoCode)
53
+ .execute()
45
54
  await this.upsertAll([language])
46
55
  return (await this.byIso(language.isoCode)) as LanguageModel
47
56
  }
@@ -52,7 +61,7 @@ export class LanguageRepository {
52
61
  if (!language) return 'not-found'
53
62
  if (language.isDefault) return 'default'
54
63
  if ((await this.all()).some((l) => l.fallbackIsoCode === language.isoCode)) return 'in-use'
55
- await this.#db.exec('DELETE FROM language WHERE iso_code = ?', [language.isoCode])
64
+ await this.#db.q.deleteFrom('language').where('iso_code', '=', language.isoCode).execute()
56
65
  return 'deleted'
57
66
  }
58
67
 
@@ -64,44 +73,48 @@ export class LanguageRepository {
64
73
  let updated = 0
65
74
  const bool = (v: boolean) => this.#db.dialect.boolValue(v)
66
75
  for (const language of languages) {
67
- const existing = await this.#db.query<{ id: number }>(
68
- 'SELECT id FROM language WHERE iso_code = ?',
69
- [language.isoCode],
70
- )
76
+ const existing = await this.#db.q
77
+ .selectFrom('language')
78
+ .select('id')
79
+ .where('iso_code', '=', language.isoCode)
80
+ .execute()
71
81
  if (existing[0]) {
72
- await this.#db.exec(
73
- 'UPDATE language SET culture_name = ?, is_default = ?, is_mandatory = ? WHERE id = ?',
74
- [
75
- language.cultureName,
76
- bool(language.isDefault),
77
- bool(language.isMandatory),
78
- Number(existing[0].id),
79
- ],
80
- )
82
+ await this.#db.q
83
+ .updateTable('language')
84
+ .set({
85
+ culture_name: language.cultureName,
86
+ is_default: bool(language.isDefault),
87
+ is_mandatory: bool(language.isMandatory),
88
+ })
89
+ .where('id', '=', Number(existing[0].id))
90
+ .execute()
81
91
  updated += 1
82
92
  } else {
83
- await this.#db.exec(
84
- 'INSERT INTO language (iso_code, culture_name, is_default, is_mandatory) VALUES (?, ?, ?, ?)',
85
- [
86
- language.isoCode,
87
- language.cultureName,
88
- bool(language.isDefault),
89
- bool(language.isMandatory),
90
- ],
91
- )
93
+ await this.#db.q
94
+ .insertInto('language')
95
+ .values({
96
+ iso_code: language.isoCode,
97
+ culture_name: language.cultureName,
98
+ is_default: bool(language.isDefault),
99
+ is_mandatory: bool(language.isMandatory),
100
+ })
101
+ .execute()
92
102
  created += 1
93
103
  }
94
104
  }
95
105
  for (const language of languages) {
96
106
  const fallback = language.fallbackIsoCode
97
- ? await this.#db.query<{ id: number }>('SELECT id FROM language WHERE iso_code = ?', [
98
- language.fallbackIsoCode,
99
- ])
107
+ ? await this.#db.q
108
+ .selectFrom('language')
109
+ .select('id')
110
+ .where('iso_code', '=', language.fallbackIsoCode)
111
+ .execute()
100
112
  : []
101
- await this.#db.exec('UPDATE language SET fallback_language_id = ? WHERE iso_code = ?', [
102
- fallback[0] ? Number(fallback[0].id) : null,
103
- language.isoCode,
104
- ])
113
+ await this.#db.q
114
+ .updateTable('language')
115
+ .set({ fallback_language_id: fallback[0] ? Number(fallback[0].id) : null })
116
+ .where('iso_code', '=', language.isoCode)
117
+ .execute()
105
118
  }
106
119
  return { created, updated }
107
120
  }
@@ -9,9 +9,11 @@ export class LogSearchRepository {
9
9
  }
10
10
 
11
11
  async all(): Promise<Array<{ name: string; query: string }>> {
12
- const rows = await this.#db.query<{ name: string; query: string }>(
13
- 'SELECT name, query FROM log_viewer_query ORDER BY id',
14
- )
12
+ const rows = await this.#db.q
13
+ .selectFrom('log_viewer_query')
14
+ .select(['name', 'query'])
15
+ .orderBy('id')
16
+ .execute()
15
17
  return rows.map((r) => ({ name: String(r.name), query: String(r.query) }))
16
18
  }
17
19
 
@@ -21,13 +23,13 @@ export class LogSearchRepository {
21
23
 
22
24
  async create(name: string, query: string): Promise<'created' | 'duplicate'> {
23
25
  if (await this.byName(name)) return 'duplicate'
24
- await this.#db.exec('INSERT INTO log_viewer_query (name, query) VALUES (?, ?)', [name, query])
26
+ await this.#db.q.insertInto('log_viewer_query').values({ name, query }).execute()
25
27
  return 'created'
26
28
  }
27
29
 
28
30
  async delete(name: string): Promise<boolean> {
29
31
  if (!(await this.byName(name))) return false
30
- await this.#db.exec('DELETE FROM log_viewer_query WHERE name = ?', [name])
32
+ await this.#db.q.deleteFrom('log_viewer_query').where('name', '=', name).execute()
31
33
  return true
32
34
  }
33
35
  }