@hamur/db 0.0.0-stage → 0.0.2

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 +55 -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,101 @@
1
+ import { rm } from "node:fs/promises"
2
+ import { join, relative, resolve } from "node:path"
3
+ import { DiagnosticError, readEnvValues, type HamurContext } from "hamur/kit"
4
+ import { createDatabases, type ClientLoaders, type ConnectorLoaders, type Databases } from "../runtime/registry.ts"
5
+ import type { ResolvedConnection, ResolvedDbOptions } from "../types.ts"
6
+
7
+ export const LOADERS = {
8
+ "bun-sql": () => import("../connectors/bun-sql.ts"),
9
+ "bun-sqlite": () => import("../connectors/bun-sqlite.ts"),
10
+ // The build runs on Bun, where node-sqlite is bun-sqlite on the same file.
11
+ "node-sqlite": () => import("../connectors/bun-sqlite.ts"),
12
+ d1: () => import("../connectors/d1.ts"),
13
+ client: () => import("../connectors/client.ts"),
14
+ } satisfies Record<ResolvedConnection["connector"], ConnectorLoaders[string]>
15
+
16
+ /** A `client` file, relative to `rootDir`, as the bundler finds it; `undefined` when nothing is there. */
17
+ export function clientFile(rootDir: string, client: string): string | undefined {
18
+ try {
19
+ return Bun.resolveSync(resolve(rootDir, client), rootDir)
20
+ } catch {
21
+ return undefined
22
+ }
23
+ }
24
+
25
+ const bundles = new WeakMap<HamurContext, Map<string, Promise<unknown>>>()
26
+ let bundleCount = 0
27
+
28
+ /**
29
+ * A client file as the server bundle runs it: built with the build's virtual modules (`#hamur/env/private`, and
30
+ * `#hamur/db/connections` behind `@hamur/db/server`) and the app's build plugins, then imported. Once per file and build context.
31
+ */
32
+ function importClient(hamur: HamurContext, file: string): Promise<unknown> {
33
+ const own = bundles.get(hamur) ?? new Map<string, Promise<unknown>>()
34
+ bundles.set(hamur, own)
35
+ const known = own.get(file)
36
+ if (known) return known
37
+ const loading = (async () => {
38
+ const outdir = join(hamur.options.buildDir, "db", "client", `${process.pid}-${++bundleCount}`)
39
+ try {
40
+ const result = await Bun.build({
41
+ entrypoints: [file],
42
+ outdir,
43
+ target: "bun",
44
+ format: "esm",
45
+ plugins: [hamur.vfs.plugin("server"), ...hamur.options.build.plugins],
46
+ define: {
47
+ "import.meta.dev": String(hamur.options.dev),
48
+ "import.meta.server": "true",
49
+ "import.meta.client": "false",
50
+ },
51
+ throw: false,
52
+ })
53
+ if (!result.success) {
54
+ throw new DiagnosticError(
55
+ "HAMUR_E5518",
56
+ `Cannot build database client ${relative(hamur.options.rootDir, file)}:\n${result.logs
57
+ .filter((log) => log.level === "error")
58
+ .map((log) => log.message)
59
+ .join("\n")}`,
60
+ )
61
+ }
62
+ const entry = result.outputs.find((output) => output.kind === "entry-point")!
63
+ return await import(entry.path)
64
+ } finally {
65
+ await rm(outdir, { recursive: true, force: true })
66
+ }
67
+ })()
68
+ loading.catch(() => own.delete(file))
69
+ own.set(file, loading)
70
+ return loading
71
+ }
72
+
73
+ /** The client file of each `client` connection, for the build's own process (`hamur db`, the migration runs, the prerender's `dev`). */
74
+ export function clientLoaders(hamur: HamurContext, connections: Record<string, ResolvedConnection>): ClientLoaders {
75
+ return Object.fromEntries(
76
+ Object.entries(connections).flatMap(([name, { client }]) => {
77
+ const file = client === undefined ? undefined : clientFile(hamur.options.rootDir, client)
78
+ return file ? [[name, () => importClient(hamur, file)]] : []
79
+ }),
80
+ )
81
+ }
82
+
83
+ /** An `app/env.ts` value as the build process reads it, validated once, from its own environment. */
84
+ function buildEnv(hamur: HamurContext): (name: string) => Promise<unknown> {
85
+ let values: Promise<Record<string, unknown>> | undefined
86
+ return async (name) => (await (values ??= readEnvValues(hamur)))[name]
87
+ }
88
+
89
+ /** The build runs on Bun, where node-sqlite is bun-sqlite on the same file. */
90
+ export const asBun = (connection: ResolvedConnection): ResolvedConnection =>
91
+ connection.connector === "node-sqlite" ? { ...connection, connector: "bun-sqlite" } : connection
92
+
93
+ /** The `dev` connection of every connection that has one, as the build's Bun process runs it. */
94
+ export function devConnections(connections: Record<string, ResolvedConnection>): Record<string, ResolvedConnection> {
95
+ return Object.fromEntries(Object.entries(connections).flatMap(([name, { dev }]) => (dev ? [[name, asBun(dev)]] : [])))
96
+ }
97
+
98
+ /** The connections opened by the build process itself (`hamur db`, `db.migrate: "build"`, the dev watcher), not the server's. */
99
+ export function openDatabases(hamur: HamurContext, options: ResolvedDbOptions): Databases {
100
+ return createDatabases(options.connections, LOADERS, buildEnv(hamur), clientLoaders(hamur, options.connections))
101
+ }
@@ -0,0 +1,135 @@
1
+ import { readdir } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { DiagnosticError, addTemplate, type HamurContext } from "hamur/kit"
4
+ import type { Dialect, ResolvedDbOptions } from "../types.ts"
5
+ import { loadMigrations, shown } from "./migrations.ts"
6
+ import { readSchema } from "./schema.ts"
7
+
8
+ const FILE = /^(.+)\.(ts|mts|js|mjs)$/
9
+ const IGNORED_FILE = /\.(test|spec)\.[^/]+$|\.d\.m?ts$/
10
+ const TABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
11
+
12
+ const ignored = (name: string) => name.startsWith("_") || name.startsWith(".")
13
+
14
+ async function entries(dir: string) {
15
+ try {
16
+ return await readdir(dir, { withFileTypes: true })
17
+ } catch (error) {
18
+ if ((error as { code?: string }).code === "ENOENT" || (error as { code?: string }).code === "ENOTDIR") return []
19
+ throw error
20
+ }
21
+ }
22
+
23
+ function distance(a: string, b: string): number {
24
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
25
+ for (let i = 1; i <= a.length; i++) {
26
+ const next = [i]
27
+ for (let j = 1; j <= b.length; j++)
28
+ next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
29
+ row = next
30
+ }
31
+ return row[b.length]!
32
+ }
33
+
34
+ function nearest(name: string, known: string[]): string | undefined {
35
+ let best: { table: string; at: number } | undefined
36
+ for (const table of known) {
37
+ const at = distance(name, table)
38
+ if (at <= 2 && (!best || at < best.at)) best = { table, at }
39
+ }
40
+ return best?.table
41
+ }
42
+
43
+ /** The app's and each layer's `server/db/factories` (`default` at its top, another connection in its own folder), the app's file first; `connection` then table name to the file. */
44
+ export async function scanFactories(
45
+ hamur: HamurContext,
46
+ options: ResolvedDbOptions,
47
+ dialects: Record<string, Dialect>,
48
+ ): Promise<Record<string, Record<string, string>>> {
49
+ const { rootDir } = hamur.options
50
+ const roots = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)].map((dir) =>
51
+ join(dir, "db", "factories"),
52
+ )
53
+ const migrations = await loadMigrations(hamur, options)
54
+ const problems: string[] = []
55
+ const found: Record<string, Record<string, string>> = {}
56
+ const schemas = new Map<string, ReturnType<typeof readSchema>>()
57
+ const schemaOf = (connection: string) => {
58
+ let schema = schemas.get(connection)
59
+ if (!schema) {
60
+ schema = readSchema(
61
+ dialects[connection] ?? options.connections[connection]!.dialect,
62
+ migrations[connection] ?? [],
63
+ )
64
+ schemas.set(connection, schema)
65
+ }
66
+ return schema
67
+ }
68
+ for (const root of roots) {
69
+ const place = async (connection: string, dir: string, folders: boolean) => {
70
+ for (const entry of (await entries(dir)).sort((a, b) => a.name.localeCompare(b.name))) {
71
+ if (ignored(entry.name)) continue
72
+ const path = join(dir, entry.name)
73
+ if (entry.isDirectory()) {
74
+ if (folders && !Object.hasOwn(options.connections, entry.name))
75
+ problems.push(`${shown(rootDir, path)}: db.connections has no connection "${entry.name}"`)
76
+ continue
77
+ }
78
+ const match = entry.isFile() ? FILE.exec(entry.name) : null
79
+ if (!match || IGNORED_FILE.test(entry.name)) continue
80
+ const table = match[1]!
81
+ if (!Object.hasOwn(options.connections, connection)) {
82
+ problems.push(`${shown(rootDir, path)}: db.connections has no connection "${connection}"`)
83
+ continue
84
+ }
85
+ const files = (found[connection] ??= {})
86
+ const schema = schemaOf(connection)
87
+ if (!TABLE.test(table) || !schema.tables.has(table)) {
88
+ const hint = nearest(table, [...schema.tables.keys()])
89
+ problems.push(
90
+ `${shown(rootDir, path)}: db "${connection}" has no table "${table}"${hint ? ` (did you mean "${hint}"?)` : ""}`,
91
+ )
92
+ continue
93
+ }
94
+ if (Object.hasOwn(files, table) && files[table]!.startsWith(root)) {
95
+ problems.push(
96
+ `${shown(rootDir, files[table]!)} and ${shown(rootDir, path)} both write the factory of "${table}"`,
97
+ )
98
+ continue
99
+ }
100
+ if (!Object.hasOwn(files, table)) files[table] = path
101
+ }
102
+ }
103
+ await place("default", root, true)
104
+ for (const connection of Object.keys(options.connections)) {
105
+ if (connection !== "default") await place(connection, join(root, connection), false)
106
+ }
107
+ }
108
+ if (problems.length) throw new DiagnosticError("HAMUR_E5525", problems.join("\n"))
109
+ return Object.fromEntries(Object.entries(found).filter(([, files]) => Object.keys(files).length > 0))
110
+ }
111
+
112
+ /** `#hamur/db/factories`, every factory file by connection and table, for `factory(table)`; a bad file fails the build. */
113
+ export function setupFactories(
114
+ options: ResolvedDbOptions,
115
+ hamur: HamurContext,
116
+ dialects: Record<string, Dialect>,
117
+ ): void {
118
+ addTemplate({
119
+ filename: "db/factories",
120
+ getContents: async () => {
121
+ const found = await scanFactories(hamur, options, dialects)
122
+ const imports: string[] = []
123
+ const tables = Object.entries(found).map(([connection, files]) => {
124
+ const members = Object.entries(files).map(([table, file]) => {
125
+ const name = `factory${imports.length}`
126
+ imports.push(`import ${name} from ${JSON.stringify(file)};`)
127
+ return `${JSON.stringify(table)}: ${name}`
128
+ })
129
+ return `${JSON.stringify(connection)}: { ${members.join(", ")} }`
130
+ })
131
+ return `${imports.join("\n")}\nexport const factories = { ${tables.join(", ")} };\n`
132
+ },
133
+ })
134
+ hamur.hooks.hook("build:before", async () => void (await scanFactories(hamur, options, dialects)))
135
+ }
@@ -0,0 +1,247 @@
1
+ import { watch, type FSWatcher } from "node:fs"
2
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
4
+ import { DiagnosticError, addTask, addTemplate, createResolver, useLogger, type HamurContext } from "hamur/kit"
5
+ import { checksumOf, compareIds, migrate, withoutBom, type Migration } from "../runtime/migrate.ts"
6
+ import type { DbSetup, ResolvedDbOptions } from "../types.ts"
7
+ import { bindingKey, cloudflareId } from "./connections.ts"
8
+ import { devConnections, openDatabases } from "./databases.ts"
9
+
10
+ const NAME = /^(\d{4,})_([a-z0-9_]+)\.sql$/
11
+ /** The presets with a server start of their own. */
12
+ const STARTS = ["bun", "node"]
13
+
14
+ export interface MigrationDir {
15
+ connection: string
16
+ dir: string
17
+ }
18
+
19
+ export const shown = (rootDir: string, path: string) => {
20
+ const from = relative(rootDir, path)
21
+ return from.startsWith("..") || isAbsolute(from) ? path : from
22
+ }
23
+
24
+ /** The app's and each layer's `server/db/migrations` (`default` at its top, another connection in its own folder), then the modules' (`db:migrations:dirs`). */
25
+ export async function migrationDirs(hamur: HamurContext, options: ResolvedDbOptions): Promise<MigrationDir[]> {
26
+ const roots = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)].map((dir) =>
27
+ join(dir, "db", "migrations"),
28
+ )
29
+ const dirs: MigrationDir[] = []
30
+ for (const root of roots) {
31
+ for (const connection of Object.keys(options.connections))
32
+ dirs.push({ connection, dir: connection === "default" ? root : join(root, connection) })
33
+ }
34
+ await hamur.hooks.callHook("db:migrations:dirs", dirs)
35
+ return dirs
36
+ }
37
+
38
+ async function sqlFiles(dir: string): Promise<string[]> {
39
+ try {
40
+ const entries = await readdir(dir, { withFileTypes: true })
41
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name)
42
+ } catch (error) {
43
+ if ((error as { code?: string }).code === "ENOENT" || (error as { code?: string }).code === "ENOTDIR") return []
44
+ throw error
45
+ }
46
+ }
47
+
48
+ /** Each connection's migrations in number order, or the build error of a bad name, a shared number or a file in two directories. */
49
+ export async function loadMigrations(
50
+ hamur: HamurContext,
51
+ options: ResolvedDbOptions,
52
+ ): Promise<Record<string, Migration[]>> {
53
+ const { rootDir } = hamur.options
54
+ const byConnection: Record<string, Map<string, { migration: Migration; dir: string }>> = {}
55
+ for (const connection of Object.keys(options.connections)) byConnection[connection] = new Map()
56
+ for (const { connection, dir } of await migrationDirs(hamur, options)) {
57
+ const found = byConnection[connection]
58
+ if (!found) continue
59
+ for (const file of (await sqlFiles(dir)).sort()) {
60
+ const match = NAME.exec(file)
61
+ if (!match)
62
+ throw new DiagnosticError(
63
+ "HAMUR_E5506",
64
+ `${shown(rootDir, join(dir, file))}: a migration is named <number>_<name>.sql (0001_init.sql)`,
65
+ )
66
+ const other = found.get(file)
67
+ if (other)
68
+ throw new DiagnosticError(
69
+ "HAMUR_E5507",
70
+ `Migration ${file} is in both ${shown(rootDir, other.dir)} and ${shown(rootDir, dir)}`,
71
+ )
72
+ const sql = withoutBom(await readFile(join(dir, file), "utf8"))
73
+ found.set(file, {
74
+ dir,
75
+ migration: { id: match[1]!, name: match[2]!, file, sql, checksum: await checksumOf(sql) },
76
+ })
77
+ }
78
+ }
79
+ const result: Record<string, Migration[]> = {}
80
+ for (const [connection, found] of Object.entries(byConnection)) {
81
+ const list = [...found.values()]
82
+ .map(({ migration }) => migration)
83
+ .sort((a, b) => compareIds(a.id, b.id) || a.file.localeCompare(b.file))
84
+ for (let i = 1; i < list.length; i++) {
85
+ const [a, b] = [list[i - 1]!, list[i]!]
86
+ if (compareIds(a.id, b.id) === 0)
87
+ throw new DiagnosticError("HAMUR_E5508", `Migrations ${a.file} and ${b.file} share the number ${a.id}`)
88
+ }
89
+ result[connection] = list
90
+ }
91
+ return result
92
+ }
93
+
94
+ /** Applies every connection's pending migrations through connections the build opens itself, logging each file. */
95
+ export async function applyAll(
96
+ hamur: HamurContext,
97
+ options: ResolvedDbOptions,
98
+ names: string[] = notD1(options),
99
+ ): Promise<void> {
100
+ const all = await loadMigrations(hamur, options)
101
+ const log = useLogger("hamur")
102
+ const databases = openDatabases(hamur, options)
103
+ try {
104
+ for (const name of names) {
105
+ const applied = await migrate(databases.use(name), all[name] ?? [], {
106
+ warn: (message) => log.warn(message),
107
+ applied: (migration, ms) =>
108
+ log.info(`Applied ${migration.id}_${migration.name} to "${name}" (${Math.round(ms)} ms)`),
109
+ })
110
+ if (applied.length) log.info(`${applied.length} migration${applied.length === 1 ? "" : "s"} applied to "${name}"`)
111
+ }
112
+ } finally {
113
+ await databases.close()
114
+ }
115
+ }
116
+
117
+ /** Before the prerender, each `dev` connection's file gets its connection's migrations, `migrate` setting aside: it is a local database the prerender reads. */
118
+ async function applyDev(hamur: HamurContext, options: ResolvedDbOptions): Promise<void> {
119
+ const devs = devConnections(options.connections)
120
+ const all = await loadMigrations(hamur, options)
121
+ const names = Object.keys(devs).filter((name) => all[name]?.length)
122
+ if (names.length) await applyAll(hamur, { ...options, connections: { ...options.connections, ...devs } }, names)
123
+ }
124
+
125
+ /** The connections whose migrations Hamur applies; wrangler applies a d1 connection's. */
126
+ export const notD1 = (options: ResolvedDbOptions): string[] =>
127
+ Object.keys(options.connections).filter((name) => options.connections[name]!.connector !== "d1")
128
+
129
+ /**
130
+ * Each d1 connection's files in `.output/migrations/<connection>/`, and `migrations_dir` on its `d1_databases` entry of
131
+ * `.output/wrangler.json` when the app's entry has none, for `wrangler d1 migrations apply`. A binding the app's config does not declare
132
+ * gets its entry from a known id.
133
+ */
134
+ async function writeD1Migrations(hamur: HamurContext, options: ResolvedDbOptions): Promise<void> {
135
+ const d1 = Object.entries(options.connections).filter(([, connection]) => connection.connector === "d1")
136
+ if (!d1.length) return
137
+ const { outputDir } = hamur.options
138
+ const all = await loadMigrations(hamur, options)
139
+ const wranglerFile = join(outputDir, "wrangler.json")
140
+ const wrangler = JSON.parse(await readFile(wranglerFile, "utf8")) as { d1_databases?: Array<Record<string, unknown>> }
141
+ for (const database of wrangler.d1_databases ?? []) {
142
+ const own = database.migrations_dir
143
+ // The preset copies the app's entry as it is, but wrangler reads its paths against .output/wrangler.json.
144
+ if (typeof own === "string" && !isAbsolute(own))
145
+ database.migrations_dir = relative(outputDir, resolve(hamur.options.rootDir, own)).split(sep).join("/")
146
+ }
147
+ for (const [name, { binding }] of d1) {
148
+ if (wrangler.d1_databases?.some((database) => database.binding === binding)) continue
149
+ const id = cloudflareId(hamur, binding!)
150
+ if (!id) continue
151
+ const taken = bindingKey(wrangler as Record<string, unknown>, binding!)
152
+ if (taken)
153
+ throw new DiagnosticError(
154
+ "HAMUR_E5509",
155
+ `db.connections.${name}.binding ${JSON.stringify(binding)} is already the ${taken} binding of the app's wrangler config; set db.connections.${name}.binding to another name`,
156
+ )
157
+ ;(wrangler.d1_databases ??= []).push({ binding, database_id: id })
158
+ }
159
+ for (const [name, { binding }] of d1) {
160
+ const dir = join(outputDir, "migrations", name)
161
+ await rm(dir, { recursive: true, force: true })
162
+ const files = all[name] ?? []
163
+ if (!files.length) continue
164
+ await mkdir(dir, { recursive: true })
165
+ for (const migration of files) await writeFile(join(dir, migration.file), migration.sql)
166
+ const entry = wrangler.d1_databases?.find((database) => database.binding === binding)
167
+ if (entry && entry.migrations_dir === undefined) entry.migrations_dir = `migrations/${name}`
168
+ }
169
+ await writeFile(wranglerFile, `${JSON.stringify(wrangler, null, 2)}\n`)
170
+ }
171
+
172
+ /** Under `hamur dev`, a migration file added or changed while it runs is applied at once; an error is logged, the server keeps running. */
173
+ async function watchMigrations(hamur: HamurContext, options: ResolvedDbOptions): Promise<() => void> {
174
+ const dirs = new Set((await migrationDirs(hamur, options)).map((entry) => entry.dir))
175
+ const serverDirs = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)]
176
+ const roots = [...serverDirs, ...[...dirs].filter((dir) => !serverDirs.some((root) => dir.startsWith(root + sep)))]
177
+ const watchers: FSWatcher[] = []
178
+ let timer: ReturnType<typeof setTimeout> | undefined
179
+ let running = Promise.resolve()
180
+ const log = useLogger("hamur")
181
+ const changed = () => {
182
+ clearTimeout(timer)
183
+ timer = setTimeout(() => {
184
+ running = running
185
+ .then(() => applyAll(hamur, options))
186
+ .catch((error: unknown) => log.error(error instanceof Error ? error.message : String(error)))
187
+ }, 100)
188
+ }
189
+ for (const root of roots) {
190
+ try {
191
+ const watcher = watch(root, { recursive: true }, (_event, file) => {
192
+ if (typeof file === "string" && file.endsWith(".sql") && dirs.has(dirname(join(root, file)))) changed()
193
+ })
194
+ watcher.on("error", () => watcher.close())
195
+ watchers.push(watcher)
196
+ } catch {
197
+ // A directory that does not exist has nothing to watch.
198
+ }
199
+ }
200
+ return () => {
201
+ clearTimeout(timer)
202
+ for (const watcher of watchers) watcher.close()
203
+ }
204
+ }
205
+
206
+ /**
207
+ * `#hamur/db/migrations` (every connection's files, for the task `db:migrate`, and `apply` for the server's own run under
208
+ * `hamur dev` and at a built server's start with `migrate: "start"`), the task, the start check, the build's run, the dev watcher.
209
+ */
210
+ export const setupMigrations: DbSetup = (options, hamur) => {
211
+ const { dev, preset } = hamur.options
212
+ const atStart = options.migrate !== false && (dev || options.migrate === "start")
213
+ addTemplate({
214
+ filename: "db/migrations",
215
+ getContents: async () => {
216
+ const all = await loadMigrations(hamur, options)
217
+ const migrations = Object.fromEntries(notD1(options).map((name) => [name, all[name] ?? []]))
218
+ return `export const apply = ${atStart};\nexport const migrations = ${JSON.stringify(migrations)};\n`
219
+ },
220
+ })
221
+ addTask({ name: "db:migrate", file: createResolver(import.meta.url).resolve("../server/task.ts") })
222
+
223
+ hamur.hooks.hook("build:before", async () => {
224
+ const d1 = Object.keys(options.connections).find((name) => options.connections[name]!.connector === "d1")
225
+ if (d1 !== undefined && (options.migrate === "build" || options.migrate === "start")) {
226
+ throw new DiagnosticError(
227
+ "HAMUR_E5510",
228
+ `db.connections.${d1} uses d1, whose migrations wrangler applies; build writes them to .output/migrations/${d1}`,
229
+ )
230
+ }
231
+ if (options.migrate === "start" && !STARTS.includes(preset)) {
232
+ throw new DiagnosticError(
233
+ "HAMUR_E5511",
234
+ `db.migrate "start" needs a server start, which the "${preset}" preset has not; use "build" or run hamur db migrate --prod in the deploy step`,
235
+ )
236
+ }
237
+ await loadMigrations(hamur, options)
238
+ })
239
+ if (!dev && options.migrate === "build") hamur.hooks.hook("prerender:routes", () => applyAll(hamur, options))
240
+ if (!dev) hamur.hooks.hook("prerender:routes", () => applyDev(hamur, options))
241
+ if (!dev && preset === "cloudflare") hamur.hooks.hook("build:done", () => writeD1Migrations(hamur, options))
242
+ if (dev && options.migrate !== false) {
243
+ let stop: Promise<() => void> | undefined
244
+ hamur.hooks.hook("dev:ready", () => void (stop = watchMigrations(hamur, options)))
245
+ hamur.hooks.hook("close", async () => (await stop)?.())
246
+ }
247
+ }
@@ -0,0 +1,29 @@
1
+ import { addTemplate, DiagnosticError, type HamurContext } from "hamur/kit"
2
+ import { QUEUE_DEFAULTS, type QueueOptions } from "../runtime/queue.ts"
3
+ import type { DbSetup } from "../types.ts"
4
+
5
+ /** `tasks.queue` when it is `{ driver: "db" }`, its defaults filled; `undefined` for another queue or none. */
6
+ export function queueOptions(hamur: HamurContext): QueueOptions | undefined {
7
+ const queue = hamur.options.tasks.queue
8
+ if (!queue || !("driver" in queue)) return undefined
9
+ return {
10
+ connection: queue.connection ?? QUEUE_DEFAULTS.connection,
11
+ table: queue.table ?? QUEUE_DEFAULTS.table,
12
+ concurrency: queue.concurrency ?? QUEUE_DEFAULTS.concurrency,
13
+ maxAttempts: queue.maxAttempts ?? QUEUE_DEFAULTS.maxAttempts,
14
+ }
15
+ }
16
+
17
+ /** `#hamur/db/queue`, which the server door reads to start the worker; the queue's connection must be one of `db.connections`. */
18
+ export const setupQueue: DbSetup = (options, hamur) => {
19
+ const queue = queueOptions(hamur)
20
+ if (queue && !Object.hasOwn(options.connections, queue.connection))
21
+ throw new DiagnosticError(
22
+ "HAMUR_E5521",
23
+ `tasks.queue.connection ${JSON.stringify(queue.connection)} is not in db.connections; set db.connections.${queue.connection} in hamur.config.ts`,
24
+ )
25
+ addTemplate({
26
+ filename: "db/queue",
27
+ getContents: () => `export const queue = ${queue ? JSON.stringify(queue) : "undefined"};\n`,
28
+ })
29
+ }