@cslug/database 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,188 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { basename, join } from 'node:path'
3
+ import { CslugError, Logger } from '@cslug/core'
4
+ import type { Database } from './database'
5
+ import { sql } from './sql'
6
+
7
+ /** The framework's own migrations (idempotency table, …), always run before the app's. */
8
+ export const FRAMEWORK_MIGRATIONS = join(import.meta.dir, '../migrations')
9
+
10
+ const packageMigrations: string[] = []
11
+ /** A package's own migrations (`@cslug/auth`'s tokens table), run with the framework's, before the app's. */
12
+ export function addMigrations(dir: string): void {
13
+ if (!packageMigrations.includes(dir)) packageMigrations.push(dir)
14
+ }
15
+
16
+ type MigrationFile = { name: string; path: string; up: string; down: string | undefined; transaction: boolean }
17
+ export type MigrationStatus = { name: string; ran: boolean; batch?: number; ranAt?: Date }
18
+
19
+ const NAME = /^\d{8}_\d{6}_[a-z0-9_]+\.sql$/
20
+
21
+ /** Split a file into its `-- up` and `-- down` sections. `-- cslug:no-transaction` runs it outside a transaction. */
22
+ export function parseMigration(path: string, text: string): MigrationFile {
23
+ const name = basename(path, '.sql')
24
+ const up = /^--\s*up\s*$/im.exec(text)
25
+ const down = /^--\s*down\s*$/im.exec(text)
26
+ if (!up) throw new CslugError('migration.invalid', `${name}: missing "-- up" section`)
27
+ const upEnd = down && down.index > up.index ? down.index : text.length
28
+ return {
29
+ name,
30
+ path,
31
+ up: text.slice(up.index + up[0].length, upEnd).trim(),
32
+ down: down
33
+ ? text.slice(down.index + down[0].length, down.index > up.index ? text.length : up.index).trim()
34
+ : undefined,
35
+ transaction: !/^--\s*cslug:no-transaction\s*$/im.test(text),
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Runs SQL-file migrations (`database/migrations/20261126_101500_create_bookings.sql`). Each migration runs in its
41
+ * own transaction (unless marked `-- cslug:no-transaction`), is recorded in `cslug_migrations` with a batch
42
+ * number, and the whole run holds an advisory lock, so concurrent runs (several instances starting) execute each
43
+ * migration once.
44
+ */
45
+ export class Migrator {
46
+ readonly paths: string[]
47
+
48
+ constructor(
49
+ private readonly db: Database,
50
+ options: { paths?: string[]; env?: string; log?: Logger } = {},
51
+ ) {
52
+ this.paths = [FRAMEWORK_MIGRATIONS, ...packageMigrations, ...(options.paths ?? [])]
53
+ this.env = options.env ?? 'development'
54
+ this.log = options.log ?? Logger.null()
55
+ }
56
+
57
+ private readonly env: string
58
+ private readonly log: Logger
59
+
60
+ /** Every migration file, ordered by name (timestamp). */
61
+ files(): MigrationFile[] {
62
+ const files: MigrationFile[] = []
63
+ for (const dir of this.paths) {
64
+ if (!existsSync(dir)) continue
65
+ for (const file of readdirSync(dir).filter((f) => f.endsWith('.sql'))) {
66
+ if (!NAME.test(file)) throw new CslugError('migration.invalid_name', `${file}: use YYYYMMDD_HHMMSS_name.sql`)
67
+ const path = join(dir, file)
68
+ files.push(parseMigration(path, readFileSync(path, 'utf8')))
69
+ }
70
+ }
71
+ const names = new Set<string>()
72
+ for (const f of files) {
73
+ if (names.has(f.name)) throw new CslugError('migration.duplicate', `Two migrations are named ${f.name}`)
74
+ names.add(f.name)
75
+ }
76
+ return files.sort((a, b) => a.name.localeCompare(b.name))
77
+ }
78
+
79
+ private async ensureTable(): Promise<void> {
80
+ await this.db.exec(sql`create table if not exists cslug_migrations (
81
+ name text primary key, batch integer not null, ran_at timestamptz not null default now())`)
82
+ }
83
+
84
+ private async ran(): Promise<Map<string, { batch: number; ranAt: Date }>> {
85
+ const rows = await this.db.many(
86
+ sql<{ name: string; batch: number; ranAt: Date }>`select name, batch, ran_at from cslug_migrations`,
87
+ )
88
+ return new Map(rows.map((r) => [r.name, { batch: r.batch, ranAt: r.ranAt }]))
89
+ }
90
+
91
+ private locked<T>(fn: () => Promise<T>): Promise<T> {
92
+ return this.db.advisoryLock('cslug:migrations', async () => {
93
+ await this.ensureTable()
94
+ return fn()
95
+ })
96
+ }
97
+
98
+ async status(): Promise<MigrationStatus[]> {
99
+ await this.ensureTable()
100
+ const ran = await this.ran()
101
+ return this.files().map((f) => ({ name: f.name, ran: ran.has(f.name), ...ran.get(f.name) }))
102
+ }
103
+
104
+ /** Run pending migrations. Returns their names. */
105
+ migrate(): Promise<string[]> {
106
+ return this.locked(async () => {
107
+ const ran = await this.ran()
108
+ const pending = this.files().filter((f) => !ran.has(f.name))
109
+ if (!pending.length) return []
110
+ const batch = Math.max(0, ...[...ran.values()].map((r) => r.batch)) + 1
111
+ for (const m of pending) {
112
+ await this.apply(m, m.up, async (run) =>
113
+ run(sql`insert into cslug_migrations (name, batch) values (${m.name}, ${batch})`),
114
+ )
115
+ this.log.info('migrated', { migration: m.name, batch })
116
+ }
117
+ return pending.map((m) => m.name)
118
+ })
119
+ }
120
+
121
+ /** Undo the last `steps` batches (default 1), newest first. Returns the names rolled back. */
122
+ rollback(options: { steps?: number } = {}): Promise<string[]> {
123
+ return this.locked(async () => {
124
+ const ran = await this.ran()
125
+ const batches = [...new Set([...ran.values()].map((r) => r.batch))]
126
+ .sort((a, b) => b - a)
127
+ .slice(0, options.steps ?? 1)
128
+ const files = new Map(this.files().map((f) => [f.name, f]))
129
+ const targets = [...ran.entries()]
130
+ .filter(([, r]) => batches.includes(r.batch))
131
+ .map(([name]) => name)
132
+ .sort()
133
+ .reverse()
134
+ for (const name of targets) {
135
+ const m = files.get(name)
136
+ if (!m) throw new CslugError('migration.missing_file', `${name} was run but its file is gone`)
137
+ if (m.down === undefined || m.down === '')
138
+ throw new CslugError('migration.no_down', `${name} has no "-- down" section`)
139
+ await this.apply(m, m.down, async (run) => run(sql`delete from cslug_migrations where name = ${name}`))
140
+ this.log.info('rolled back', { migration: name })
141
+ }
142
+ return targets
143
+ })
144
+ }
145
+
146
+ /** Drop everything in the public schema and migrate from scratch. Refused in production. */
147
+ async fresh(): Promise<string[]> {
148
+ if (this.env === 'production')
149
+ throw new CslugError('migration.fresh_in_production', 'migrate:fresh is refused when APP_ENV=production')
150
+ await this.db.pool.unsafe('drop schema public cascade; create schema public;')
151
+ return this.migrate()
152
+ }
153
+
154
+ private async apply(
155
+ m: MigrationFile,
156
+ script: string,
157
+ record: (run: (q: ReturnType<typeof sql>) => Promise<unknown>) => Promise<unknown>,
158
+ ) {
159
+ try {
160
+ if (m.transaction) {
161
+ await this.db.transaction(async (tx) => {
162
+ await tx.handle.unsafe(script)
163
+ await record((q) => tx.exec(q))
164
+ })
165
+ } else {
166
+ await this.db.pool.unsafe(script)
167
+ await record((q) => this.db.exec(q))
168
+ }
169
+ } catch (error) {
170
+ throw new CslugError('migration.failed', `Migration ${m.name} failed: ${(error as Error).message}`, {
171
+ cause: error,
172
+ })
173
+ }
174
+ }
175
+
176
+ /** Write a new, empty migration file (for `cslug make:migration name`). Returns its path. */
177
+ static create(dir: string, name: string, now = new Date()): string {
178
+ const slug = name
179
+ .toLowerCase()
180
+ .replace(/[^a-z0-9]+/g, '_')
181
+ .replace(/^_|_$/g, '')
182
+ const stamp = now.toISOString().replace(/[-:]/g, '').replace('T', '_').slice(0, 15)
183
+ mkdirSync(dir, { recursive: true })
184
+ const path = join(dir, `${stamp}_${slug}.sql`)
185
+ writeFileSync(path, '-- up\n\n\n-- down\n\n')
186
+ return path
187
+ }
188
+ }
@@ -0,0 +1,28 @@
1
+ import { type SqlFragment, sql } from './sql'
2
+
3
+ /** A condition on one column, built by the operator helpers below. */
4
+ export class Op<T = unknown> {
5
+ declare readonly _type: T
6
+ constructor(readonly render: (column: unknown) => SqlFragment<unknown>) {}
7
+ }
8
+
9
+ export const eq = <T>(v: T) => new Op<T>((c) => sql`${c} = ${v}`)
10
+ export const ne = <T>(v: T) => new Op<T>((c) => sql`${c} <> ${v}`)
11
+ export const gt = <T>(v: T) => new Op<T>((c) => sql`${c} > ${v}`)
12
+ export const gte = <T>(v: T) => new Op<T>((c) => sql`${c} >= ${v}`)
13
+ export const lt = <T>(v: T) => new Op<T>((c) => sql`${c} < ${v}`)
14
+ export const lte = <T>(v: T) => new Op<T>((c) => sql`${c} <= ${v}`)
15
+ export const between = <T>(from: T, to: T) => new Op<T>((c) => sql`${c} between ${from} and ${to}`)
16
+ /** `in (…)`; an empty list matches nothing (instead of being a syntax error). */
17
+ export const inList = <T>(values: readonly T[]) =>
18
+ new Op<T>((c) => (values.length ? sql`${c} in (${sql.join(values)})` : sql`false`))
19
+ export const notIn = <T>(values: readonly T[]) =>
20
+ new Op<T>((c) => (values.length ? sql`${c} not in (${sql.join(values)})` : sql`true`))
21
+ export const like = (pattern: string) => new Op<string>((c) => sql`${c} like ${pattern}`)
22
+ export const ilike = (pattern: string) => new Op<string>((c) => sql`${c} ilike ${pattern}`)
23
+ // biome-ignore lint/suspicious/noExplicitAny: matches any column type
24
+ export const isNull = () => new Op<any>((c) => sql`${c} is null`)
25
+ // biome-ignore lint/suspicious/noExplicitAny: matches any column type
26
+ export const notNull = () => new Op<any>((c) => sql`${c} is not null`)
27
+ /** Negate an operator: `not(inList(['a', 'b']))`. */
28
+ export const not = <T>(op: Op<T>) => new Op<T>((c) => sql`not (${op.render(c)})`)
@@ -0,0 +1,28 @@
1
+ import { HEALTH_CHECKS, healthCheck, Logger, ServiceProvider } from '@cslug/core'
2
+ import { databaseCommands } from './commands'
3
+ import { Database, type DatabaseConfig } from './database'
4
+ import { setEncryptionKey } from './encryption'
5
+
6
+ /** Binds `Database` from `config('database')`, checks the connection at boot, closes the pool at shutdown. */
7
+ export class DatabaseProvider extends ServiceProvider {
8
+ register() {
9
+ this.commands(databaseCommands)
10
+ setEncryptionKey(this.app.config<string | undefined>('app.key'))
11
+ this.app.singleton(Database, (c) => {
12
+ const config = this.app.config<DatabaseConfig | undefined>('database')
13
+ if (!config?.url) throw new Error('config/database.ts must define `url` (usually env.DATABASE_URL)')
14
+ return new Database(config, c.resolve(Logger))
15
+ })
16
+ const check = healthCheck('database')
17
+ this.app.singleton(check, (c) => ({ name: 'database', check: () => c.resolve(Database).ping() }))
18
+ this.app.tag([check], HEALTH_CHECKS)
19
+ }
20
+
21
+ async boot() {
22
+ await this.app.resolve(Database).ping()
23
+ }
24
+
25
+ async shutdown() {
26
+ await this.app.resolve(Database).close()
27
+ }
28
+ }
package/src/query.ts ADDED
@@ -0,0 +1,234 @@
1
+ import { CslugError } from '@cslug/core'
2
+ import type { Database, Queryable } from './database'
3
+ import { Op } from './operators'
4
+ import { type SqlFragment, sql } from './sql'
5
+ import type { Row, Table } from './table'
6
+ import { writeValue } from './write'
7
+
8
+ /** `where` objects: a value (equality), `null` (IS NULL), or an operator. `undefined` keys are ignored. */
9
+ export type Where<T extends Table> = {
10
+ [K in keyof Row<T>]?: Row<T>[K] | Op<NonNullable<Row<T>[K]>> | (null extends Row<T>[K] ? null : never) | undefined
11
+ }
12
+
13
+ type Order = { key: string; dir: 'asc' | 'desc'; nulls?: 'first' | 'last' }
14
+ type Trashed = 'without' | 'with' | 'only'
15
+
16
+ export type Page<R> = { data: R[]; meta: { page: number; perPage: number; total: number; lastPage: number } }
17
+
18
+ /** Render a where object for a table (AND of its conditions). */
19
+ export function whereSql<T extends Table>(table: T, where: Where<T>): SqlFragment<unknown> | null {
20
+ const parts: SqlFragment<unknown>[] = []
21
+ for (const [key, value] of Object.entries(where)) {
22
+ if (value === undefined) continue
23
+ const column = (table.c as Record<string, unknown>)[key]
24
+ if (!column) throw new CslugError('db.unknown_column', `${table.name} has no column "${key}"`)
25
+ if (table.columns[key]?.def.encrypted) {
26
+ throw new CslugError(
27
+ 'db.encrypted_where',
28
+ `${table.name}.${key} is encrypted and cannot be used in a where condition`,
29
+ )
30
+ }
31
+ if (value === null) parts.push(sql`${column} is null`)
32
+ else if (value instanceof Op) parts.push(value.render(column))
33
+ else parts.push(sql`${column} = ${value}`)
34
+ }
35
+ return parts.length ? sql.join(parts, sql` and `) : null
36
+ }
37
+
38
+ /** A query on one table. Immutable: every method returns a new query. */
39
+ export class Query<T extends Table, R = Row<T>> {
40
+ constructor(
41
+ readonly table: T,
42
+ protected readonly source: () => Queryable & Pick<Database, 'current'>,
43
+ protected readonly state: {
44
+ ands: SqlFragment<unknown>[]
45
+ ors: SqlFragment<unknown>[][]
46
+ order: Order[]
47
+ limit?: number
48
+ offset?: number
49
+ columns?: string[]
50
+ lock?: 'update' | 'update skip locked' | 'update nowait'
51
+ trashed: Trashed
52
+ } = { ands: [], ors: [], order: [], trashed: 'without' },
53
+ ) {}
54
+
55
+ protected with<R2 = R>(patch: Partial<Query<T, R>['state']>): Query<T, R2> {
56
+ return new Query<T, R2>(this.table, this.source, { ...this.state, ...patch })
57
+ }
58
+
59
+ where(where: Where<T>): Query<T, R> {
60
+ const s = whereSql(this.table, where)
61
+ return s ? this.with({ ands: [...this.state.ands, s] }) : this
62
+ }
63
+
64
+ /** `(previous conditions) OR (these)`. */
65
+ orWhere(where: Where<T>): Query<T, R> {
66
+ const s = whereSql(this.table, where)
67
+ return s ? this.with({ ors: [...this.state.ors, [s]] }) : this
68
+ }
69
+
70
+ /** A raw condition when no operator fits: `.whereSql(sql\`${t.c.title} % ${q}\`)`. */
71
+ whereSql(condition: SqlFragment<unknown>): Query<T, R> {
72
+ return this.with({ ands: [...this.state.ands, condition] })
73
+ }
74
+
75
+ orderBy(
76
+ key: keyof Row<T> & string,
77
+ dir: 'asc' | 'desc' = 'asc',
78
+ options: { nulls?: 'first' | 'last' } = {},
79
+ ): Query<T, R> {
80
+ return this.with({ order: [...this.state.order, { key, dir, nulls: options.nulls }] })
81
+ }
82
+
83
+ limit(n: number): Query<T, R> {
84
+ return this.with({ limit: n })
85
+ }
86
+
87
+ offset(n: number): Query<T, R> {
88
+ return this.with({ offset: n })
89
+ }
90
+
91
+ /** Only some columns: the result type narrows to them. */
92
+ select<K extends keyof Row<T> & string>(...keys: K[]): Query<T, Pick<Row<T>, K>> {
93
+ return this.with<Pick<Row<T>, K>>({ columns: keys })
94
+ }
95
+
96
+ /** `SELECT … FOR UPDATE` (inside a transaction). */
97
+ lockForUpdate(options: { skipLocked?: boolean; noWait?: boolean } = {}): Query<T, R> {
98
+ return this.with({ lock: options.skipLocked ? 'update skip locked' : options.noWait ? 'update nowait' : 'update' })
99
+ }
100
+
101
+ /** Include soft-deleted rows. */
102
+ withTrashed(): Query<T, R> {
103
+ return this.with({ trashed: 'with' })
104
+ }
105
+
106
+ /** Only soft-deleted rows. */
107
+ onlyTrashed(): Query<T, R> {
108
+ return this.with({ trashed: 'only' })
109
+ }
110
+
111
+ /** The WHERE clause (with the soft-delete scope). */
112
+ protected conditions(): SqlFragment<unknown> | null {
113
+ const ands = [...this.state.ands]
114
+ if (this.table.softDeletes && this.state.trashed !== 'with') {
115
+ const deleted = (this.table.c as Record<string, unknown>).deletedAt
116
+ ands.push(this.state.trashed === 'only' ? sql`${deleted} is not null` : sql`${deleted} is null`)
117
+ }
118
+ const base = ands.length ? sql.join(ands, sql` and `) : null
119
+ if (!this.state.ors.length) return base
120
+ const groups = [...(base ? [base] : []), ...this.state.ors.map((g) => sql.join(g, sql` and `))]
121
+ return sql`(${sql.join(
122
+ groups.map((g) => sql`(${g})`),
123
+ sql` or `,
124
+ )})`
125
+ }
126
+
127
+ protected whereClause(): SqlFragment<unknown> {
128
+ const c = this.conditions()
129
+ return c ? sql` where ${c}` : sql.empty
130
+ }
131
+
132
+ /** The SELECT statement. */
133
+ toSql(): SqlFragment<unknown> {
134
+ const t = this.table
135
+ const cols = this.state.columns
136
+ ? sql.join(this.state.columns.map((k) => (t.c as Record<string, unknown>)[k]))
137
+ : t.star
138
+ const order = this.state.order.length
139
+ ? sql` order by ${sql.join(
140
+ this.state.order.map(
141
+ (o) =>
142
+ sql`${(t.c as Record<string, unknown>)[o.key]} ${sql.raw(o.dir)}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql.empty}`,
143
+ ),
144
+ )}`
145
+ : sql.empty
146
+ const limit = this.state.limit !== undefined ? sql` limit ${this.state.limit}` : sql.empty
147
+ const offset = this.state.offset !== undefined ? sql` offset ${this.state.offset}` : sql.empty
148
+ const lock = this.state.lock ? sql.raw(` for ${this.state.lock}`) : sql.empty
149
+ return sql`select ${cols} from ${t}${this.whereClause()}${order}${limit}${offset}${lock}`
150
+ }
151
+
152
+ private db() {
153
+ const db = this.source()
154
+ if (this.state.lock && !db.current) {
155
+ throw new CslugError('db.lock_outside_transaction', 'lockForUpdate() only makes sense inside db.transaction(…)')
156
+ }
157
+ return db
158
+ }
159
+
160
+ async all(): Promise<R[]> {
161
+ return (await this.db().many(this.toSql(), this.table)) as R[]
162
+ }
163
+
164
+ async first(): Promise<R | null> {
165
+ return ((await this.limit(1).all())[0] ?? null) as R | null
166
+ }
167
+
168
+ async count(): Promise<number> {
169
+ return Number(await this.source().value(sql`select count(*)::int from ${this.table}${this.whereClause()}`))
170
+ }
171
+
172
+ async exists(): Promise<boolean> {
173
+ return Boolean(await this.source().value(sql`select exists (select 1 from ${this.table}${this.whereClause()})`))
174
+ }
175
+
176
+ /** Update matching rows; `updatedAt` is refreshed. Returns the number of rows changed. */
177
+ async update(values: Partial<Row<T>>): Promise<number> {
178
+ const sets = setClause(this.table, values as Record<string, unknown>)
179
+ return this.source().exec(sql`update ${this.table} set ${sets}${this.whereClause()}`)
180
+ }
181
+
182
+ /** Delete matching rows (soft delete when the table has `deletedAt`). Returns the number of rows. */
183
+ async delete(): Promise<number> {
184
+ if (this.table.softDeletes) return this.update({ deletedAt: new Date() } as Partial<Row<T>>)
185
+ return this.forceDelete()
186
+ }
187
+
188
+ async forceDelete(): Promise<number> {
189
+ return this.source().exec(sql`delete from ${this.table}${this.whereClause()}`)
190
+ }
191
+
192
+ async paginate(page = 1, perPage = 20): Promise<Page<R>> {
193
+ const p = Math.max(1, Math.floor(page))
194
+ const total = await this.count()
195
+ const data = await this.limit(perPage)
196
+ .offset((p - 1) * perPage)
197
+ .all()
198
+ return { data, meta: { page: p, perPage, total, lastPage: Math.max(1, Math.ceil(total / perPage)) } }
199
+ }
200
+
201
+ /** Keyset pagination on one column (stable and fast on large tables). `next` feeds the following call. */
202
+ async cursor(options: {
203
+ after?: unknown
204
+ limit: number
205
+ orderBy?: keyof Row<T> & string
206
+ }): Promise<{ data: R[]; next: unknown }> {
207
+ const key = options.orderBy ?? (this.table.primaryKey as keyof Row<T> & string)
208
+ const column = (this.table.c as Record<string, unknown>)[key]
209
+ const q = options.after === undefined ? this : this.whereSql(sql`${column} > ${options.after}`)
210
+ const data = await q.orderBy(key).limit(options.limit).all()
211
+ const last = data.at(-1) as Record<string, unknown> | undefined
212
+ return { data, next: data.length === options.limit && last ? last[key] : null }
213
+ }
214
+
215
+ /** Stream every matching row, in batches (keyset on the primary key). */
216
+ async *each(options: { batch?: number } = {}): AsyncGenerator<R> {
217
+ let after: unknown
218
+ for (;;) {
219
+ const { data, next } = await this.cursor({ after, limit: options.batch ?? 500 })
220
+ yield* data
221
+ if (next === null) return
222
+ after = next
223
+ }
224
+ }
225
+ }
226
+
227
+ /** `col = $1, col2 = $2`, with `updatedAt` refreshed. */
228
+ export function setClause(table: Table, values: Record<string, unknown>): SqlFragment<unknown> {
229
+ const pairs = table.toDb(values)
230
+ const touched = Object.entries(table.columns).find(([k, c]) => c.def.touch && !(k in values))
231
+ if (touched) pairs.push([table.sqlNames.get(touched[0]) as string, new Date(), touched[1]])
232
+ if (!pairs.length) throw new CslugError('db.empty_update', `Nothing to update on ${table.name}`)
233
+ return sql.join(pairs.map(([name, value, column]) => sql`${sql.ident(name)} = ${writeValue(value, column)}`))
234
+ }
@@ -0,0 +1,79 @@
1
+ import { resolve } from '@cslug/core'
2
+ import { Database } from './database'
3
+ import { inList } from './operators'
4
+ import { Query } from './query'
5
+ import type { Row, Table } from './table'
6
+
7
+ type Relation<T extends Table, Many extends boolean> = {
8
+ table: T
9
+ /** Key on the rows being loaded (belongsTo) or on the related table (hasMany). */
10
+ key: string
11
+ many: Many
12
+ orderBy?: string
13
+ }
14
+
15
+ /** The row has `key` pointing at the related table's primary key: `belongsTo(operators, 'operatorId')`. */
16
+ export const belongsTo = <T extends Table>(table: T, foreignKey: string): Relation<T, false> => ({
17
+ table,
18
+ key: foreignKey,
19
+ many: false,
20
+ })
21
+
22
+ /** The related table has `key` pointing at the row's primary key: `hasMany(milestones, 'bookingId')`. */
23
+ export const hasMany = <T extends Table>(
24
+ table: T,
25
+ foreignKey: keyof Row<T> & string,
26
+ options: { orderBy?: keyof Row<T> & string } = {},
27
+ ): Relation<T, true> => ({
28
+ table,
29
+ key: foreignKey,
30
+ many: true,
31
+ orderBy: options.orderBy,
32
+ })
33
+
34
+ // biome-ignore lint/suspicious/noExplicitAny: any relation
35
+ type Relations = Record<string, Relation<any, boolean>>
36
+ type Loaded<R extends Relations> = {
37
+ [K in keyof R]: R[K] extends Relation<infer T, true>
38
+ ? Row<T>[]
39
+ : R[K] extends Relation<infer T, false>
40
+ ? Row<T> | null
41
+ : never
42
+ }
43
+
44
+ /**
45
+ * Load related rows for a list, one query per relation (no N+1):
46
+ *
47
+ * ```ts
48
+ * const rows = await preload(list, { operator: belongsTo(operators, 'operatorId'), milestones: hasMany(milestones, 'bookingId') })
49
+ * ```
50
+ */
51
+ export async function preload<Rw extends Record<string, unknown>, R extends Relations>(
52
+ rows: Rw[],
53
+ relations: R,
54
+ options: { primaryKey?: string; db?: Database } = {},
55
+ ): Promise<(Rw & Loaded<R>)[]> {
56
+ const db = options.db ?? resolve(Database)
57
+ const pk = options.primaryKey ?? 'id'
58
+ const out = rows.map((r) => ({ ...r })) as Record<string, unknown>[]
59
+ for (const [name, rel] of Object.entries(relations)) {
60
+ if (rel.many) {
61
+ const ids = [...new Set(rows.map((r) => r[pk]))]
62
+ let q = new Query(rel.table, () => db).where({ [rel.key]: inList(ids) })
63
+ if (rel.orderBy) q = q.orderBy(rel.orderBy as never)
64
+ const related = (await q.all()) as Record<string, unknown>[]
65
+ for (const row of out) row[name] = related.filter((x) => x[rel.key] === row[pk])
66
+ } else {
67
+ const ids = [...new Set(rows.map((r) => r[rel.key]).filter((v) => v !== null && v !== undefined))]
68
+ const related = ids.length
69
+ ? ((await new Query(rel.table, () => db).where({ [rel.table.primaryKey]: inList(ids) }).all()) as Record<
70
+ string,
71
+ unknown
72
+ >[])
73
+ : []
74
+ const byId = new Map(related.map((x) => [x[rel.table.primaryKey], x]))
75
+ for (const row of out) row[name] = byId.get(row[rel.key]) ?? null
76
+ }
77
+ }
78
+ return out as (Rw & Loaded<R>)[]
79
+ }