@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,419 @@
|
|
|
1
|
+
import { namedDriver } from "hamur/server/internal"
|
|
2
|
+
import { outsideTransaction } from "../runtime/database.ts"
|
|
3
|
+
import type { Database, Dialect, Transaction } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
export interface DbStorageOptions {
|
|
6
|
+
/** Connection name of `db.connections` (default `"default"`). */
|
|
7
|
+
connection?: string
|
|
8
|
+
/** Table name (default `hamur_storage`). */
|
|
9
|
+
table?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The storage driver (`StorageDriver` of `hamur/server`) with every optional method this driver implements. */
|
|
13
|
+
export interface DbStorageDriver {
|
|
14
|
+
getItem(key: string): Promise<Uint8Array | undefined>
|
|
15
|
+
setItem(key: string, value: Uint8Array, expires?: number): Promise<void>
|
|
16
|
+
hasItem(key: string): Promise<boolean>
|
|
17
|
+
removeItem(key: string): Promise<void>
|
|
18
|
+
getKeys(prefix: string): Promise<string[]>
|
|
19
|
+
clear(prefix: string): Promise<void>
|
|
20
|
+
getItems(keys: string[]): Promise<Array<Uint8Array | undefined>>
|
|
21
|
+
setItems(items: Array<{ key: string; value: Uint8Array | undefined; expires?: number }>): Promise<void>
|
|
22
|
+
getMeta(key: string): Promise<{ size?: number; mtime?: Date; expires?: number } | undefined>
|
|
23
|
+
increment(key: string, by: number, expires?: number): Promise<number | undefined>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Runner = Pick<Database, "sql" | "first" | "run">
|
|
27
|
+
type Statement = { sql: string; params: unknown[] }
|
|
28
|
+
|
|
29
|
+
const encoder = new TextEncoder()
|
|
30
|
+
const decoder = new TextDecoder()
|
|
31
|
+
/** D1 allows 100 bound parameters in one statement. */
|
|
32
|
+
const KEYS_PER_SELECT: Record<Dialect, number> = { sqlite: 90, postgres: 1000, mysql: 1000 }
|
|
33
|
+
const SAFE = Number.MAX_SAFE_INTEGER
|
|
34
|
+
const INTEGER = /^(0|-?[1-9][0-9]*)$/
|
|
35
|
+
/** Bytes of a stored key on every dialect: the mount's part, the key and the `$` of its metadata record. */
|
|
36
|
+
export const MAX_KEY_BYTES = 1024
|
|
37
|
+
const RETRIES = 5
|
|
38
|
+
/** One write in this many also deletes up to `SWEEP_ROWS` expired rows. */
|
|
39
|
+
const SWEEP_EVERY = 128
|
|
40
|
+
const SWEEP_ROWS = 100
|
|
41
|
+
|
|
42
|
+
const bytes = (value: unknown): Uint8Array => new Uint8Array(value as ArrayLike<number>)
|
|
43
|
+
const text = (value: unknown): string => (typeof value === "string" ? value : decoder.decode(bytes(value)))
|
|
44
|
+
const escapeLike = (value: string): string => value.replace(/[!%_]/g, "!$&")
|
|
45
|
+
|
|
46
|
+
/** SQLSTATE 40P01 and 40001 on Postgres, error 1213 on MySQL, by the code the server sent. */
|
|
47
|
+
function isDeadlock(error: unknown): boolean {
|
|
48
|
+
const code = (error as { errno?: unknown })?.errno
|
|
49
|
+
return code === "40P01" || code === "40001" || code === 1213 || code === "1213"
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const pause = (attempt: number) => new Promise<void>((resolve) => setTimeout(resolve, Math.random() * 10 * attempt))
|
|
53
|
+
|
|
54
|
+
/** Runs `work`, again after a deadlock the server broke (its transaction rolled back whole), up to `RETRIES` times. */
|
|
55
|
+
async function retrying<T>(work: () => Promise<T>): Promise<T> {
|
|
56
|
+
for (let attempt = 1; ; attempt++) {
|
|
57
|
+
try {
|
|
58
|
+
return await work()
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (attempt >= RETRIES || !isDeadlock(error)) throw error
|
|
61
|
+
await pause(attempt)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A statement written with `?` for every value, whichever the dialect; `Database` turns them into its own placeholders. */
|
|
67
|
+
function template(sql: string): TemplateStringsArray {
|
|
68
|
+
const parts = sql.split("?")
|
|
69
|
+
return Object.assign(parts, { raw: parts })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const all = <T>(run: Runner, { sql, params }: Statement) => run.sql<T>(template(sql), ...(params as never[]))
|
|
73
|
+
const first = <T>(run: Runner, { sql, params }: Statement) => run.first<T>(template(sql), ...(params as never[]))
|
|
74
|
+
const exec = (run: Runner, { sql, params }: Statement) => run.run(template(sql), ...(params as never[]))
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* One table, `(key, value, expires, mtime)` (`BYTEA` and `BIGINT` on postgres, a binary `key` and `LONGBLOB` on mysql),
|
|
78
|
+
* written in the SQL of the connection's dialect; the table is created at first use. A mount's keys are stored as
|
|
79
|
+
* `<mount>|<key>`, so mounts that share a table never see each other's rows.
|
|
80
|
+
*/
|
|
81
|
+
export function dbStorageDriver(
|
|
82
|
+
database: () => Database,
|
|
83
|
+
options: DbStorageOptions = {},
|
|
84
|
+
mount?: string,
|
|
85
|
+
): DbStorageDriver {
|
|
86
|
+
const table = options.table ?? "hamur_storage"
|
|
87
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
88
|
+
throw new TypeError(`Invalid db storage table name ${JSON.stringify(table)}`)
|
|
89
|
+
const base = mount === undefined ? "" : `${mount.replace(/[%|]/g, (char) => (char === "%" ? "%25" : "%7C"))}|`
|
|
90
|
+
let ready: Promise<Database> | undefined
|
|
91
|
+
let writes = 0
|
|
92
|
+
|
|
93
|
+
const open = (): Promise<Database> =>
|
|
94
|
+
(ready ??= (async () => {
|
|
95
|
+
const db = database()
|
|
96
|
+
const { t, key, value, expires, mtime } = names(db.dialect)
|
|
97
|
+
const types: Record<Dialect, [string, string, string]> = {
|
|
98
|
+
sqlite: ["TEXT", "BLOB", "INTEGER"],
|
|
99
|
+
postgres: ["TEXT", "BYTEA", "BIGINT"],
|
|
100
|
+
mysql: [`VARBINARY(${MAX_KEY_BYTES})`, "LONGBLOB", "BIGINT"],
|
|
101
|
+
}
|
|
102
|
+
const [keyType, valueType, numberType] = types[db.dialect]
|
|
103
|
+
try {
|
|
104
|
+
await db.exec(
|
|
105
|
+
`CREATE TABLE IF NOT EXISTS ${t} (${key} ${keyType} NOT NULL PRIMARY KEY, ${value} ${valueType} NOT NULL, ${expires} ${numberType}, ${mtime} ${numberType})`,
|
|
106
|
+
)
|
|
107
|
+
} catch (error) {
|
|
108
|
+
// two processes creating the table at once: the loser fails on the catalog, and the table is there
|
|
109
|
+
try {
|
|
110
|
+
await db.exec(`SELECT 1 FROM ${t} WHERE 1 = 0`)
|
|
111
|
+
} catch {
|
|
112
|
+
throw error
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
await createIndex(db)
|
|
116
|
+
return db
|
|
117
|
+
})().catch((error: unknown) => {
|
|
118
|
+
ready = undefined
|
|
119
|
+
throw error
|
|
120
|
+
}))
|
|
121
|
+
|
|
122
|
+
const indexName = `${table}_expires_idx`.slice(0, 63)
|
|
123
|
+
|
|
124
|
+
/** An index on `expires`, for the sweep; D1 takes it as SQLite does. MySQL has no `IF NOT EXISTS`, and Postgres can fail on the catalog when two processes race, so a failure passes when the index is there. */
|
|
125
|
+
async function createIndex(db: Database): Promise<void> {
|
|
126
|
+
const { t, expires } = names(db.dialect)
|
|
127
|
+
const quote = db.dialect === "mysql" ? "`" : '"'
|
|
128
|
+
const create = `CREATE INDEX ${db.dialect === "mysql" ? "" : "IF NOT EXISTS "}${quote}${indexName}${quote} ON ${t} (${expires})`
|
|
129
|
+
try {
|
|
130
|
+
await db.exec(create)
|
|
131
|
+
} catch (error) {
|
|
132
|
+
const found =
|
|
133
|
+
db.dialect === "postgres"
|
|
134
|
+
? await first(db, {
|
|
135
|
+
sql: "SELECT 1 AS found FROM pg_indexes WHERE tablename = ? AND indexname = ?",
|
|
136
|
+
params: [table, indexName],
|
|
137
|
+
})
|
|
138
|
+
: db.dialect === "mysql"
|
|
139
|
+
? await first(db, {
|
|
140
|
+
sql: "SELECT 1 AS found FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?",
|
|
141
|
+
params: [table, indexName],
|
|
142
|
+
})
|
|
143
|
+
: undefined
|
|
144
|
+
if (!found) throw error
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function names(dialect: Dialect) {
|
|
149
|
+
const quote = dialect === "mysql" ? "`" : '"'
|
|
150
|
+
return {
|
|
151
|
+
t: `${quote}${table}${quote}`,
|
|
152
|
+
key: `${quote}key${quote}`,
|
|
153
|
+
value: `${quote}value${quote}`,
|
|
154
|
+
expires: `${quote}expires${quote}`,
|
|
155
|
+
mtime: `${quote}mtime${quote}`,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The row key of `key`, refused when it or its `<key>$` record would not fit. */
|
|
160
|
+
function rowKey(key: string): string {
|
|
161
|
+
const full = base + key
|
|
162
|
+
const size = encoder.encode(full).length + (key.endsWith("$") ? 0 : 1)
|
|
163
|
+
if (size > MAX_KEY_BYTES) {
|
|
164
|
+
const shown = key.length > 40 ? `${key.slice(0, 40)}…` : key
|
|
165
|
+
throw new RangeError(
|
|
166
|
+
`db storage key ${JSON.stringify(shown)} is too long: ${size} bytes with its mount and a trailing "$", the limit is ${MAX_KEY_BYTES}`,
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
return full
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** `WHERE` for the rows of this mount equal to `prefix` or below it. */
|
|
173
|
+
function under(dialect: Dialect, prefix: string): Statement {
|
|
174
|
+
const { key } = names(dialect)
|
|
175
|
+
if (prefix === "") {
|
|
176
|
+
if (base === "") return { sql: "1 = 1", params: [] }
|
|
177
|
+
if (dialect === "sqlite") return { sql: `substr(${key}, 1, ?) = ?`, params: [[...base].length, base] }
|
|
178
|
+
return { sql: `${key} LIKE ? ESCAPE '!'`, params: [`${escapeLike(base)}%`] }
|
|
179
|
+
}
|
|
180
|
+
const full = base + prefix
|
|
181
|
+
if (prefix.endsWith(":")) {
|
|
182
|
+
if (dialect === "sqlite") return { sql: `substr(${key}, 1, ?) = ?`, params: [[...full].length, full] }
|
|
183
|
+
return { sql: `${key} LIKE ? ESCAPE '!'`, params: [`${escapeLike(full)}%`] }
|
|
184
|
+
}
|
|
185
|
+
// SQLite's LIKE ignores case; its substr compares exactly
|
|
186
|
+
if (dialect === "sqlite")
|
|
187
|
+
return { sql: `(${key} = ? OR substr(${key}, 1, ?) = ?)`, params: [full, [...full].length + 1, `${full}:`] }
|
|
188
|
+
return { sql: `(${key} = ? OR ${key} LIKE ? ESCAPE '!')`, params: [full, `${escapeLike(full)}:%`] }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function upsert(dialect: Dialect, key: string, value: Uint8Array, expires: number | undefined): Statement {
|
|
192
|
+
const { t, key: k, value: v, expires: e, mtime: m } = names(dialect)
|
|
193
|
+
const head = `INSERT INTO ${t} (${k}, ${v}, ${e}, ${m}) VALUES (?, ?, ?, ?)`
|
|
194
|
+
const params = [rowKey(key), value, expires ?? null, Date.now()]
|
|
195
|
+
if (dialect === "mysql")
|
|
196
|
+
return {
|
|
197
|
+
sql: `${head} ON DUPLICATE KEY UPDATE ${v} = VALUES(${v}), ${e} = VALUES(${e}), ${m} = VALUES(${m})`,
|
|
198
|
+
params,
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
sql: `${head} ON CONFLICT (${k}) DO UPDATE SET ${v} = EXCLUDED.${v}, ${e} = EXCLUDED.${e}, ${m} = EXCLUDED.${m}`,
|
|
202
|
+
params,
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function removal(dialect: Dialect, key: string): Statement {
|
|
207
|
+
const { t, key: k } = names(dialect)
|
|
208
|
+
return { sql: `DELETE FROM ${t} WHERE ${k} = ?`, params: [base + key] }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** After a write, now and then: deletes a bounded number of expired rows, whoever's they are; a failing sweep is not the write's failure. */
|
|
212
|
+
async function sweep(db: Database): Promise<void> {
|
|
213
|
+
if (++writes % SWEEP_EVERY !== 0) return
|
|
214
|
+
const { t, key: k, expires: e } = names(db.dialect)
|
|
215
|
+
try {
|
|
216
|
+
await exec(db, {
|
|
217
|
+
sql: `DELETE FROM ${t} WHERE ${k} IN (SELECT ${k} FROM (SELECT ${k} FROM ${t} WHERE ${e} <= ? LIMIT ${SWEEP_ROWS}) AS expired)`,
|
|
218
|
+
params: [Date.now()],
|
|
219
|
+
})
|
|
220
|
+
} catch {}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function read(key: string): Promise<Uint8Array | undefined> {
|
|
224
|
+
const db = await open()
|
|
225
|
+
const { t, key: k, value, expires } = names(db.dialect)
|
|
226
|
+
const row = await first<{ value: unknown; expires: unknown }>(db, {
|
|
227
|
+
sql: `SELECT ${value} AS value, ${expires} AS expires FROM ${t} WHERE ${k} = ?`,
|
|
228
|
+
params: [base + key],
|
|
229
|
+
})
|
|
230
|
+
if (!row) return undefined
|
|
231
|
+
if (row.expires !== null && Number(row.expires) <= Date.now()) {
|
|
232
|
+
await exec(db, { sql: `DELETE FROM ${t} WHERE ${k} = ? AND ${expires} <= ?`, params: [base + key, Date.now()] })
|
|
233
|
+
return undefined
|
|
234
|
+
}
|
|
235
|
+
return bytes(row.value)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function incrementInSql(
|
|
239
|
+
db: Database,
|
|
240
|
+
key: string,
|
|
241
|
+
by: number,
|
|
242
|
+
expires: number | undefined,
|
|
243
|
+
): Promise<number | undefined> {
|
|
244
|
+
const { t, key: k, value: v, expires: e, mtime: m } = names(db.dialect)
|
|
245
|
+
const now = Date.now()
|
|
246
|
+
const params: unknown[] = []
|
|
247
|
+
const $ = (value: unknown): string => (params.push(value), "?")
|
|
248
|
+
if (db.dialect === "sqlite") {
|
|
249
|
+
const expired = () => `(${e} IS NOT NULL AND ${e} <= ${$(now)})`
|
|
250
|
+
const old = `CAST(CAST(${v} AS TEXT) AS INTEGER)`
|
|
251
|
+
// BETWEEN, not abs(): abs of the smallest 64-bit integer raises "integer overflow"
|
|
252
|
+
const row = await first<{ value: string }>(db, {
|
|
253
|
+
sql: `INSERT INTO ${t} (${k}, ${v}, ${e}, ${m}) VALUES (${$(rowKey(key))}, CAST(CAST(${$(by)} AS INTEGER) AS BLOB), ${$(expires ?? null)}, ${$(now)})
|
|
254
|
+
ON CONFLICT (${k}) DO UPDATE SET
|
|
255
|
+
${v} = CAST(CASE WHEN ${expired()} THEN CAST(${$(by)} AS INTEGER) ELSE ${old} + CAST(${$(by)} AS INTEGER) END AS BLOB),
|
|
256
|
+
${e} = CASE WHEN ${expired()} THEN ${$(expires ?? null)} ELSE ${e} END,
|
|
257
|
+
${m} = ${$(now)}
|
|
258
|
+
WHERE ${expired()} OR (CAST(${old} AS TEXT) = CAST(${v} AS TEXT) AND ${old} BETWEEN -${SAFE} AND ${SAFE} AND ${old} + CAST(${$(by)} AS INTEGER) BETWEEN -${SAFE} AND ${SAFE})
|
|
259
|
+
RETURNING CAST(${v} AS TEXT) AS value`,
|
|
260
|
+
params,
|
|
261
|
+
})
|
|
262
|
+
return row ? Number(row.value) : undefined
|
|
263
|
+
}
|
|
264
|
+
const old = `encode(${t}.${v}, 'escape')`
|
|
265
|
+
const expired = () => `(${t}.${e} IS NOT NULL AND ${t}.${e} <= CAST(${$(now)} AS BIGINT))`
|
|
266
|
+
// the pattern guards the cast: a CASE is the one place Postgres promises to evaluate in order
|
|
267
|
+
const row = await first<{ value: string }>(db, {
|
|
268
|
+
sql: `INSERT INTO ${t} (${k}, ${v}, ${e}, ${m}) VALUES (${$(rowKey(key))}, ${$(encoder.encode(String(by)))}, CAST(${$(expires ?? null)} AS BIGINT), CAST(${$(now)} AS BIGINT))
|
|
269
|
+
ON CONFLICT (${k}) DO UPDATE SET
|
|
270
|
+
${v} = CASE WHEN ${expired()} THEN EXCLUDED.${v} ELSE convert_to((${old}::bigint + CAST(${$(by)} AS BIGINT))::text, 'UTF8') END,
|
|
271
|
+
${e} = CASE WHEN ${expired()} THEN EXCLUDED.${e} ELSE ${t}.${e} END,
|
|
272
|
+
${m} = EXCLUDED.${m}
|
|
273
|
+
WHERE ${expired()} OR (CASE WHEN octet_length(${t}.${v}) <= 18 AND ${old} ~ '^(0|(-|)[1-9][0-9]*)$' THEN ${old}::bigint BETWEEN -${SAFE} AND ${SAFE} AND ${old}::bigint + CAST(${$(by)} AS BIGINT) BETWEEN -${SAFE} AND ${SAFE} ELSE FALSE END)
|
|
274
|
+
RETURNING encode(${t}.${v}, 'escape') AS value`,
|
|
275
|
+
params,
|
|
276
|
+
})
|
|
277
|
+
return row ? Number(row.value) : undefined
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function incrementLocked(
|
|
281
|
+
db: Database,
|
|
282
|
+
key: string,
|
|
283
|
+
by: number,
|
|
284
|
+
expires: number | undefined,
|
|
285
|
+
): Promise<number | undefined> {
|
|
286
|
+
const { t, key: k, value: v, expires: e, mtime: m } = names(db.dialect)
|
|
287
|
+
const stored = rowKey(key)
|
|
288
|
+
for (let attempt = 1; ; attempt++) {
|
|
289
|
+
try {
|
|
290
|
+
const result = await db.transaction(async (tx: Transaction) => {
|
|
291
|
+
const now = Date.now()
|
|
292
|
+
// the row is made first, so the locking read below finds one: without a row it locks a gap, and two callers deadlock
|
|
293
|
+
await exec(tx, {
|
|
294
|
+
sql: `INSERT INTO ${t} (${k}, ${v}, ${e}, ${m}) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE ${k} = ${k}`,
|
|
295
|
+
params: [stored, encoder.encode("0"), expires ?? null, now],
|
|
296
|
+
})
|
|
297
|
+
const row = await first<{ value: unknown; expires: unknown }>(tx, {
|
|
298
|
+
sql: `SELECT ${v} AS value, ${e} AS expires FROM ${t} WHERE ${k} = ? FOR UPDATE`,
|
|
299
|
+
params: [stored],
|
|
300
|
+
})
|
|
301
|
+
if (!row) return "retry" as const
|
|
302
|
+
const expired = row.expires !== null && Number(row.expires) <= now
|
|
303
|
+
const current = expired ? "0" : text(row.value)
|
|
304
|
+
if (!INTEGER.test(current) || Math.abs(Number(current)) > SAFE || Math.abs(Number(current) + by) > SAFE)
|
|
305
|
+
return undefined
|
|
306
|
+
const next = Number(current) + by
|
|
307
|
+
const kept = expired ? (expires ?? null) : row.expires === null ? null : Number(row.expires)
|
|
308
|
+
await exec(tx, {
|
|
309
|
+
sql: `UPDATE ${t} SET ${v} = ?, ${e} = ?, ${m} = ? WHERE ${k} = ?`,
|
|
310
|
+
params: [encoder.encode(String(next)), kept, now, stored],
|
|
311
|
+
})
|
|
312
|
+
return next
|
|
313
|
+
})
|
|
314
|
+
if (result !== "retry") return result
|
|
315
|
+
if (attempt >= RETRIES)
|
|
316
|
+
throw new Error(
|
|
317
|
+
`db storage: the row of ${JSON.stringify(key)} was removed ${RETRIES} times while it was incremented`,
|
|
318
|
+
)
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (attempt >= RETRIES || !isDeadlock(error)) throw error
|
|
321
|
+
await pause(attempt)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const driver: DbStorageDriver = {
|
|
327
|
+
getItem: (key) => read(key),
|
|
328
|
+
async setItem(key, value, expires) {
|
|
329
|
+
const db = await open()
|
|
330
|
+
await exec(db, upsert(db.dialect, key, value, expires))
|
|
331
|
+
await sweep(db)
|
|
332
|
+
},
|
|
333
|
+
async hasItem(key) {
|
|
334
|
+
return (await read(key)) !== undefined
|
|
335
|
+
},
|
|
336
|
+
async removeItem(key) {
|
|
337
|
+
const db = await open()
|
|
338
|
+
await exec(db, removal(db.dialect, key))
|
|
339
|
+
},
|
|
340
|
+
async getKeys(prefix) {
|
|
341
|
+
const db = await open()
|
|
342
|
+
const { t, key: k, expires: e } = names(db.dialect)
|
|
343
|
+
const where = under(db.dialect, prefix)
|
|
344
|
+
const rows = await all<{ key: unknown }>(db, {
|
|
345
|
+
sql: `SELECT ${k} AS ${k} FROM ${t} WHERE ${where.sql} AND (${e} IS NULL OR ${e} > ?) ORDER BY ${k}`,
|
|
346
|
+
params: [...where.params, Date.now()],
|
|
347
|
+
})
|
|
348
|
+
return rows.map((row) => text(row.key).slice(base.length))
|
|
349
|
+
},
|
|
350
|
+
async clear(prefix) {
|
|
351
|
+
const db = await open()
|
|
352
|
+
const where = under(db.dialect, prefix)
|
|
353
|
+
await exec(db, { sql: `DELETE FROM ${names(db.dialect).t} WHERE ${where.sql}`, params: where.params })
|
|
354
|
+
},
|
|
355
|
+
async getItems(keys) {
|
|
356
|
+
const db = await open()
|
|
357
|
+
const { t, key: k, value: v, expires: e } = names(db.dialect)
|
|
358
|
+
const found = new Map<string, Uint8Array>()
|
|
359
|
+
const now = Date.now()
|
|
360
|
+
const size = KEYS_PER_SELECT[db.dialect]
|
|
361
|
+
for (let i = 0; i < keys.length; i += size) {
|
|
362
|
+
const chunk = keys.slice(i, i + size).map((key) => base + key)
|
|
363
|
+
const rows = await all<{ key: unknown; value: unknown }>(db, {
|
|
364
|
+
sql: `SELECT ${k} AS ${k}, ${v} AS value FROM ${t} WHERE ${k} IN (${chunk.map(() => "?").join(", ")}) AND (${e} IS NULL OR ${e} > ?)`,
|
|
365
|
+
params: [...chunk, now],
|
|
366
|
+
})
|
|
367
|
+
for (const row of rows) found.set(text(row.key), bytes(row.value))
|
|
368
|
+
}
|
|
369
|
+
return keys.map((key) => found.get(base + key))
|
|
370
|
+
},
|
|
371
|
+
async setItems(items) {
|
|
372
|
+
if (!items.length) return
|
|
373
|
+
const db = await open()
|
|
374
|
+
// a later item of a key wins; sorted by key, so two callers that overlap lock rows in one order
|
|
375
|
+
const last = new Map<string, (typeof items)[number]>()
|
|
376
|
+
for (const item of items) last.set(item.key, item)
|
|
377
|
+
const statements = [...last.values()]
|
|
378
|
+
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
|
|
379
|
+
.map((item) =>
|
|
380
|
+
item.value === undefined
|
|
381
|
+
? removal(db.dialect, item.key)
|
|
382
|
+
: upsert(db.dialect, item.key, item.value, item.expires),
|
|
383
|
+
)
|
|
384
|
+
await retrying(() => db.batch(statements.map(({ sql, params }) => db.run(template(sql), ...(params as never[])))))
|
|
385
|
+
await sweep(db)
|
|
386
|
+
},
|
|
387
|
+
async getMeta(key) {
|
|
388
|
+
const db = await open()
|
|
389
|
+
const { t, key: k, value: v, expires: e, mtime: m } = names(db.dialect)
|
|
390
|
+
const size = db.dialect === "postgres" ? "octet_length" : "length"
|
|
391
|
+
const row = await first<{ size: unknown; expires: unknown; mtime: unknown }>(db, {
|
|
392
|
+
sql: `SELECT ${size}(${v}) AS size, ${e} AS expires, ${m} AS mtime FROM ${t} WHERE ${k} = ? AND (${e} IS NULL OR ${e} > ?)`,
|
|
393
|
+
params: [base + key, Date.now()],
|
|
394
|
+
})
|
|
395
|
+
if (!row) return undefined
|
|
396
|
+
return {
|
|
397
|
+
size: Number(row.size),
|
|
398
|
+
...(row.mtime === null ? {} : { mtime: new Date(Number(row.mtime)) }),
|
|
399
|
+
...(row.expires === null ? {} : { expires: Number(row.expires) }),
|
|
400
|
+
}
|
|
401
|
+
},
|
|
402
|
+
async increment(key, by, expires) {
|
|
403
|
+
const db = await open()
|
|
404
|
+
const next = await (db.dialect === "mysql"
|
|
405
|
+
? incrementLocked(db, key, by, expires)
|
|
406
|
+
: incrementInSql(db, key, by, expires))
|
|
407
|
+
await sweep(db)
|
|
408
|
+
return next
|
|
409
|
+
},
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Every call runs outside the `db.transaction` its caller may be in (see `outsideTransaction`). */
|
|
413
|
+
const detached = {} as Record<string, unknown>
|
|
414
|
+
for (const [name, method] of Object.entries(driver)) {
|
|
415
|
+
detached[name] = (...args: unknown[]) =>
|
|
416
|
+
outsideTransaction(database(), () => (method as (...a: unknown[]) => Promise<unknown>)(...args))
|
|
417
|
+
}
|
|
418
|
+
return namedDriver("db", detached as unknown as DbStorageDriver)
|
|
419
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { useDatabase } from "../server/index.ts"
|
|
2
|
+
import { dbStorageDriver, type DbStorageDriver, type DbStorageOptions } from "./driver.ts"
|
|
3
|
+
|
|
4
|
+
/** The storage driver of a `dbStorage({ connection?, table? })` mount, given the mount's name; the connection opens at the mount's first use. */
|
|
5
|
+
export default function db(options: DbStorageOptions = {}, mount?: string): DbStorageDriver {
|
|
6
|
+
return dbStorageDriver(() => useDatabase(options.connection ?? "default"), options, mount)
|
|
7
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// The augmentation alone does not load "hamur" under TS 7.
|
|
2
|
+
import type {} from "hamur"
|
|
3
|
+
import type { HamurContext } from "hamur/kit"
|
|
4
|
+
import type { Secret } from "hamur/server"
|
|
5
|
+
import type { createSqlFragment } from "hamur/server/internal"
|
|
6
|
+
|
|
7
|
+
export type Dialect = "sqlite" | "postgres" | "mysql"
|
|
8
|
+
|
|
9
|
+
export type { Secret }
|
|
10
|
+
|
|
11
|
+
/** `hamur/server`'s `SqlFragment`, named through the entry that holds its symbol so both resolve to one declaration. */
|
|
12
|
+
export type SqlFragment = ReturnType<typeof createSqlFragment>
|
|
13
|
+
|
|
14
|
+
export type Connection = (
|
|
15
|
+
| { connector: "bun-sql"; url?: Secret; dialect?: Dialect }
|
|
16
|
+
| { connector: "bun-sqlite"; path: string }
|
|
17
|
+
| { connector: "node-sqlite"; path: string }
|
|
18
|
+
| { connector: "d1"; binding: string }
|
|
19
|
+
| { connector: "client"; dialect: Dialect; client: string }
|
|
20
|
+
) & { dev?: Connection }
|
|
21
|
+
|
|
22
|
+
export interface DbConfig {
|
|
23
|
+
migrate?: "dev" | "start" | "build" | false
|
|
24
|
+
connections?: Record<string, Connection>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One connection as the build resolved it: the connector, its dialect and the options the connector opens with. */
|
|
28
|
+
export interface ResolvedConnection {
|
|
29
|
+
connector: Connection["connector"]
|
|
30
|
+
dialect: Dialect
|
|
31
|
+
url?: Secret
|
|
32
|
+
path?: string
|
|
33
|
+
binding?: string
|
|
34
|
+
/** The client file as configured, relative to `rootDir`. */
|
|
35
|
+
client?: string
|
|
36
|
+
/** Replaces this connection under `hamur dev` and in the prerender; the build reads it and does not pass it on. */
|
|
37
|
+
dev?: ResolvedConnection
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ResolvedDbOptions {
|
|
41
|
+
migrate: "dev" | "start" | "build" | false
|
|
42
|
+
/** The configured connections; `default` is added by `setupConnections` when the preset has a database of its own. */
|
|
43
|
+
connections: Record<string, ResolvedConnection>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type DbSetup = (options: ResolvedDbOptions, hamur: HamurContext) => void | Promise<void>
|
|
47
|
+
|
|
48
|
+
export type SqlValue = string | number | bigint | boolean | null | Date | Uint8Array | readonly SqlValue[]
|
|
49
|
+
|
|
50
|
+
export interface RunResult {
|
|
51
|
+
changes: number
|
|
52
|
+
lastInsertId?: number | string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface Query<R> extends PromiseLike<R> {
|
|
56
|
+
/** The statement with the dialect's placeholders: `$1 … $n` on postgres, `?` on sqlite and mysql. */
|
|
57
|
+
readonly text: string
|
|
58
|
+
readonly values: readonly SqlValue[]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface Database {
|
|
62
|
+
readonly name: string
|
|
63
|
+
readonly dialect: Dialect
|
|
64
|
+
sql<T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: Array<SqlValue | SqlFragment>): Query<T[]>
|
|
65
|
+
first<T = Record<string, unknown>>(
|
|
66
|
+
strings: TemplateStringsArray,
|
|
67
|
+
...values: Array<SqlValue | SqlFragment>
|
|
68
|
+
): Query<T | undefined>
|
|
69
|
+
run(strings: TemplateStringsArray, ...values: Array<SqlValue | SqlFragment>): Query<RunResult>
|
|
70
|
+
exec(text: string): Promise<void>
|
|
71
|
+
batch<const Q extends readonly Query<unknown>[]>(queries: Q): Promise<{ [K in keyof Q]: Awaited<Q[K]> }>
|
|
72
|
+
transaction<R>(fn: (tx: Transaction) => Promise<R>): Promise<R>
|
|
73
|
+
close(): Promise<void>
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type Transaction = Omit<Database, "transaction" | "close">
|
|
77
|
+
|
|
78
|
+
/** The app's own driver adapted to one shape; `text` holds the dialect's placeholders and `params` the values in order. */
|
|
79
|
+
export interface DatabaseClient {
|
|
80
|
+
query(
|
|
81
|
+
text: string,
|
|
82
|
+
params: unknown[],
|
|
83
|
+
): Promise<{ rows: Record<string, unknown>[]; changes?: number; lastInsertId?: number | string }>
|
|
84
|
+
/**
|
|
85
|
+
* One connection held until `release`; `transaction` and `batch` run on it, since a `BEGIN` sent to a pool lands on any connection.
|
|
86
|
+
* `release(error)` gets the error that left the connection in an unknown state (a failed `ROLLBACK`, a failed migration run):
|
|
87
|
+
* the pool should drop it, not hand it out again.
|
|
88
|
+
*/
|
|
89
|
+
reserve?(): Promise<{ query: DatabaseClient["query"]; release(error?: Error): void | Promise<void> }>
|
|
90
|
+
end?(): Promise<void>
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
declare module "hamur" {
|
|
94
|
+
interface HamurModuleOptions {
|
|
95
|
+
db?: DbConfig
|
|
96
|
+
}
|
|
97
|
+
interface HamurHooks {
|
|
98
|
+
/** A module adds a directory of `<number>_<name>.sql` files for a connection. */
|
|
99
|
+
"db:migrations:dirs": (dirs: Array<{ connection: string; dir: string }>) => void | Promise<void>
|
|
100
|
+
}
|
|
101
|
+
}
|