@hamur/db 0.0.0-stage → 0.0.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 (125) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
  4. package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
  5. package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
  6. package/dist/chunks/browser-d1-a16d23f0.js +8 -0
  7. package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
  8. package/dist/chunks/browser-index-kf697bfy.js +113 -0
  9. package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
  10. package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
  11. package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
  12. package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
  13. package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
  14. package/dist/chunks/bun-index-06tj00dn.js +11 -0
  15. package/dist/chunks/bun-index-9na2zkqq.js +224 -0
  16. package/dist/chunks/bun-index-b47nngck.js +352 -0
  17. package/dist/chunks/bun-index-hrx1eqma.js +29 -0
  18. package/dist/chunks/bun-index-pd6k99dv.js +114 -0
  19. package/dist/src/cli.js +1692 -0
  20. package/dist/src/devtools.js +153 -0
  21. package/dist/src/index.js +1491 -0
  22. package/dist/src/server/index.js +584 -0
  23. package/dist/src/storage/define.js +7 -0
  24. package/dist/types/src/build/connections.d.ts +8 -0
  25. package/dist/types/src/build/databases.d.ts +20 -0
  26. package/dist/types/src/build/factories.d.ts +6 -0
  27. package/dist/types/src/build/migrations.d.ts +21 -0
  28. package/dist/types/src/build/queue.d.ts +7 -0
  29. package/dist/types/src/build/schema.d.ts +50 -0
  30. package/dist/types/src/build/tables.d.ts +7 -0
  31. package/dist/types/src/build/types.d.ts +4 -0
  32. package/dist/types/src/cli.d.ts +26 -0
  33. package/dist/types/src/connectors/bun-sql.d.ts +3 -0
  34. package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
  35. package/dist/types/src/connectors/client-fakes.d.ts +57 -0
  36. package/dist/types/src/connectors/client.d.ts +3 -0
  37. package/dist/types/src/connectors/d1-fake.d.ts +32 -0
  38. package/dist/types/src/connectors/d1.d.ts +26 -0
  39. package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
  40. package/dist/types/src/connectors/node-test.d.ts +17 -0
  41. package/dist/types/src/connectors/suite.d.ts +13 -0
  42. package/dist/types/src/devtools.d.ts +6 -0
  43. package/dist/types/src/index.d.ts +25 -0
  44. package/dist/types/src/module.d.ts +6 -0
  45. package/dist/types/src/options.d.ts +9 -0
  46. package/dist/types/src/runtime/connector.d.ts +53 -0
  47. package/dist/types/src/runtime/database.d.ts +15 -0
  48. package/dist/types/src/runtime/migrate.d.ts +56 -0
  49. package/dist/types/src/runtime/query.d.ts +12 -0
  50. package/dist/types/src/runtime/queue-process.d.ts +1 -0
  51. package/dist/types/src/runtime/queue.d.ts +85 -0
  52. package/dist/types/src/runtime/registry.d.ts +16 -0
  53. package/dist/types/src/server/client.d.ts +3 -0
  54. package/dist/types/src/server/databases.d.ts +4 -0
  55. package/dist/types/src/server/define-factory.d.ts +9 -0
  56. package/dist/types/src/server/devtools-routes.d.ts +4 -0
  57. package/dist/types/src/server/devtools.d.ts +26 -0
  58. package/dist/types/src/server/door-dev.d.ts +3 -0
  59. package/dist/types/src/server/door.d.ts +2 -0
  60. package/dist/types/src/server/factory-core.d.ts +12 -0
  61. package/dist/types/src/server/factory.d.ts +6 -0
  62. package/dist/types/src/server/fake.d.ts +35 -0
  63. package/dist/types/src/server/index.d.ts +12 -0
  64. package/dist/types/src/server/migrations.d.ts +5 -0
  65. package/dist/types/src/server/page.d.ts +26 -0
  66. package/dist/types/src/server/plugin.d.ts +1 -0
  67. package/dist/types/src/server/queue.d.ts +6 -0
  68. package/dist/types/src/server/table-entities.d.ts +33 -0
  69. package/dist/types/src/server/task.d.ts +6 -0
  70. package/dist/types/src/storage/define.d.ts +12 -0
  71. package/dist/types/src/storage/driver.d.ts +36 -0
  72. package/dist/types/src/storage/index.d.ts +3 -0
  73. package/dist/types/src/types.d.ts +103 -0
  74. package/package.json +40 -4
  75. package/src/build/connections.ts +225 -0
  76. package/src/build/databases.ts +101 -0
  77. package/src/build/factories.ts +135 -0
  78. package/src/build/migrations.ts +247 -0
  79. package/src/build/queue.ts +29 -0
  80. package/src/build/schema.ts +636 -0
  81. package/src/build/tables.ts +20 -0
  82. package/src/build/types.ts +46 -0
  83. package/src/cli.ts +153 -0
  84. package/src/connectors/bun-sql.ts +68 -0
  85. package/src/connectors/bun-sqlite.ts +69 -0
  86. package/src/connectors/client-fakes.ts +257 -0
  87. package/src/connectors/client.ts +161 -0
  88. package/src/connectors/d1-fake.ts +92 -0
  89. package/src/connectors/d1.ts +151 -0
  90. package/src/connectors/node-sqlite.ts +83 -0
  91. package/src/connectors/node-test.ts +31 -0
  92. package/src/connectors/suite.ts +406 -0
  93. package/src/devtools.ts +264 -0
  94. package/src/env.d.ts +28 -0
  95. package/src/index.ts +46 -0
  96. package/src/module.ts +36 -0
  97. package/src/options.ts +104 -0
  98. package/src/runtime/connector.ts +87 -0
  99. package/src/runtime/database.ts +353 -0
  100. package/src/runtime/migrate.ts +307 -0
  101. package/src/runtime/query.ts +82 -0
  102. package/src/runtime/queue-process.ts +39 -0
  103. package/src/runtime/queue.ts +380 -0
  104. package/src/runtime/registry.ts +61 -0
  105. package/src/server/client.ts +6 -0
  106. package/src/server/databases.ts +24 -0
  107. package/src/server/define-factory.ts +22 -0
  108. package/src/server/devtools-routes.ts +34 -0
  109. package/src/server/devtools.ts +205 -0
  110. package/src/server/door-dev.ts +6 -0
  111. package/src/server/door.ts +4 -0
  112. package/src/server/factory-core.ts +91 -0
  113. package/src/server/factory.ts +19 -0
  114. package/src/server/fake.ts +348 -0
  115. package/src/server/index.ts +17 -0
  116. package/src/server/migrations.ts +26 -0
  117. package/src/server/page.ts +181 -0
  118. package/src/server/plugin.ts +14 -0
  119. package/src/server/queue.ts +38 -0
  120. package/src/server/table-entities.ts +29 -0
  121. package/src/server/task.ts +15 -0
  122. package/src/storage/define.ts +12 -0
  123. package/src/storage/driver.ts +419 -0
  124. package/src/storage/index.ts +7 -0
  125. package/src/types.ts +101 -0
@@ -0,0 +1,380 @@
1
+ import type { Database, Dialect, Transaction } from "../types.ts"
2
+
3
+ /** `tasks.queue: { driver: "db" }` with its defaults filled. */
4
+ export interface QueueOptions {
5
+ connection: string
6
+ table: string
7
+ concurrency: number
8
+ maxAttempts: number
9
+ }
10
+
11
+ export const QUEUE_DEFAULTS: QueueOptions = {
12
+ connection: "default",
13
+ table: "_hamur_queue",
14
+ concurrency: 4,
15
+ maxAttempts: 3,
16
+ }
17
+
18
+ /** A claimed row stays locked this long; the worker renews the lock while its run goes on. */
19
+ export const LOCK_MS = 5 * 60_000
20
+ const RENEW_MS = LOCK_MS / 5
21
+ const BACKOFF_MS = 10_000
22
+ const BACKOFF_MAX_MS = 60 * 60_000
23
+ const POLL_MS = 1000
24
+ const ERROR_LENGTH = 4000
25
+ const LOST = "the run did not end before its lock expired: the process running it stopped"
26
+
27
+ /** A row of the queue table; times are ms since the epoch. */
28
+ export interface QueueRow {
29
+ id: string
30
+ task: string
31
+ payload: string
32
+ runAt: number
33
+ attempts: number
34
+ lastError: string | null
35
+ lockedUntil: number | null
36
+ createdAt: number
37
+ failedAt: number | null
38
+ }
39
+
40
+ /** A row this worker holds; `attempts` counts this run, and `claim` is the row's claim count, which only grows: the row is written only while it still has that count. */
41
+ export interface ClaimedRow {
42
+ id: string
43
+ task: string
44
+ payload: string
45
+ attempts: number
46
+ claim: number
47
+ }
48
+
49
+ /** What `retry` did: `due`, no failed row of that id (`missing`), or a row still locked by a run until `until`. */
50
+ export type RetryResult = { state: "due" } | { state: "missing" } | { state: "locked"; until: number }
51
+
52
+ export interface QueueTable {
53
+ readonly maxAttempts: number
54
+ /** `CREATE TABLE IF NOT EXISTS` and its index, once per table object. */
55
+ ensure(): Promise<void>
56
+ insert(task: string, payload: string, delaySeconds: number): Promise<string>
57
+ /** Up to `limit` due rows, locked for `LOCK_MS` and their `attempts` and `claims` raised, in one transaction. */
58
+ claim(limit: number): Promise<ClaimedRow[]>
59
+ /** Extends the lock; `false` when another claim took the row. */
60
+ renew(row: ClaimedRow): Promise<boolean>
61
+ /** Deletes the row of a run that resolved; after a throw, sets it due after the backoff, or keeps it failed after `maxAttempts`. */
62
+ finish(row: ClaimedRow, failure?: { error: unknown }): Promise<void>
63
+ failed(): Promise<QueueRow[]>
64
+ /** Sets a failed row due now with its attempts at 0, unless a run still holds its lock. */
65
+ retry(id: string): Promise<RetryResult>
66
+ }
67
+
68
+ /** The wait before the next run of a row whose `attempts`-th run threw: 10 s, doubled each time, at most 1 h. */
69
+ export function backoff(attempts: number): number {
70
+ return Math.min(BACKOFF_MS * 2 ** Math.max(attempts - 1, 0), BACKOFF_MAX_MS)
71
+ }
72
+
73
+ type Runner = Pick<Database, "sql" | "run">
74
+
75
+ /** A statement written with `?` for every value; `Database` turns them into the dialect's placeholders. */
76
+ function template(sql: string): TemplateStringsArray {
77
+ const parts = sql.split("?")
78
+ return Object.assign(parts, { raw: parts })
79
+ }
80
+
81
+ const all = (db: Runner, sql: string, params: unknown[] = []) =>
82
+ db.sql<Record<string, unknown>>(template(sql), ...(params as never[]))
83
+ const write = (db: Runner, sql: string, params: unknown[] = []) => db.run(template(sql), ...(params as never[]))
84
+
85
+ const COLUMNS: Record<Dialect, { id: string; task: string; text: string; time: string; count: string }> = {
86
+ sqlite: { id: "TEXT", task: "TEXT", text: "TEXT", time: "INTEGER", count: "INTEGER" },
87
+ postgres: { id: "TEXT", task: "TEXT", text: "TEXT", time: "BIGINT", count: "INTEGER" },
88
+ mysql: { id: "VARCHAR(36)", task: "VARCHAR(255)", text: "LONGTEXT", time: "BIGINT", count: "INT" },
89
+ }
90
+
91
+ const nullable = (value: unknown): number | null => (value === null || value === undefined ? null : Number(value))
92
+
93
+ function message(error: unknown): string {
94
+ const text = error instanceof Error ? error.message : String(error)
95
+ return text.length > ERROR_LENGTH ? `${text.slice(0, ERROR_LENGTH)}…` : text
96
+ }
97
+
98
+ /**
99
+ * The queue table `(id, task, payload, run_at, attempts, last_error, locked_until, created_at, failed_at)` on one
100
+ * connection, in its dialect's SQL. A claim selects due rows with `FOR UPDATE SKIP LOCKED` on postgres and mysql, and inside
101
+ * sqlite's `BEGIN IMMEDIATE`, so one row goes to one worker across processes.
102
+ */
103
+ export function createQueueTable(
104
+ database: () => Database,
105
+ options: Pick<QueueOptions, "table" | "maxAttempts">,
106
+ now: () => number = Date.now,
107
+ ): QueueTable {
108
+ const { table, maxAttempts } = options
109
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new TypeError(`Invalid queue table name ${JSON.stringify(table)}`)
110
+ let ready: Promise<Database> | undefined
111
+
112
+ const quote = (dialect: Dialect, name: string) => (dialect === "mysql" ? `\`${name}\`` : `"${name}"`)
113
+ const indexName = `${table}_due`.slice(0, 63)
114
+
115
+ const open = (): Promise<Database> =>
116
+ (ready ??= (async () => {
117
+ const db = database()
118
+ const t = quote(db.dialect, table)
119
+ const type = COLUMNS[db.dialect]
120
+ const inline = db.dialect === "mysql" ? `, INDEX ${quote("mysql", indexName)} (failed_at, run_at)` : ""
121
+ try {
122
+ await db.exec(
123
+ `CREATE TABLE IF NOT EXISTS ${t} (id ${type.id} NOT NULL PRIMARY KEY, task ${type.task} NOT NULL, payload ${type.text} NOT NULL, run_at ${type.time} NOT NULL, attempts ${type.count} NOT NULL DEFAULT 0, claims ${type.count} NOT NULL DEFAULT 0, last_error ${type.text}, locked_until ${type.time}, created_at ${type.time} NOT NULL, failed_at ${type.time}${inline})`,
124
+ )
125
+ } catch (error) {
126
+ // two processes creating the table at once: the loser fails on the catalog, and the table is there
127
+ try {
128
+ await db.exec(`SELECT 1 FROM ${t} WHERE 1 = 0`)
129
+ } catch {
130
+ throw error
131
+ }
132
+ }
133
+ if (db.dialect !== "mysql") {
134
+ try {
135
+ await db.exec(`CREATE INDEX IF NOT EXISTS ${quote(db.dialect, indexName)} ON ${t} (failed_at, run_at)`)
136
+ } catch (error) {
137
+ const found =
138
+ db.dialect === "postgres"
139
+ ? await all(db, "SELECT 1 AS found FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
140
+ table,
141
+ indexName,
142
+ ])
143
+ : []
144
+ if (!found.length) throw error
145
+ }
146
+ }
147
+ return db
148
+ })().catch((error: unknown) => {
149
+ ready = undefined
150
+ throw error
151
+ }))
152
+
153
+ const named = async () => {
154
+ const db = await open()
155
+ return { db, t: quote(db.dialect, table) }
156
+ }
157
+
158
+ const row = (raw: Record<string, unknown>): QueueRow => ({
159
+ id: String(raw.id),
160
+ task: String(raw.task),
161
+ payload: String(raw.payload),
162
+ runAt: Number(raw.run_at),
163
+ attempts: Number(raw.attempts),
164
+ lastError: raw.last_error === null || raw.last_error === undefined ? null : String(raw.last_error),
165
+ lockedUntil: nullable(raw.locked_until),
166
+ createdAt: Number(raw.created_at),
167
+ failedAt: nullable(raw.failed_at),
168
+ })
169
+
170
+ return {
171
+ maxAttempts,
172
+ async ensure() {
173
+ await open()
174
+ },
175
+ async insert(task, payload, delaySeconds) {
176
+ const { db, t } = await named()
177
+ const id = crypto.randomUUID()
178
+ const at = now()
179
+ await write(db, `INSERT INTO ${t} (id, task, payload, run_at, attempts, created_at) VALUES (?, ?, ?, ?, 0, ?)`, [
180
+ id,
181
+ task,
182
+ payload,
183
+ at + delaySeconds * 1000,
184
+ at,
185
+ ])
186
+ return id
187
+ },
188
+ async claim(limit) {
189
+ const { db, t } = await named()
190
+ const at = now()
191
+ const lock = db.dialect === "sqlite" ? "" : " FOR UPDATE SKIP LOCKED"
192
+ const count = Math.max(1, Math.floor(limit))
193
+ return db.transaction(async (tx: Transaction) => {
194
+ const due = await all(
195
+ tx,
196
+ `SELECT id, task, payload, attempts, claims FROM ${t} WHERE failed_at IS NULL AND run_at <= ? AND (locked_until IS NULL OR locked_until <= ?) ORDER BY run_at, created_at LIMIT ${count}${lock}`,
197
+ [at, at],
198
+ )
199
+ const claimed: ClaimedRow[] = []
200
+ for (const found of due) {
201
+ const id = String(found.id)
202
+ await write(
203
+ tx,
204
+ `UPDATE ${t} SET locked_until = ?, attempts = attempts + 1, claims = claims + 1 WHERE id = ?`,
205
+ [at + LOCK_MS, id],
206
+ )
207
+ claimed.push({
208
+ id,
209
+ task: String(found.task),
210
+ payload: String(found.payload),
211
+ attempts: Number(found.attempts) + 1,
212
+ claim: Number(found.claims) + 1,
213
+ })
214
+ }
215
+ return claimed
216
+ })
217
+ },
218
+ async renew(claimed) {
219
+ const { db, t } = await named()
220
+ const result = await write(
221
+ db,
222
+ `UPDATE ${t} SET locked_until = ? WHERE id = ? AND claims = ? AND failed_at IS NULL`,
223
+ [now() + LOCK_MS, claimed.id, claimed.claim],
224
+ )
225
+ return result.changes > 0
226
+ },
227
+ async finish(claimed, failure) {
228
+ const { db, t } = await named()
229
+ if (!failure) {
230
+ await write(db, `DELETE FROM ${t} WHERE id = ? AND claims = ?`, [claimed.id, claimed.claim])
231
+ return
232
+ }
233
+ const at = now()
234
+ if (claimed.attempts >= maxAttempts) {
235
+ await write(
236
+ db,
237
+ `UPDATE ${t} SET failed_at = ?, last_error = ?, locked_until = NULL WHERE id = ? AND claims = ?`,
238
+ [at, message(failure.error), claimed.id, claimed.claim],
239
+ )
240
+ return
241
+ }
242
+ await write(db, `UPDATE ${t} SET run_at = ?, last_error = ?, locked_until = NULL WHERE id = ? AND claims = ?`, [
243
+ at + backoff(claimed.attempts),
244
+ message(failure.error),
245
+ claimed.id,
246
+ claimed.claim,
247
+ ])
248
+ },
249
+ async failed() {
250
+ const { db, t } = await named()
251
+ const rows = await all(
252
+ db,
253
+ `SELECT id, task, payload, run_at, attempts, last_error, locked_until, created_at, failed_at FROM ${t} WHERE failed_at IS NOT NULL ORDER BY failed_at, id`,
254
+ )
255
+ return rows.map(row)
256
+ },
257
+ async retry(id) {
258
+ const { db, t } = await named()
259
+ const at = now()
260
+ const result = await write(
261
+ db,
262
+ `UPDATE ${t} SET failed_at = NULL, attempts = 0, run_at = ?, locked_until = NULL WHERE id = ? AND failed_at IS NOT NULL AND (locked_until IS NULL OR locked_until <= ?)`,
263
+ [at, id, at],
264
+ )
265
+ if (result.changes > 0) return { state: "due" }
266
+ const [found] = await all(db, `SELECT failed_at, locked_until FROM ${t} WHERE id = ?`, [id])
267
+ const until = nullable(found?.locked_until)
268
+ if (found && nullable(found.failed_at) !== null && until !== null && until > at) return { state: "locked", until }
269
+ return { state: "missing" }
270
+ },
271
+ }
272
+ }
273
+
274
+ export interface QueueWorkerOptions {
275
+ concurrency: number
276
+ /** One run of a claimed row: what it threw, else `undefined`; it never rejects. */
277
+ run(row: ClaimedRow): Promise<{ error: unknown } | undefined>
278
+ /** Where a failed claim or write goes; the worker claims again at its next poll. */
279
+ error(error: unknown): void
280
+ pollMs?: number
281
+ /** How often the lock of each held run is renewed (default 1 min). */
282
+ renewMs?: number
283
+ }
284
+
285
+ export interface QueueWorker {
286
+ /** Claims now instead of at the next poll (after a local insert). */
287
+ wake(): void
288
+ /** Stops claiming and resolves once the runs it holds ended; a run cut short is claimed again once its lock expired. */
289
+ stop(): Promise<void>
290
+ }
291
+
292
+ /** Claims due rows up to `concurrency` runs at once, every `pollMs` (1 s) and as soon as a run ends, and renews the lock of each run it holds. */
293
+ export function startQueueWorker(queue: QueueTable, options: QueueWorkerOptions): QueueWorker {
294
+ const { concurrency, run, error } = options
295
+ const pollMs = options.pollMs ?? POLL_MS
296
+ /** Keyed by claim, not by row: the same row claimed again after its lock expired is another entry. */
297
+ const running = new Map<string, { row: ClaimedRow; lost: boolean; done: Promise<void> }>()
298
+ let stopped = false
299
+ let claiming: Promise<void> | undefined
300
+ let again = false
301
+ let timer: ReturnType<typeof setTimeout> | undefined
302
+ const renewal = setInterval(() => {
303
+ for (const held of running.values()) {
304
+ if (held.lost) continue
305
+ void queue.renew(held.row).then((kept) => {
306
+ if (kept || held.lost) return
307
+ held.lost = true
308
+ error(
309
+ new Error(
310
+ `Task run ${held.row.id} (${held.row.task}) lost its lock to another claim; its result will not be written`,
311
+ ),
312
+ )
313
+ }, error)
314
+ }
315
+ }, options.renewMs ?? RENEW_MS)
316
+
317
+ const schedule = (ms: number): void => {
318
+ if (stopped) return
319
+ if (claiming) {
320
+ again = true
321
+ return
322
+ }
323
+ if (timer !== undefined) {
324
+ if (ms > 0) return
325
+ clearTimeout(timer)
326
+ }
327
+ timer = setTimeout(() => {
328
+ timer = undefined
329
+ const polling = poll()
330
+ claiming = polling.then(() => {})
331
+ void polling.then((next) => {
332
+ claiming = undefined
333
+ if (next !== undefined) schedule(again ? 0 : next)
334
+ })
335
+ }, ms)
336
+ }
337
+
338
+ const start = (row: ClaimedRow): void => {
339
+ const key = `${row.id}\0${row.claim}`
340
+ const held = { row, lost: false, done: Promise.resolve() }
341
+ running.set(key, held)
342
+ held.done = (async () => {
343
+ const failure = row.attempts > queue.maxAttempts ? { error: new Error(LOST) } : await run(row)
344
+ await queue.finish(row, failure)
345
+ })()
346
+ .catch(error)
347
+ .finally(() => {
348
+ running.delete(key)
349
+ schedule(0)
350
+ })
351
+ }
352
+
353
+ /** Claims what fits; resolves to the wait before the next claim, `undefined` when every slot is taken (a run's end claims again). */
354
+ const poll = async (): Promise<number | undefined> => {
355
+ const free = concurrency - running.size
356
+ if (stopped || free <= 0) return undefined
357
+ again = false
358
+ let rows: ClaimedRow[] = []
359
+ try {
360
+ rows = await queue.claim(free)
361
+ } catch (failure) {
362
+ error(failure)
363
+ }
364
+ for (const row of rows) start(row)
365
+ return rows.length > 0 && rows.length === free ? 0 : pollMs
366
+ }
367
+
368
+ schedule(0)
369
+ return {
370
+ wake: () => schedule(0),
371
+ async stop() {
372
+ stopped = true
373
+ clearTimeout(timer)
374
+ timer = undefined
375
+ await claiming
376
+ clearInterval(renewal)
377
+ await Promise.all([...running.values()].map((held) => held.done))
378
+ },
379
+ }
380
+ }
@@ -0,0 +1,61 @@
1
+ import type { Database, ResolvedConnection, Secret } from "../types.ts"
2
+ import type { ClientLoader, OpenConnector } from "./connector.ts"
3
+ import { createDatabase } from "./database.ts"
4
+
5
+ export type ConnectorLoaders = Record<string, () => Promise<{ default: OpenConnector }>>
6
+
7
+ /** The client file of each `client` connection, by connection name. */
8
+ export type ClientLoaders = Record<string, ClientLoader>
9
+
10
+ export interface Databases {
11
+ use(name?: string): Database
12
+ /** Closes every connection that was opened. */
13
+ close(): Promise<void>
14
+ }
15
+
16
+ /** The value of an `app/env.ts` entry: the server's, read at start, or one the build process reads itself. */
17
+ export type EnvReader = (name: string) => unknown
18
+
19
+ async function secret(name: string, value: Secret | undefined, env: EnvReader): Promise<string | undefined> {
20
+ if (value === undefined || typeof value === "string") return value
21
+ const read = await env(value["~env"])
22
+ if (typeof read !== "string" || read === "")
23
+ throw new Error(`db.connections.${name}.url reads env ${JSON.stringify(value["~env"])}, which is not set`)
24
+ return read
25
+ }
26
+
27
+ /** One `Database` per connection name for the process, its connector imported and opened at the first query. */
28
+ export function createDatabases(
29
+ connections: Record<string, ResolvedConnection>,
30
+ loaders: ConnectorLoaders,
31
+ env: EnvReader,
32
+ clients: ClientLoaders = {},
33
+ ): Databases {
34
+ const made = new Map<string, Database>()
35
+ return {
36
+ use(name = "default") {
37
+ const existing = made.get(name)
38
+ if (existing) return existing
39
+ const connection = Object.hasOwn(connections, name) ? connections[name] : undefined
40
+ if (!connection) throw new Error(`No database "${name}": set db.connections.${name} in hamur.config.ts`)
41
+ const database = createDatabase(name, connection.dialect, async () => {
42
+ const url = await secret(name, connection.url, env)
43
+ const client = connection.connector === "client" && Object.hasOwn(clients, name) ? clients[name] : undefined
44
+ const { default: open } = await loaders[connection.connector]!()
45
+ return open({
46
+ name,
47
+ dialect: connection.dialect,
48
+ ...(url === undefined ? {} : { url }),
49
+ ...(connection.path === undefined ? {} : { path: connection.path }),
50
+ ...(connection.binding === undefined ? {} : { binding: connection.binding }),
51
+ ...(client === undefined ? {} : { client }),
52
+ })
53
+ })
54
+ made.set(name, database)
55
+ return database
56
+ },
57
+ async close() {
58
+ await Promise.all([...made.values()].map((database) => database.close()))
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,6 @@
1
+ import type { DatabaseClient } from "../types.ts"
2
+
3
+ /** The default export of a `client` connection's file; Hamur calls `factory` once per process, at the first query. */
4
+ export function defineDatabaseClient(factory: () => DatabaseClient | Promise<DatabaseClient>): typeof factory {
5
+ return factory
6
+ }
@@ -0,0 +1,24 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { clients, connections, connectors } from "#hamur/db/connections"
3
+ import { envValue } from "hamur/server/internal"
4
+ import { createDatabases, type ClientLoaders, type ConnectorLoaders } from "../runtime/registry.ts"
5
+ import type { ResolvedConnection } from "../types.ts"
6
+
7
+ interface Prerender {
8
+ connections: Record<string, ResolvedConnection>
9
+ loaders: ConnectorLoaders
10
+ clients: ClientLoaders
11
+ }
12
+
13
+ /** While the build prerenders, the build hands over each connection's `dev`, the loaders of its connectors and its client files. */
14
+ const handed = import.meta.prerender
15
+ ? (globalThis as { __HAMUR_DB_PRERENDER__?: Prerender }).__HAMUR_DB_PRERENDER__
16
+ : undefined
17
+
18
+ /** The connections this run uses: the bundled ones, each replaced by its `dev` while prerendering. */
19
+ export const active: Record<string, ResolvedConnection> = { ...connections, ...handed?.connections }
20
+
21
+ export const databases = createDatabases(active, { ...connectors, ...handed?.loaders }, envValue, {
22
+ ...clients,
23
+ ...handed?.clients,
24
+ })
@@ -0,0 +1,22 @@
1
+ import type { DatabaseName, DefaultDatabase, Insert, TableName } from "../index.ts"
2
+ import type { Fake } from "./fake.ts"
3
+
4
+ /** What `defineFactory` returns, the default export of `server/db/factories/<table>.ts`. */
5
+ export interface Factory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase> {
6
+ readonly make: (n: number, fake: Fake) => Insert<T, C>
7
+ }
8
+
9
+ const defined = new WeakSet<object>()
10
+
11
+ /** The rows of table `T` as `make(n, fake)` writes them, `n` counting from 1. */
12
+ export function defineFactory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase>(
13
+ make: (n: number, fake: Fake) => Insert<T, C>,
14
+ ): Factory<T, C> {
15
+ if (typeof make !== "function") throw new TypeError("defineFactory takes a function (n, fake) => row")
16
+ const factory = Object.freeze({ make })
17
+ defined.add(factory)
18
+ return factory
19
+ }
20
+
21
+ export const isFactory = (value: unknown): value is Factory<never, never> =>
22
+ typeof value === "object" && value !== null && defined.has(value)
@@ -0,0 +1,34 @@
1
+ import { defineHandler } from "hamur/server"
2
+ import { answerMigrations, answerQuery, answerRows, answerTables } from "./devtools.ts"
3
+
4
+ export const devtoolsDbTables = defineHandler({
5
+ route: "/_hamur/devtools/api/db/tables",
6
+ method: "*",
7
+ raw: true,
8
+ meta: { hidden: true },
9
+ handler: (_, { event }) => answerTables(event.request),
10
+ })
11
+
12
+ export const devtoolsDbRows = defineHandler({
13
+ route: "/_hamur/devtools/api/db/rows",
14
+ method: "*",
15
+ raw: true,
16
+ meta: { hidden: true },
17
+ handler: (_, { event }) => answerRows(event.request),
18
+ })
19
+
20
+ export const devtoolsDbQuery = defineHandler({
21
+ route: "/_hamur/devtools/api/db/query",
22
+ method: "*",
23
+ raw: true,
24
+ meta: { hidden: true },
25
+ handler: (_, { event }) => answerQuery(event.request),
26
+ })
27
+
28
+ export const devtoolsDbMigrations = defineHandler({
29
+ route: "/_hamur/devtools/api/db/migrations",
30
+ method: "*",
31
+ raw: true,
32
+ meta: { hidden: true },
33
+ handler: (_, { event }) => answerMigrations(event.request),
34
+ })