@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,161 @@
1
+ import {
2
+ insertId,
3
+ type ClientLoader,
4
+ type Connector,
5
+ type ConnectorOptions,
6
+ type ConnectorSession,
7
+ type ReservedSession,
8
+ type TransactionSession,
9
+ } from "../runtime/connector.ts"
10
+ import { mysqlStatements } from "../runtime/migrate.ts"
11
+ import type { DatabaseClient, Dialect, RunResult } from "../types.ts"
12
+ import { sqliteStatements } from "./d1.ts"
13
+
14
+ type Query = DatabaseClient["query"]
15
+ type Reserved = Awaited<ReturnType<NonNullable<DatabaseClient["reserve"]>>>
16
+
17
+ const BEGIN: Record<Dialect, string> = { postgres: "BEGIN", mysql: "START TRANSACTION", sqlite: "BEGIN IMMEDIATE" }
18
+
19
+ /** A client the factory made that is not a `DatabaseClient`: the factory is not called again for that file. */
20
+ const refused = new WeakMap<ClientLoader, Error>()
21
+
22
+ /**
23
+ * A driver that prepares its text (`mysql2`'s `execute`, `better-sqlite3`) refuses several statements in one call, so mysql and
24
+ * sqlite text goes one statement at a time. Postgres text goes whole: `pg` runs a query without parameters on the simple
25
+ * protocol, which takes several statements, and a split would have to read dollar-quoted bodies.
26
+ */
27
+ function statementsOf(dialect: Dialect, text: string): string[] {
28
+ if (dialect === "mysql") return mysqlStatements(text)
29
+ if (dialect === "sqlite") return sqliteStatements(text)
30
+ return [text]
31
+ }
32
+
33
+ /** `error`, carrying `cause` when it has none of its own: the error that came first stays reachable. */
34
+ function after(error: unknown, cause: unknown): unknown {
35
+ if (error instanceof Error && error.cause === undefined) error.cause = cause
36
+ return error
37
+ }
38
+
39
+ const asError = (value: unknown) => (value instanceof Error ? value : new Error(String(value)))
40
+
41
+ /** The app's file, its default export `defineDatabaseClient(() => client)` called once at the connection's first query. */
42
+ export default async function openClient({ name, dialect, client: load }: ConnectorOptions): Promise<Connector> {
43
+ if (!load) throw new TypeError("The client connector needs a client file")
44
+ const at = `db.connections.${name}`
45
+ const known = refused.get(load)
46
+ if (known) throw known
47
+ const factory = ((await load()) as { default?: unknown }).default
48
+ if (typeof factory !== "function")
49
+ throw new TypeError(`The database client of ${at} must export default defineDatabaseClient(() => client)`)
50
+ const client = (await factory()) as DatabaseClient
51
+ if (typeof client !== "object" || client === null || typeof client.query !== "function") {
52
+ const error = new TypeError(
53
+ `The database client of ${at} has no query(text, params); return { query, reserve?, end? } from defineDatabaseClient`,
54
+ )
55
+ refused.set(load, error)
56
+ await (client as Partial<DatabaseClient> | null)?.end?.().catch(() => {})
57
+ throw error
58
+ }
59
+
60
+ const call = async (query: Query, text: string, params: unknown[]) => {
61
+ const result = await query(text, params)
62
+ if (typeof result !== "object" || result === null || !Array.isArray(result.rows)) {
63
+ throw new TypeError(
64
+ `The database client of ${at} returned no rows array from query(); return { rows, changes?, lastInsertId? }`,
65
+ )
66
+ }
67
+ return result
68
+ }
69
+ /** Text whose result is not read: `exec`, `BEGIN`, `COMMIT`. A driver may answer several statements with a list of results (`pg`). */
70
+ const send = async (query: Query, text: string) => void (await query(text, []))
71
+
72
+ const sessionOf = (query: Query): ConnectorSession => ({
73
+ all: async (text, params) => (await call(query, text, params)).rows,
74
+ async run(text, params): Promise<RunResult> {
75
+ const result = await call(query, text, params)
76
+ const changes = result.changes ?? 0
77
+ const id = dialect === "postgres" ? undefined : insertId(result.lastInsertId)
78
+ return id === undefined ? { changes } : { changes, lastInsertId: id }
79
+ },
80
+ async exec(text) {
81
+ for (const statement of statementsOf(dialect, text)) await send(query, statement)
82
+ },
83
+ })
84
+
85
+ /** Runs `fn` on a reserved connection; `fn` reports through `broken` an error that leaves the connection unusable, which `release` gets. */
86
+ const reserved = async <R>(
87
+ needs: string,
88
+ fn: (query: Query, broken: (error: unknown) => void) => Promise<R>,
89
+ ): Promise<R> => {
90
+ if (typeof client.reserve !== "function")
91
+ throw new Error(`${needs} a client with reserve(); the client of ${at} has none`)
92
+ const connection: Reserved = await client.reserve()
93
+ let bad: Error | undefined
94
+ let result: R
95
+ try {
96
+ result = await fn(connection.query.bind(connection), (error) => void (bad ??= asError(error)))
97
+ } catch (error) {
98
+ try {
99
+ await connection.release(bad)
100
+ } catch (released) {
101
+ throw after(released, error)
102
+ }
103
+ throw error
104
+ }
105
+ await connection.release(bad)
106
+ return result
107
+ }
108
+
109
+ const inTransaction = async <R>(query: Query, broken: (error: unknown) => void, fn: () => Promise<R>): Promise<R> => {
110
+ await send(query, BEGIN[dialect])
111
+ try {
112
+ const result = await fn()
113
+ await send(query, "COMMIT")
114
+ return result
115
+ } catch (error) {
116
+ await send(query, "ROLLBACK").catch((failed: unknown) => broken(after(failed, error)))
117
+ throw error
118
+ }
119
+ }
120
+
121
+ const savepoint =
122
+ (query: Query) =>
123
+ async <S>(fn: (session: ConnectorSession) => Promise<S>): Promise<S> => {
124
+ await send(query, "SAVEPOINT hamur_batch")
125
+ try {
126
+ const result = await fn(sessionOf(query))
127
+ await send(query, "RELEASE SAVEPOINT hamur_batch")
128
+ return result
129
+ } catch (error) {
130
+ try {
131
+ await send(query, "ROLLBACK TO SAVEPOINT hamur_batch")
132
+ await send(query, "RELEASE SAVEPOINT hamur_batch")
133
+ } catch (failed) {
134
+ throw after(failed, error)
135
+ }
136
+ throw error
137
+ }
138
+ }
139
+
140
+ return {
141
+ ...sessionOf(client.query.bind(client)),
142
+ transaction: <R>(fn: (session: TransactionSession) => Promise<R>) =>
143
+ reserved("transaction needs", (query, broken) =>
144
+ inTransaction(query, broken, () => fn({ ...sessionOf(query), savepoint: savepoint(query) })),
145
+ ),
146
+ reserve: <R>(fn: (session: ReservedSession) => Promise<R>) =>
147
+ reserved("migrations need", async (query, broken) => {
148
+ const session = sessionOf(query)
149
+ try {
150
+ return await fn({ ...session, transaction: (inner) => inTransaction(query, broken, () => inner(session)) })
151
+ } catch (error) {
152
+ // A failed run may leave its lock (pg_advisory_lock, GET_LOCK) on the connection.
153
+ broken(error)
154
+ throw error
155
+ }
156
+ }),
157
+ async close() {
158
+ await client.end?.()
159
+ },
160
+ }
161
+ }
@@ -0,0 +1,92 @@
1
+ import { Database as SQLite, type SQLQueryBindings } from "bun:sqlite"
2
+
3
+ interface FakeResult {
4
+ results: Record<string, unknown>[]
5
+ success: true
6
+ meta: { changes: number; last_row_id: number }
7
+ }
8
+
9
+ /** D1's type conversion: null, number, string, boolean and bytes bind; anything else (a bigint) is refused as D1 refuses it. */
10
+ function bindable(value: unknown): SQLQueryBindings {
11
+ if (value === null || typeof value === "number" || typeof value === "string") return value
12
+ if (typeof value === "boolean") return value ? 1 : 0
13
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
14
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
15
+ throw new Error(`D1_TYPE_ERROR: Type '${typeof value}' not supported for value '${String(value)}'`)
16
+ }
17
+
18
+ /** D1 gives a blob back as an array of bytes. */
19
+ const d1Row = (row: Record<string, unknown>) =>
20
+ Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value instanceof Uint8Array ? [...value] : value]))
21
+
22
+ class FakeStatement {
23
+ readonly db: SQLite
24
+ readonly text: string
25
+ readonly values: SQLQueryBindings[]
26
+
27
+ constructor(db: SQLite, text: string, values: SQLQueryBindings[] = []) {
28
+ this.db = db
29
+ this.text = text
30
+ this.values = values
31
+ }
32
+
33
+ bind(...values: unknown[]): FakeStatement {
34
+ return new FakeStatement(this.db, this.text, values.map(bindable))
35
+ }
36
+
37
+ execute(): FakeResult {
38
+ const statement = this.db.query<Record<string, unknown>, SQLQueryBindings[]>(this.text)
39
+ if (statement.columnNames.length) {
40
+ const results = statement.all(...this.values).map(d1Row)
41
+ const { changes, id } = this.db
42
+ .query<{ changes: number; id: number }, []>("select changes() as changes, last_insert_rowid() as id")
43
+ .get()!
44
+ return {
45
+ results,
46
+ success: true,
47
+ meta: { changes: /^\s*select\b/i.test(this.text) ? 0 : changes, last_row_id: id },
48
+ }
49
+ }
50
+ const { changes, lastInsertRowid } = statement.run(...this.values)
51
+ return { results: [], success: true, meta: { changes, last_row_id: Number(lastInsertRowid) } }
52
+ }
53
+
54
+ async all(): Promise<FakeResult> {
55
+ return this.execute()
56
+ }
57
+
58
+ async run(): Promise<FakeResult> {
59
+ return this.execute()
60
+ }
61
+
62
+ async first(column?: string): Promise<unknown> {
63
+ const row = this.execute().results[0]
64
+ if (!row) return null
65
+ return column === undefined ? row : row[column]
66
+ }
67
+ }
68
+
69
+ /** A D1 binding (`env.DB`) over `bun:sqlite` for tests: `prepare().bind().all()/first()/run()`, an atomic `batch` and `exec`. */
70
+ export function fakeD1(path = ":memory:") {
71
+ const db = new SQLite(path, { create: true, strict: true })
72
+ return {
73
+ prepare: (text: string) => new FakeStatement(db, text),
74
+ async batch(statements: FakeStatement[]): Promise<FakeResult[]> {
75
+ return db.transaction(() => statements.map((statement) => statement.execute()))()
76
+ },
77
+ /** As D1's `exec`: the trimmed text split at `\n`, each line a query of its own. */
78
+ async exec(text: string) {
79
+ const started = performance.now()
80
+ const lines = text.trim().split("\n")
81
+ for (const [index, line] of lines.entries()) {
82
+ try {
83
+ db.run(line)
84
+ } catch (error) {
85
+ throw new Error(`D1_EXEC_ERROR: Error in line ${index + 1}: ${line}: ${(error as Error).message}`)
86
+ }
87
+ }
88
+ return { count: lines.length, duration: performance.now() - started }
89
+ },
90
+ close: () => db.close(),
91
+ }
92
+ }
@@ -0,0 +1,151 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { outsideWorker } from "hamur/server"
3
+ import {
4
+ insertId,
5
+ type BatchStatement,
6
+ type Connector,
7
+ type ConnectorOptions,
8
+ type ConnectorSession,
9
+ } from "../runtime/connector.ts"
10
+ import type { RunResult } from "../types.ts"
11
+
12
+ interface D1Result {
13
+ results?: Record<string, unknown>[]
14
+ meta: { changes?: number; last_row_id?: number | null }
15
+ }
16
+
17
+ interface D1PreparedStatement {
18
+ bind(...values: unknown[]): D1PreparedStatement
19
+ all(): Promise<D1Result>
20
+ run(): Promise<D1Result>
21
+ }
22
+
23
+ /** The part of a D1 binding (`env.DB`) the connector calls. */
24
+ export interface D1Database {
25
+ prepare(query: string): D1PreparedStatement
26
+ batch(statements: D1PreparedStatement[]): Promise<D1Result[]>
27
+ }
28
+
29
+ const TRANSACTION =
30
+ "transaction is not available on the d1 connector: D1 has no interactive transactions; use batch([...])"
31
+
32
+ /** `env` of `cloudflare:workers`, imported at first use through a specifier the bundler leaves alone; on Bun outside `hamur dev` (`hamur task run --prod`) the error names the binding and, in a task, `tasks.http`. */
33
+ async function workersEnv(name: string, binding: string | undefined): Promise<Record<string, unknown>> {
34
+ const specifier = "cloudflare:workers"
35
+ try {
36
+ return ((await import(specifier)) as { env: Record<string, unknown> }).env
37
+ } catch {
38
+ if (import.meta.dev) {
39
+ throw new Error(
40
+ `db.connections.${name} uses d1, which hamur dev reaches only through the app's wrangler; set db.connections.${name}.dev to a bun-sqlite connection`,
41
+ )
42
+ }
43
+ return outsideWorker(`db.connections.${name} uses the d1 binding ${JSON.stringify(binding)}`)
44
+ }
45
+ }
46
+
47
+ /** D1 binds no bigint: one in the safe range binds as a number, a larger one as its decimal text, which an INTEGER column stores as the integer. */
48
+ const param = (value: unknown) =>
49
+ typeof value === "bigint"
50
+ ? value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER)
51
+ ? Number(value)
52
+ : String(value)
53
+ : value
54
+
55
+ /** D1 reads a blob back as an array of bytes; the connector gives a `Uint8Array`. */
56
+ function rowOf(row: Record<string, unknown>): Record<string, unknown> {
57
+ const out: Record<string, unknown> = {}
58
+ for (const [key, value] of Object.entries(row))
59
+ out[key] = Array.isArray(value) ? Uint8Array.from(value as number[]) : value
60
+ return out
61
+ }
62
+
63
+ /**
64
+ * The statements of SQLite text, split at `;` outside quotes, brackets and comments, comments dropped; a `CREATE TRIGGER` runs
65
+ * to its `END`. D1's own `exec` sends each line as a query of its own, so multi-line text cannot go through it.
66
+ */
67
+ export function sqliteStatements(sql: string): string[] {
68
+ const statements: string[] = []
69
+ let current = ""
70
+ const push = () => {
71
+ if (current.trim()) statements.push(current.trim())
72
+ current = ""
73
+ }
74
+ for (let i = 0; i < sql.length; i++) {
75
+ const char = sql[i]!
76
+ const next = sql[i + 1]
77
+ if (char === "'" || char === '"' || char === "`" || char === "[") {
78
+ const close = char === "[" ? "]" : char
79
+ let end = i + 1
80
+ while (end < sql.length) {
81
+ if (sql[end] === close && close !== "]" && sql[end + 1] === close) end += 2
82
+ else if (sql[end] === close) break
83
+ else end++
84
+ }
85
+ current += sql.slice(i, end + 1)
86
+ i = end
87
+ } else if (char === "-" && next === "-") {
88
+ while (i < sql.length && sql[i] !== "\n") i++
89
+ current += "\n"
90
+ } else if (char === "/" && next === "*") {
91
+ const end = sql.indexOf("*/", i + 2)
92
+ i = end < 0 ? sql.length : end + 1
93
+ current += " "
94
+ } else if (char === ";") {
95
+ if (/^\s*create\s+(?:temp\s+|temporary\s+)?trigger\b/i.test(current) && !/\bend\s*$/i.test(current))
96
+ current += char
97
+ else push()
98
+ } else current += char
99
+ }
100
+ push()
101
+ return statements
102
+ }
103
+
104
+ const written = ({ meta }: D1Result): RunResult => {
105
+ const changes = meta.changes ?? 0
106
+ const id = insertId(meta.last_row_id)
107
+ return id === undefined ? { changes } : { changes, lastInsertId: id }
108
+ }
109
+
110
+ /** `env[binding]` of `cloudflare:workers`; `batch` is D1's `batch`, and `transaction` is refused, as D1 has none. */
111
+ export default async function openD1(
112
+ { name, binding }: ConnectorOptions,
113
+ env: () => Promise<Record<string, unknown>> = () => workersEnv(name, binding),
114
+ ): Promise<Connector> {
115
+ if (!binding) throw new TypeError("The d1 connector needs a binding")
116
+ const db = (await env())[binding] as D1Database | undefined
117
+ if (!db || typeof db.prepare !== "function" || typeof db.batch !== "function") {
118
+ throw new Error(
119
+ `The d1 connector found no D1 binding "${binding}" in env (db.connections.${name}.binding; declare it in d1_databases of the wrangler config)`,
120
+ )
121
+ }
122
+ const statement = (text: string, params: unknown[]) => {
123
+ const prepared = db.prepare(text)
124
+ return params.length ? prepared.bind(...params.map(param)) : prepared
125
+ }
126
+ const session: ConnectorSession = {
127
+ all: async (text, params) => ((await statement(text, params).all()).results ?? []).map(rowOf),
128
+ run: async (text, params) => written(await statement(text, params).run()),
129
+ async exec(text) {
130
+ const statements = sqliteStatements(text)
131
+ if (statements.length) await db.batch(statements.map((sql) => db.prepare(sql)))
132
+ },
133
+ }
134
+ return {
135
+ ...session,
136
+ concurrent: true,
137
+ async batch(statements: BatchStatement[]) {
138
+ const results = await db.batch(statements.map(({ text, params }) => statement(text, params)))
139
+ return results.map((result, index) =>
140
+ statements[index]!.kind === "run" ? written(result) : (result.results ?? []).map(rowOf),
141
+ )
142
+ },
143
+ async transaction() {
144
+ throw new Error(TRANSACTION)
145
+ },
146
+ async reserve() {
147
+ throw new Error(`db.connections.${name} uses d1; run wrangler d1 migrations apply or list`)
148
+ },
149
+ async close() {},
150
+ }
151
+ }
@@ -0,0 +1,83 @@
1
+ import { mkdirSync } from "node:fs"
2
+ import { dirname, resolve } from "node:path"
3
+ import { DatabaseSync, type SQLInputValue } from "node:sqlite"
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
+ /** `DatabaseSync` of `node:sqlite` (Node ≥ 24) on `path` (against the working directory, its directory created), WAL unless in memory. */
15
+ export default function openNodeSqlite({ path }: ConnectorOptions): Connector {
16
+ if (!path) throw new TypeError("The node-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 DatabaseSync(file)
21
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT}`)
22
+ if (!memory) journalWal((text) => db.exec(text))
23
+ const bindings = (params: unknown[]) => params as SQLInputValue[]
24
+ // node:sqlite throws ERR_OUT_OF_RANGE on an integer above 2^53 by default; it is read as bun:sqlite does, a number.
25
+ const prepare = (text: string) => {
26
+ const statement = db.prepare(text)
27
+ statement.setReadBigInts(true)
28
+ return statement
29
+ }
30
+ const session: ConnectorSession = {
31
+ all: async (text, params) =>
32
+ prepare(text)
33
+ .all(...bindings(params))
34
+ .map((row) =>
35
+ Object.fromEntries(
36
+ Object.entries(row).map(([key, value]) => [key, typeof value === "bigint" ? Number(value) : value]),
37
+ ),
38
+ ),
39
+ async run(text, params) {
40
+ const result = prepare(text).run(...bindings(params))
41
+ const changes = Number(result.changes)
42
+ const id = insertId(result.lastInsertRowid)
43
+ return id === undefined ? { changes } : { changes, lastInsertId: id }
44
+ },
45
+ async exec(text) {
46
+ db.exec(text)
47
+ },
48
+ }
49
+ const inTransaction: TransactionSession = {
50
+ ...session,
51
+ async savepoint(fn) {
52
+ db.exec("SAVEPOINT hamur_batch")
53
+ try {
54
+ const result = await fn(session)
55
+ db.exec("RELEASE SAVEPOINT hamur_batch")
56
+ return result
57
+ } catch (error) {
58
+ db.exec("ROLLBACK TO SAVEPOINT hamur_batch")
59
+ db.exec("RELEASE SAVEPOINT hamur_batch")
60
+ throw error
61
+ }
62
+ },
63
+ }
64
+ const transaction = async <R>(fn: (session: TransactionSession) => Promise<R>): Promise<R> => {
65
+ db.exec("BEGIN IMMEDIATE")
66
+ try {
67
+ const result = await fn(inTransaction)
68
+ db.exec("COMMIT")
69
+ return result
70
+ } catch (error) {
71
+ if (db.isTransaction) db.exec("ROLLBACK")
72
+ throw error
73
+ }
74
+ }
75
+ return {
76
+ ...session,
77
+ transaction,
78
+ reserve: (fn) => fn({ ...session, transaction }),
79
+ async close() {
80
+ db.close()
81
+ },
82
+ }
83
+ }
@@ -0,0 +1,31 @@
1
+ import assert from "node:assert/strict"
2
+ import { after, before, describe as nodeDescribe, test } from "node:test"
3
+
4
+ /** The part of `bun:test` that `suite.ts` calls, on `node:test` and `node:assert`, so the connector suite runs under real `node`. */
5
+ type Expected = string | Error | undefined
6
+
7
+ const matches = (expected: Expected) => (error: unknown) => {
8
+ const message = (error as Error | undefined)?.message ?? ""
9
+ if (expected === undefined) return true
10
+ if (typeof expected === "string") return message.includes(expected)
11
+ return (error as Error).constructor === expected.constructor && message === expected.message
12
+ }
13
+
14
+ export function expect(actual: unknown) {
15
+ return {
16
+ toBe: (expected: unknown) => assert.equal(actual, expected),
17
+ toEqual: (expected: unknown) => assert.deepEqual(actual, expected),
18
+ toBeUndefined: () => assert.equal(actual, undefined),
19
+ toThrow: (expected?: Expected) => assert.throws(actual as () => unknown, matches(expected)),
20
+ rejects: {
21
+ toThrow: (expected?: Expected) => assert.rejects(actual as Promise<unknown>, matches(expected)),
22
+ toBe: (expected: unknown) => assert.rejects(actual as Promise<unknown>, (error) => error === expected),
23
+ },
24
+ }
25
+ }
26
+
27
+ export const describe = Object.assign((name: string, fn: () => void) => nodeDescribe(name, fn), {
28
+ skipIf: (skip: boolean) => (name: string, fn: () => void) => nodeDescribe(name, { skip }, fn),
29
+ })
30
+
31
+ export { after as afterAll, before as beforeAll, test }