@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.
- package/LICENSE +22 -0
- package/README.md +38 -2
- package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
- package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
- package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
- package/dist/chunks/browser-d1-a16d23f0.js +8 -0
- package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
- package/dist/chunks/browser-index-kf697bfy.js +113 -0
- package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
- package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
- package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
- package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
- package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
- package/dist/chunks/bun-index-06tj00dn.js +11 -0
- package/dist/chunks/bun-index-9na2zkqq.js +224 -0
- package/dist/chunks/bun-index-b47nngck.js +352 -0
- package/dist/chunks/bun-index-hrx1eqma.js +29 -0
- package/dist/chunks/bun-index-pd6k99dv.js +114 -0
- package/dist/src/cli.js +1692 -0
- package/dist/src/devtools.js +153 -0
- package/dist/src/index.js +1491 -0
- package/dist/src/server/index.js +584 -0
- package/dist/src/storage/define.js +7 -0
- package/dist/types/src/build/connections.d.ts +8 -0
- package/dist/types/src/build/databases.d.ts +20 -0
- package/dist/types/src/build/factories.d.ts +6 -0
- package/dist/types/src/build/migrations.d.ts +21 -0
- package/dist/types/src/build/queue.d.ts +7 -0
- package/dist/types/src/build/schema.d.ts +50 -0
- package/dist/types/src/build/tables.d.ts +7 -0
- package/dist/types/src/build/types.d.ts +4 -0
- package/dist/types/src/cli.d.ts +26 -0
- package/dist/types/src/connectors/bun-sql.d.ts +3 -0
- package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/client-fakes.d.ts +57 -0
- package/dist/types/src/connectors/client.d.ts +3 -0
- package/dist/types/src/connectors/d1-fake.d.ts +32 -0
- package/dist/types/src/connectors/d1.d.ts +26 -0
- package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/node-test.d.ts +17 -0
- package/dist/types/src/connectors/suite.d.ts +13 -0
- package/dist/types/src/devtools.d.ts +6 -0
- package/dist/types/src/index.d.ts +25 -0
- package/dist/types/src/module.d.ts +6 -0
- package/dist/types/src/options.d.ts +9 -0
- package/dist/types/src/runtime/connector.d.ts +53 -0
- package/dist/types/src/runtime/database.d.ts +15 -0
- package/dist/types/src/runtime/migrate.d.ts +56 -0
- package/dist/types/src/runtime/query.d.ts +12 -0
- package/dist/types/src/runtime/queue-process.d.ts +1 -0
- package/dist/types/src/runtime/queue.d.ts +85 -0
- package/dist/types/src/runtime/registry.d.ts +16 -0
- package/dist/types/src/server/client.d.ts +3 -0
- package/dist/types/src/server/databases.d.ts +4 -0
- package/dist/types/src/server/define-factory.d.ts +9 -0
- package/dist/types/src/server/devtools-routes.d.ts +4 -0
- package/dist/types/src/server/devtools.d.ts +26 -0
- package/dist/types/src/server/door-dev.d.ts +3 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/factory-core.d.ts +12 -0
- package/dist/types/src/server/factory.d.ts +6 -0
- package/dist/types/src/server/fake.d.ts +35 -0
- package/dist/types/src/server/index.d.ts +12 -0
- package/dist/types/src/server/migrations.d.ts +5 -0
- package/dist/types/src/server/page.d.ts +26 -0
- package/dist/types/src/server/plugin.d.ts +1 -0
- package/dist/types/src/server/queue.d.ts +6 -0
- package/dist/types/src/server/table-entities.d.ts +33 -0
- package/dist/types/src/server/task.d.ts +6 -0
- package/dist/types/src/storage/define.d.ts +12 -0
- package/dist/types/src/storage/driver.d.ts +36 -0
- package/dist/types/src/storage/index.d.ts +3 -0
- package/dist/types/src/types.d.ts +103 -0
- package/package.json +40 -4
- package/src/build/connections.ts +225 -0
- package/src/build/databases.ts +101 -0
- package/src/build/factories.ts +135 -0
- package/src/build/migrations.ts +247 -0
- package/src/build/queue.ts +29 -0
- package/src/build/schema.ts +636 -0
- package/src/build/tables.ts +20 -0
- package/src/build/types.ts +46 -0
- package/src/cli.ts +153 -0
- package/src/connectors/bun-sql.ts +68 -0
- package/src/connectors/bun-sqlite.ts +69 -0
- package/src/connectors/client-fakes.ts +257 -0
- package/src/connectors/client.ts +161 -0
- package/src/connectors/d1-fake.ts +92 -0
- package/src/connectors/d1.ts +151 -0
- package/src/connectors/node-sqlite.ts +83 -0
- package/src/connectors/node-test.ts +31 -0
- package/src/connectors/suite.ts +406 -0
- package/src/devtools.ts +264 -0
- package/src/env.d.ts +28 -0
- package/src/index.ts +46 -0
- package/src/module.ts +36 -0
- package/src/options.ts +104 -0
- package/src/runtime/connector.ts +87 -0
- package/src/runtime/database.ts +353 -0
- package/src/runtime/migrate.ts +307 -0
- package/src/runtime/query.ts +82 -0
- package/src/runtime/queue-process.ts +39 -0
- package/src/runtime/queue.ts +380 -0
- package/src/runtime/registry.ts +61 -0
- package/src/server/client.ts +6 -0
- package/src/server/databases.ts +24 -0
- package/src/server/define-factory.ts +22 -0
- package/src/server/devtools-routes.ts +34 -0
- package/src/server/devtools.ts +205 -0
- package/src/server/door-dev.ts +6 -0
- package/src/server/door.ts +4 -0
- package/src/server/factory-core.ts +91 -0
- package/src/server/factory.ts +19 -0
- package/src/server/fake.ts +348 -0
- package/src/server/index.ts +17 -0
- package/src/server/migrations.ts +26 -0
- package/src/server/page.ts +181 -0
- package/src/server/plugin.ts +14 -0
- package/src/server/queue.ts +38 -0
- package/src/server/table-entities.ts +29 -0
- package/src/server/task.ts +15 -0
- package/src/storage/define.ts +12 -0
- package/src/storage/driver.ts +419 -0
- package/src/storage/index.ts +7 -0
- package/src/types.ts +101 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import type { Database, Dialect } from "../types.ts"
|
|
2
|
+
import type { ConnectorSession, ReservedSession } from "./connector.ts"
|
|
3
|
+
import { reserveConnection } from "./database.ts"
|
|
4
|
+
|
|
5
|
+
/** One SQL file of a connection, read and hashed by the build. */
|
|
6
|
+
export interface Migration {
|
|
7
|
+
/** The number, as written: `0001`. */
|
|
8
|
+
id: string
|
|
9
|
+
/** The rest of the name: `init`. */
|
|
10
|
+
name: string
|
|
11
|
+
/** `0001_init.sql`. */
|
|
12
|
+
file: string
|
|
13
|
+
sql: string
|
|
14
|
+
/** SHA-256 hex of `sql` with CRLF turned into LF. */
|
|
15
|
+
checksum: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface MigrationRow {
|
|
19
|
+
id: string
|
|
20
|
+
name: string
|
|
21
|
+
checksum: string
|
|
22
|
+
applied_at: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface MigrateOptions {
|
|
26
|
+
/** An applied migration whose file is gone; a rollback deploy has fewer files, so it is not an error. */
|
|
27
|
+
warn?: (message: string) => void
|
|
28
|
+
applied?: (migration: Migration, ms: number) => void
|
|
29
|
+
/** How long a run waits for another instance's lock, in ms. */
|
|
30
|
+
lockTimeout?: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type MigrationState =
|
|
34
|
+
| { id: string; name: string; state: "applied"; appliedAt: string }
|
|
35
|
+
| { id: string; name: string; state: "pending" | "changed" | "missing file" }
|
|
36
|
+
|
|
37
|
+
const TABLE = "_hamur_migrations"
|
|
38
|
+
const LOCK_TIMEOUT = 60_000
|
|
39
|
+
/** A fixed `pg_advisory_lock` key: the bytes of "hamurmig" as a signed 64-bit integer. */
|
|
40
|
+
const PG_LOCK_KEY = "8316297378322540903"
|
|
41
|
+
|
|
42
|
+
const CREATE: Record<Dialect, string> = {
|
|
43
|
+
sqlite: `create table if not exists ${TABLE} (id text primary key, name text not null, checksum text not null, applied_at text not null)`,
|
|
44
|
+
postgres: `create table if not exists ${TABLE} (id text primary key, name text not null, checksum text not null, applied_at text not null)`,
|
|
45
|
+
// MySQL cannot index a TEXT column without a prefix length.
|
|
46
|
+
mysql: `create table if not exists ${TABLE} (id varchar(64) primary key, name varchar(255) not null, checksum char(64) not null, applied_at varchar(32) not null)`,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const EXISTS: Record<Dialect, string> = {
|
|
50
|
+
sqlite: `select count(*) as n from sqlite_master where type = 'table' and name = '${TABLE}'`,
|
|
51
|
+
postgres: `select count(*)::int as n from information_schema.tables where table_schema = current_schema() and table_name = '${TABLE}'`,
|
|
52
|
+
mysql: `select count(*) as n from information_schema.tables where table_schema = database() and table_name = '${TABLE}'`,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A migration file's text without the UTF-8 BOM an editor may add, which SQLite and Postgres would read as part of a name. */
|
|
56
|
+
export const withoutBom = (text: string) => (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text)
|
|
57
|
+
|
|
58
|
+
/** SHA-256 hex of the file without a BOM and with CRLF turned into LF, so neither an editor nor a Windows checkout changes it. */
|
|
59
|
+
export async function checksumOf(text: string): Promise<string> {
|
|
60
|
+
const digest = await crypto.subtle.digest(
|
|
61
|
+
"SHA-256",
|
|
62
|
+
new TextEncoder().encode(withoutBom(text).replace(/\r\n/g, "\n")),
|
|
63
|
+
)
|
|
64
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* MySQL: the statements of a file, split at `;` outside quotes, backticks and comments, comments dropped. Bun's docs do not say
|
|
69
|
+
* that a multi-statement `.simple()` on MySQL rejects for a later statement's error, so each statement runs on its own. A routine
|
|
70
|
+
* body holding `;` is split too and fails as a syntax error.
|
|
71
|
+
*/
|
|
72
|
+
export function mysqlStatements(sql: string): string[] {
|
|
73
|
+
const statements: string[] = []
|
|
74
|
+
let current = ""
|
|
75
|
+
for (let i = 0; i < sql.length; i++) {
|
|
76
|
+
const char = sql[i]!
|
|
77
|
+
const next = sql[i + 1]
|
|
78
|
+
if (char === "'" || char === '"' || char === "`") {
|
|
79
|
+
let end = i + 1
|
|
80
|
+
while (end < sql.length) {
|
|
81
|
+
if (sql[end] === "\\" && char !== "`") end += 2
|
|
82
|
+
else if (sql[end] === char && sql[end + 1] === char) end += 2
|
|
83
|
+
else if (sql[end] === char) break
|
|
84
|
+
else end++
|
|
85
|
+
}
|
|
86
|
+
current += sql.slice(i, end + 1)
|
|
87
|
+
i = end
|
|
88
|
+
} else if ((char === "-" && next === "-" && (sql[i + 2] === undefined || /\s/.test(sql[i + 2]!))) || char === "#") {
|
|
89
|
+
while (i < sql.length && sql[i] !== "\n") i++
|
|
90
|
+
current += "\n"
|
|
91
|
+
} else if (char === "/" && next === "*") {
|
|
92
|
+
const end = sql.indexOf("*/", i + 2)
|
|
93
|
+
const stop = end < 0 ? sql.length : end + 2
|
|
94
|
+
// MySQL runs a versioned comment (`/*!40101 SET … */`) and reads an optimizer hint (`/*+ … */`); they stay.
|
|
95
|
+
current += sql[i + 2] === "!" || sql[i + 2] === "+" ? sql.slice(i, stop) : " "
|
|
96
|
+
i = stop - 1
|
|
97
|
+
} else if (char === ";") {
|
|
98
|
+
if (current.trim()) statements.push(current.trim())
|
|
99
|
+
current = ""
|
|
100
|
+
} else current += char
|
|
101
|
+
}
|
|
102
|
+
if (current.trim()) statements.push(current.trim())
|
|
103
|
+
return statements
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const placeholder = (dialect: Dialect, n: number) => (dialect === "postgres" ? `$${n}` : "?")
|
|
107
|
+
|
|
108
|
+
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
|
|
109
|
+
|
|
110
|
+
const isBusy = (error: unknown) =>
|
|
111
|
+
(error as { code?: unknown } | null)?.code === "SQLITE_BUSY" || /database is locked/.test(messageOf(error))
|
|
112
|
+
|
|
113
|
+
/** SQLite refuses text with no statement; a file of comments (as `hamur db new` writes it) is recorded without running. */
|
|
114
|
+
function hasStatement(sql: string): boolean {
|
|
115
|
+
return (
|
|
116
|
+
sql
|
|
117
|
+
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
118
|
+
.replace(/--[^\n]*/g, "")
|
|
119
|
+
.trim() !== ""
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const changed = (migration: Migration) => new Error(`Migration ${migration.file} changed after it was applied`)
|
|
124
|
+
|
|
125
|
+
/** `0002` and `00002` are one number. */
|
|
126
|
+
const numberOf = (id: string) => BigInt(id).toString()
|
|
127
|
+
|
|
128
|
+
const fileOf = (row: MigrationRow) => `${row.id}_${row.name}.sql`
|
|
129
|
+
|
|
130
|
+
async function readRows(session: ConnectorSession, dialect: Dialect): Promise<MigrationRow[]> {
|
|
131
|
+
const [exists] = await session.all(EXISTS[dialect], [])
|
|
132
|
+
if (!Number(exists?.n)) return []
|
|
133
|
+
const rows = await session.all(`select id, name, checksum, applied_at from ${TABLE}`, [])
|
|
134
|
+
return rows.map((row) => ({
|
|
135
|
+
id: String(row.id),
|
|
136
|
+
name: String(row.name),
|
|
137
|
+
checksum: String(row.checksum),
|
|
138
|
+
applied_at: String(row.applied_at),
|
|
139
|
+
}))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const sameFile = (row: MigrationRow, migration: Migration) =>
|
|
143
|
+
row.checksum === migration.checksum && row.name === migration.name
|
|
144
|
+
|
|
145
|
+
/** Takes the run's lock on `session` and returns its release. */
|
|
146
|
+
async function lock(
|
|
147
|
+
db: Database,
|
|
148
|
+
session: ReservedSession,
|
|
149
|
+
timeout: number,
|
|
150
|
+
failed: () => Error,
|
|
151
|
+
): Promise<() => Promise<void>> {
|
|
152
|
+
if (db.dialect === "sqlite") {
|
|
153
|
+
const [row] = await session.all("PRAGMA busy_timeout", [])
|
|
154
|
+
const previous = Number(row?.timeout ?? 0)
|
|
155
|
+
await session.exec(`PRAGMA busy_timeout = ${Math.round(timeout)}`)
|
|
156
|
+
return () => session.exec(`PRAGMA busy_timeout = ${previous}`)
|
|
157
|
+
}
|
|
158
|
+
if (db.dialect === "mysql") {
|
|
159
|
+
// A lock name is server-wide and at most 64 characters: one per database, its name cut to fit.
|
|
160
|
+
const name = `concat('${TABLE}.', left(database(), 45))`
|
|
161
|
+
const [row] = await session.all(`select GET_LOCK(${name}, ${Math.ceil(timeout / 1000)}) as locked`, [])
|
|
162
|
+
if (Number(row?.locked) !== 1) throw failed()
|
|
163
|
+
return async () => void (await session.all(`select RELEASE_LOCK(${name}) as released`, []))
|
|
164
|
+
}
|
|
165
|
+
// pg_advisory_lock waits without a bound unless the session's lock_timeout changes; polling the try form keeps the session as it is.
|
|
166
|
+
const deadline = Date.now() + timeout
|
|
167
|
+
for (;;) {
|
|
168
|
+
const [row] = await session.all(`select pg_try_advisory_lock(${PG_LOCK_KEY}) as locked`, [])
|
|
169
|
+
if (row?.locked === true) break
|
|
170
|
+
if (Date.now() >= deadline) throw failed()
|
|
171
|
+
await new Promise((done) => setTimeout(done, Math.min(200, Math.max(0, deadline - Date.now()))))
|
|
172
|
+
}
|
|
173
|
+
return async () => void (await session.all(`select pg_advisory_unlock(${PG_LOCK_KEY}) as released`, []))
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The checks before anything runs: an applied file that changed, a pending file that is an applied one renamed, a
|
|
178
|
+
* pending file numbered below the highest applied one. Warns for each applied file that is gone.
|
|
179
|
+
*/
|
|
180
|
+
function checkFiles(
|
|
181
|
+
name: string,
|
|
182
|
+
rows: Map<string, MigrationRow>,
|
|
183
|
+
migrations: readonly Migration[],
|
|
184
|
+
warn: MigrateOptions["warn"],
|
|
185
|
+
): void {
|
|
186
|
+
const files = new Set(migrations.map((migration) => numberOf(migration.id)))
|
|
187
|
+
const missing = [...rows.entries()].filter(([number]) => !files.has(number)).map(([, row]) => row)
|
|
188
|
+
for (const migration of migrations) {
|
|
189
|
+
const row = rows.get(numberOf(migration.id))
|
|
190
|
+
if (row && !sameFile(row, migration)) throw changed(migration)
|
|
191
|
+
}
|
|
192
|
+
const pending = migrations.filter((migration) => !rows.has(numberOf(migration.id)))
|
|
193
|
+
for (const migration of pending) {
|
|
194
|
+
const renamed = missing.find((row) => row.checksum === migration.checksum)
|
|
195
|
+
if (renamed)
|
|
196
|
+
throw new Error(`Migration ${migration.file} was applied as ${fileOf(renamed)}; give it its old name back`)
|
|
197
|
+
}
|
|
198
|
+
const highest = [...rows.values()].sort((a, b) => compareIds(a.id, b.id)).at(-1)
|
|
199
|
+
const early = highest && pending.find((migration) => compareIds(migration.id, highest.id) < 0)
|
|
200
|
+
if (early && highest) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`Migration ${early.file} is numbered below ${fileOf(highest)}, which is already applied; renumber it after ${highest.id}`,
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
for (const row of missing) warn?.(`Migration ${fileOf(row)} is applied on "${name}" but its file is missing`)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Applies each pending migration of `db` once, in the order given, on one connection under the dialect's lock; returns
|
|
210
|
+
* those this run applied. The checks of `checkFiles` fail before anything runs; a failed file stops the run, its own transaction
|
|
211
|
+
* rolled back (except on mysql) and the earlier ones kept.
|
|
212
|
+
*/
|
|
213
|
+
export function migrate(
|
|
214
|
+
db: Database,
|
|
215
|
+
migrations: readonly Migration[],
|
|
216
|
+
options: MigrateOptions = {},
|
|
217
|
+
): Promise<Migration[]> {
|
|
218
|
+
const { dialect } = db
|
|
219
|
+
const timeout = options.lockTimeout ?? LOCK_TIMEOUT
|
|
220
|
+
const waited = () =>
|
|
221
|
+
new Error(`Migrations of "${db.name}" waited ${Math.round(timeout / 1000)} s for another instance's lock`)
|
|
222
|
+
const sqliteLocked = <T>(work: () => Promise<T>): Promise<T> =>
|
|
223
|
+
work().catch((error: unknown) => {
|
|
224
|
+
throw dialect === "sqlite" && isBusy(error) ? waited() : error
|
|
225
|
+
})
|
|
226
|
+
const insert = `insert into ${TABLE} (id, name, checksum, applied_at) values (${[1, 2, 3, 4].map((n) => placeholder(dialect, n)).join(", ")})`
|
|
227
|
+
|
|
228
|
+
const apply = async (session: ConnectorSession, migration: Migration) => {
|
|
229
|
+
try {
|
|
230
|
+
if (dialect === "mysql") for (const statement of mysqlStatements(migration.sql)) await session.exec(statement)
|
|
231
|
+
else if (hasStatement(migration.sql)) await session.exec(migration.sql)
|
|
232
|
+
await session.run(insert, [migration.id, migration.name, migration.checksum, new Date().toISOString()])
|
|
233
|
+
} catch (error) {
|
|
234
|
+
const tail = dialect === "mysql" ? " (mysql commits DDL one statement at a time; check the database)" : ""
|
|
235
|
+
throw new Error(`Migration ${migration.file} failed: ${messageOf(error)}${tail}`, { cause: error })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return reserveConnection(db, async (session) => {
|
|
240
|
+
const release = await lock(db, session, timeout, waited)
|
|
241
|
+
let failed = false
|
|
242
|
+
try {
|
|
243
|
+
await sqliteLocked(() => session.exec(CREATE[dialect]))
|
|
244
|
+
const rows = new Map((await readRows(session, dialect)).map((row) => [numberOf(row.id), row]))
|
|
245
|
+
checkFiles(db.name, rows, migrations, options.warn)
|
|
246
|
+
const applied: Migration[] = []
|
|
247
|
+
for (const migration of migrations) {
|
|
248
|
+
if (rows.has(numberOf(migration.id))) continue
|
|
249
|
+
const started = performance.now()
|
|
250
|
+
const ran =
|
|
251
|
+
dialect === "mysql"
|
|
252
|
+
? (await apply(session, migration), true)
|
|
253
|
+
: await sqliteLocked(() =>
|
|
254
|
+
session.transaction(async (tx) => {
|
|
255
|
+
if (dialect === "sqlite") {
|
|
256
|
+
const [again] = await tx.all(`select name, checksum from ${TABLE} where id = ?`, [migration.id])
|
|
257
|
+
if (again) {
|
|
258
|
+
if (again.checksum !== migration.checksum || again.name !== migration.name)
|
|
259
|
+
throw changed(migration)
|
|
260
|
+
return false
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
await apply(tx, migration)
|
|
264
|
+
return true
|
|
265
|
+
}),
|
|
266
|
+
)
|
|
267
|
+
if (!ran) continue
|
|
268
|
+
applied.push(migration)
|
|
269
|
+
options.applied?.(migration, performance.now() - started)
|
|
270
|
+
}
|
|
271
|
+
return applied
|
|
272
|
+
} catch (error) {
|
|
273
|
+
failed = true
|
|
274
|
+
throw error
|
|
275
|
+
} finally {
|
|
276
|
+
// After a failure the run's own error is the one to report; the lock goes with the connection anyway.
|
|
277
|
+
await release().catch((error: unknown) => {
|
|
278
|
+
if (!failed) throw error
|
|
279
|
+
options.warn?.(`Releasing the migration lock of "${db.name}" failed: ${messageOf(error)}`)
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Every migration of `db` and its state, in id order; reads, never writes. */
|
|
286
|
+
export function migrationStatus(db: Database, migrations: readonly Migration[]): Promise<MigrationState[]> {
|
|
287
|
+
return reserveConnection(db, async (session) => {
|
|
288
|
+
const rows = new Map((await readRows(session, db.dialect)).map((row) => [numberOf(row.id), row]))
|
|
289
|
+
const states: MigrationState[] = migrations.map((migration) => {
|
|
290
|
+
const row = rows.get(numberOf(migration.id))
|
|
291
|
+
if (!row) return { id: migration.id, name: migration.name, state: "pending" }
|
|
292
|
+
if (!sameFile(row, migration)) return { id: migration.id, name: migration.name, state: "changed" }
|
|
293
|
+
return { id: migration.id, name: migration.name, state: "applied", appliedAt: row.applied_at }
|
|
294
|
+
})
|
|
295
|
+
const files = new Set(migrations.map((migration) => numberOf(migration.id)))
|
|
296
|
+
for (const [number, row] of rows)
|
|
297
|
+
if (!files.has(number)) states.push({ id: row.id, name: row.name, state: "missing file" })
|
|
298
|
+
return states.sort((a, b) => compareIds(a.id, b.id))
|
|
299
|
+
})
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Migration numbers in numeric order: `0009` before `0010`, `9999` before `10000`. */
|
|
303
|
+
export function compareIds(a: string, b: string): number {
|
|
304
|
+
const x = BigInt(a)
|
|
305
|
+
const y = BigInt(b)
|
|
306
|
+
return x < y ? -1 : x > y ? 1 : 0
|
|
307
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createSqlFragment, sqlFragment } from "hamur/server/internal"
|
|
2
|
+
import type { Dialect, SqlFragment, SqlValue } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
const JSON_TABLE: Record<Dialect, string> = { sqlite: "json_each", mysql: "JSON_TABLE", postgres: "" }
|
|
5
|
+
|
|
6
|
+
function bind(method: string, dialect: Dialect, value: unknown, position: number): unknown {
|
|
7
|
+
const refuse = (what: string) => new TypeError(`db.${method} value ${position} is ${what}`)
|
|
8
|
+
if (value === null || typeof value === "string" || typeof value === "bigint") return value
|
|
9
|
+
if (typeof value === "number") {
|
|
10
|
+
if (Number.isNaN(value)) throw refuse("NaN")
|
|
11
|
+
return value
|
|
12
|
+
}
|
|
13
|
+
if (value === undefined) throw refuse("undefined; pass null")
|
|
14
|
+
if (typeof value === "boolean") return dialect === "postgres" ? value : value ? 1 : 0
|
|
15
|
+
if (value instanceof Date) return dialect === "sqlite" ? value.toISOString() : value
|
|
16
|
+
if (value instanceof Uint8Array) return value
|
|
17
|
+
if (Array.isArray(value)) {
|
|
18
|
+
if (dialect !== "postgres")
|
|
19
|
+
throw refuse(
|
|
20
|
+
`an array, which ${dialect} cannot bind; bind one value per placeholder or JSON with ${JSON_TABLE[dialect]}`,
|
|
21
|
+
)
|
|
22
|
+
return value.map((item) => bind(method, dialect, item, position))
|
|
23
|
+
}
|
|
24
|
+
if (typeof value === "object") throw refuse("an object; bind JSON.stringify(value) for a json column")
|
|
25
|
+
throw refuse(`a ${typeof value}`)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Compiled {
|
|
29
|
+
text: string
|
|
30
|
+
values: readonly SqlValue[]
|
|
31
|
+
/** The values as the dialect binds them. */
|
|
32
|
+
params: unknown[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const make = createSqlFragment(() => ({ text: "", values: [] }))[sqlFragment]
|
|
36
|
+
const apply = Reflect.apply
|
|
37
|
+
|
|
38
|
+
/** A fragment Hamur made; an object that only carries a function under the symbol is an ordinary value. */
|
|
39
|
+
function fragmentOf(value: unknown): (SqlFragment & { readonly dialect?: Dialect }) | undefined {
|
|
40
|
+
if (typeof value !== "object" || value === null) return undefined
|
|
41
|
+
return (value as Partial<SqlFragment>)[sqlFragment] === make
|
|
42
|
+
? (value as SqlFragment & { readonly dialect?: Dialect })
|
|
43
|
+
: undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The template's text with a placeholder per value, and the values bound in order; no app value ever becomes
|
|
48
|
+
* text. A `SqlFragment` is spliced as its text, its values bound at its place.
|
|
49
|
+
*/
|
|
50
|
+
export function compile(
|
|
51
|
+
method: string,
|
|
52
|
+
name: string,
|
|
53
|
+
dialect: Dialect,
|
|
54
|
+
strings: TemplateStringsArray,
|
|
55
|
+
values: readonly unknown[],
|
|
56
|
+
): Compiled {
|
|
57
|
+
const given: SqlValue[] = []
|
|
58
|
+
const params: unknown[] = []
|
|
59
|
+
let text = strings[0] ?? ""
|
|
60
|
+
for (let index = 1; index < strings.length; index++) {
|
|
61
|
+
const value = values[index - 1]
|
|
62
|
+
const fragment = fragmentOf(value)
|
|
63
|
+
if (fragment) {
|
|
64
|
+
if (fragment.dialect !== undefined && fragment.dialect !== dialect)
|
|
65
|
+
throw new TypeError(
|
|
66
|
+
`db.${method} value ${index} is a SqlFragment made for ${fragment.dialect}; this connection "${name}" is ${dialect}`,
|
|
67
|
+
)
|
|
68
|
+
const piece = apply(make, fragment, [dialect, params.length + 1])
|
|
69
|
+
for (const item of piece.values) {
|
|
70
|
+
params.push(bind(method, dialect, item, index))
|
|
71
|
+
given.push(item)
|
|
72
|
+
}
|
|
73
|
+
text += piece.text
|
|
74
|
+
} else {
|
|
75
|
+
params.push(bind(method, dialect, value, index))
|
|
76
|
+
given.push(value as SqlValue)
|
|
77
|
+
text += dialect === "postgres" ? `$${params.length}` : "?"
|
|
78
|
+
}
|
|
79
|
+
text += strings[index]
|
|
80
|
+
}
|
|
81
|
+
return { text, values: Object.freeze(given), params }
|
|
82
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import openBunSql from "../connectors/bun-sql.ts"
|
|
2
|
+
import openBunSqlite from "../connectors/bun-sqlite.ts"
|
|
3
|
+
import type { Dialect } from "../types.ts"
|
|
4
|
+
import { createDatabase } from "./database.ts"
|
|
5
|
+
import { createQueueTable, startQueueWorker } from "./queue.ts"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One server process of `queue.test.ts`: `bun queue-process.ts <dialect> <path or url> <table>` runs a worker over the table
|
|
9
|
+
* until no row is left, then prints the payloads it ran as JSON.
|
|
10
|
+
*/
|
|
11
|
+
const [dialect, target, table] = process.argv.slice(2) as [Dialect, string, string]
|
|
12
|
+
const db = createDatabase("queue", dialect, () =>
|
|
13
|
+
dialect === "sqlite"
|
|
14
|
+
? openBunSqlite({ name: "queue", dialect, path: target })
|
|
15
|
+
: openBunSql({ name: "queue", dialect, url: target }),
|
|
16
|
+
)
|
|
17
|
+
const queue = createQueueTable(() => db, { table, maxAttempts: 3 })
|
|
18
|
+
await queue.ensure()
|
|
19
|
+
const ran: string[] = []
|
|
20
|
+
const worker = startQueueWorker(queue, {
|
|
21
|
+
concurrency: 4,
|
|
22
|
+
pollMs: 5,
|
|
23
|
+
run: async (row) => {
|
|
24
|
+
ran.push(row.payload)
|
|
25
|
+
await Bun.sleep(1)
|
|
26
|
+
return undefined
|
|
27
|
+
},
|
|
28
|
+
error: (error) => void process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`),
|
|
29
|
+
})
|
|
30
|
+
const quoted = dialect === "mysql" ? `\`${table}\`` : `"${table}"`
|
|
31
|
+
const count = `SELECT COUNT(*) AS n FROM ${quoted}`
|
|
32
|
+
for (;;) {
|
|
33
|
+
await Bun.sleep(20)
|
|
34
|
+
const [left] = await db.sql<{ n: unknown }>(Object.assign([count], { raw: [count] }))
|
|
35
|
+
if (Number(left?.n) === 0) break
|
|
36
|
+
}
|
|
37
|
+
await worker.stop()
|
|
38
|
+
await db.close()
|
|
39
|
+
process.stdout.write(JSON.stringify(ran))
|