@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
package/src/env.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ declare module "#hamur/db/connections" {
2
+ export const connections: Record<string, import("./types.ts").ResolvedConnection>
3
+ export const connectors: import("./runtime/registry.ts").ConnectorLoaders
4
+ export const clients: import("./runtime/registry.ts").ClientLoaders
5
+ }
6
+
7
+ declare module "#hamur/db/queue" {
8
+ /** `tasks.queue` when it is `{ driver: "db" }`, its defaults filled. */
9
+ export const queue: import("./runtime/queue.ts").QueueOptions | undefined
10
+ }
11
+
12
+ declare module "#hamur/db/factories" {
13
+ /** The default export of each `server/db/factories` file, by connection and table. */
14
+ export const factories: Record<string, Record<string, unknown>>
15
+ }
16
+
17
+ declare module "#hamur/db/migrations" {
18
+ /** Whether the server applies `migrations` when its plugins run. */
19
+ export const apply: boolean
20
+ export const migrations: Record<string, import("./runtime/migrate.ts").Migration[]>
21
+ }
22
+
23
+ interface ImportMeta {
24
+ /** `true` in the server bundle while the build prerenders. */
25
+ readonly prerender?: boolean
26
+ /** `true` in the bundles of `hamur dev`. */
27
+ readonly dev?: boolean
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ export { default } from "./module.ts"
2
+ export type { Connection, Database, DatabaseClient, DbConfig, Query, SqlFragment, Transaction } from "./types.ts"
3
+
4
+ /** Typegen fills it, `HamurDatabases[<connection>] = { dialect, tables, inserts }`; empty until the app has a connection. */
5
+ export interface HamurDatabases {}
6
+
7
+ /** The connection names of the app, `string` while typegen has written none. */
8
+ export type DatabaseName = keyof HamurDatabases extends never ? string : keyof HamurDatabases & string
9
+
10
+ /** `"default"`, or any name when the app has no `default` connection (a preset without a database of its own). */
11
+ export type DefaultDatabase = "default" extends DatabaseName ? "default" : DatabaseName
12
+
13
+ /** The tables migrations created in connection `C`, `string` while typegen has written none. */
14
+ export type TableName<C extends DatabaseName = DefaultDatabase> = C extends keyof HamurDatabases
15
+ ? HamurDatabases[C] extends { tables: infer T }
16
+ ? keyof T & string
17
+ : string
18
+ : string
19
+
20
+ /** The type of table `T` in the connections `C` that have it; `never` when none does. */
21
+ type TableOf<T, C> = C extends keyof HamurDatabases
22
+ ? HamurDatabases[C] extends { tables: infer Tables }
23
+ ? T extends keyof Tables
24
+ ? Tables[T]
25
+ : never
26
+ : never
27
+ : never
28
+
29
+ /** The row of a table, as the migrations leave it: `db.sql<Row<"todos">>`select * from todos``. */
30
+ export type Row<T extends TableName<C>, C extends DatabaseName = DefaultDatabase> = [TableOf<T, C>] extends [never]
31
+ ? Record<string, unknown>
32
+ : TableOf<T, C>
33
+
34
+ /** The insert type of table `T` in the connections `C` that have it; `never` when none does. */
35
+ type InsertOf<T, C> = C extends keyof HamurDatabases
36
+ ? HamurDatabases[C] extends { inserts: infer Inserts }
37
+ ? T extends keyof Inserts
38
+ ? Inserts[T]
39
+ : never
40
+ : never
41
+ : never
42
+
43
+ /** The values `insert into` takes for a table: a nullable column, one with a `DEFAULT` and one the database fills are optional. */
44
+ export type Insert<T extends TableName<C>, C extends DatabaseName = DefaultDatabase> = [InsertOf<T, C>] extends [never]
45
+ ? Record<string, unknown>
46
+ : InsertOf<T, C>
package/src/module.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { addDevtoolsTab, createResolver, defineModule, type HamurContext } from "hamur/kit"
2
+ import { setupConnections } from "./build/connections.ts"
3
+ import { setupFactories } from "./build/factories.ts"
4
+ import { setupMigrations } from "./build/migrations.ts"
5
+ import { setupQueue } from "./build/queue.ts"
6
+ import { setupTypes } from "./build/types.ts"
7
+ import { resolveOptions } from "./options.ts"
8
+ import type { DbConfig, ResolvedDbOptions } from "./types.ts"
9
+
10
+ const DATABASE_ICON =
11
+ '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 6.5v11c0 1.9 3.4 3 7.5 3s7.5-1.1 7.5-3v-11c0 1.9-3.4 3-7.5 3s-7.5-1.1-7.5-3z" fill="currentColor" fill-opacity="0.16" stroke="none"></path><path d="M4.5 6.5c0-1.9 3.4-3 7.5-3s7.5 1.1 7.5 3-3.4 3-7.5 3-7.5-1.1-7.5-3zM4.5 6.5v11c0 1.9 3.4 3 7.5 3s7.5-1.1 7.5-3v-11"></path></svg>'
12
+
13
+ /** The options each context's setup resolved, for `runDbCommand`. */
14
+ export const resolvedOptions = new WeakMap<HamurContext, ResolvedDbOptions>()
15
+
16
+ export default defineModule<DbConfig>({
17
+ meta: { name: "db", configKey: "db", hooks: ["db:migrations:dirs"] },
18
+ async setup(input, hamur) {
19
+ const options = resolveOptions(input)
20
+ const dialects = Object.fromEntries(
21
+ Object.entries(options.connections).map(([name, connection]) => [name, connection.dialect]),
22
+ )
23
+ await setupConnections(options, hamur)
24
+ await setupMigrations(options, hamur)
25
+ await setupQueue(options, hamur)
26
+ setupTypes(options, hamur, dialects)
27
+ setupFactories(options, hamur, dialects)
28
+ resolvedOptions.set(hamur, options)
29
+ addDevtoolsTab({
30
+ name: "database",
31
+ title: "Database",
32
+ icon: DATABASE_ICON,
33
+ view: { type: "module", entry: createResolver(import.meta.url).resolve("./devtools.ts") },
34
+ })
35
+ },
36
+ })
package/src/options.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { Dialect, DbConfig, ResolvedConnection, ResolvedDbOptions, Secret } from "./types.ts"
2
+ import { DiagnosticError, isEnvRef } from "hamur/kit"
3
+
4
+ /** Each connector and the presets it runs on (`static` runs the server only at build, on Bun). */
5
+ export const CONNECTORS: Record<ResolvedConnection["connector"], { presets: string[] }> = {
6
+ "bun-sql": { presets: ["bun", "static"] },
7
+ "bun-sqlite": { presets: ["bun", "static"] },
8
+ "node-sqlite": { presets: ["node"] },
9
+ d1: { presets: ["cloudflare"] },
10
+ client: { presets: ["bun", "node", "static", "vercel", "netlify", "cloudflare"] },
11
+ }
12
+
13
+ const MIGRATE = ["dev", "start", "build", false] as const
14
+ const DIALECTS: Dialect[] = ["postgres", "mysql", "sqlite"]
15
+ const NAME = /^[A-Za-z0-9_]+$/
16
+ const BINDING = /^[A-Za-z_$][A-Za-z0-9_$]*$/
17
+ const KEYS = new Set(["migrate", "connections"])
18
+
19
+ function fail(message: string): never {
20
+ throw new DiagnosticError("HAMUR_E5505", message)
21
+ }
22
+
23
+ function shown(value: unknown): string {
24
+ if (Array.isArray(value)) return "an array"
25
+ if (typeof value === "function") return "a function"
26
+ if (value === undefined) return "undefined"
27
+ return JSON.stringify(value)
28
+ }
29
+
30
+ function list(values: readonly unknown[]): string {
31
+ const quoted = values.map((value) => JSON.stringify(value))
32
+ return `${quoted.slice(0, -1).join(", ")} or ${quoted.at(-1)}`
33
+ }
34
+
35
+ const isObject = (value: unknown): value is Record<string, unknown> =>
36
+ typeof value === "object" && value !== null && !Array.isArray(value)
37
+
38
+ /** The dialect a literal url names by its scheme, else postgres. */
39
+ export function dialectOf(url: Secret | undefined): Dialect {
40
+ if (typeof url !== "string") return "postgres"
41
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url)?.[1]?.toLowerCase()
42
+ if (scheme === "mysql" || scheme === "mariadb") return "mysql"
43
+ if (scheme === "sqlite" || scheme === "file") return "sqlite"
44
+ return "postgres"
45
+ }
46
+
47
+ function resolveConnection(at: string, input: unknown, nested = false): ResolvedConnection {
48
+ const connection = isObject(input) ? input : {}
49
+ const connector = connection.connector
50
+ if (typeof connector !== "string" || !Object.hasOwn(CONNECTORS, connector))
51
+ fail(`${at}.connector must be ${list(Object.keys(CONNECTORS))} (got ${shown(connector)})`)
52
+ if (nested && connector === "d1")
53
+ fail(`${at}.connector must be ${list(Object.keys(CONNECTORS).filter((name) => name !== "d1"))} (got "d1")`)
54
+ if (nested && connection.dev !== undefined) fail(`${at}.dev is not allowed; a dev connection has no dev of its own`)
55
+ const dev = connection.dev === undefined ? {} : { dev: resolveConnection(`${at}.dev`, connection.dev, true) }
56
+ if (connector === "bun-sqlite" || connector === "node-sqlite") {
57
+ if (typeof connection.path !== "string" || !connection.path)
58
+ fail(`${at}.path is required for the ${connector} connector`)
59
+ return { connector, dialect: "sqlite", path: connection.path, ...dev }
60
+ }
61
+ if (connector === "d1") {
62
+ if (typeof connection.binding !== "string" || !BINDING.test(connection.binding))
63
+ fail(`${at}.binding must be a binding name (got ${shown(connection.binding)})`)
64
+ return { connector, dialect: "sqlite", binding: connection.binding, ...dev }
65
+ }
66
+ if (connector === "client") {
67
+ const dialect = connection.dialect
68
+ if (dialect === undefined) fail(`${at}.dialect is required for the client connector`)
69
+ if (!DIALECTS.includes(dialect as Dialect)) fail(`${at}.dialect must be ${list(DIALECTS)} (got ${shown(dialect)})`)
70
+ if (typeof connection.client !== "string" || !connection.client)
71
+ fail(`${at}.client must be a path to a file (got ${shown(connection.client)})`)
72
+ return { connector, dialect: dialect as Dialect, client: connection.client, ...dev }
73
+ }
74
+ const url = connection.url
75
+ if (url !== undefined && typeof url !== "string" && !isEnvRef(url))
76
+ fail(`${at}.url must be a URL or env("NAME") (got ${shown(url)})`)
77
+ const dialect = connection.dialect
78
+ if (dialect !== undefined && !DIALECTS.includes(dialect as Dialect))
79
+ fail(`${at}.dialect must be ${list(DIALECTS)} (got ${shown(dialect)})`)
80
+ return {
81
+ connector: "bun-sql",
82
+ dialect: (dialect as Dialect | undefined) ?? dialectOf(url as Secret | undefined),
83
+ ...(url === undefined ? {} : { url: url as Secret }),
84
+ ...dev,
85
+ }
86
+ }
87
+
88
+ /** The checked options, or the build error of the first value that is wrong. */
89
+ export function resolveOptions(input: Partial<DbConfig> | undefined): ResolvedDbOptions {
90
+ const options = (input ?? {}) as Record<string, unknown>
91
+ for (const key of Object.keys(options))
92
+ if (!KEYS.has(key)) fail(`db has no ${JSON.stringify(key)}; connections go under db.connections`)
93
+ const migrate = options.migrate ?? "dev"
94
+ if (!MIGRATE.includes(migrate as (typeof MIGRATE)[number]))
95
+ fail(`db.migrate must be "dev", "start", "build" or false (got ${shown(migrate)})`)
96
+ const given = options.connections ?? {}
97
+ if (!isObject(given)) fail(`db.connections must be an object of connections (got ${shown(given)})`)
98
+ const connections: Record<string, ResolvedConnection> = {}
99
+ for (const [key, connection] of Object.entries(given)) {
100
+ if (!NAME.test(key)) fail(`db.connections[${JSON.stringify(key)}]: a connection name holds A-Z, a-z, 0-9 and _`)
101
+ connections[key] = resolveConnection(`db.connections.${key}`, connection)
102
+ }
103
+ return { migrate: migrate as ResolvedDbOptions["migrate"], connections }
104
+ }
@@ -0,0 +1,87 @@
1
+ import type { Dialect, RunResult } from "../types.ts"
2
+
3
+ /** Another process may hold the write lock (the previous `hamur dev` generation, `hamur db migrate`); wait for it, not fail. */
4
+ export const BUSY_TIMEOUT = 5000
5
+
6
+ const isBusy = (error: unknown) => {
7
+ const { code, errcode, message } = (error ?? {}) as { code?: unknown; errcode?: unknown; message?: unknown }
8
+ return code === "SQLITE_BUSY" || errcode === 5 || (typeof message === "string" && /database is locked/.test(message))
9
+ }
10
+
11
+ /** SQLite answers BUSY at once, without the busy timeout, while another connection switches the journal mode; retried as the storage driver does. */
12
+ export function journalWal(run: (text: string) => void): void {
13
+ const pause = new Int32Array(new SharedArrayBuffer(4))
14
+ for (let attempt = 1; ; attempt++) {
15
+ try {
16
+ run("PRAGMA journal_mode = WAL")
17
+ return
18
+ } catch (error) {
19
+ if (!isBusy(error) || attempt === 100) throw error
20
+ Atomics.wait(pause, 0, 0, 10)
21
+ }
22
+ }
23
+ }
24
+
25
+ /** What one connection, or one transaction on it, runs: text with the dialect's placeholders and the bound values in order. */
26
+ export interface ConnectorSession {
27
+ all(text: string, params: unknown[]): Promise<Record<string, unknown>[]>
28
+ run(text: string, params: unknown[]): Promise<RunResult>
29
+ exec(text: string): Promise<void>
30
+ }
31
+
32
+ /** A session inside a transaction. */
33
+ export interface TransactionSession extends ConnectorSession {
34
+ /** Runs `fn` in a savepoint: released when it resolves, rolled back to and rethrown when it rejects. */
35
+ savepoint<R>(fn: (session: ConnectorSession) => Promise<R>): Promise<R>
36
+ }
37
+
38
+ /** One connection held for a whole migration run. */
39
+ export interface ReservedSession extends ConnectorSession {
40
+ /** A transaction on this same connection; `BEGIN IMMEDIATE` on sqlite. */
41
+ transaction<R>(fn: (session: ConnectorSession) => Promise<R>): Promise<R>
42
+ }
43
+
44
+ /** One statement of a connector's own batch: `all` resolves to rows, `run` to the rows written. */
45
+ export interface BatchStatement {
46
+ kind: "all" | "run"
47
+ text: string
48
+ params: unknown[]
49
+ }
50
+
51
+ /** The code that runs one connection's queries on one backend. */
52
+ export interface Connector extends ConnectorSession {
53
+ /** Commits when `fn` resolves, rolls back and rethrows when it rejects. */
54
+ transaction<R>(fn: (session: TransactionSession) => Promise<R>): Promise<R>
55
+ /** Runs `fn` on one connection (a pool's reserved one, or SQLite's only one) and gives it back when `fn` settles. */
56
+ reserve<R>(fn: (session: ReservedSession) => Promise<R>): Promise<R>
57
+ /** The backend's own atomic batch in one round trip (D1's); without it `batch` runs in a transaction. */
58
+ batch?(statements: BatchStatement[]): Promise<Array<Record<string, unknown>[] | RunResult>>
59
+ /** The process shares no connection (D1: every statement is a request of its own), so statements take no process lock. */
60
+ readonly concurrent?: boolean
61
+ close(): Promise<void>
62
+ }
63
+
64
+ /** The options a connector opens with: `url` already read from the runtime config, `path` and `binding` as configured, `client` bundled. */
65
+ export interface ConnectorOptions {
66
+ name: string
67
+ dialect: Dialect
68
+ url?: string
69
+ path?: string
70
+ binding?: string
71
+ /** Imports the connection's client file. */
72
+ client?: ClientLoader
73
+ }
74
+
75
+ export type ClientLoader = () => Promise<unknown>
76
+
77
+ export type OpenConnector = (options: ConnectorOptions) => Connector | Promise<Connector>
78
+
79
+ /** `lastInsertRowid` of `bun:sqlite` and `Bun.SQL`: a number, a decimal string above `Number.MAX_SAFE_INTEGER`, none when null. */
80
+ export function insertId(value: number | bigint | string | null | undefined): number | string | undefined {
81
+ if (value === null || value === undefined) return undefined
82
+ if (typeof value === "bigint")
83
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER)
84
+ ? Number(value)
85
+ : String(value)
86
+ return value
87
+ }
@@ -0,0 +1,353 @@
1
+ import { withSpan } from "hamur/server"
2
+ import type { Database, Dialect, Query, Transaction } from "../types.ts"
3
+ import type { Connector, ConnectorSession, ReservedSession, TransactionSession } from "./connector.ts"
4
+ import { compile } from "./query.ts"
5
+
6
+ type Reserve = <R>(fn: (session: ReservedSession) => Promise<R>) => Promise<R>
7
+
8
+ const reservations = new WeakMap<Database, Reserve>()
9
+ const detachers = new WeakMap<Database, <R>(fn: () => Promise<R>) => Promise<R>>()
10
+
11
+ /**
12
+ * Runs `fn`, which uses `db` the way code outside a transaction does, from inside `db.transaction` too: on a pool the calls
13
+ * take another connection. Where one connection serves the process (SQLite) they would wait for the transaction that waits for
14
+ * them, so that fails with what to do instead.
15
+ */
16
+ export function outsideTransaction<R>(db: Database, fn: () => Promise<R>): Promise<R> {
17
+ const detach = detachers.get(db)
18
+ if (!detach) throw new TypeError("outsideTransaction takes a Database of @hamur/db")
19
+ return detach(fn)
20
+ }
21
+
22
+ /** Runs `fn` on one connection of `db` for a migration run; on sqlite under the process lock, so the app's statements wait. */
23
+ export function reserveConnection<R>(db: Database, fn: (session: ReservedSession) => Promise<R>): Promise<R> {
24
+ const reserve = reservations.get(db)
25
+ if (!reserve) throw new TypeError("reserveConnection takes a Database of @hamur/db")
26
+ return reserve(fn)
27
+ }
28
+
29
+ type Kind = "all" | "first" | "run"
30
+
31
+ interface Core {
32
+ readonly name: string
33
+ readonly dialect: Dialect
34
+ }
35
+
36
+ interface QueryInfo {
37
+ core: Core
38
+ kind: Kind
39
+ params: unknown[]
40
+ }
41
+
42
+ interface TransactionState {
43
+ ended: boolean
44
+ /** The first statement of the transaction that failed on postgres. */
45
+ failed?: { error: unknown }
46
+ }
47
+
48
+ interface Store {
49
+ core: Core
50
+ active: boolean
51
+ }
52
+
53
+ interface AsyncStorage<T> {
54
+ getStore(): T | undefined
55
+ run<R>(store: T, fn: () => R): R
56
+ }
57
+
58
+ type Scope = {
59
+ AsyncLocalStorage?: new <T>() => AsyncStorage<T>
60
+ process?: { getBuiltinModule?: (id: string) => { AsyncLocalStorage?: new <T>() => AsyncStorage<T> } | undefined }
61
+ }
62
+
63
+ /** bun, node, and cloudflare with `nodejs_compat`; without one the misuse checks are off. */
64
+ function asyncStorage<T>(): AsyncStorage<T> | undefined {
65
+ const scope = globalThis as Scope
66
+ const Storage = scope.AsyncLocalStorage ?? scope.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage
67
+ return Storage ? new Storage<T>() : undefined
68
+ }
69
+
70
+ const transactions = asyncStorage<Store>()
71
+ const queries = new WeakMap<object, QueryInfo>()
72
+
73
+ const SYSTEM: Record<Dialect, string> = { sqlite: "sqlite", postgres: "postgresql", mysql: "mysql" }
74
+
75
+ function createLock(): <T>(fn: () => Promise<T>) => Promise<T> {
76
+ let tail: Promise<unknown> = Promise.resolve()
77
+ return (fn) => {
78
+ const result = tail.then(fn)
79
+ tail = result.then(
80
+ () => {},
81
+ () => {},
82
+ )
83
+ return result
84
+ }
85
+ }
86
+
87
+ class SqlQuery<R> implements Query<R> {
88
+ readonly text: string
89
+ readonly values: Query<R>["values"]
90
+ #start: () => Promise<R>
91
+ #promise?: Promise<R>
92
+
93
+ constructor(text: string, values: Query<R>["values"], start: () => Promise<R>) {
94
+ this.text = text
95
+ this.values = values
96
+ this.#start = start
97
+ }
98
+
99
+ then<A = R, B = never>(
100
+ onfulfilled?: ((value: R) => A | PromiseLike<A>) | null,
101
+ onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
102
+ ): Promise<A | B> {
103
+ this.#promise ??= this.#start()
104
+ return this.#promise.then(onfulfilled, onrejected)
105
+ }
106
+ }
107
+
108
+ /**
109
+ * One connection's `Database`. `open` makes the connector at the first query. On sqlite one connection serves the
110
+ * process, so every statement and transaction runs under one lock.
111
+ */
112
+ export function createDatabase(name: string, dialect: Dialect, open: () => Connector | Promise<Connector>): Database {
113
+ const core: Core = { name, dialect }
114
+ const lock = dialect === "sqlite" ? createLock() : undefined
115
+ const serial = <T>(session: Connector, fn: () => Promise<T>): Promise<T> =>
116
+ lock && !session.concurrent ? lock(fn) : fn()
117
+ let connector: Promise<Connector> | undefined
118
+ let closing: Promise<void> | undefined
119
+ let closed = false
120
+
121
+ const connection = (): Promise<Connector> => {
122
+ if (closing) return Promise.reject(new Error(`Database "${name}" is closed`))
123
+ connector ??= Promise.resolve()
124
+ .then(open)
125
+ .catch((error: unknown) => {
126
+ connector = undefined
127
+ throw error
128
+ })
129
+ return connector
130
+ }
131
+
132
+ const perform = (session: ConnectorSession, kind: Kind | "exec", text: string, params: unknown[]): Promise<unknown> =>
133
+ withSpan(
134
+ `db.query ${name}`,
135
+ async () => {
136
+ if (kind === "exec") return session.exec(text)
137
+ if (kind === "run") return session.run(text, params)
138
+ const rows = await session.all(text, params)
139
+ return kind === "first" ? rows[0] : rows
140
+ },
141
+ { kind: "client", attributes: { "db.system.name": SYSTEM[dialect], "db.query.text": text } },
142
+ )
143
+
144
+ const inside = (): boolean => {
145
+ const store = transactions?.getStore()
146
+ return store?.active === true && store.core === core
147
+ }
148
+
149
+ const misuse = (method: string): void => {
150
+ if (inside()) throw new Error(`db.${method} was called inside db.transaction; use the tx argument`)
151
+ }
152
+
153
+ const outside = async (method: string, kind: Kind | "exec", text: string, params: unknown[]): Promise<unknown> => {
154
+ misuse(method)
155
+ const session = await connection()
156
+ return serial(session, () => {
157
+ if (closed) throw new Error(`Database "${name}" is closed`)
158
+ return perform(session, kind, text, params)
159
+ })
160
+ }
161
+
162
+ const tagged =
163
+ (
164
+ method: string,
165
+ kind: Kind,
166
+ run: (method: string, kind: Kind, text: string, params: unknown[]) => Promise<unknown>,
167
+ guarded: boolean,
168
+ ) =>
169
+ (strings: TemplateStringsArray, ...values: unknown[]) => {
170
+ if (guarded) misuse(method)
171
+ const { text, values: given, params } = compile(method, name, dialect, strings, values)
172
+ const query = new SqlQuery(text, given, () => run(method, kind, text, params))
173
+ queries.set(query, { core, kind, params })
174
+ return query
175
+ }
176
+
177
+ const inBatch = (queryList: readonly Query<unknown>[]): QueryInfo[] =>
178
+ queryList.map((query) => {
179
+ const info = typeof query === "object" && query !== null ? queries.get(query) : undefined
180
+ if (!info)
181
+ throw new TypeError(`batch takes queries of this database ("${name}"), got a value that is not a query`)
182
+ if (info.core !== core)
183
+ throw new Error(`batch takes queries of this database ("${name}"), got one of "${info.core.name}"`)
184
+ return info
185
+ })
186
+
187
+ const runAll = async (
188
+ session: ConnectorSession,
189
+ queryList: readonly Query<unknown>[],
190
+ infos: QueryInfo[],
191
+ ): Promise<unknown[]> => {
192
+ const results: unknown[] = []
193
+ for (const [index, info] of infos.entries())
194
+ results.push(await perform(session, info.kind, queryList[index]!.text, info.params))
195
+ return results
196
+ }
197
+
198
+ const transaction = async <R>(body: (session: TransactionSession) => Promise<R>): Promise<R> => {
199
+ const session = await connection()
200
+ return serial(session, () => {
201
+ if (closed) throw new Error(`Database "${name}" is closed`)
202
+ return session.transaction(body)
203
+ })
204
+ }
205
+
206
+ /** The connector's own batch, one round trip; one span for it, its texts joined by `; ` as OpenTelemetry names a batch. */
207
+ const ownBatch = async (
208
+ session: Connector & Required<Pick<Connector, "batch">>,
209
+ queryList: readonly Query<unknown>[],
210
+ infos: QueryInfo[],
211
+ ): Promise<unknown[]> => {
212
+ const statements = infos.map((info, index) => ({
213
+ kind: info.kind === "run" ? ("run" as const) : ("all" as const),
214
+ text: queryList[index]!.text,
215
+ params: info.params,
216
+ }))
217
+ const results = await serial(session, () => {
218
+ if (closed) throw new Error(`Database "${name}" is closed`)
219
+ return withSpan(`db.query ${name}`, () => session.batch(statements), {
220
+ kind: "client",
221
+ attributes: {
222
+ "db.system.name": SYSTEM[dialect],
223
+ "db.query.text": statements.map((statement) => statement.text).join("; "),
224
+ "db.operation.batch.size": statements.length,
225
+ },
226
+ })
227
+ })
228
+ return results.map((result, index) => (infos[index]!.kind === "first" ? (result as unknown[])[0] : result))
229
+ }
230
+
231
+ const scoped = (session: TransactionSession, state: TransactionState): Transaction => {
232
+ const live = (method: string) => {
233
+ if (state.ended)
234
+ throw new Error(`tx.${method} was called after its transaction ended; run it inside the transaction function`)
235
+ }
236
+ // A failed statement aborts a postgres transaction, whose COMMIT then rolls back without an error.
237
+ const watched = <T>(work: Promise<T>): Promise<T> =>
238
+ dialect === "postgres"
239
+ ? work.catch((error: unknown) => {
240
+ state.failed ??= { error }
241
+ throw error
242
+ })
243
+ : work
244
+ const run = async (method: string, kind: Kind, text: string, params: unknown[]) => {
245
+ live(method)
246
+ return watched(perform(session, kind, text, params))
247
+ }
248
+ return {
249
+ name,
250
+ dialect,
251
+ sql: tagged("sql", "all", run, false) as Transaction["sql"],
252
+ first: tagged("first", "first", run, false) as Transaction["first"],
253
+ run: tagged("run", "run", run, false) as Transaction["run"],
254
+ async exec(text) {
255
+ live("exec")
256
+ await watched(perform(session, "exec", text, []))
257
+ },
258
+ batch: (async (queryList: readonly Query<unknown>[]) => {
259
+ live("batch")
260
+ const infos = inBatch(queryList)
261
+ return session.savepoint((point) => runAll(point, queryList, infos))
262
+ }) as Transaction["batch"],
263
+ }
264
+ }
265
+
266
+ const detach = async <R>(fn: () => Promise<R>): Promise<R> => {
267
+ if (!inside()) return fn()
268
+ if (lock && !(await connection()).concurrent) {
269
+ throw new Error(
270
+ `Database "${name}" has one connection, which db.transaction holds; a storage call on it inside the transaction would wait for the transaction. Use storage before or after the transaction, or mount it on another connection (storage.<mount>.connection)`,
271
+ )
272
+ }
273
+ return transactions!.run({ core, active: false }, fn)
274
+ }
275
+
276
+ const reserve: Reserve = async (fn) => {
277
+ const session = await connection()
278
+ return serial(session, () => {
279
+ if (closed) throw new Error(`Database "${name}" is closed`)
280
+ return session.reserve(fn)
281
+ })
282
+ }
283
+
284
+ const database: Database = {
285
+ name,
286
+ dialect,
287
+ sql: tagged("sql", "all", outside, true) as Database["sql"],
288
+ first: tagged("first", "first", outside, true) as Database["first"],
289
+ run: tagged("run", "run", outside, true) as Database["run"],
290
+ async exec(text) {
291
+ await outside("exec", "exec", text, [])
292
+ },
293
+ batch: (async (queryList: readonly Query<unknown>[]) => {
294
+ misuse("batch")
295
+ const infos = inBatch(queryList)
296
+ const session = await connection()
297
+ if (session.batch) return ownBatch(session as Connector & Required<Pick<Connector, "batch">>, queryList, infos)
298
+ return transaction((inner) => runAll(inner, queryList, infos))
299
+ }) as Database["batch"],
300
+ async transaction(fn) {
301
+ if (inside()) throw new Error("transaction cannot be nested; use the tx argument")
302
+ return transaction(async (session) => {
303
+ const own: Store = { core, active: true }
304
+ const state: TransactionState = { ended: false }
305
+ try {
306
+ const result = await (transactions
307
+ ? transactions.run(own, () => fn(scoped(session, state)))
308
+ : fn(scoped(session, state)))
309
+ if (holdsQuery(result))
310
+ throw new Error("transaction returned a query it did not await; await it inside the transaction function")
311
+ if (state.failed) {
312
+ throw new Error(
313
+ "transaction was rolled back: a statement in it failed, which aborts a postgres transaction; let the error end the transaction function, or run the statement in tx.batch",
314
+ {
315
+ cause: state.failed.error,
316
+ },
317
+ )
318
+ }
319
+ return result
320
+ } finally {
321
+ own.active = false
322
+ state.ended = true
323
+ }
324
+ })
325
+ },
326
+ close() {
327
+ if (inside())
328
+ return Promise.reject(
329
+ new Error("db.close was called inside db.transaction; close it after the transaction ends"),
330
+ )
331
+ closing ??= (async () => {
332
+ const opened = connector
333
+ const mark = async () => {
334
+ closed = true
335
+ }
336
+ await (lock ? lock(mark) : mark())
337
+ if (opened) await (await opened.catch(() => undefined))?.close()
338
+ })()
339
+ return closing
340
+ },
341
+ }
342
+ reservations.set(database, reserve)
343
+ detachers.set(database, detach)
344
+ return database
345
+ }
346
+
347
+ function holdsQuery(value: unknown): boolean {
348
+ if (typeof value !== "object" || value === null) return false
349
+ return (
350
+ queries.has(value) ||
351
+ (Array.isArray(value) && value.some((item) => typeof item === "object" && item !== null && queries.has(item)))
352
+ )
353
+ }