@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,46 @@
1
+ import { addTypeTemplate, diagnostic, useLogger, type HamurContext } from "hamur/kit"
2
+ import type { Dialect, ResolvedDbOptions } from "../types.ts"
3
+ import { loadMigrations } from "./migrations.ts"
4
+ import { isOptionalOnInsert, readSchema, typeOfColumn, warningsOf } from "./schema.ts"
5
+
6
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
7
+ const key = (name: string) => (IDENTIFIER.test(name) ? name : JSON.stringify(name))
8
+
9
+ /** `.hamur/types/db.d.ts`, one `HamurDatabases` entry per connection with the tables its migrations leave; `dialects` are the configured ones, before `dev` replaced a connection. */
10
+ export function setupTypes(
11
+ options: ResolvedDbOptions,
12
+ hamur: HamurContext,
13
+ dialects: Record<string, Dialect> = {},
14
+ ): void {
15
+ addTypeTemplate({
16
+ filename: "db.d.ts",
17
+ getContents: async () => {
18
+ const all = await loadMigrations(hamur, options)
19
+ const log = useLogger("hamur")
20
+ const entries: string[] = []
21
+ for (const [name, connection] of Object.entries(options.connections)) {
22
+ const dialect = dialects[name] ?? connection.dialect
23
+ const schema = readSchema(dialect, all[name] ?? [])
24
+ for (const warning of warningsOf(schema)) log.warn(diagnostic("HAMUR_W5519", `db "${name}": ${warning}`))
25
+ const tables = [...schema.tables.values()]
26
+ .sort((a, b) => a.name.localeCompare(b.name))
27
+ .map(
28
+ (table) =>
29
+ ` ${key(table.name)}: { ${[...table.columns.values()].map((column) => `${key(column.name)}: ${typeOfColumn(column)}`).join("; ")} };`,
30
+ )
31
+ const inserts = [...schema.tables.values()]
32
+ .sort((a, b) => a.name.localeCompare(b.name))
33
+ .map(
34
+ (table) =>
35
+ ` ${key(table.name)}: { ${[...table.columns.values()].map((column) => `${key(column.name)}${isOptionalOnInsert(column, dialect) ? "?" : ""}: ${typeOfColumn(column)}`).join("; ")} };`,
36
+ )
37
+ const block = (field: string, lines: string[]) =>
38
+ ` ${field}: {${lines.length ? `\n${lines.join("\n")}\n ` : " "}};`
39
+ entries.push(
40
+ ` ${key(name)}: {\n dialect: ${JSON.stringify(dialect)};\n${block("tables", tables)}\n${block("inserts", inserts)}\n };`,
41
+ )
42
+ }
43
+ return `declare module "@hamur/db" {\n interface HamurDatabases {\n${entries.join("\n")}\n }\n}\nexport {};\n`
44
+ },
45
+ })
46
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,153 @@
1
+ import { mkdir, writeFile } from "node:fs/promises"
2
+ import { join, relative } from "node:path"
3
+ import { DiagnosticError, useLogger, type HamurContext } from "hamur/kit"
4
+ import { openDatabases } from "./build/databases.ts"
5
+ import { loadMigrations } from "./build/migrations.ts"
6
+ import { queueOptions } from "./build/queue.ts"
7
+ import { resolvedOptions } from "./module.ts"
8
+ import { compareIds, migrate, migrationStatus } from "./runtime/migrate.ts"
9
+ import { createQueueTable } from "./runtime/queue.ts"
10
+
11
+ export { tableProblem } from "./build/tables.ts"
12
+
13
+ export interface DbCommand {
14
+ command: "migrate" | "status" | "new"
15
+ /** The migration name of `new`. */
16
+ name?: string
17
+ /** `--connection`: one connection instead of every one. */
18
+ connection?: string
19
+ out(line: string): void
20
+ }
21
+
22
+ const MIGRATION_NAME = /^[a-z0-9_]+$/
23
+
24
+ /**
25
+ * The body of `hamur db`, on a context `createContext` made with the dev config (or the production one for `--prod`).
26
+ * Resolves to the exit code; a failure rejects with the message the CLI prints.
27
+ */
28
+ export async function runDbCommand(args: DbCommand, hamur: HamurContext): Promise<number> {
29
+ const options = resolvedOptions.get(hamur)
30
+ if (!options)
31
+ throw new DiagnosticError("HAMUR_E5501", "hamur db needs @hamur/db (bun add @hamur/db, then add it to modules)")
32
+ const { connection, out } = args
33
+ if (connection !== undefined && !Object.hasOwn(options.connections, connection)) {
34
+ throw new DiagnosticError(
35
+ "HAMUR_E5502",
36
+ `No database "${connection}": set db.connections.${connection} in hamur.config.ts`,
37
+ )
38
+ }
39
+ const names = connection === undefined ? Object.keys(options.connections) : [connection]
40
+ const all = await loadMigrations(hamur, options)
41
+
42
+ if (args.command === "new") {
43
+ const { name } = args
44
+ if (name === undefined)
45
+ throw new DiagnosticError("HAMUR_E5503", "hamur db new needs a migration name (hamur db new add_users)")
46
+ if (!MIGRATION_NAME.test(name))
47
+ throw new DiagnosticError("HAMUR_E5504", `Migration name ${JSON.stringify(name)} may hold only a-z, 0-9 and _`)
48
+ const target = connection ?? "default"
49
+ if (!Object.hasOwn(options.connections, target))
50
+ throw new DiagnosticError(
51
+ "HAMUR_E5502",
52
+ `No database "${target}": set db.connections.${target} in hamur.config.ts`,
53
+ )
54
+ const last = (all[target] ?? [])
55
+ .map((migration) => migration.id)
56
+ .sort(compareIds)
57
+ .at(-1)
58
+ const next = String(last === undefined ? 1n : BigInt(last) + 1n).padStart(4, "0")
59
+ const dir = join(hamur.options.serverDir, "db", "migrations", ...(target === "default" ? [] : [target]))
60
+ const file = join(dir, `${next}_${name}.sql`)
61
+ await mkdir(dir, { recursive: true })
62
+ await writeFile(file, `-- ${name}\n`, { flag: "wx" })
63
+ out(`Created ${relative(hamur.options.rootDir, file)}`)
64
+ return 0
65
+ }
66
+
67
+ const databases = openDatabases(hamur, options)
68
+ try {
69
+ for (const name of names) {
70
+ if (options.connections[name]!.connector === "d1") {
71
+ out(`db.connections.${name} uses d1; run wrangler d1 migrations apply or list`)
72
+ continue
73
+ }
74
+ const list = all[name] ?? []
75
+ if (args.command === "migrate") {
76
+ const applied = await migrate(databases.use(name), list, {
77
+ warn: (message) => useLogger("hamur").warn(message),
78
+ applied: (migration, ms) => out(`Applied ${migration.id}_${migration.name} (${Math.round(ms)} ms)`),
79
+ })
80
+ out(
81
+ applied.length
82
+ ? `${applied.length} migration${applied.length === 1 ? "" : "s"} applied to "${name}"`
83
+ : `No pending migrations on "${name}"`,
84
+ )
85
+ continue
86
+ }
87
+ if (names.length > 1) out(`${name}:`)
88
+ const states = await migrationStatus(databases.use(name), list)
89
+ if (!states.length) out(`No migrations on "${name}"`)
90
+ for (const state of states)
91
+ out(
92
+ [`${state.id}_${state.name}`, state.state, ...(state.state === "applied" ? [state.appliedAt] : [])].join(
93
+ " ",
94
+ ),
95
+ )
96
+ }
97
+ } finally {
98
+ await databases.close()
99
+ }
100
+ return 0
101
+ }
102
+
103
+ export interface QueueCommand {
104
+ command: "failed" | "retry"
105
+ /** The row id of `retry`. */
106
+ id?: string
107
+ out(line: string): void
108
+ }
109
+
110
+ const firstLine = (text: string | null) => (text ?? "").split("\n", 1)[0]
111
+
112
+ /**
113
+ * The body of `hamur task failed` and `hamur task retry <id>`, on a context `createContext` made with the production
114
+ * config: they read the queue table of the server's own connection. Resolves to the exit code.
115
+ */
116
+ export async function runQueueCommand(args: QueueCommand, hamur: HamurContext): Promise<number> {
117
+ const options = resolvedOptions.get(hamur)
118
+ const queue = queueOptions(hamur)
119
+ if (!options || !queue) throw new DiagnosticError("HAMUR_E5522", 'tasks.queue.driver "db" needs @hamur/db in modules')
120
+ const databases = openDatabases(hamur, options)
121
+ try {
122
+ const table = createQueueTable(() => databases.use(queue.connection), queue)
123
+ await table.ensure()
124
+ if (args.command === "retry") {
125
+ const id = args.id ?? ""
126
+ const retried = await table.retry(id)
127
+ if (retried.state === "missing")
128
+ throw new DiagnosticError("HAMUR_E5523", `No failed task run ${JSON.stringify(id)} in ${queue.table}`)
129
+ if (retried.state === "locked")
130
+ throw new DiagnosticError(
131
+ "HAMUR_E5524",
132
+ `Task run ${JSON.stringify(id)} is still locked by a run until ${new Date(retried.until).toISOString()}; retry it after that`,
133
+ )
134
+ args.out(`Task run ${id} is due again`)
135
+ return 0
136
+ }
137
+ const rows = await table.failed()
138
+ if (!rows.length) args.out("No failed task runs")
139
+ for (const row of rows)
140
+ args.out(
141
+ [
142
+ row.id,
143
+ row.task,
144
+ `${row.attempts} ${row.attempts === 1 ? "attempt" : "attempts"}`,
145
+ new Date(row.failedAt!).toISOString(),
146
+ firstLine(row.lastError),
147
+ ].join(" "),
148
+ )
149
+ return 0
150
+ } finally {
151
+ await databases.close()
152
+ }
153
+ }
@@ -0,0 +1,68 @@
1
+ import type { SQL } from "bun"
2
+ import {
3
+ insertId,
4
+ type Connector,
5
+ type ConnectorOptions,
6
+ type ConnectorSession,
7
+ type ReservedSession,
8
+ type TransactionSession,
9
+ } from "../runtime/connector.ts"
10
+ import type { Dialect } from "../types.ts"
11
+
12
+ const ADAPTER: Record<string, Dialect> = { postgres: "postgres", mysql: "mysql", mariadb: "mysql", sqlite: "sqlite" }
13
+
14
+ /** `new Bun.SQL(url)`, or `Bun.SQL`'s own env default without one; the adapter it chose must be the connection's dialect. */
15
+ export default async function openBunSql({ name, dialect, url }: ConnectorOptions): Promise<Connector> {
16
+ const sql = url === undefined ? new Bun.SQL() : new Bun.SQL(url)
17
+ const adapter = String(sql.options.adapter ?? "postgres")
18
+ if (ADAPTER[adapter] !== dialect) {
19
+ await sql.close()
20
+ throw new Error(
21
+ `db.connections.${name} is dialect ${dialect} but its url is ${adapter}:; set db.connections.${name}.dialect`,
22
+ )
23
+ }
24
+ const sessionOf = (client: SQL): ConnectorSession => {
25
+ const bind = (params: unknown[]) =>
26
+ dialect === "postgres" ? params.map((value) => (Array.isArray(value) ? client.array(value) : value)) : params
27
+ return {
28
+ all: async (text, params) => [...(await client.unsafe<Record<string, unknown>[]>(text, bind(params)))],
29
+ async run(text, params) {
30
+ const result = await client.unsafe(text, bind(params))
31
+ const id = dialect === "postgres" ? undefined : insertId(result.lastInsertRowid)
32
+ return id === undefined ? { changes: result.affectedRows } : { changes: result.affectedRows, lastInsertId: id }
33
+ },
34
+ async exec(text) {
35
+ await client.unsafe(text).simple()
36
+ },
37
+ }
38
+ }
39
+ const reservedOf = (client: SQL): ReservedSession => ({
40
+ ...sessionOf(client),
41
+ transaction: <R>(fn: (session: ConnectorSession) => Promise<R>) =>
42
+ (dialect === "sqlite"
43
+ ? client.begin("immediate", (tx) => fn(sessionOf(tx)))
44
+ : client.begin((tx) => fn(sessionOf(tx)))) as Promise<R>,
45
+ })
46
+ return {
47
+ ...sessionOf(sql),
48
+ async reserve(fn) {
49
+ // Bun.SQL on SQLite has one connection and no reserve(); the Database's process lock already holds it.
50
+ if (dialect === "sqlite") return fn(reservedOf(sql))
51
+ const reserved = await sql.reserve()
52
+ try {
53
+ return await fn(reservedOf(reserved))
54
+ } finally {
55
+ await reserved.release()
56
+ }
57
+ },
58
+ transaction: <R>(fn: (session: TransactionSession) => Promise<R>) =>
59
+ sql.begin((tx) =>
60
+ fn({
61
+ ...sessionOf(tx),
62
+ savepoint: <S>(inner: (session: ConnectorSession) => Promise<S>) =>
63
+ tx.savepoint("batch", (point) => inner(sessionOf(point))) as Promise<S>,
64
+ }),
65
+ ) as Promise<R>,
66
+ close: () => sql.close(),
67
+ }
68
+ }
@@ -0,0 +1,69 @@
1
+ import { Database as SQLite, type SQLQueryBindings } from "bun:sqlite"
2
+ import { mkdirSync } from "node:fs"
3
+ import { dirname, resolve } from "node:path"
4
+ import {
5
+ BUSY_TIMEOUT,
6
+ insertId,
7
+ journalWal,
8
+ type Connector,
9
+ type ConnectorOptions,
10
+ type ConnectorSession,
11
+ type TransactionSession,
12
+ } from "../runtime/connector.ts"
13
+
14
+ /** `Database` of `bun:sqlite` on `path` (against the working directory, its directory created), WAL unless in memory. */
15
+ export default function openBunSqlite({ path }: ConnectorOptions): Connector {
16
+ if (!path) throw new TypeError("The bun-sqlite connector needs a path")
17
+ const memory = path === ":memory:"
18
+ const file = memory ? path : resolve(path)
19
+ if (!memory) mkdirSync(dirname(file), { recursive: true })
20
+ const db = new SQLite(file, { create: true, strict: true })
21
+ db.run(`PRAGMA busy_timeout = ${BUSY_TIMEOUT}`)
22
+ if (!memory) journalWal((text) => db.run(text))
23
+ const bindings = (params: unknown[]) => params as SQLQueryBindings[]
24
+ const session: ConnectorSession = {
25
+ all: async (text, params) => db.query<Record<string, unknown>, SQLQueryBindings[]>(text).all(...bindings(params)),
26
+ async run(text, params) {
27
+ const result = db.query<unknown, SQLQueryBindings[]>(text).run(...bindings(params))
28
+ const id = insertId(result.lastInsertRowid)
29
+ return id === undefined ? { changes: result.changes } : { changes: result.changes, lastInsertId: id }
30
+ },
31
+ async exec(text) {
32
+ db.run(text)
33
+ },
34
+ }
35
+ const inTransaction: TransactionSession = {
36
+ ...session,
37
+ async savepoint(fn) {
38
+ db.run("SAVEPOINT hamur_batch")
39
+ try {
40
+ const result = await fn(session)
41
+ db.run("RELEASE SAVEPOINT hamur_batch")
42
+ return result
43
+ } catch (error) {
44
+ db.run("ROLLBACK TO SAVEPOINT hamur_batch")
45
+ db.run("RELEASE SAVEPOINT hamur_batch")
46
+ throw error
47
+ }
48
+ },
49
+ }
50
+ const transaction = async <R>(fn: (session: TransactionSession) => Promise<R>): Promise<R> => {
51
+ db.run("BEGIN IMMEDIATE")
52
+ try {
53
+ const result = await fn(inTransaction)
54
+ db.run("COMMIT")
55
+ return result
56
+ } catch (error) {
57
+ if (db.inTransaction) db.run("ROLLBACK")
58
+ throw error
59
+ }
60
+ }
61
+ return {
62
+ ...session,
63
+ transaction,
64
+ reserve: (fn) => fn({ ...session, transaction }),
65
+ async close() {
66
+ db.close()
67
+ },
68
+ }
69
+ }
@@ -0,0 +1,257 @@
1
+ import { Database as SQLite, type SQLQueryBindings } from "bun:sqlite"
2
+ import { SQL } from "bun"
3
+ import { mysqlStatements } from "../runtime/migrate.ts"
4
+ import type { DatabaseClient } from "../types.ts"
5
+
6
+ /** A driver over `bun:sqlite` that takes `$n` placeholders, as a Postgres driver does, and `?`; one connection, so `reserve` gives it. */
7
+ export function fakeSqliteClient(): DatabaseClient & { ended: boolean } {
8
+ const db = new SQLite(":memory:", { strict: true })
9
+ const query: DatabaseClient["query"] = async (text, params) => {
10
+ const statement = db.query<Record<string, unknown>, SQLQueryBindings[]>(text.replace(/\$(\d+)/g, "?$1"))
11
+ const values = params as SQLQueryBindings[]
12
+ if (statement.columnNames.length) return { rows: statement.all(...values) }
13
+ const { changes, lastInsertRowid } = statement.run(...values)
14
+ return { rows: [], changes, lastInsertId: Number(lastInsertRowid) }
15
+ }
16
+ const client = {
17
+ ended: false,
18
+ query,
19
+ reserve: async () => ({ query, release() {} }),
20
+ async end() {
21
+ client.ended = true
22
+ db.close()
23
+ },
24
+ }
25
+ return client
26
+ }
27
+
28
+ /*
29
+ * The fakes below stand in for `pg` 8 and `mysql2` 3, which are not installed: each is the part of the library's API the samples
30
+ * call, over `Bun.SQL`, with the library's own handling of values and results as far as it is known without its source.
31
+ */
32
+
33
+ /** `pg`'s `QueryResult`. */
34
+ export interface QueryResult {
35
+ rows: Record<string, unknown>[]
36
+ rowCount: number | null
37
+ }
38
+
39
+ /** `pg`'s `PoolClient`: `query` resolves to one `QueryResult` per statement, a list when the text holds several. */
40
+ export interface PoolClient {
41
+ query(text: string, values?: unknown[]): Promise<QueryResult>
42
+ /** An error (or `true`) destroys the connection instead of returning it to the pool. */
43
+ release(error?: Error | boolean): void
44
+ }
45
+
46
+ /** `pg`'s `Pool`. */
47
+ export interface Pool {
48
+ query(text: string, values?: unknown[]): Promise<QueryResult>
49
+ connect(): Promise<PoolClient>
50
+ end(): Promise<void>
51
+ }
52
+
53
+ /** `mysql2`'s `ResultSetHeader`: what a write resolves to. */
54
+ export interface ResultSetHeader {
55
+ affectedRows: number
56
+ /** A string above `Number.MAX_SAFE_INTEGER` with `supportBigNumbers`. */
57
+ insertId: number | string
58
+ }
59
+
60
+ type MysqlResult = [Record<string, unknown>[] | ResultSetHeader, unknown]
61
+
62
+ /** `mysql2/promise`'s `PoolConnection`. */
63
+ export interface PoolConnection {
64
+ /** Text protocol: `values` are escaped into the text on the client, one per `?`, quotes or not. */
65
+ query(sql: string, values?: unknown[]): Promise<MysqlResult>
66
+ /** A server-side prepared statement: `values` are bound, never put in the text. */
67
+ execute(sql: string, values?: unknown[]): Promise<MysqlResult>
68
+ release(): void
69
+ /** Closes the connection instead of returning it to the pool. */
70
+ destroy(): void
71
+ }
72
+
73
+ /** `mysql2/promise`'s `Pool`. */
74
+ export interface MysqlPool {
75
+ query(sql: string, values?: unknown[]): Promise<MysqlResult>
76
+ execute(sql: string, values?: unknown[]): Promise<MysqlResult>
77
+ getConnection(): Promise<PoolConnection>
78
+ end(): Promise<void>
79
+ }
80
+
81
+ const pad = (value: number, size = 2) => String(value).padStart(size, "0")
82
+
83
+ /** `pg`'s `dateToString`: local time with its offset. */
84
+ function pgDate(date: Date): string {
85
+ const offset = -date.getTimezoneOffset()
86
+ const sign = offset >= 0 ? "+" : "-"
87
+ const local = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
88
+ return `${local}${sign}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`
89
+ }
90
+
91
+ /** `pg`'s array literal: `{1,"a b",NULL}`. */
92
+ function pgArray(values: readonly unknown[]): string {
93
+ const item = (value: unknown): string => {
94
+ if (value === null || value === undefined) return "NULL"
95
+ if (Array.isArray(value)) return pgArray(value)
96
+ const text = String(pgValue(value))
97
+ return `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`
98
+ }
99
+ return `{${values.map(item).join(",")}}`
100
+ }
101
+
102
+ /** `pg`'s `prepareValue`: every value goes as untyped text, which the server reads in its context, except bytes. */
103
+ function pgValue(value: unknown): unknown {
104
+ if (value === null || value === undefined) return null
105
+ if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
106
+ if (value instanceof Date) return pgDate(value)
107
+ if (Array.isArray(value)) return pgArray(value)
108
+ if (typeof value === "object") return JSON.stringify(value)
109
+ return String(value)
110
+ }
111
+
112
+ /** A `pg` `Pool` over `Bun.SQL`: text parameters, the simple protocol without values, and a list of results for several statements. */
113
+ export function fakePgPool(url: string): Pool & { released: Array<Error | boolean | undefined> } {
114
+ const sql = new SQL(url)
115
+ const resultOf = (rows: Record<string, unknown>[] & { count?: number }): QueryResult => ({
116
+ rows: [...rows],
117
+ rowCount: rows.count ?? null,
118
+ })
119
+ const on =
120
+ (client: SQL) =>
121
+ async (text: string, values: unknown[] = []): Promise<QueryResult> => {
122
+ if (values.length) return resultOf(await client.unsafe(text, values.map(pgValue)))
123
+ const result = await client.unsafe(text).simple()
124
+ // Several statements: Bun resolves to a list of results, as pg does.
125
+ return (
126
+ Array.isArray(result[0])
127
+ ? (result as unknown as Array<Record<string, unknown>[]>).map(resultOf)
128
+ : resultOf(result)
129
+ ) as QueryResult
130
+ }
131
+ const released: Array<Error | boolean | undefined> = []
132
+ return {
133
+ released,
134
+ query: on(sql),
135
+ async connect() {
136
+ const reserved = await sql.reserve()
137
+ return {
138
+ query: on(reserved),
139
+ release(error) {
140
+ released.push(error)
141
+ if (error) void reserved.close()
142
+ else void reserved.release()
143
+ },
144
+ }
145
+ },
146
+ end: () => sql.close(),
147
+ }
148
+ }
149
+
150
+ /** `sqlstring.escape`: a value as SQL text. A `Uint8Array` that is not a `Buffer` is an object: its keys become `key` = value pairs. */
151
+ function escape(value: unknown): string {
152
+ if (value === null || value === undefined) return "NULL"
153
+ if (typeof value === "boolean") return value ? "true" : "false"
154
+ if (typeof value === "number" || typeof value === "bigint") return String(value)
155
+ if (value instanceof Date) return `'${mysqlDate(value)}'`
156
+ if (Buffer.isBuffer(value)) return `X'${value.toString("hex")}'`
157
+ if (Array.isArray(value)) return value.map(escape).join(", ")
158
+ if (typeof value === "object")
159
+ return Object.entries(value)
160
+ .map(([key, item]) => `\`${key}\` = ${escape(item)}`)
161
+ .join(", ")
162
+ return `'${String(value).replace(/[\0\b\t\n\r\x1a"'\\]/g, (char) => `\\${char === "\0" ? "0" : char}`)}'`
163
+ }
164
+
165
+ /** `sqlstring.format`: each `?` takes the next value, inside quotes too. */
166
+ function format(sql: string, values: unknown[]): string {
167
+ let index = 0
168
+ return sql.replace(/\?+/g, (match) => (match.length === 1 && index < values.length ? escape(values[index++]) : match))
169
+ }
170
+
171
+ /** `mysql2`'s `timezone: "local"`: a `Date` is written and read as local wall time. */
172
+ function mysqlDate(date: Date): string {
173
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
174
+ }
175
+
176
+ /** `mysql2`'s binary protocol value: a `Date` in local time, a `Buffer` as bytes, any other object as JSON. */
177
+ function mysqlParam(value: unknown): unknown {
178
+ if (value === undefined)
179
+ throw new TypeError("Bind parameters must not contain undefined. To pass SQL NULL specify JS null")
180
+ if (value === null || typeof value !== "object" || Buffer.isBuffer(value)) return value
181
+ if (value instanceof Date) return mysqlDate(value)
182
+ return JSON.stringify(value)
183
+ }
184
+
185
+ const LONGLONG = 8
186
+ const DATES = new Set([7, 10, 12])
187
+
188
+ /** A `mysql2/promise` `Pool` over `Bun.SQL`, its pool options as given: `supportBigNumbers` reads a BIGINT above 2^53 as a string. */
189
+ export function fakeMysqlPool(
190
+ url: string,
191
+ { supportBigNumbers = false }: { supportBigNumbers?: boolean } = {},
192
+ ): MysqlPool & { destroyed: number } {
193
+ // mysql2 sets CLIENT_FOUND_ROWS: affectedRows counts the rows an UPDATE matched.
194
+ const sql = new SQL(url, { foundRows: true })
195
+ const big = (value: unknown) => {
196
+ if (typeof value !== "string" && typeof value !== "bigint") return value
197
+ const number = Number(value)
198
+ return supportBigNumbers && !Number.isSafeInteger(number) ? String(value) : number
199
+ }
200
+ const resultOf = (result: Record<string, unknown>[] & SQL.ResultMetadata): MysqlResult => {
201
+ if (!result.columns?.length) {
202
+ return [
203
+ { affectedRows: result.affectedRows, insertId: big(result.lastInsertRowid ?? 0) as number | string },
204
+ undefined,
205
+ ]
206
+ }
207
+ const rows = [...result].map((row) => {
208
+ const out = { ...row }
209
+ for (const column of result.columns!) {
210
+ const value = out[column.name]
211
+ if (column.type === LONGLONG) out[column.name] = big(value)
212
+ else if (DATES.has(column.type) && value instanceof Date) {
213
+ out[column.name] = new Date(
214
+ value.getUTCFullYear(),
215
+ value.getUTCMonth(),
216
+ value.getUTCDate(),
217
+ value.getUTCHours(),
218
+ value.getUTCMinutes(),
219
+ value.getUTCSeconds(),
220
+ value.getUTCMilliseconds(),
221
+ )
222
+ }
223
+ }
224
+ return out
225
+ })
226
+ return [rows, result.columns]
227
+ }
228
+ const on = (client: SQL) => ({
229
+ async query(text: string, values: unknown[] = []): Promise<MysqlResult> {
230
+ const formatted = values.length ? format(text, values) : text
231
+ // multipleStatements is off by default.
232
+ if (mysqlStatements(formatted).length > 1)
233
+ throw Object.assign(new Error("You have an error in your SQL syntax"), { code: "ER_PARSE_ERROR" })
234
+ return resultOf((await client.unsafe(formatted).simple()) as never)
235
+ },
236
+ async execute(text: string, values: unknown[] = []): Promise<MysqlResult> {
237
+ return resultOf((await client.unsafe(text, values.map(mysqlParam))) as never)
238
+ },
239
+ })
240
+ const pool = {
241
+ destroyed: 0,
242
+ ...on(sql),
243
+ async getConnection(): Promise<PoolConnection> {
244
+ const reserved = await sql.reserve()
245
+ return {
246
+ ...on(reserved),
247
+ release: () => void reserved.release(),
248
+ destroy() {
249
+ pool.destroyed++
250
+ void reserved.close()
251
+ },
252
+ }
253
+ },
254
+ end: () => sql.close(),
255
+ }
256
+ return pool
257
+ }