@cslug/database 0.0.0-stage → 0.2.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.
- package/README.md +7 -2
- package/docs/README.md +28 -0
- package/docs/api.md +153 -0
- package/package.json +31 -4
- package/src/columns.ts +169 -0
- package/src/commands.ts +186 -0
- package/src/database.ts +333 -0
- package/src/encryption.ts +44 -0
- package/src/errors.ts +40 -0
- package/src/factory.ts +112 -0
- package/src/fake.ts +115 -0
- package/src/index.ts +42 -0
- package/src/migrator.ts +194 -0
- package/src/operators.ts +28 -0
- package/src/provider.ts +28 -0
- package/src/query.ts +234 -0
- package/src/relations.ts +79 -0
- package/src/repository.ts +241 -0
- package/src/sql.ts +110 -0
- package/src/table.ts +135 -0
- package/src/write.ts +10 -0
- package/stubs/factory.stub +6 -0
- package/stubs/migration.create.stub +9 -0
- package/stubs/migration.stub +5 -0
- package/stubs/repository.stub +6 -0
- package/stubs/seeder.stub +5 -0
- package/stubs/table.stub +9 -0
package/src/database.ts
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { type Context, currentContext, Logger, runInContext, type TransactionHooks } from '@cslug/core'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { isRetryable, RowCountError, toQueryError } from './errors'
|
|
4
|
+
import { SqlFragment } from './sql'
|
|
5
|
+
import type { Row, Table } from './table'
|
|
6
|
+
|
|
7
|
+
export type DatabaseConfig = {
|
|
8
|
+
url: string
|
|
9
|
+
/**
|
|
10
|
+
* `max` connections for queries, and as many again for transactions (a separate pool that is only used
|
|
11
|
+
* through `reserve()`, see `transactionPool`).
|
|
12
|
+
*/
|
|
13
|
+
pool?: { max?: number; idleTimeout?: string | number; connectTimeout?: string | number }
|
|
14
|
+
/** Queries slower than this are logged as warnings (text only, never parameters). Default 200 ms. */
|
|
15
|
+
slowQueryMs?: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Driver = {
|
|
19
|
+
unsafe(text: string, params?: unknown[]): Promise<Record<string, unknown>[] & { count?: number }>
|
|
20
|
+
}
|
|
21
|
+
/** A connection reserved from the pool for one transaction. */
|
|
22
|
+
type Reserved = Driver & { release(): void }
|
|
23
|
+
|
|
24
|
+
const camel = (s: string) => s.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase())
|
|
25
|
+
const camelKeys = (row: Record<string, unknown>) =>
|
|
26
|
+
Object.fromEntries(Object.entries(row).map(([k, v]) => [camel(k), v]))
|
|
27
|
+
const seconds = (v: string | number | undefined, fallback: number) =>
|
|
28
|
+
v === undefined ? fallback : typeof v === 'number' ? v : Number.parseFloat(v) * (v.endsWith('ms') ? 0.001 : 1)
|
|
29
|
+
|
|
30
|
+
/** A value after a JSON round trip: bigint and Date become strings. What `idempotent()` returns. */
|
|
31
|
+
export type Json<T> = T extends bigint | Date
|
|
32
|
+
? string
|
|
33
|
+
: T extends (infer U)[]
|
|
34
|
+
? Json<U>[]
|
|
35
|
+
: T extends object
|
|
36
|
+
? { [K in keyof T]: Json<T[K]> }
|
|
37
|
+
: T
|
|
38
|
+
|
|
39
|
+
export type TransactionOptions = {
|
|
40
|
+
isolation?: 'read committed' | 'repeatable read' | 'serializable'
|
|
41
|
+
/** Retry the whole transaction this many times on serialization failures and deadlocks. */
|
|
42
|
+
retry?: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Query methods shared by the database and a transaction handle. */
|
|
46
|
+
export abstract class Queryable {
|
|
47
|
+
protected abstract driver(): Driver
|
|
48
|
+
protected abstract readonly log: Logger
|
|
49
|
+
protected abstract readonly slowQueryMs: number
|
|
50
|
+
|
|
51
|
+
/** Run a query; rows keyed in camelCase, or mapped and typed by `table`. */
|
|
52
|
+
async many<T>(query: SqlFragment<T>): Promise<T[]>
|
|
53
|
+
async many<T extends Table>(query: SqlFragment<unknown>, table: T): Promise<Row<T>[]>
|
|
54
|
+
async many(query: SqlFragment<unknown>, table?: Table): Promise<unknown[]> {
|
|
55
|
+
const rows = await this.run(query)
|
|
56
|
+
return table ? rows.map((r) => table.fromDb(r)) : rows.map(camelKeys)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Exactly one row, else `RowCountError`. */
|
|
60
|
+
async one<T>(query: SqlFragment<T>): Promise<T>
|
|
61
|
+
async one<T extends Table>(query: SqlFragment<unknown>, table: T): Promise<Row<T>>
|
|
62
|
+
async one(query: SqlFragment<unknown>, table?: Table): Promise<unknown> {
|
|
63
|
+
const rows = table ? await this.many(query, table) : await this.many(query)
|
|
64
|
+
if (rows.length !== 1) throw new RowCountError('db.row_count', `Expected exactly one row, got ${rows.length}`)
|
|
65
|
+
return rows[0]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The first row, or null. */
|
|
69
|
+
async maybeOne<T>(query: SqlFragment<T>): Promise<T | null>
|
|
70
|
+
async maybeOne<T extends Table>(query: SqlFragment<unknown>, table: T): Promise<Row<T> | null>
|
|
71
|
+
async maybeOne(query: SqlFragment<unknown>, table?: Table): Promise<unknown> {
|
|
72
|
+
const rows = table ? await this.many(query, table) : await this.many(query)
|
|
73
|
+
return rows[0] ?? null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The first column of the first row (or undefined). */
|
|
77
|
+
async value<T = unknown>(query: SqlFragment<unknown>): Promise<T | undefined> {
|
|
78
|
+
const [row] = await this.run(query)
|
|
79
|
+
return row ? (Object.values(row)[0] as T) : undefined
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A statement without rows; returns the affected row count. */
|
|
83
|
+
async exec(query: SqlFragment<unknown>): Promise<number> {
|
|
84
|
+
const result = await this.run(query)
|
|
85
|
+
return Number(result.count ?? result.length)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
protected async run(query: SqlFragment<unknown>): Promise<Record<string, unknown>[] & { count?: number }> {
|
|
89
|
+
const { text, params } = query.compile()
|
|
90
|
+
const started = performance.now()
|
|
91
|
+
try {
|
|
92
|
+
return await this.driver().unsafe(text, params)
|
|
93
|
+
} catch (error) {
|
|
94
|
+
throw toQueryError(error, text)
|
|
95
|
+
} finally {
|
|
96
|
+
const ms = performance.now() - started
|
|
97
|
+
if (ms > this.slowQueryMs) this.log.warn('slow query', { ms: Math.round(ms), sql: text })
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** An open transaction (or savepoint). Its `afterCommit` hooks run only if the outermost transaction commits. */
|
|
103
|
+
export class Transaction extends Queryable implements TransactionHooks {
|
|
104
|
+
readonly hooks: (() => unknown)[] = []
|
|
105
|
+
|
|
106
|
+
constructor(
|
|
107
|
+
readonly handle: Driver,
|
|
108
|
+
protected readonly log: Logger,
|
|
109
|
+
protected readonly slowQueryMs: number,
|
|
110
|
+
readonly depth = 0,
|
|
111
|
+
) {
|
|
112
|
+
super()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
protected driver(): Driver {
|
|
116
|
+
return this.handle
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
afterCommit(fn: () => unknown): void {
|
|
120
|
+
this.hooks.push(fn)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The database: a `Bun.sql` connection pool. Queries run on the **current transaction** when one is open
|
|
126
|
+
* (ambient, through the async context), else on the pool.
|
|
127
|
+
*/
|
|
128
|
+
export class Database extends Queryable {
|
|
129
|
+
readonly pool: SQL
|
|
130
|
+
/**
|
|
131
|
+
* Transactions get connections from their own pool, only ever through `reserve()`. Bun.sql (1.3.14) can,
|
|
132
|
+
* while a pool opens its connections under concurrency, run a plain pooled query on a connection that is
|
|
133
|
+
* reserved for a transaction: the query lands inside someone else's transaction and both stall ("idle in
|
|
134
|
+
* transaction"). With no plain queries in this pool, that cannot happen. See docs/open-questions.md.
|
|
135
|
+
*/
|
|
136
|
+
readonly transactionPool: SQL
|
|
137
|
+
protected readonly slowQueryMs: number
|
|
138
|
+
|
|
139
|
+
constructor(
|
|
140
|
+
readonly config: DatabaseConfig,
|
|
141
|
+
protected readonly log: Logger = Logger.null(),
|
|
142
|
+
) {
|
|
143
|
+
super()
|
|
144
|
+
this.slowQueryMs = config.slowQueryMs ?? 200
|
|
145
|
+
const options = {
|
|
146
|
+
bigint: true, // int8 as bigint (money!), not strings
|
|
147
|
+
max: config.pool?.max ?? 10,
|
|
148
|
+
idleTimeout: seconds(config.pool?.idleTimeout, 30),
|
|
149
|
+
connectionTimeout: seconds(config.pool?.connectTimeout, 5),
|
|
150
|
+
}
|
|
151
|
+
this.pool = new SQL(config.url, options)
|
|
152
|
+
this.transactionPool = new SQL(config.url, options)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Set by `pin()` (the test kit): queries without an ambient transaction use it. */
|
|
156
|
+
private pinned?: Transaction
|
|
157
|
+
|
|
158
|
+
/** The transaction open in the current context, else the pinned one, if any. */
|
|
159
|
+
get current(): Transaction | undefined {
|
|
160
|
+
const tx = currentContext()?.tx
|
|
161
|
+
return tx instanceof Transaction ? tx : this.pinned
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Open a transaction that stays open until `release()`, and route every query that has no ambient transaction
|
|
166
|
+
* to it. `release()` rolls it back. The test kit pins one per test, so tests never leave data behind.
|
|
167
|
+
* Nested `transaction()` calls become savepoints, and their `afterCommit` hooks run when the savepoint is
|
|
168
|
+
* released (as if committed), so after-commit behaviour stays testable.
|
|
169
|
+
*/
|
|
170
|
+
async pin(): Promise<{ release(): Promise<void> }> {
|
|
171
|
+
if (this.pinned) throw new Error('A transaction is already pinned')
|
|
172
|
+
const conn = (await this.transactionPool.reserve()) as unknown as Reserved
|
|
173
|
+
await conn.unsafe('begin')
|
|
174
|
+
this.pinned = new Transaction(conn, this.log, this.slowQueryMs)
|
|
175
|
+
return {
|
|
176
|
+
release: async () => {
|
|
177
|
+
this.pinned = undefined
|
|
178
|
+
try {
|
|
179
|
+
await conn.unsafe('rollback')
|
|
180
|
+
} finally {
|
|
181
|
+
conn.release()
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
protected driver(): Driver {
|
|
188
|
+
return (this.current?.handle ?? this.pool) as unknown as Driver
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Fails if the database is unreachable (used by the provider's boot and `/health/ready`). */
|
|
192
|
+
async ping(): Promise<void> {
|
|
193
|
+
await this.run(new SqlFragment(['select 1'], []))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Run `fn` in a transaction. Repositories and `db` calls inside it use the transaction automatically; a throw
|
|
198
|
+
* rolls back. Nested calls are savepoints. `afterCommit` hooks (jobs, queued listeners, mail) run after the
|
|
199
|
+
* outermost commit, and never on rollback.
|
|
200
|
+
*/
|
|
201
|
+
async transaction<T>(fn: (tx: Transaction) => Promise<T> | T, options: TransactionOptions = {}): Promise<T> {
|
|
202
|
+
const parent = this.current
|
|
203
|
+
const ctx = currentContext()
|
|
204
|
+
const enter = (tx: Transaction) => runInContext({ ...(ctx ?? {}), tx } as Context, () => fn(tx))
|
|
205
|
+
if (parent) return this.savepoint(parent, enter)
|
|
206
|
+
|
|
207
|
+
for (let attempt = 0; ; attempt++) {
|
|
208
|
+
// a connection of the transaction pool, with explicit BEGIN/COMMIT (see `transactionPool`)
|
|
209
|
+
const conn = (await this.transactionPool.reserve()) as unknown as Reserved
|
|
210
|
+
let tx: Transaction | undefined
|
|
211
|
+
let committed = false
|
|
212
|
+
try {
|
|
213
|
+
await conn.unsafe(options.isolation ? `begin isolation level ${options.isolation}` : 'begin')
|
|
214
|
+
tx = new Transaction(conn, this.log, this.slowQueryMs)
|
|
215
|
+
const result = await enter(tx)
|
|
216
|
+
await conn.unsafe('commit')
|
|
217
|
+
committed = true
|
|
218
|
+
conn.release()
|
|
219
|
+
await this.runHooks(tx)
|
|
220
|
+
return result
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (!committed) {
|
|
223
|
+
await conn.unsafe('rollback').catch(() => {})
|
|
224
|
+
conn.release()
|
|
225
|
+
}
|
|
226
|
+
if (!committed && attempt < (options.retry ?? 0) && isRetryable(error)) continue
|
|
227
|
+
throw error
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private savepoints = 0
|
|
233
|
+
|
|
234
|
+
/** A nested transaction: a savepoint on the parent's connection. */
|
|
235
|
+
private async savepoint<T>(parent: Transaction, enter: (tx: Transaction) => Promise<T> | T): Promise<T> {
|
|
236
|
+
const name = `cslug_sp_${++this.savepoints}`
|
|
237
|
+
await parent.handle.unsafe(`savepoint ${name}`)
|
|
238
|
+
const child = new Transaction(parent.handle, this.log, this.slowQueryMs, parent.depth + 1)
|
|
239
|
+
let result: T
|
|
240
|
+
try {
|
|
241
|
+
result = await enter(child)
|
|
242
|
+
} catch (error) {
|
|
243
|
+
await parent.handle.unsafe(`rollback to savepoint ${name}`).catch(() => {})
|
|
244
|
+
await parent.handle.unsafe(`release savepoint ${name}`).catch(() => {})
|
|
245
|
+
throw error
|
|
246
|
+
}
|
|
247
|
+
await parent.handle.unsafe(`release savepoint ${name}`)
|
|
248
|
+
// a released savepoint's hooks belong to the parent, except under a pin, where it counts as committed
|
|
249
|
+
if (parent === this.pinned) await this.runHooks(child)
|
|
250
|
+
else parent.hooks.push(...child.hooks)
|
|
251
|
+
return result
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private async runHooks(tx: Transaction | undefined): Promise<void> {
|
|
255
|
+
if (!tx) return
|
|
256
|
+
const ctx = currentContext()
|
|
257
|
+
for (const hook of tx.hooks) {
|
|
258
|
+
try {
|
|
259
|
+
// outside the (now finished) transaction
|
|
260
|
+
await runInContext({ ...(ctx ?? {}), tx: undefined } as Context, async () => hook())
|
|
261
|
+
} catch (error) {
|
|
262
|
+
this.log.error('afterCommit hook failed (the transaction is committed)', { error })
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Run `fn` outside the current transaction (e.g. an audit log that must survive a rollback). */
|
|
268
|
+
withoutTransaction<T>(fn: () => T): T {
|
|
269
|
+
const ctx = currentContext()
|
|
270
|
+
return ctx ? runInContext({ ...ctx, tx: undefined }, fn) : fn()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* A cluster-wide mutex in Postgres: only one holder of `key` at a time, across all app instances. Inside a
|
|
275
|
+
* transaction the lock lasts until it ends; outside, a dedicated connection holds it while `fn` runs.
|
|
276
|
+
*/
|
|
277
|
+
async advisoryLock<T>(key: string, fn: () => Promise<T> | T): Promise<T> {
|
|
278
|
+
const tx = this.current
|
|
279
|
+
if (tx) {
|
|
280
|
+
await tx.exec(new SqlFragment(['select pg_advisory_xact_lock(hashtextextended(', ', 0))'], [key]))
|
|
281
|
+
return fn()
|
|
282
|
+
}
|
|
283
|
+
const conn = await this.transactionPool.reserve() // reserve-only pool (see transactionPool)
|
|
284
|
+
try {
|
|
285
|
+
await conn.unsafe('select pg_advisory_lock(hashtextextended($1, 0))', [key])
|
|
286
|
+
try {
|
|
287
|
+
return await fn()
|
|
288
|
+
} finally {
|
|
289
|
+
await conn.unsafe('select pg_advisory_unlock(hashtextextended($1, 0))', [key])
|
|
290
|
+
}
|
|
291
|
+
} finally {
|
|
292
|
+
conn.release()
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Run `fn` once per key: the first result is stored as JSON and returned to every call with the same key,
|
|
298
|
+
* the first one included, so the shape is always the same (`Json<T>`: bigint and Date as strings).
|
|
299
|
+
* Concurrent calls wait for each other (advisory lock). Inside a transaction, the record commits or rolls back
|
|
300
|
+
* with your changes. Needs the framework migration `cslug_idempotency` (run by `cslug migrate`).
|
|
301
|
+
*
|
|
302
|
+
* ```ts
|
|
303
|
+
* const transfer = await db.idempotent(`release:${bookingId}:1`, () => gateway.release(…))
|
|
304
|
+
* ```
|
|
305
|
+
*/
|
|
306
|
+
async idempotent<T>(key: string, fn: () => Promise<T> | T, options: { scope?: string } = {}): Promise<Json<T>> {
|
|
307
|
+
const scope = options.scope ?? 'default'
|
|
308
|
+
return this.advisoryLock(`idempotent:${scope}:${key}`, async () => {
|
|
309
|
+
const existing = await this.maybeOne(
|
|
310
|
+
new SqlFragment<{ result: Json<T> }>(
|
|
311
|
+
['select result from cslug_idempotency where scope = ', ' and key = ', ''],
|
|
312
|
+
[scope, key],
|
|
313
|
+
),
|
|
314
|
+
)
|
|
315
|
+
if (existing) return existing.result
|
|
316
|
+
const result = await fn()
|
|
317
|
+
const json = JSON.stringify(result === undefined ? null : result, (_k, v) =>
|
|
318
|
+
typeof v === 'bigint' ? v.toString() : v,
|
|
319
|
+
)
|
|
320
|
+
await this.exec(
|
|
321
|
+
new SqlFragment(
|
|
322
|
+
['insert into cslug_idempotency (scope, key, result) values (', ', ', ', (', '::text)::jsonb)'],
|
|
323
|
+
[scope, key, json],
|
|
324
|
+
),
|
|
325
|
+
)
|
|
326
|
+
return JSON.parse(json) as Json<T>
|
|
327
|
+
})
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async close(): Promise<void> {
|
|
331
|
+
await Promise.all([this.pool.close(), this.transactionPool.close()])
|
|
332
|
+
}
|
|
333
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
|
|
2
|
+
import { CslugError } from '@cslug/core'
|
|
3
|
+
|
|
4
|
+
let key: Buffer | undefined
|
|
5
|
+
|
|
6
|
+
/** Set the encryption key from `APP_KEY` (DatabaseProvider does this at register). */
|
|
7
|
+
export function setEncryptionKey(appKey: string | undefined): void {
|
|
8
|
+
key = appKey ? createHash('sha256').update(appKey).digest() : undefined
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const requireKey = (): Buffer => {
|
|
12
|
+
if (!key)
|
|
13
|
+
throw new CslugError(
|
|
14
|
+
'db.no_encryption_key',
|
|
15
|
+
'Encrypted columns need APP_KEY (config app.key). Run `cslug key:generate`.',
|
|
16
|
+
)
|
|
17
|
+
return key
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** AES-256-GCM with a random IV: `v1.<iv>.<tag>.<ciphertext>` (base64url). */
|
|
21
|
+
export function encrypt(plain: string): string {
|
|
22
|
+
const iv = randomBytes(12)
|
|
23
|
+
const cipher = createCipheriv('aes-256-gcm', requireKey(), iv)
|
|
24
|
+
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()])
|
|
25
|
+
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join(
|
|
26
|
+
'.',
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Reverse of `encrypt()`; throws `db.decrypt_failed` on a tampered value or a wrong APP_KEY. */
|
|
31
|
+
export function decrypt(stored: string): string {
|
|
32
|
+
const [version, iv, tag, data] = stored.split('.')
|
|
33
|
+
if (version !== 'v1' || !iv || !tag || data === undefined)
|
|
34
|
+
throw new CslugError('db.decrypt_failed', 'Not an encrypted value')
|
|
35
|
+
try {
|
|
36
|
+
const decipher = createDecipheriv('aes-256-gcm', requireKey(), Buffer.from(iv, 'base64url'))
|
|
37
|
+
decipher.setAuthTag(Buffer.from(tag, 'base64url'))
|
|
38
|
+
return Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString('utf8')
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new CslugError('db.decrypt_failed', 'Could not decrypt a value (wrong APP_KEY, or the value was altered)', {
|
|
41
|
+
cause: error,
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** A query failed. `sqlState` is the Postgres error code; the original error is the `cause`. */
|
|
4
|
+
export class QueryError extends CslugError {
|
|
5
|
+
constructor(
|
|
6
|
+
code: string,
|
|
7
|
+
message: string,
|
|
8
|
+
readonly sqlState?: string,
|
|
9
|
+
readonly constraint?: string,
|
|
10
|
+
options?: { cause?: unknown },
|
|
11
|
+
) {
|
|
12
|
+
super(code, message, options)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 23505: a unique constraint was violated (`constraint` names it). */
|
|
17
|
+
export class UniqueViolationError extends QueryError {}
|
|
18
|
+
|
|
19
|
+
/** 40001 / 40P01: retryable; `db.transaction(fn, { retry })` retries these. */
|
|
20
|
+
export class SerializationError extends QueryError {}
|
|
21
|
+
|
|
22
|
+
/** `db.one()` found no row (or more than one). */
|
|
23
|
+
export class RowCountError extends CslugError {}
|
|
24
|
+
|
|
25
|
+
const RETRYABLE = new Set(['40001', '40P01'])
|
|
26
|
+
/** Serialization failure or deadlock (40001, 40P01): the transaction can be run again. */
|
|
27
|
+
export const isRetryable = (e: unknown) =>
|
|
28
|
+
e instanceof SerializationError || RETRYABLE.has((e as { errno?: string })?.errno ?? '')
|
|
29
|
+
|
|
30
|
+
/** Wrap a driver error in a typed error. The SQL text is kept for logs; parameters never are. */
|
|
31
|
+
export function toQueryError(error: unknown, text: string): Error {
|
|
32
|
+
const e = error as { errno?: string; constraint?: string; message?: string }
|
|
33
|
+
const state = e?.errno
|
|
34
|
+
const message = `${e?.message ?? String(error)} (query: ${text.length > 300 ? `${text.slice(0, 300)}…` : text})`
|
|
35
|
+
if (state === '23505')
|
|
36
|
+
return new UniqueViolationError('db.unique_violation', message, state, e.constraint, { cause: error })
|
|
37
|
+
if (state && RETRYABLE.has(state))
|
|
38
|
+
return new SerializationError('db.serialization_failure', message, state, undefined, { cause: error })
|
|
39
|
+
return new QueryError('db.query_failed', message, state, e?.constraint, { cause: error })
|
|
40
|
+
}
|
package/src/factory.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Clock, currentApp, resolve } from '@cslug/core'
|
|
2
|
+
import { Database } from './database'
|
|
3
|
+
import { Fake } from './fake'
|
|
4
|
+
import { Repository } from './repository'
|
|
5
|
+
import type { NewRow, Row, Table } from './table'
|
|
6
|
+
|
|
7
|
+
export type FactoryContext = { seq: number; fake: Fake; clock: Clock }
|
|
8
|
+
|
|
9
|
+
/** Attribute values; a function is called at build time (and may be async, e.g. to create a parent row). */
|
|
10
|
+
export type FactoryValues<T extends Table> = {
|
|
11
|
+
[K in keyof NewRow<T>]?: NewRow<T>[K] | (() => NewRow<T>[K] | Promise<NewRow<T>[K]>)
|
|
12
|
+
}
|
|
13
|
+
type Definition<T extends Table> = FactoryValues<T> | ((ctx: FactoryContext) => FactoryValues<T>)
|
|
14
|
+
|
|
15
|
+
const sequences = new Map<string, number>()
|
|
16
|
+
const fake = new Fake()
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Test data for a table:
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* export const OperatorFactory = factory(operators, ({ seq, fake }) => ({ companyName: `Operator ${seq}`, phone: fake.phone('MG') }))
|
|
23
|
+
* .state('verified', { verificationStatus: 'verified' })
|
|
24
|
+
* await OperatorFactory.state('verified').createMany(12)
|
|
25
|
+
* await TodoFactory.for({ userId: me.id }).create({ title: 'Buy bread' })
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export class Factory<T extends Table> {
|
|
29
|
+
constructor(
|
|
30
|
+
readonly table: T,
|
|
31
|
+
private readonly base: Definition<T>,
|
|
32
|
+
private readonly states: ReadonlyMap<string, Definition<T>> = new Map(),
|
|
33
|
+
private readonly applied: readonly Definition<T>[] = [],
|
|
34
|
+
private readonly database?: Database,
|
|
35
|
+
) {}
|
|
36
|
+
|
|
37
|
+
/** `state(name, values)` defines a state; `state(name)` applies it. States combine. */
|
|
38
|
+
state(name: string, definition?: Definition<T>): Factory<T> {
|
|
39
|
+
if (definition !== undefined) {
|
|
40
|
+
return new Factory(
|
|
41
|
+
this.table,
|
|
42
|
+
this.base,
|
|
43
|
+
new Map([...this.states, [name, definition]]),
|
|
44
|
+
this.applied,
|
|
45
|
+
this.database,
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
const found = this.states.get(name)
|
|
49
|
+
if (!found)
|
|
50
|
+
throw new Error(
|
|
51
|
+
`${this.table.name} factory has no state "${name}" (defined: ${[...this.states.keys()].join(', ') || 'none'})`,
|
|
52
|
+
)
|
|
53
|
+
return new Factory(this.table, this.base, this.states, [...this.applied, found], this.database)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Fixed attributes for every row: `.for({ userId: me.id })`. */
|
|
57
|
+
for(values: FactoryValues<T>): Factory<T> {
|
|
58
|
+
return new Factory(this.table, this.base, this.states, [...this.applied, values], this.database)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Use a specific database instead of the current app's. */
|
|
62
|
+
on(db: Database): Factory<T> {
|
|
63
|
+
return new Factory(this.table, this.base, this.states, this.applied, db)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Build the attributes without saving. */
|
|
67
|
+
async make(overrides: FactoryValues<T> = {}): Promise<NewRow<T>> {
|
|
68
|
+
const seq = (sequences.get(this.table.name) ?? 0) + 1
|
|
69
|
+
sequences.set(this.table.name, seq)
|
|
70
|
+
const ctx: FactoryContext = { seq, fake, clock: clockOrDefault() }
|
|
71
|
+
const layers = [this.base, ...this.applied, overrides].map((d) => (typeof d === 'function' ? d(ctx) : d))
|
|
72
|
+
const merged: Record<string, unknown> = Object.assign({}, ...layers)
|
|
73
|
+
for (const [k, v] of Object.entries(merged)) if (typeof v === 'function') merged[k] = await (v as () => unknown)()
|
|
74
|
+
return merged as NewRow<T>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async create(overrides: FactoryValues<T> = {}): Promise<Row<T>> {
|
|
78
|
+
return this.repository().create(await this.make(overrides))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async createMany(count: number, overrides: FactoryValues<T> = {}): Promise<Row<T>[]> {
|
|
82
|
+
const rows: Row<T>[] = []
|
|
83
|
+
for (let i = 0; i < count; i++) rows.push(await this.create(overrides))
|
|
84
|
+
return rows
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private repository() {
|
|
88
|
+
const db = this.database ?? resolve(Database)
|
|
89
|
+
const Repo = Repository(this.table)
|
|
90
|
+
const repo = Object.create((Repo as unknown as { prototype: object }).prototype) as InstanceType<typeof Repo>
|
|
91
|
+
Object.assign(repo, { table: this.table, db })
|
|
92
|
+
return repo
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const clockOrDefault = (): Clock => {
|
|
97
|
+
try {
|
|
98
|
+
return currentApp().resolve(Clock)
|
|
99
|
+
} catch {
|
|
100
|
+
return new Clock()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** `factory(users, ({ seq, fake }) => ({ … }))`: builds and inserts test rows (guide 09). */
|
|
105
|
+
export const factory = <T extends Table>(table: T, definition: Definition<T>) => new Factory(table, definition)
|
|
106
|
+
|
|
107
|
+
/** Seeders: `export default seeder(async () => { … })`, run by `cslug db:seed`. */
|
|
108
|
+
export const SEEDER: unique symbol = Symbol('cslug.seeder')
|
|
109
|
+
export type Seeder = { [SEEDER]: true; run: () => Promise<void> | void }
|
|
110
|
+
export const seeder = (run: () => Promise<void> | void): Seeder => ({ [SEEDER]: true, run })
|
|
111
|
+
export const isSeeder = (value: unknown): value is Seeder =>
|
|
112
|
+
typeof value === 'object' && value !== null && SEEDER in value
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small, deterministic fake-data generator for factories (seeded PRNG: the same seed gives the same data).
|
|
3
|
+
* Deliberately small; add what your tests need with plain functions.
|
|
4
|
+
*/
|
|
5
|
+
const FIRST = ['Ada', 'Rova', 'Giulia', 'Hery', 'Camille', 'Lova', 'Marco', 'Fara', 'Sofia', 'Tiana', 'Luca', 'Noa']
|
|
6
|
+
const LAST = ['Rakoto', 'Rossi', 'Martin', 'Rasoa', 'Bianchi', 'Dubois', 'Randria', 'Ferrari', 'Bernard', 'Andria']
|
|
7
|
+
const WORDS = [
|
|
8
|
+
'baobab',
|
|
9
|
+
'lemur',
|
|
10
|
+
'tsingy',
|
|
11
|
+
'zebu',
|
|
12
|
+
'vanilla',
|
|
13
|
+
'reef',
|
|
14
|
+
'canyon',
|
|
15
|
+
'forest',
|
|
16
|
+
'river',
|
|
17
|
+
'island',
|
|
18
|
+
'road',
|
|
19
|
+
'trail',
|
|
20
|
+
'coast',
|
|
21
|
+
'village',
|
|
22
|
+
'market',
|
|
23
|
+
]
|
|
24
|
+
const COMPANY = ['Tours', 'Trails', 'Travel', 'Expeditions', 'Drive', 'Adventures']
|
|
25
|
+
const MOBILE: Record<string, [string, string[]]> = {
|
|
26
|
+
MG: ['+261', ['32', '33', '34', '38']],
|
|
27
|
+
FR: ['+33', ['6', '7']],
|
|
28
|
+
IT: ['+39', ['347', '333', '320']],
|
|
29
|
+
GB: ['+44', ['7']],
|
|
30
|
+
US: ['+1', ['202', '415']],
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const hashCache = new Map<string, string>()
|
|
34
|
+
|
|
35
|
+
/** The generator: `new Fake(seed)`; factories share one seeded at 42. */
|
|
36
|
+
export class Fake {
|
|
37
|
+
private state: number
|
|
38
|
+
|
|
39
|
+
constructor(seed = 42) {
|
|
40
|
+
this.state = seed >>> 0
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
seed(seed: number): this {
|
|
44
|
+
this.state = seed >>> 0
|
|
45
|
+
return this
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A float in [0, 1) (mulberry32). */
|
|
49
|
+
random(): number {
|
|
50
|
+
this.state = (this.state + 0x6d2b79f5) >>> 0
|
|
51
|
+
let t = this.state
|
|
52
|
+
t = Math.imul(t ^ (t >>> 15), t | 1)
|
|
53
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
|
54
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
int(min = 0, max = 1000): number {
|
|
58
|
+
return min + Math.floor(this.random() * (max - min + 1))
|
|
59
|
+
}
|
|
60
|
+
bool(): boolean {
|
|
61
|
+
return this.random() < 0.5
|
|
62
|
+
}
|
|
63
|
+
pick<T>(items: readonly T[]): T {
|
|
64
|
+
return items[Math.floor(this.random() * items.length)] as T
|
|
65
|
+
}
|
|
66
|
+
digits(n: number): string {
|
|
67
|
+
return Array.from({ length: n }, () => this.int(0, 9)).join('')
|
|
68
|
+
}
|
|
69
|
+
firstName(): string {
|
|
70
|
+
return this.pick(FIRST)
|
|
71
|
+
}
|
|
72
|
+
lastName(): string {
|
|
73
|
+
return this.pick(LAST)
|
|
74
|
+
}
|
|
75
|
+
name(): string {
|
|
76
|
+
return `${this.firstName()} ${this.lastName()}`
|
|
77
|
+
}
|
|
78
|
+
company(): string {
|
|
79
|
+
return `${this.pick(WORDS).replace(/^./, (c) => c.toUpperCase())} ${this.pick(COMPANY)}`
|
|
80
|
+
}
|
|
81
|
+
word(): string {
|
|
82
|
+
return this.pick(WORDS)
|
|
83
|
+
}
|
|
84
|
+
words(n: number): string {
|
|
85
|
+
return Array.from({ length: n }, () => this.word()).join(' ')
|
|
86
|
+
}
|
|
87
|
+
sentence(words = 6): string {
|
|
88
|
+
const s = this.words(words)
|
|
89
|
+
return `${s.charAt(0).toUpperCase()}${s.slice(1)}.`
|
|
90
|
+
}
|
|
91
|
+
email(): string {
|
|
92
|
+
return `${this.firstName().toLowerCase()}.${this.lastName().toLowerCase()}${this.int(1, 999)}@example.test`
|
|
93
|
+
}
|
|
94
|
+
/** A plausible mobile number in E.164 for MG, FR, IT, GB or US. */
|
|
95
|
+
phone(country: keyof typeof MOBILE | string = 'MG'): string {
|
|
96
|
+
const [code, prefixes] = MOBILE[country] ?? (MOBILE.MG as [string, string[]])
|
|
97
|
+
const prefix = this.pick(prefixes)
|
|
98
|
+
return `${code}${prefix}${this.digits(9 - prefix.length + (code === '+1' ? 1 : 0))}`
|
|
99
|
+
}
|
|
100
|
+
/** `'YYYY-MM-DD'` between two dates (inclusive). */
|
|
101
|
+
date(from = '2027-01-01', to = '2027-12-31'): string {
|
|
102
|
+
const a = Date.parse(`${from}T00:00:00Z`)
|
|
103
|
+
const b = Date.parse(`${to}T00:00:00Z`)
|
|
104
|
+
return new Date(a + Math.floor(this.random() * ((b - a) / 86_400_000 + 1)) * 86_400_000).toISOString().slice(0, 10)
|
|
105
|
+
}
|
|
106
|
+
/** An argon2id hash of `plain`, cheap parameters, cached (for test users). */
|
|
107
|
+
passwordHash(plain: string): string {
|
|
108
|
+
let hash = hashCache.get(plain)
|
|
109
|
+
if (!hash) {
|
|
110
|
+
hash = Bun.password.hashSync(plain, { algorithm: 'argon2id', memoryCost: 1024, timeCost: 1 })
|
|
111
|
+
hashCache.set(plain, hash)
|
|
112
|
+
}
|
|
113
|
+
return hash
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/database: PostgreSQL on Bun.sql. Typed tables, the `sql` tag, ambient transactions, advisory locks,
|
|
3
|
+
* the single-table query builder, repositories, preload, migrations, factories, seeders and encrypted columns.
|
|
4
|
+
*/
|
|
5
|
+
export {
|
|
6
|
+
type AnyColumn,
|
|
7
|
+
amount,
|
|
8
|
+
bigint,
|
|
9
|
+
boolean,
|
|
10
|
+
Column,
|
|
11
|
+
type ColumnDef,
|
|
12
|
+
type ColumnKind,
|
|
13
|
+
currency,
|
|
14
|
+
date,
|
|
15
|
+
id,
|
|
16
|
+
integer,
|
|
17
|
+
jsonb,
|
|
18
|
+
numeric,
|
|
19
|
+
shortCode,
|
|
20
|
+
softDeletes,
|
|
21
|
+
TextColumn,
|
|
22
|
+
text,
|
|
23
|
+
timestamp,
|
|
24
|
+
timestamps,
|
|
25
|
+
translated,
|
|
26
|
+
uuid,
|
|
27
|
+
varchar,
|
|
28
|
+
} from './columns'
|
|
29
|
+
export { DbSeedCommand, databaseCommands, MigrateCommand } from './commands'
|
|
30
|
+
export { Database, type DatabaseConfig, type Json, Queryable, Transaction, type TransactionOptions } from './database'
|
|
31
|
+
export { decrypt, encrypt, setEncryptionKey } from './encryption'
|
|
32
|
+
export { isRetryable, QueryError, RowCountError, SerializationError, UniqueViolationError } from './errors'
|
|
33
|
+
export { Factory, type FactoryContext, type FactoryValues, factory, isSeeder, type Seeder, seeder } from './factory'
|
|
34
|
+
export { Fake } from './fake'
|
|
35
|
+
export { addMigrations, FRAMEWORK_MIGRATIONS, type MigrationStatus, Migrator, parseMigration } from './migrator'
|
|
36
|
+
export { between, eq, gt, gte, ilike, inList, isNull, like, lt, lte, ne, not, notIn, notNull, Op } from './operators'
|
|
37
|
+
export { DatabaseProvider } from './provider'
|
|
38
|
+
export { type Page, Query, type Where } from './query'
|
|
39
|
+
export { belongsTo, hasMany, preload } from './relations'
|
|
40
|
+
export { Repository, type RepositoryApi } from './repository'
|
|
41
|
+
export { JsonParam, quote, Raw, SqlFragment, type SqlIdentifier, sql } from './sql'
|
|
42
|
+
export { type ColumnRef, type Columns, type IndexDef, type NewRow, type Row, snake, Table, table } from './table'
|