@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
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,1692 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
createDatabases
|
|
4
|
+
} from "../chunks/bun-index-b47nngck.js";
|
|
5
|
+
import {
|
|
6
|
+
withoutBom,
|
|
7
|
+
checksumOf,
|
|
8
|
+
migrate,
|
|
9
|
+
migrationStatus,
|
|
10
|
+
compareIds
|
|
11
|
+
} from "../chunks/bun-index-9na2zkqq.js";
|
|
12
|
+
import {
|
|
13
|
+
dbStorage2
|
|
14
|
+
} from "../chunks/bun-index-06tj00dn.js";
|
|
15
|
+
|
|
16
|
+
// packages/db/src/cli.ts
|
|
17
|
+
import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
|
|
18
|
+
import { join as join5, relative as relative3 } from "path";
|
|
19
|
+
import { DiagnosticError as DiagnosticError7, useLogger as useLogger4 } from "hamur/kit";
|
|
20
|
+
|
|
21
|
+
// packages/db/src/build/databases.ts
|
|
22
|
+
import { rm } from "fs/promises";
|
|
23
|
+
import { join, relative, resolve } from "path";
|
|
24
|
+
import { DiagnosticError, readEnvValues } from "hamur/kit";
|
|
25
|
+
var LOADERS = {
|
|
26
|
+
"bun-sql": () => import("../chunks/bun-bun-sql-vaz9ggc8.js"),
|
|
27
|
+
"bun-sqlite": () => import("../chunks/bun-bun-sqlite-qcd011rm.js"),
|
|
28
|
+
"node-sqlite": () => import("../chunks/bun-bun-sqlite-qcd011rm.js"),
|
|
29
|
+
d1: () => import("../chunks/bun-d1-d36z1pyr.js"),
|
|
30
|
+
client: () => import("../chunks/bun-client-cnt1ddnf.js")
|
|
31
|
+
};
|
|
32
|
+
function clientFile(rootDir, client) {
|
|
33
|
+
try {
|
|
34
|
+
return Bun.resolveSync(resolve(rootDir, client), rootDir);
|
|
35
|
+
} catch {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
var bundles = new WeakMap;
|
|
40
|
+
var bundleCount = 0;
|
|
41
|
+
function importClient(hamur, file) {
|
|
42
|
+
const own = bundles.get(hamur) ?? new Map;
|
|
43
|
+
bundles.set(hamur, own);
|
|
44
|
+
const known = own.get(file);
|
|
45
|
+
if (known)
|
|
46
|
+
return known;
|
|
47
|
+
const loading = (async () => {
|
|
48
|
+
const outdir = join(hamur.options.buildDir, "db", "client", `${process.pid}-${++bundleCount}`);
|
|
49
|
+
try {
|
|
50
|
+
const result = await Bun.build({
|
|
51
|
+
entrypoints: [file],
|
|
52
|
+
outdir,
|
|
53
|
+
target: "bun",
|
|
54
|
+
format: "esm",
|
|
55
|
+
plugins: [hamur.vfs.plugin("server"), ...hamur.options.build.plugins],
|
|
56
|
+
define: {
|
|
57
|
+
"import.meta.dev": String(hamur.options.dev),
|
|
58
|
+
"import.meta.server": "true",
|
|
59
|
+
"import.meta.client": "false"
|
|
60
|
+
},
|
|
61
|
+
throw: false
|
|
62
|
+
});
|
|
63
|
+
if (!result.success) {
|
|
64
|
+
throw new DiagnosticError("HAMUR_E5518", `Cannot build database client ${relative(hamur.options.rootDir, file)}:
|
|
65
|
+
${result.logs.filter((log) => log.level === "error").map((log) => log.message).join(`
|
|
66
|
+
`)}`);
|
|
67
|
+
}
|
|
68
|
+
const entry = result.outputs.find((output) => output.kind === "entry-point");
|
|
69
|
+
return await import(entry.path);
|
|
70
|
+
} finally {
|
|
71
|
+
await rm(outdir, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
})();
|
|
74
|
+
loading.catch(() => own.delete(file));
|
|
75
|
+
own.set(file, loading);
|
|
76
|
+
return loading;
|
|
77
|
+
}
|
|
78
|
+
function clientLoaders(hamur, connections) {
|
|
79
|
+
return Object.fromEntries(Object.entries(connections).flatMap(([name, { client }]) => {
|
|
80
|
+
const file = client === undefined ? undefined : clientFile(hamur.options.rootDir, client);
|
|
81
|
+
return file ? [[name, () => importClient(hamur, file)]] : [];
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
function buildEnv(hamur) {
|
|
85
|
+
let values;
|
|
86
|
+
return async (name) => (await (values ??= readEnvValues(hamur)))[name];
|
|
87
|
+
}
|
|
88
|
+
var asBun = (connection) => connection.connector === "node-sqlite" ? { ...connection, connector: "bun-sqlite" } : connection;
|
|
89
|
+
function devConnections(connections) {
|
|
90
|
+
return Object.fromEntries(Object.entries(connections).flatMap(([name, { dev }]) => dev ? [[name, asBun(dev)]] : []));
|
|
91
|
+
}
|
|
92
|
+
function openDatabases(hamur, options) {
|
|
93
|
+
return createDatabases(options.connections, LOADERS, buildEnv(hamur), clientLoaders(hamur, options.connections));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// packages/db/src/build/migrations.ts
|
|
97
|
+
import { watch } from "fs";
|
|
98
|
+
import { mkdir, readdir, readFile, rm as rm2, writeFile } from "fs/promises";
|
|
99
|
+
import { dirname, isAbsolute, join as join3, relative as relative2, resolve as resolve2, sep } from "path";
|
|
100
|
+
import { DiagnosticError as DiagnosticError4, addTask, addTemplate as addTemplate2, createResolver as createResolver2, useLogger as useLogger2 } from "hamur/kit";
|
|
101
|
+
|
|
102
|
+
// packages/db/src/build/connections.ts
|
|
103
|
+
import { join as join2 } from "path";
|
|
104
|
+
import {
|
|
105
|
+
DiagnosticError as DiagnosticError3,
|
|
106
|
+
addServer,
|
|
107
|
+
addTemplate,
|
|
108
|
+
createResolver,
|
|
109
|
+
diagnostic,
|
|
110
|
+
useLogger
|
|
111
|
+
} from "hamur/kit";
|
|
112
|
+
|
|
113
|
+
// packages/db/src/options.ts
|
|
114
|
+
import { DiagnosticError as DiagnosticError2, isEnvRef } from "hamur/kit";
|
|
115
|
+
var CONNECTORS = {
|
|
116
|
+
"bun-sql": { presets: ["bun", "static"] },
|
|
117
|
+
"bun-sqlite": { presets: ["bun", "static"] },
|
|
118
|
+
"node-sqlite": { presets: ["node"] },
|
|
119
|
+
d1: { presets: ["cloudflare"] },
|
|
120
|
+
client: { presets: ["bun", "node", "static", "vercel", "netlify", "cloudflare"] }
|
|
121
|
+
};
|
|
122
|
+
var MIGRATE = ["dev", "start", "build", false];
|
|
123
|
+
var DIALECTS = ["postgres", "mysql", "sqlite"];
|
|
124
|
+
var NAME = /^[A-Za-z0-9_]+$/;
|
|
125
|
+
var BINDING = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
126
|
+
var KEYS = new Set(["migrate", "connections"]);
|
|
127
|
+
function fail(message) {
|
|
128
|
+
throw new DiagnosticError2("HAMUR_E5505", message);
|
|
129
|
+
}
|
|
130
|
+
function shown(value) {
|
|
131
|
+
if (Array.isArray(value))
|
|
132
|
+
return "an array";
|
|
133
|
+
if (typeof value === "function")
|
|
134
|
+
return "a function";
|
|
135
|
+
if (value === undefined)
|
|
136
|
+
return "undefined";
|
|
137
|
+
return JSON.stringify(value);
|
|
138
|
+
}
|
|
139
|
+
function list(values) {
|
|
140
|
+
const quoted = values.map((value) => JSON.stringify(value));
|
|
141
|
+
return `${quoted.slice(0, -1).join(", ")} or ${quoted.at(-1)}`;
|
|
142
|
+
}
|
|
143
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
144
|
+
function dialectOf(url) {
|
|
145
|
+
if (typeof url !== "string")
|
|
146
|
+
return "postgres";
|
|
147
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url)?.[1]?.toLowerCase();
|
|
148
|
+
if (scheme === "mysql" || scheme === "mariadb")
|
|
149
|
+
return "mysql";
|
|
150
|
+
if (scheme === "sqlite" || scheme === "file")
|
|
151
|
+
return "sqlite";
|
|
152
|
+
return "postgres";
|
|
153
|
+
}
|
|
154
|
+
function resolveConnection(at, input, nested = false) {
|
|
155
|
+
const connection = isObject(input) ? input : {};
|
|
156
|
+
const connector = connection.connector;
|
|
157
|
+
if (typeof connector !== "string" || !Object.hasOwn(CONNECTORS, connector))
|
|
158
|
+
fail(`${at}.connector must be ${list(Object.keys(CONNECTORS))} (got ${shown(connector)})`);
|
|
159
|
+
if (nested && connector === "d1")
|
|
160
|
+
fail(`${at}.connector must be ${list(Object.keys(CONNECTORS).filter((name) => name !== "d1"))} (got "d1")`);
|
|
161
|
+
if (nested && connection.dev !== undefined)
|
|
162
|
+
fail(`${at}.dev is not allowed; a dev connection has no dev of its own`);
|
|
163
|
+
const dev = connection.dev === undefined ? {} : { dev: resolveConnection(`${at}.dev`, connection.dev, true) };
|
|
164
|
+
if (connector === "bun-sqlite" || connector === "node-sqlite") {
|
|
165
|
+
if (typeof connection.path !== "string" || !connection.path)
|
|
166
|
+
fail(`${at}.path is required for the ${connector} connector`);
|
|
167
|
+
return { connector, dialect: "sqlite", path: connection.path, ...dev };
|
|
168
|
+
}
|
|
169
|
+
if (connector === "d1") {
|
|
170
|
+
if (typeof connection.binding !== "string" || !BINDING.test(connection.binding))
|
|
171
|
+
fail(`${at}.binding must be a binding name (got ${shown(connection.binding)})`);
|
|
172
|
+
return { connector, dialect: "sqlite", binding: connection.binding, ...dev };
|
|
173
|
+
}
|
|
174
|
+
if (connector === "client") {
|
|
175
|
+
const dialect = connection.dialect;
|
|
176
|
+
if (dialect === undefined)
|
|
177
|
+
fail(`${at}.dialect is required for the client connector`);
|
|
178
|
+
if (!DIALECTS.includes(dialect))
|
|
179
|
+
fail(`${at}.dialect must be ${list(DIALECTS)} (got ${shown(dialect)})`);
|
|
180
|
+
if (typeof connection.client !== "string" || !connection.client)
|
|
181
|
+
fail(`${at}.client must be a path to a file (got ${shown(connection.client)})`);
|
|
182
|
+
return { connector, dialect, client: connection.client, ...dev };
|
|
183
|
+
}
|
|
184
|
+
const url = connection.url;
|
|
185
|
+
if (url !== undefined && typeof url !== "string" && !isEnvRef(url))
|
|
186
|
+
fail(`${at}.url must be a URL or env("NAME") (got ${shown(url)})`);
|
|
187
|
+
const dialect = connection.dialect;
|
|
188
|
+
if (dialect !== undefined && !DIALECTS.includes(dialect))
|
|
189
|
+
fail(`${at}.dialect must be ${list(DIALECTS)} (got ${shown(dialect)})`);
|
|
190
|
+
return {
|
|
191
|
+
connector: "bun-sql",
|
|
192
|
+
dialect: dialect ?? dialectOf(url),
|
|
193
|
+
...url === undefined ? {} : { url },
|
|
194
|
+
...dev
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function resolveOptions(input) {
|
|
198
|
+
const options = input ?? {};
|
|
199
|
+
for (const key of Object.keys(options))
|
|
200
|
+
if (!KEYS.has(key))
|
|
201
|
+
fail(`db has no ${JSON.stringify(key)}; connections go under db.connections`);
|
|
202
|
+
const migrate = options.migrate ?? "dev";
|
|
203
|
+
if (!MIGRATE.includes(migrate))
|
|
204
|
+
fail(`db.migrate must be "dev", "start", "build" or false (got ${shown(migrate)})`);
|
|
205
|
+
const given = options.connections ?? {};
|
|
206
|
+
if (!isObject(given))
|
|
207
|
+
fail(`db.connections must be an object of connections (got ${shown(given)})`);
|
|
208
|
+
const connections = {};
|
|
209
|
+
for (const [key, connection] of Object.entries(given)) {
|
|
210
|
+
if (!NAME.test(key))
|
|
211
|
+
fail(`db.connections[${JSON.stringify(key)}]: a connection name holds A-Z, a-z, 0-9 and _`);
|
|
212
|
+
connections[key] = resolveConnection(`db.connections.${key}`, connection);
|
|
213
|
+
}
|
|
214
|
+
return { migrate, connections };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// packages/db/src/build/connections.ts
|
|
218
|
+
var SERVER = "@hamur/db/server";
|
|
219
|
+
var PRERENDER_CONNECTIONS = "__HAMUR_DB_PRERENDER__";
|
|
220
|
+
var BUN_DATABASE = {
|
|
221
|
+
connector: "bun-sqlite",
|
|
222
|
+
dialect: "sqlite",
|
|
223
|
+
path: ".data/db.sqlite"
|
|
224
|
+
};
|
|
225
|
+
var PRESET_DATABASES = {
|
|
226
|
+
bun: BUN_DATABASE,
|
|
227
|
+
static: BUN_DATABASE,
|
|
228
|
+
node: { connector: "node-sqlite", dialect: "sqlite", path: ".data/db.sqlite" },
|
|
229
|
+
cloudflare: { connector: "d1", dialect: "sqlite", binding: "DB" }
|
|
230
|
+
};
|
|
231
|
+
var NO_KEPT_FILES = ["vercel", "netlify"];
|
|
232
|
+
var WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"];
|
|
233
|
+
function hasPassword(url) {
|
|
234
|
+
try {
|
|
235
|
+
return new URL(url).password !== "";
|
|
236
|
+
} catch {
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
241
|
+
async function declaredD1Bindings(rootDir, env) {
|
|
242
|
+
let config = {};
|
|
243
|
+
for (const name of WRANGLER_FILES) {
|
|
244
|
+
const file = Bun.file(join2(rootDir, name));
|
|
245
|
+
if (!await file.exists())
|
|
246
|
+
continue;
|
|
247
|
+
let parsed;
|
|
248
|
+
try {
|
|
249
|
+
parsed = Bun.JSONC.parse(await file.text());
|
|
250
|
+
} catch (error) {
|
|
251
|
+
throw new DiagnosticError3("HAMUR_E5512", `Cannot parse ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
252
|
+
}
|
|
253
|
+
if (!isObject2(parsed))
|
|
254
|
+
throw new DiagnosticError3("HAMUR_E5513", `${name} must contain a JSON object`);
|
|
255
|
+
config = parsed;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
const envs = isObject2(config.env) ? config.env : {};
|
|
259
|
+
if (env !== undefined && !(Object.hasOwn(envs, env) && isObject2(envs[env]))) {
|
|
260
|
+
throw new DiagnosticError3("HAMUR_E5514", `cloudflare.env ${JSON.stringify(env)} is not in wrangler.json (envs: ${Object.keys(envs).sort().join(", ") || "none"})`);
|
|
261
|
+
}
|
|
262
|
+
const chosen = env !== undefined ? { ...config, ...envs[env] } : config;
|
|
263
|
+
const databases = Array.isArray(chosen.d1_databases) ? chosen.d1_databases : [];
|
|
264
|
+
return databases.flatMap((database) => isObject2(database) && typeof database.binding === "string" ? [database.binding] : []);
|
|
265
|
+
}
|
|
266
|
+
var idVariable = (binding) => `HAMUR_CF_${binding.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_ID`;
|
|
267
|
+
var cloudflareId = (hamur, binding) => hamur.options.cloudflare.bindings?.[binding]?.id || process.env[idVariable(binding)] || undefined;
|
|
268
|
+
function bindingKey(config, name) {
|
|
269
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
270
|
+
const names = (value, inDurableObjects) => {
|
|
271
|
+
if (Array.isArray(value))
|
|
272
|
+
return value.some((item) => names(item, inDurableObjects));
|
|
273
|
+
if (!isRecord(value))
|
|
274
|
+
return false;
|
|
275
|
+
if (value.binding === name || inDurableObjects && value.name === name)
|
|
276
|
+
return true;
|
|
277
|
+
return Object.values(value).some((item) => names(item, inDurableObjects));
|
|
278
|
+
};
|
|
279
|
+
for (const [key, value] of Object.entries(config)) {
|
|
280
|
+
if (key === "env")
|
|
281
|
+
continue;
|
|
282
|
+
if (key === "vars" ? isRecord(value) && Object.hasOwn(value, name) : names(value, key === "durable_objects"))
|
|
283
|
+
return key;
|
|
284
|
+
}
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
var withoutDev = ({ dev: _, ...connection }) => connection;
|
|
288
|
+
var setupConnections = (options, hamur) => {
|
|
289
|
+
const { preset, dev } = hamur.options;
|
|
290
|
+
const { connections } = options;
|
|
291
|
+
const presetDatabase = dev ? BUN_DATABASE : PRESET_DATABASES[preset];
|
|
292
|
+
if (!connections.default && presetDatabase)
|
|
293
|
+
connections.default = { ...presetDatabase };
|
|
294
|
+
if (dev) {
|
|
295
|
+
for (const [name, connection] of Object.entries(connections))
|
|
296
|
+
connections[name] = asBun(connection.dev ?? connection);
|
|
297
|
+
}
|
|
298
|
+
const served = Object.fromEntries(Object.entries(connections).map(([name, connection]) => [name, withoutDev(connection)]));
|
|
299
|
+
const { rootDir } = hamur.options;
|
|
300
|
+
const missing = Object.entries(connections).flatMap(([name, { client, dev: own }]) => [
|
|
301
|
+
[`db.connections.${name}`, client],
|
|
302
|
+
[`db.connections.${name}.dev`, own?.client]
|
|
303
|
+
]).flatMap(([at, client]) => client !== undefined && !clientFile(rootDir, client) ? [`Cannot find database client ${JSON.stringify(client)} for ${at}`] : []);
|
|
304
|
+
if (missing.length)
|
|
305
|
+
throw new DiagnosticError3("HAMUR_E5515", missing.join(`
|
|
306
|
+
`));
|
|
307
|
+
const clients = Object.fromEntries(Object.entries(served).flatMap(([name, { client }]) => client === undefined ? [] : [[name, clientFile(rootDir, client)]]));
|
|
308
|
+
for (const [name, connection] of Object.entries(connections)) {
|
|
309
|
+
if (typeof connection.url === "string" && hasPassword(connection.url))
|
|
310
|
+
useLogger("hamur").warn(diagnostic("HAMUR_W5520", `db.connections.${name}.url holds a password; read it from the env with env("NAME")`));
|
|
311
|
+
}
|
|
312
|
+
const protection = hamur.options.build.importProtection;
|
|
313
|
+
const client = protection.client ??= {};
|
|
314
|
+
(client.deny ??= []).push(SERVER);
|
|
315
|
+
const r = createResolver(new URL("../../src/build/connections.ts", import.meta.url).href);
|
|
316
|
+
const used = [...new Set(Object.values(served).map((connection) => connection.connector))];
|
|
317
|
+
addTemplate({
|
|
318
|
+
filename: "db/connections",
|
|
319
|
+
getContents: () => `export const connections = ${JSON.stringify(served)};
|
|
320
|
+
export const connectors = {
|
|
321
|
+
${used.map((connector) => ` ${JSON.stringify(connector)}: () => import(${JSON.stringify(r.resolve(`../connectors/${connector}.ts`))}),`).join(`
|
|
322
|
+
`)}
|
|
323
|
+
};
|
|
324
|
+
export const clients = {
|
|
325
|
+
${Object.entries(clients).map(([name, file]) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`).join(`
|
|
326
|
+
`)}
|
|
327
|
+
};
|
|
328
|
+
`
|
|
329
|
+
});
|
|
330
|
+
addServer(r.resolve(dev ? "../server/door-dev.ts" : "../server/door.ts"));
|
|
331
|
+
const unknown = [];
|
|
332
|
+
const driver = dbStorage2({}).driver;
|
|
333
|
+
for (const [mount, config] of Object.entries(hamur.options.storage)) {
|
|
334
|
+
if (config.driver !== driver)
|
|
335
|
+
continue;
|
|
336
|
+
const connection = config.options.connection ?? "default";
|
|
337
|
+
if (typeof connection !== "string" || !Object.hasOwn(connections, connection)) {
|
|
338
|
+
unknown.push(`Storage mount "${mount}" uses the db driver with connection ${JSON.stringify(connection)}, which db.connections does not have`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (unknown.length)
|
|
342
|
+
throw new DiagnosticError3("HAMUR_E5516", unknown.join(`
|
|
343
|
+
`));
|
|
344
|
+
if (!dev) {
|
|
345
|
+
hamur.hooks.hook("prerender:routes", () => {
|
|
346
|
+
const overrides = devConnections(connections);
|
|
347
|
+
const scope = globalThis;
|
|
348
|
+
if (Object.keys(overrides).length)
|
|
349
|
+
scope[PRERENDER_CONNECTIONS] = {
|
|
350
|
+
connections: overrides,
|
|
351
|
+
loaders: LOADERS,
|
|
352
|
+
clients: clientLoaders(hamur, overrides)
|
|
353
|
+
};
|
|
354
|
+
else
|
|
355
|
+
delete scope[PRERENDER_CONNECTIONS];
|
|
356
|
+
});
|
|
357
|
+
hamur.hooks.hook("build:done", () => void delete globalThis[PRERENDER_CONNECTIONS]);
|
|
358
|
+
}
|
|
359
|
+
hamur.hooks.hook("build:before", async () => {
|
|
360
|
+
const problems = [];
|
|
361
|
+
if (!connections.default && NO_KEPT_FILES.includes(preset)) {
|
|
362
|
+
problems.push(`@hamur/db needs db.connections.default on the ${preset} preset: its file system does not keep files`);
|
|
363
|
+
}
|
|
364
|
+
for (const [name, connection] of Object.entries(dev ? {} : connections)) {
|
|
365
|
+
const { presets } = CONNECTORS[connection.connector];
|
|
366
|
+
if (!presets.includes(preset)) {
|
|
367
|
+
problems.push(`Database "${name}" uses the "${connection.connector}" connector, which the "${preset}" preset cannot run (it runs on: ${presets.join(", ")})`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const d1 = Object.entries(connections).filter(([, connection]) => !dev && connection.connector === "d1" && preset === "cloudflare");
|
|
371
|
+
if (d1.length) {
|
|
372
|
+
const declared = await declaredD1Bindings(hamur.options.rootDir, hamur.options.cloudflare.env);
|
|
373
|
+
for (const [name, { binding }] of d1) {
|
|
374
|
+
if (!declared.includes(binding) && !cloudflareId(hamur, binding)) {
|
|
375
|
+
problems.push(`db.connections.${name} uses the d1 binding "${binding}", which the app's wrangler config does not declare; add a d1_databases entry with binding "${binding}"`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (problems.length)
|
|
380
|
+
throw new DiagnosticError3("HAMUR_E5517", problems.join(`
|
|
381
|
+
`));
|
|
382
|
+
});
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
// packages/db/src/build/migrations.ts
|
|
386
|
+
var NAME2 = /^(\d{4,})_([a-z0-9_]+)\.sql$/;
|
|
387
|
+
var STARTS = ["bun", "node"];
|
|
388
|
+
var shown2 = (rootDir, path) => {
|
|
389
|
+
const from = relative2(rootDir, path);
|
|
390
|
+
return from.startsWith("..") || isAbsolute(from) ? path : from;
|
|
391
|
+
};
|
|
392
|
+
async function migrationDirs(hamur, options) {
|
|
393
|
+
const roots = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)].map((dir) => join3(dir, "db", "migrations"));
|
|
394
|
+
const dirs = [];
|
|
395
|
+
for (const root of roots) {
|
|
396
|
+
for (const connection of Object.keys(options.connections))
|
|
397
|
+
dirs.push({ connection, dir: connection === "default" ? root : join3(root, connection) });
|
|
398
|
+
}
|
|
399
|
+
await hamur.hooks.callHook("db:migrations:dirs", dirs);
|
|
400
|
+
return dirs;
|
|
401
|
+
}
|
|
402
|
+
async function sqlFiles(dir) {
|
|
403
|
+
try {
|
|
404
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
405
|
+
return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name);
|
|
406
|
+
} catch (error) {
|
|
407
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
408
|
+
return [];
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
async function loadMigrations(hamur, options) {
|
|
413
|
+
const { rootDir } = hamur.options;
|
|
414
|
+
const byConnection = {};
|
|
415
|
+
for (const connection of Object.keys(options.connections))
|
|
416
|
+
byConnection[connection] = new Map;
|
|
417
|
+
for (const { connection, dir } of await migrationDirs(hamur, options)) {
|
|
418
|
+
const found = byConnection[connection];
|
|
419
|
+
if (!found)
|
|
420
|
+
continue;
|
|
421
|
+
for (const file of (await sqlFiles(dir)).sort()) {
|
|
422
|
+
const match = NAME2.exec(file);
|
|
423
|
+
if (!match)
|
|
424
|
+
throw new DiagnosticError4("HAMUR_E5506", `${shown2(rootDir, join3(dir, file))}: a migration is named <number>_<name>.sql (0001_init.sql)`);
|
|
425
|
+
const other = found.get(file);
|
|
426
|
+
if (other)
|
|
427
|
+
throw new DiagnosticError4("HAMUR_E5507", `Migration ${file} is in both ${shown2(rootDir, other.dir)} and ${shown2(rootDir, dir)}`);
|
|
428
|
+
const sql = withoutBom(await readFile(join3(dir, file), "utf8"));
|
|
429
|
+
found.set(file, {
|
|
430
|
+
dir,
|
|
431
|
+
migration: { id: match[1], name: match[2], file, sql, checksum: await checksumOf(sql) }
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
const result = {};
|
|
436
|
+
for (const [connection, found] of Object.entries(byConnection)) {
|
|
437
|
+
const list = [...found.values()].map(({ migration }) => migration).sort((a, b) => compareIds(a.id, b.id) || a.file.localeCompare(b.file));
|
|
438
|
+
for (let i = 1;i < list.length; i++) {
|
|
439
|
+
const [a, b] = [list[i - 1], list[i]];
|
|
440
|
+
if (compareIds(a.id, b.id) === 0)
|
|
441
|
+
throw new DiagnosticError4("HAMUR_E5508", `Migrations ${a.file} and ${b.file} share the number ${a.id}`);
|
|
442
|
+
}
|
|
443
|
+
result[connection] = list;
|
|
444
|
+
}
|
|
445
|
+
return result;
|
|
446
|
+
}
|
|
447
|
+
async function applyAll(hamur, options, names = notD1(options)) {
|
|
448
|
+
const all = await loadMigrations(hamur, options);
|
|
449
|
+
const log = useLogger2("hamur");
|
|
450
|
+
const databases = openDatabases(hamur, options);
|
|
451
|
+
try {
|
|
452
|
+
for (const name of names) {
|
|
453
|
+
const applied = await migrate(databases.use(name), all[name] ?? [], {
|
|
454
|
+
warn: (message) => log.warn(message),
|
|
455
|
+
applied: (migration, ms) => log.info(`Applied ${migration.id}_${migration.name} to "${name}" (${Math.round(ms)} ms)`)
|
|
456
|
+
});
|
|
457
|
+
if (applied.length)
|
|
458
|
+
log.info(`${applied.length} migration${applied.length === 1 ? "" : "s"} applied to "${name}"`);
|
|
459
|
+
}
|
|
460
|
+
} finally {
|
|
461
|
+
await databases.close();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
async function applyDev(hamur, options) {
|
|
465
|
+
const devs = devConnections(options.connections);
|
|
466
|
+
const all = await loadMigrations(hamur, options);
|
|
467
|
+
const names = Object.keys(devs).filter((name) => all[name]?.length);
|
|
468
|
+
if (names.length)
|
|
469
|
+
await applyAll(hamur, { ...options, connections: { ...options.connections, ...devs } }, names);
|
|
470
|
+
}
|
|
471
|
+
var notD1 = (options) => Object.keys(options.connections).filter((name) => options.connections[name].connector !== "d1");
|
|
472
|
+
async function writeD1Migrations(hamur, options) {
|
|
473
|
+
const d1 = Object.entries(options.connections).filter(([, connection]) => connection.connector === "d1");
|
|
474
|
+
if (!d1.length)
|
|
475
|
+
return;
|
|
476
|
+
const { outputDir } = hamur.options;
|
|
477
|
+
const all = await loadMigrations(hamur, options);
|
|
478
|
+
const wranglerFile = join3(outputDir, "wrangler.json");
|
|
479
|
+
const wrangler = JSON.parse(await readFile(wranglerFile, "utf8"));
|
|
480
|
+
for (const database of wrangler.d1_databases ?? []) {
|
|
481
|
+
const own = database.migrations_dir;
|
|
482
|
+
if (typeof own === "string" && !isAbsolute(own))
|
|
483
|
+
database.migrations_dir = relative2(outputDir, resolve2(hamur.options.rootDir, own)).split(sep).join("/");
|
|
484
|
+
}
|
|
485
|
+
for (const [name, { binding }] of d1) {
|
|
486
|
+
if (wrangler.d1_databases?.some((database) => database.binding === binding))
|
|
487
|
+
continue;
|
|
488
|
+
const id = cloudflareId(hamur, binding);
|
|
489
|
+
if (!id)
|
|
490
|
+
continue;
|
|
491
|
+
const taken = bindingKey(wrangler, binding);
|
|
492
|
+
if (taken)
|
|
493
|
+
throw new DiagnosticError4("HAMUR_E5509", `db.connections.${name}.binding ${JSON.stringify(binding)} is already the ${taken} binding of the app's wrangler config; set db.connections.${name}.binding to another name`);
|
|
494
|
+
(wrangler.d1_databases ??= []).push({ binding, database_id: id });
|
|
495
|
+
}
|
|
496
|
+
for (const [name, { binding }] of d1) {
|
|
497
|
+
const dir = join3(outputDir, "migrations", name);
|
|
498
|
+
await rm2(dir, { recursive: true, force: true });
|
|
499
|
+
const files = all[name] ?? [];
|
|
500
|
+
if (!files.length)
|
|
501
|
+
continue;
|
|
502
|
+
await mkdir(dir, { recursive: true });
|
|
503
|
+
for (const migration of files)
|
|
504
|
+
await writeFile(join3(dir, migration.file), migration.sql);
|
|
505
|
+
const entry = wrangler.d1_databases?.find((database) => database.binding === binding);
|
|
506
|
+
if (entry && entry.migrations_dir === undefined)
|
|
507
|
+
entry.migrations_dir = `migrations/${name}`;
|
|
508
|
+
}
|
|
509
|
+
await writeFile(wranglerFile, `${JSON.stringify(wrangler, null, 2)}
|
|
510
|
+
`);
|
|
511
|
+
}
|
|
512
|
+
async function watchMigrations(hamur, options) {
|
|
513
|
+
const dirs = new Set((await migrationDirs(hamur, options)).map((entry) => entry.dir));
|
|
514
|
+
const serverDirs = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)];
|
|
515
|
+
const roots = [...serverDirs, ...[...dirs].filter((dir) => !serverDirs.some((root) => dir.startsWith(root + sep)))];
|
|
516
|
+
const watchers = [];
|
|
517
|
+
let timer;
|
|
518
|
+
let running = Promise.resolve();
|
|
519
|
+
const log = useLogger2("hamur");
|
|
520
|
+
const changed = () => {
|
|
521
|
+
clearTimeout(timer);
|
|
522
|
+
timer = setTimeout(() => {
|
|
523
|
+
running = running.then(() => applyAll(hamur, options)).catch((error) => log.error(error instanceof Error ? error.message : String(error)));
|
|
524
|
+
}, 100);
|
|
525
|
+
};
|
|
526
|
+
for (const root of roots) {
|
|
527
|
+
try {
|
|
528
|
+
const watcher = watch(root, { recursive: true }, (_event, file) => {
|
|
529
|
+
if (typeof file === "string" && file.endsWith(".sql") && dirs.has(dirname(join3(root, file))))
|
|
530
|
+
changed();
|
|
531
|
+
});
|
|
532
|
+
watcher.on("error", () => watcher.close());
|
|
533
|
+
watchers.push(watcher);
|
|
534
|
+
} catch {}
|
|
535
|
+
}
|
|
536
|
+
return () => {
|
|
537
|
+
clearTimeout(timer);
|
|
538
|
+
for (const watcher of watchers)
|
|
539
|
+
watcher.close();
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
var setupMigrations = (options, hamur) => {
|
|
543
|
+
const { dev, preset } = hamur.options;
|
|
544
|
+
const atStart = options.migrate !== false && (dev || options.migrate === "start");
|
|
545
|
+
addTemplate2({
|
|
546
|
+
filename: "db/migrations",
|
|
547
|
+
getContents: async () => {
|
|
548
|
+
const all = await loadMigrations(hamur, options);
|
|
549
|
+
const migrations = Object.fromEntries(notD1(options).map((name) => [name, all[name] ?? []]));
|
|
550
|
+
return `export const apply = ${atStart};
|
|
551
|
+
export const migrations = ${JSON.stringify(migrations)};
|
|
552
|
+
`;
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
addTask({ name: "db:migrate", file: createResolver2(new URL("../../src/build/migrations.ts", import.meta.url).href).resolve("../server/task.ts") });
|
|
556
|
+
hamur.hooks.hook("build:before", async () => {
|
|
557
|
+
const d1 = Object.keys(options.connections).find((name) => options.connections[name].connector === "d1");
|
|
558
|
+
if (d1 !== undefined && (options.migrate === "build" || options.migrate === "start")) {
|
|
559
|
+
throw new DiagnosticError4("HAMUR_E5510", `db.connections.${d1} uses d1, whose migrations wrangler applies; build writes them to .output/migrations/${d1}`);
|
|
560
|
+
}
|
|
561
|
+
if (options.migrate === "start" && !STARTS.includes(preset)) {
|
|
562
|
+
throw new DiagnosticError4("HAMUR_E5511", `db.migrate "start" needs a server start, which the "${preset}" preset has not; use "build" or run hamur db migrate --prod in the deploy step`);
|
|
563
|
+
}
|
|
564
|
+
await loadMigrations(hamur, options);
|
|
565
|
+
});
|
|
566
|
+
if (!dev && options.migrate === "build")
|
|
567
|
+
hamur.hooks.hook("prerender:routes", () => applyAll(hamur, options));
|
|
568
|
+
if (!dev)
|
|
569
|
+
hamur.hooks.hook("prerender:routes", () => applyDev(hamur, options));
|
|
570
|
+
if (!dev && preset === "cloudflare")
|
|
571
|
+
hamur.hooks.hook("build:done", () => writeD1Migrations(hamur, options));
|
|
572
|
+
if (dev && options.migrate !== false) {
|
|
573
|
+
let stop;
|
|
574
|
+
hamur.hooks.hook("dev:ready", () => void (stop = watchMigrations(hamur, options)));
|
|
575
|
+
hamur.hooks.hook("close", async () => (await stop)?.());
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
// packages/db/src/build/queue.ts
|
|
580
|
+
import { addTemplate as addTemplate3, DiagnosticError as DiagnosticError5 } from "hamur/kit";
|
|
581
|
+
|
|
582
|
+
// packages/db/src/runtime/queue.ts
|
|
583
|
+
var QUEUE_DEFAULTS = {
|
|
584
|
+
connection: "default",
|
|
585
|
+
table: "_hamur_queue",
|
|
586
|
+
concurrency: 4,
|
|
587
|
+
maxAttempts: 3
|
|
588
|
+
};
|
|
589
|
+
var LOCK_MS = 5 * 60000;
|
|
590
|
+
var RENEW_MS = LOCK_MS / 5;
|
|
591
|
+
var BACKOFF_MS = 1e4;
|
|
592
|
+
var BACKOFF_MAX_MS = 60 * 60000;
|
|
593
|
+
var ERROR_LENGTH = 4000;
|
|
594
|
+
function backoff(attempts) {
|
|
595
|
+
return Math.min(BACKOFF_MS * 2 ** Math.max(attempts - 1, 0), BACKOFF_MAX_MS);
|
|
596
|
+
}
|
|
597
|
+
function template(sql) {
|
|
598
|
+
const parts = sql.split("?");
|
|
599
|
+
return Object.assign(parts, { raw: parts });
|
|
600
|
+
}
|
|
601
|
+
var all = (db, sql, params = []) => db.sql(template(sql), ...params);
|
|
602
|
+
var write = (db, sql, params = []) => db.run(template(sql), ...params);
|
|
603
|
+
var COLUMNS = {
|
|
604
|
+
sqlite: { id: "TEXT", task: "TEXT", text: "TEXT", time: "INTEGER", count: "INTEGER" },
|
|
605
|
+
postgres: { id: "TEXT", task: "TEXT", text: "TEXT", time: "BIGINT", count: "INTEGER" },
|
|
606
|
+
mysql: { id: "VARCHAR(36)", task: "VARCHAR(255)", text: "LONGTEXT", time: "BIGINT", count: "INT" }
|
|
607
|
+
};
|
|
608
|
+
var nullable = (value) => value === null || value === undefined ? null : Number(value);
|
|
609
|
+
function message(error) {
|
|
610
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
611
|
+
return text.length > ERROR_LENGTH ? `${text.slice(0, ERROR_LENGTH)}\u2026` : text;
|
|
612
|
+
}
|
|
613
|
+
function createQueueTable(database, options, now = Date.now) {
|
|
614
|
+
const { table, maxAttempts } = options;
|
|
615
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
616
|
+
throw new TypeError(`Invalid queue table name ${JSON.stringify(table)}`);
|
|
617
|
+
let ready;
|
|
618
|
+
const quote = (dialect, name) => dialect === "mysql" ? `\`${name}\`` : `"${name}"`;
|
|
619
|
+
const indexName = `${table}_due`.slice(0, 63);
|
|
620
|
+
const open = () => ready ??= (async () => {
|
|
621
|
+
const db = database();
|
|
622
|
+
const t = quote(db.dialect, table);
|
|
623
|
+
const type = COLUMNS[db.dialect];
|
|
624
|
+
const inline = db.dialect === "mysql" ? `, INDEX ${quote("mysql", indexName)} (failed_at, run_at)` : "";
|
|
625
|
+
try {
|
|
626
|
+
await db.exec(`CREATE TABLE IF NOT EXISTS ${t} (id ${type.id} NOT NULL PRIMARY KEY, task ${type.task} NOT NULL, payload ${type.text} NOT NULL, run_at ${type.time} NOT NULL, attempts ${type.count} NOT NULL DEFAULT 0, claims ${type.count} NOT NULL DEFAULT 0, last_error ${type.text}, locked_until ${type.time}, created_at ${type.time} NOT NULL, failed_at ${type.time}${inline})`);
|
|
627
|
+
} catch (error) {
|
|
628
|
+
try {
|
|
629
|
+
await db.exec(`SELECT 1 FROM ${t} WHERE 1 = 0`);
|
|
630
|
+
} catch {
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (db.dialect !== "mysql") {
|
|
635
|
+
try {
|
|
636
|
+
await db.exec(`CREATE INDEX IF NOT EXISTS ${quote(db.dialect, indexName)} ON ${t} (failed_at, run_at)`);
|
|
637
|
+
} catch (error) {
|
|
638
|
+
const found = db.dialect === "postgres" ? await all(db, "SELECT 1 AS found FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
|
|
639
|
+
table,
|
|
640
|
+
indexName
|
|
641
|
+
]) : [];
|
|
642
|
+
if (!found.length)
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return db;
|
|
647
|
+
})().catch((error) => {
|
|
648
|
+
ready = undefined;
|
|
649
|
+
throw error;
|
|
650
|
+
});
|
|
651
|
+
const named = async () => {
|
|
652
|
+
const db = await open();
|
|
653
|
+
return { db, t: quote(db.dialect, table) };
|
|
654
|
+
};
|
|
655
|
+
const row = (raw) => ({
|
|
656
|
+
id: String(raw.id),
|
|
657
|
+
task: String(raw.task),
|
|
658
|
+
payload: String(raw.payload),
|
|
659
|
+
runAt: Number(raw.run_at),
|
|
660
|
+
attempts: Number(raw.attempts),
|
|
661
|
+
lastError: raw.last_error === null || raw.last_error === undefined ? null : String(raw.last_error),
|
|
662
|
+
lockedUntil: nullable(raw.locked_until),
|
|
663
|
+
createdAt: Number(raw.created_at),
|
|
664
|
+
failedAt: nullable(raw.failed_at)
|
|
665
|
+
});
|
|
666
|
+
return {
|
|
667
|
+
maxAttempts,
|
|
668
|
+
async ensure() {
|
|
669
|
+
await open();
|
|
670
|
+
},
|
|
671
|
+
async insert(task, payload, delaySeconds) {
|
|
672
|
+
const { db, t } = await named();
|
|
673
|
+
const id = crypto.randomUUID();
|
|
674
|
+
const at = now();
|
|
675
|
+
await write(db, `INSERT INTO ${t} (id, task, payload, run_at, attempts, created_at) VALUES (?, ?, ?, ?, 0, ?)`, [
|
|
676
|
+
id,
|
|
677
|
+
task,
|
|
678
|
+
payload,
|
|
679
|
+
at + delaySeconds * 1000,
|
|
680
|
+
at
|
|
681
|
+
]);
|
|
682
|
+
return id;
|
|
683
|
+
},
|
|
684
|
+
async claim(limit) {
|
|
685
|
+
const { db, t } = await named();
|
|
686
|
+
const at = now();
|
|
687
|
+
const lock = db.dialect === "sqlite" ? "" : " FOR UPDATE SKIP LOCKED";
|
|
688
|
+
const count = Math.max(1, Math.floor(limit));
|
|
689
|
+
return db.transaction(async (tx) => {
|
|
690
|
+
const due = await all(tx, `SELECT id, task, payload, attempts, claims FROM ${t} WHERE failed_at IS NULL AND run_at <= ? AND (locked_until IS NULL OR locked_until <= ?) ORDER BY run_at, created_at LIMIT ${count}${lock}`, [at, at]);
|
|
691
|
+
const claimed = [];
|
|
692
|
+
for (const found of due) {
|
|
693
|
+
const id = String(found.id);
|
|
694
|
+
await write(tx, `UPDATE ${t} SET locked_until = ?, attempts = attempts + 1, claims = claims + 1 WHERE id = ?`, [at + LOCK_MS, id]);
|
|
695
|
+
claimed.push({
|
|
696
|
+
id,
|
|
697
|
+
task: String(found.task),
|
|
698
|
+
payload: String(found.payload),
|
|
699
|
+
attempts: Number(found.attempts) + 1,
|
|
700
|
+
claim: Number(found.claims) + 1
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
return claimed;
|
|
704
|
+
});
|
|
705
|
+
},
|
|
706
|
+
async renew(claimed) {
|
|
707
|
+
const { db, t } = await named();
|
|
708
|
+
const result = await write(db, `UPDATE ${t} SET locked_until = ? WHERE id = ? AND claims = ? AND failed_at IS NULL`, [now() + LOCK_MS, claimed.id, claimed.claim]);
|
|
709
|
+
return result.changes > 0;
|
|
710
|
+
},
|
|
711
|
+
async finish(claimed, failure) {
|
|
712
|
+
const { db, t } = await named();
|
|
713
|
+
if (!failure) {
|
|
714
|
+
await write(db, `DELETE FROM ${t} WHERE id = ? AND claims = ?`, [claimed.id, claimed.claim]);
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
const at = now();
|
|
718
|
+
if (claimed.attempts >= maxAttempts) {
|
|
719
|
+
await write(db, `UPDATE ${t} SET failed_at = ?, last_error = ?, locked_until = NULL WHERE id = ? AND claims = ?`, [at, message(failure.error), claimed.id, claimed.claim]);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
await write(db, `UPDATE ${t} SET run_at = ?, last_error = ?, locked_until = NULL WHERE id = ? AND claims = ?`, [
|
|
723
|
+
at + backoff(claimed.attempts),
|
|
724
|
+
message(failure.error),
|
|
725
|
+
claimed.id,
|
|
726
|
+
claimed.claim
|
|
727
|
+
]);
|
|
728
|
+
},
|
|
729
|
+
async failed() {
|
|
730
|
+
const { db, t } = await named();
|
|
731
|
+
const rows = await all(db, `SELECT id, task, payload, run_at, attempts, last_error, locked_until, created_at, failed_at FROM ${t} WHERE failed_at IS NOT NULL ORDER BY failed_at, id`);
|
|
732
|
+
return rows.map(row);
|
|
733
|
+
},
|
|
734
|
+
async retry(id) {
|
|
735
|
+
const { db, t } = await named();
|
|
736
|
+
const at = now();
|
|
737
|
+
const result = await write(db, `UPDATE ${t} SET failed_at = NULL, attempts = 0, run_at = ?, locked_until = NULL WHERE id = ? AND failed_at IS NOT NULL AND (locked_until IS NULL OR locked_until <= ?)`, [at, id, at]);
|
|
738
|
+
if (result.changes > 0)
|
|
739
|
+
return { state: "due" };
|
|
740
|
+
const [found] = await all(db, `SELECT failed_at, locked_until FROM ${t} WHERE id = ?`, [id]);
|
|
741
|
+
const until = nullable(found?.locked_until);
|
|
742
|
+
if (found && nullable(found.failed_at) !== null && until !== null && until > at)
|
|
743
|
+
return { state: "locked", until };
|
|
744
|
+
return { state: "missing" };
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// packages/db/src/build/queue.ts
|
|
750
|
+
function queueOptions(hamur) {
|
|
751
|
+
const queue = hamur.options.tasks.queue;
|
|
752
|
+
if (!queue || !("driver" in queue))
|
|
753
|
+
return;
|
|
754
|
+
return {
|
|
755
|
+
connection: queue.connection ?? QUEUE_DEFAULTS.connection,
|
|
756
|
+
table: queue.table ?? QUEUE_DEFAULTS.table,
|
|
757
|
+
concurrency: queue.concurrency ?? QUEUE_DEFAULTS.concurrency,
|
|
758
|
+
maxAttempts: queue.maxAttempts ?? QUEUE_DEFAULTS.maxAttempts
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
var setupQueue = (options, hamur) => {
|
|
762
|
+
const queue = queueOptions(hamur);
|
|
763
|
+
if (queue && !Object.hasOwn(options.connections, queue.connection))
|
|
764
|
+
throw new DiagnosticError5("HAMUR_E5521", `tasks.queue.connection ${JSON.stringify(queue.connection)} is not in db.connections; set db.connections.${queue.connection} in hamur.config.ts`);
|
|
765
|
+
addTemplate3({
|
|
766
|
+
filename: "db/queue",
|
|
767
|
+
getContents: () => `export const queue = ${queue ? JSON.stringify(queue) : "undefined"};
|
|
768
|
+
`
|
|
769
|
+
});
|
|
770
|
+
};
|
|
771
|
+
|
|
772
|
+
// packages/db/src/module.ts
|
|
773
|
+
import { addDevtoolsTab, createResolver as createResolver3, defineModule } from "hamur/kit";
|
|
774
|
+
|
|
775
|
+
// packages/db/src/build/factories.ts
|
|
776
|
+
import { readdir as readdir2 } from "fs/promises";
|
|
777
|
+
import { join as join4 } from "path";
|
|
778
|
+
import { DiagnosticError as DiagnosticError6, addTemplate as addTemplate4 } from "hamur/kit";
|
|
779
|
+
|
|
780
|
+
// packages/db/src/build/schema.ts
|
|
781
|
+
var DOLLAR = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/;
|
|
782
|
+
var WORD = /[A-Za-z0-9_$\u0080-\uFFFF]/;
|
|
783
|
+
var token = (kind, text) => ({
|
|
784
|
+
kind,
|
|
785
|
+
text,
|
|
786
|
+
lower: kind === "word" ? text.toLowerCase() : ""
|
|
787
|
+
});
|
|
788
|
+
function tokenize(sql, dialect) {
|
|
789
|
+
const tokens = [];
|
|
790
|
+
let i = 0;
|
|
791
|
+
const quoted = (close, escapes) => {
|
|
792
|
+
let text = "";
|
|
793
|
+
i++;
|
|
794
|
+
while (i < sql.length) {
|
|
795
|
+
const char = sql[i];
|
|
796
|
+
if (char === "\\" && escapes && i + 1 < sql.length) {
|
|
797
|
+
text += sql[i + 1];
|
|
798
|
+
i += 2;
|
|
799
|
+
} else if (char === close) {
|
|
800
|
+
if (sql[i + 1] === close) {
|
|
801
|
+
text += close;
|
|
802
|
+
i += 2;
|
|
803
|
+
} else {
|
|
804
|
+
i++;
|
|
805
|
+
return text;
|
|
806
|
+
}
|
|
807
|
+
} else {
|
|
808
|
+
text += char;
|
|
809
|
+
i++;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return text;
|
|
813
|
+
};
|
|
814
|
+
while (i < sql.length) {
|
|
815
|
+
const char = sql[i];
|
|
816
|
+
if (/\s/.test(char))
|
|
817
|
+
i++;
|
|
818
|
+
else if (char === "-" && sql[i + 1] === "-")
|
|
819
|
+
i = sql.indexOf(`
|
|
820
|
+
`, i) < 0 ? sql.length : sql.indexOf(`
|
|
821
|
+
`, i);
|
|
822
|
+
else if (char === "#" && dialect === "mysql")
|
|
823
|
+
i = sql.indexOf(`
|
|
824
|
+
`, i) < 0 ? sql.length : sql.indexOf(`
|
|
825
|
+
`, i);
|
|
826
|
+
else if (char === "/" && sql[i + 1] === "*")
|
|
827
|
+
i = sql.indexOf("*/", i + 2) < 0 ? sql.length : sql.indexOf("*/", i + 2) + 2;
|
|
828
|
+
else if (char === "'") {
|
|
829
|
+
const prev = tokens.at(-1);
|
|
830
|
+
const escapeString = dialect === "postgres" && prev?.kind === "word" && prev.lower === "e" && sql[i - 1] === prev.text;
|
|
831
|
+
tokens.push(token("string", quoted("'", dialect === "mysql" || escapeString)));
|
|
832
|
+
} else if (char === '"')
|
|
833
|
+
tokens.push(token("ident", quoted('"', dialect === "mysql")));
|
|
834
|
+
else if (char === "`")
|
|
835
|
+
tokens.push(token("ident", quoted("`", false)));
|
|
836
|
+
else if (char === "[" && !/^\[\s*\d*\s*\]/.test(sql.slice(i, i + 12))) {
|
|
837
|
+
const end = sql.indexOf("]", i);
|
|
838
|
+
const stop = end < 0 ? sql.length : end;
|
|
839
|
+
tokens.push(token("ident", sql.slice(i + 1, stop)));
|
|
840
|
+
i = stop + 1;
|
|
841
|
+
} else if (char === "$" && dialect === "postgres" && DOLLAR.test(sql.slice(i, i + 64))) {
|
|
842
|
+
const tag = DOLLAR.exec(sql.slice(i, i + 64))[0];
|
|
843
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
844
|
+
tokens.push(token("string", ""));
|
|
845
|
+
i = end < 0 ? sql.length : end + tag.length;
|
|
846
|
+
} else if (WORD.test(char)) {
|
|
847
|
+
const start = i;
|
|
848
|
+
while (i < sql.length && WORD.test(sql[i]))
|
|
849
|
+
i++;
|
|
850
|
+
tokens.push(token("word", sql.slice(start, i)));
|
|
851
|
+
} else {
|
|
852
|
+
tokens.push(token("punct", char));
|
|
853
|
+
i++;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
return tokens;
|
|
857
|
+
}
|
|
858
|
+
var isWord = (tok, ...words) => tok?.kind === "word" && words.includes(tok.lower);
|
|
859
|
+
var isPunct = (tok, text) => tok?.kind === "punct" && tok.text === text;
|
|
860
|
+
var ROUTINES = ["procedure", "function", "trigger", "event"];
|
|
861
|
+
var BLOCK_SUFFIXES = ["if", "loop", "while", "repeat"];
|
|
862
|
+
var isRoutine = (statement) => isWord(statement[0], "create") && statement.slice(1, 10).some((tok) => isWord(tok, ...ROUTINES));
|
|
863
|
+
function statements(tokens) {
|
|
864
|
+
const out = [];
|
|
865
|
+
let current = [];
|
|
866
|
+
let depth = 0;
|
|
867
|
+
for (let i = 0;i < tokens.length; i++) {
|
|
868
|
+
const tok = tokens[i];
|
|
869
|
+
if (isPunct(tok, ";") && (depth <= 0 || !isRoutine(current))) {
|
|
870
|
+
if (current.length)
|
|
871
|
+
out.push(current);
|
|
872
|
+
current = [];
|
|
873
|
+
depth = 0;
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
if (isWord(tok, "begin", "case"))
|
|
877
|
+
depth++;
|
|
878
|
+
else if (isWord(tok, "end") && !isWord(tokens[i + 1], ...BLOCK_SUFFIXES))
|
|
879
|
+
depth--;
|
|
880
|
+
current.push(tok);
|
|
881
|
+
}
|
|
882
|
+
if (current.length)
|
|
883
|
+
out.push(current);
|
|
884
|
+
return out;
|
|
885
|
+
}
|
|
886
|
+
function delimited(sql) {
|
|
887
|
+
const out = [];
|
|
888
|
+
let delimiter = ";";
|
|
889
|
+
let chunk = "";
|
|
890
|
+
const flush = () => {
|
|
891
|
+
if (!chunk.trim())
|
|
892
|
+
return;
|
|
893
|
+
if (delimiter === ";")
|
|
894
|
+
out.push({ sql: chunk, whole: false });
|
|
895
|
+
else
|
|
896
|
+
for (const piece of chunk.split(delimiter))
|
|
897
|
+
if (piece.trim())
|
|
898
|
+
out.push({ sql: piece, whole: true });
|
|
899
|
+
chunk = "";
|
|
900
|
+
};
|
|
901
|
+
for (const line of sql.split(`
|
|
902
|
+
`)) {
|
|
903
|
+
const match = /^\s*delimiter\s+(\S+)/i.exec(line);
|
|
904
|
+
if (match) {
|
|
905
|
+
flush();
|
|
906
|
+
delimiter = match[1];
|
|
907
|
+
} else
|
|
908
|
+
chunk += `${line}
|
|
909
|
+
`;
|
|
910
|
+
}
|
|
911
|
+
flush();
|
|
912
|
+
return out;
|
|
913
|
+
}
|
|
914
|
+
function splitTop(tokens) {
|
|
915
|
+
const out = [];
|
|
916
|
+
let depth = 0;
|
|
917
|
+
let current = [];
|
|
918
|
+
for (const tok of tokens) {
|
|
919
|
+
if (isPunct(tok, "("))
|
|
920
|
+
depth++;
|
|
921
|
+
else if (isPunct(tok, ")"))
|
|
922
|
+
depth--;
|
|
923
|
+
if (depth === 0 && isPunct(tok, ",")) {
|
|
924
|
+
out.push(current);
|
|
925
|
+
current = [];
|
|
926
|
+
} else
|
|
927
|
+
current.push(tok);
|
|
928
|
+
}
|
|
929
|
+
if (current.length)
|
|
930
|
+
out.push(current);
|
|
931
|
+
return out;
|
|
932
|
+
}
|
|
933
|
+
function closing(tokens, open) {
|
|
934
|
+
let depth = 0;
|
|
935
|
+
for (let i = open;i < tokens.length; i++) {
|
|
936
|
+
if (isPunct(tokens[i], "("))
|
|
937
|
+
depth++;
|
|
938
|
+
else if (isPunct(tokens[i], ")") && --depth === 0)
|
|
939
|
+
return i;
|
|
940
|
+
}
|
|
941
|
+
return -1;
|
|
942
|
+
}
|
|
943
|
+
var POSTGRES = {
|
|
944
|
+
integer: "number",
|
|
945
|
+
int: "number",
|
|
946
|
+
smallint: "number",
|
|
947
|
+
real: "number",
|
|
948
|
+
"double precision": "number",
|
|
949
|
+
serial: "number",
|
|
950
|
+
smallserial: "number",
|
|
951
|
+
bigint: "string",
|
|
952
|
+
bigserial: "string",
|
|
953
|
+
numeric: "string",
|
|
954
|
+
decimal: "string",
|
|
955
|
+
text: "string",
|
|
956
|
+
varchar: "string",
|
|
957
|
+
char: "string",
|
|
958
|
+
uuid: "string",
|
|
959
|
+
boolean: "boolean",
|
|
960
|
+
timestamp: "Date",
|
|
961
|
+
timestamptz: "Date",
|
|
962
|
+
date: "Date",
|
|
963
|
+
bytea: "Uint8Array",
|
|
964
|
+
json: "unknown",
|
|
965
|
+
jsonb: "unknown"
|
|
966
|
+
};
|
|
967
|
+
var MYSQL = {
|
|
968
|
+
int: "number",
|
|
969
|
+
integer: "number",
|
|
970
|
+
tinyint: "number",
|
|
971
|
+
smallint: "number",
|
|
972
|
+
mediumint: "number",
|
|
973
|
+
float: "number",
|
|
974
|
+
double: "number",
|
|
975
|
+
"double precision": "number",
|
|
976
|
+
real: "number",
|
|
977
|
+
boolean: "number",
|
|
978
|
+
bool: "number",
|
|
979
|
+
bigint: "number | string",
|
|
980
|
+
serial: "number | string",
|
|
981
|
+
decimal: "string",
|
|
982
|
+
numeric: "string",
|
|
983
|
+
varchar: "string",
|
|
984
|
+
char: "string",
|
|
985
|
+
text: "string",
|
|
986
|
+
tinytext: "string",
|
|
987
|
+
mediumtext: "string",
|
|
988
|
+
longtext: "string",
|
|
989
|
+
datetime: "Date",
|
|
990
|
+
timestamp: "Date",
|
|
991
|
+
date: "Date",
|
|
992
|
+
blob: "Uint8Array",
|
|
993
|
+
tinyblob: "Uint8Array",
|
|
994
|
+
mediumblob: "Uint8Array",
|
|
995
|
+
longblob: "Uint8Array",
|
|
996
|
+
binary: "Uint8Array",
|
|
997
|
+
varbinary: "Uint8Array",
|
|
998
|
+
json: "unknown"
|
|
999
|
+
};
|
|
1000
|
+
var POSTGRES_ALIASES = {
|
|
1001
|
+
int4: "integer",
|
|
1002
|
+
int2: "smallint",
|
|
1003
|
+
int8: "bigint",
|
|
1004
|
+
float4: "real",
|
|
1005
|
+
float: "double precision",
|
|
1006
|
+
serial2: "smallserial",
|
|
1007
|
+
serial4: "serial",
|
|
1008
|
+
serial8: "bigserial",
|
|
1009
|
+
float8: "double precision",
|
|
1010
|
+
bool: "boolean",
|
|
1011
|
+
"character varying": "varchar",
|
|
1012
|
+
character: "char",
|
|
1013
|
+
bpchar: "char",
|
|
1014
|
+
"timestamp with time zone": "timestamptz",
|
|
1015
|
+
"timestamp without time zone": "timestamp"
|
|
1016
|
+
};
|
|
1017
|
+
var IGNORED_TYPE_WORDS = new Set(["unsigned", "signed", "zerofill"]);
|
|
1018
|
+
function sqliteType(type) {
|
|
1019
|
+
const name = type.toUpperCase();
|
|
1020
|
+
if (name === "NUMERIC")
|
|
1021
|
+
return "number";
|
|
1022
|
+
if (name.includes("INT"))
|
|
1023
|
+
return "number";
|
|
1024
|
+
if (/CHAR|CLOB|TEXT/.test(name))
|
|
1025
|
+
return "string";
|
|
1026
|
+
if (name.includes("BLOB"))
|
|
1027
|
+
return "Uint8Array";
|
|
1028
|
+
if (/REAL|FLOA|DOUB/.test(name))
|
|
1029
|
+
return "number";
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
function mapType(dialect, declared) {
|
|
1033
|
+
let type = declared.toLowerCase().split(/\s+/).filter((word) => word && !IGNORED_TYPE_WORDS.has(word)).join(" ");
|
|
1034
|
+
if (dialect === "sqlite")
|
|
1035
|
+
return sqliteType(type);
|
|
1036
|
+
if (dialect === "postgres") {
|
|
1037
|
+
type = POSTGRES_ALIASES[type] ?? type;
|
|
1038
|
+
return POSTGRES[type];
|
|
1039
|
+
}
|
|
1040
|
+
return MYSQL[type];
|
|
1041
|
+
}
|
|
1042
|
+
var TYPE_STOPS = new Set([
|
|
1043
|
+
"not",
|
|
1044
|
+
"null",
|
|
1045
|
+
"primary",
|
|
1046
|
+
"default",
|
|
1047
|
+
"references",
|
|
1048
|
+
"check",
|
|
1049
|
+
"unique",
|
|
1050
|
+
"constraint",
|
|
1051
|
+
"collate",
|
|
1052
|
+
"generated",
|
|
1053
|
+
"as",
|
|
1054
|
+
"auto_increment",
|
|
1055
|
+
"autoincrement",
|
|
1056
|
+
"comment",
|
|
1057
|
+
"on",
|
|
1058
|
+
"key",
|
|
1059
|
+
"charset",
|
|
1060
|
+
"invisible",
|
|
1061
|
+
"visible",
|
|
1062
|
+
"after",
|
|
1063
|
+
"first",
|
|
1064
|
+
"stored",
|
|
1065
|
+
"virtual",
|
|
1066
|
+
"storage",
|
|
1067
|
+
"compression"
|
|
1068
|
+
]);
|
|
1069
|
+
var CONSTRAINTS = new Set(["constraint", "primary", "unique", "check", "foreign", "like"]);
|
|
1070
|
+
var MYSQL_INDEXES = new Set(["key", "index", "fulltext", "spatial"]);
|
|
1071
|
+
var nameKey = (dialect, name) => dialect === "postgres" ? name : name.toLowerCase();
|
|
1072
|
+
|
|
1073
|
+
class Reader {
|
|
1074
|
+
dialect;
|
|
1075
|
+
schema = { tables: new Map, warnings: [] };
|
|
1076
|
+
file = "";
|
|
1077
|
+
constructor(dialect) {
|
|
1078
|
+
this.dialect = dialect;
|
|
1079
|
+
}
|
|
1080
|
+
display(tok) {
|
|
1081
|
+
return this.dialect === "postgres" && tok.kind === "word" ? tok.text.toLowerCase() : tok.text;
|
|
1082
|
+
}
|
|
1083
|
+
key(display) {
|
|
1084
|
+
return nameKey(this.dialect, display);
|
|
1085
|
+
}
|
|
1086
|
+
isConstraint(item) {
|
|
1087
|
+
const first = item[0];
|
|
1088
|
+
if (first?.kind !== "word")
|
|
1089
|
+
return false;
|
|
1090
|
+
if (CONSTRAINTS.has(first.lower))
|
|
1091
|
+
return true;
|
|
1092
|
+
if (this.dialect === "mysql" && MYSQL_INDEXES.has(first.lower))
|
|
1093
|
+
return true;
|
|
1094
|
+
return this.dialect === "postgres" && first.lower === "exclude" && (isWord(item[1], "using") || isPunct(item[1], "("));
|
|
1095
|
+
}
|
|
1096
|
+
warn(message) {
|
|
1097
|
+
this.schema.warnings.push(`${this.file}: ${message}`);
|
|
1098
|
+
}
|
|
1099
|
+
name(s, from) {
|
|
1100
|
+
if (s[from]?.kind !== "word" && s[from]?.kind !== "ident")
|
|
1101
|
+
return;
|
|
1102
|
+
let i = from;
|
|
1103
|
+
while (isPunct(s[i + 1], ".") && (s[i + 2]?.kind === "word" || s[i + 2]?.kind === "ident"))
|
|
1104
|
+
i += 2;
|
|
1105
|
+
return { display: this.display(s[i]), next: i + 1 };
|
|
1106
|
+
}
|
|
1107
|
+
ifClause(s, i, ...words) {
|
|
1108
|
+
return words.every((word, k) => isWord(s[i + k], word)) ? i + words.length : i;
|
|
1109
|
+
}
|
|
1110
|
+
statement(s) {
|
|
1111
|
+
if (isWord(s[0], "create")) {
|
|
1112
|
+
let i = 1;
|
|
1113
|
+
if (isWord(s[i], "or") && isWord(s[i + 1], "replace"))
|
|
1114
|
+
i += 2;
|
|
1115
|
+
if (isWord(s[i], "unlogged"))
|
|
1116
|
+
i++;
|
|
1117
|
+
if (isWord(s[i], "table"))
|
|
1118
|
+
this.createTable(s, i + 1);
|
|
1119
|
+
} else if (isWord(s[0], "rename") && isWord(s[1], "table"))
|
|
1120
|
+
this.renameTables(s);
|
|
1121
|
+
else if (isWord(s[0], "drop") && isWord(s[1], "table"))
|
|
1122
|
+
this.dropTable(s, 2);
|
|
1123
|
+
else if (isWord(s[0], "alter") && isWord(s[1], "table"))
|
|
1124
|
+
this.alterTable(s, 2);
|
|
1125
|
+
}
|
|
1126
|
+
createTable(s, from) {
|
|
1127
|
+
const i = this.ifClause(s, from, "if", "not", "exists");
|
|
1128
|
+
const ifNotExists = i !== from;
|
|
1129
|
+
const name = this.name(s, i);
|
|
1130
|
+
if (!name)
|
|
1131
|
+
return;
|
|
1132
|
+
const key = this.key(name.display);
|
|
1133
|
+
if (ifNotExists && this.schema.tables.has(key))
|
|
1134
|
+
return;
|
|
1135
|
+
this.schema.tables.delete(key);
|
|
1136
|
+
if (!isPunct(s[name.next], "(")) {
|
|
1137
|
+
this.warn(`CREATE TABLE ${name.display} without a column list is not read; ${JSON.stringify(name.display)} has no Row type`);
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
const end = closing(s, name.next);
|
|
1141
|
+
if (end < 0) {
|
|
1142
|
+
this.warn(`CREATE TABLE ${name.display} has unbalanced parentheses and is not read; ${JSON.stringify(name.display)} has no Row type`);
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
const table = { name: name.display, columns: new Map };
|
|
1146
|
+
const items = splitTop(s.slice(name.next + 1, end));
|
|
1147
|
+
for (const item of items)
|
|
1148
|
+
if (!this.isConstraint(item))
|
|
1149
|
+
this.item(table, item);
|
|
1150
|
+
for (const item of items)
|
|
1151
|
+
if (this.isConstraint(item))
|
|
1152
|
+
this.item(table, item);
|
|
1153
|
+
const options = s.slice(end + 1);
|
|
1154
|
+
if (isWord(options[0], "inherits"))
|
|
1155
|
+
this.warn(`CREATE TABLE ${name.display} INHERITS is not read; the columns of the parent table are missing from Row<${JSON.stringify(name.display)}>`);
|
|
1156
|
+
const strict = this.dialect === "sqlite" && options.some((tok, k) => isWord(tok, "strict") || isWord(tok, "without") && isWord(options[k + 1], "rowid"));
|
|
1157
|
+
if (strict)
|
|
1158
|
+
for (const column of table.columns.values())
|
|
1159
|
+
column.pkNotNull = true;
|
|
1160
|
+
this.schema.tables.set(key, table);
|
|
1161
|
+
}
|
|
1162
|
+
renameTables(s) {
|
|
1163
|
+
let i = 2;
|
|
1164
|
+
for (;; ) {
|
|
1165
|
+
const from = this.name(s, i);
|
|
1166
|
+
if (!from || !isWord(s[from.next], "to"))
|
|
1167
|
+
return;
|
|
1168
|
+
const to = this.name(s, from.next + 1);
|
|
1169
|
+
if (!to)
|
|
1170
|
+
return;
|
|
1171
|
+
const table = this.schema.tables.get(this.key(from.display));
|
|
1172
|
+
if (table)
|
|
1173
|
+
this.renameTable(this.key(from.display), table, s[to.next - 1]);
|
|
1174
|
+
if (!isPunct(s[to.next], ","))
|
|
1175
|
+
return;
|
|
1176
|
+
i = to.next + 1;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
item(table, item, ifNotExists = false) {
|
|
1180
|
+
if (!item.length)
|
|
1181
|
+
return;
|
|
1182
|
+
if (this.isConstraint(item)) {
|
|
1183
|
+
if (isWord(item[0], "like")) {
|
|
1184
|
+
this.warn(`LIKE in table ${JSON.stringify(table.name)} is not read; its columns have no type`);
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
const at = item.findIndex((tok, k) => isWord(tok, "primary") && isWord(item[k + 1], "key"));
|
|
1188
|
+
if (at < 0)
|
|
1189
|
+
return;
|
|
1190
|
+
const open = item.findIndex((tok, k) => k > at && isPunct(tok, "("));
|
|
1191
|
+
const close = open < 0 ? -1 : closing(item, open);
|
|
1192
|
+
if (close < 0)
|
|
1193
|
+
return;
|
|
1194
|
+
for (const part of splitTop(item.slice(open + 1, close))) {
|
|
1195
|
+
const column = part[0] && (part[0].kind === "word" || part[0].kind === "ident") ? table.columns.get(this.key(this.display(part[0]))) : undefined;
|
|
1196
|
+
if (column)
|
|
1197
|
+
column.primary = true;
|
|
1198
|
+
}
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
const nameTok = item[0];
|
|
1202
|
+
if (nameTok.kind !== "word" && nameTok.kind !== "ident")
|
|
1203
|
+
return;
|
|
1204
|
+
const display = this.display(nameTok);
|
|
1205
|
+
const key = this.key(display);
|
|
1206
|
+
if (ifNotExists && table.columns.has(key))
|
|
1207
|
+
return;
|
|
1208
|
+
table.columns.set(key, this.column(table, display, item.slice(1)));
|
|
1209
|
+
}
|
|
1210
|
+
column(table, name, rest) {
|
|
1211
|
+
const words = [];
|
|
1212
|
+
let array = false;
|
|
1213
|
+
let i = 0;
|
|
1214
|
+
for (;i < rest.length; i++) {
|
|
1215
|
+
const tok = rest[i];
|
|
1216
|
+
if (tok.kind === "word") {
|
|
1217
|
+
if (TYPE_STOPS.has(tok.lower) || tok.lower === "character" && isWord(rest[i + 1], "set"))
|
|
1218
|
+
break;
|
|
1219
|
+
words.push(tok.lower);
|
|
1220
|
+
} else if (isPunct(tok, "(")) {
|
|
1221
|
+
const close = closing(rest, i);
|
|
1222
|
+
if (close < 0)
|
|
1223
|
+
break;
|
|
1224
|
+
i = close;
|
|
1225
|
+
} else if (isPunct(tok, "[")) {
|
|
1226
|
+
array = true;
|
|
1227
|
+
i = rest.findIndex((t, k) => k > i && isPunct(t, "]"));
|
|
1228
|
+
if (i < 0)
|
|
1229
|
+
break;
|
|
1230
|
+
} else
|
|
1231
|
+
break;
|
|
1232
|
+
}
|
|
1233
|
+
let notNull = false;
|
|
1234
|
+
let primary = false;
|
|
1235
|
+
let hasDefault = false;
|
|
1236
|
+
let auto = false;
|
|
1237
|
+
let depth = 0;
|
|
1238
|
+
for (let k = i;k < rest.length; k++) {
|
|
1239
|
+
const tok = rest[k];
|
|
1240
|
+
if (isPunct(tok, "("))
|
|
1241
|
+
depth++;
|
|
1242
|
+
else if (isPunct(tok, ")"))
|
|
1243
|
+
depth--;
|
|
1244
|
+
else if (depth === 0) {
|
|
1245
|
+
if (isWord(tok, "not") && isWord(rest[k + 1], "null"))
|
|
1246
|
+
notNull = true;
|
|
1247
|
+
else if (isWord(tok, "primary") && isWord(rest[k + 1], "key"))
|
|
1248
|
+
primary = true;
|
|
1249
|
+
else if (isWord(tok, "identity"))
|
|
1250
|
+
notNull = auto = true;
|
|
1251
|
+
else if (isWord(tok, "default"))
|
|
1252
|
+
hasDefault = true;
|
|
1253
|
+
else if (isWord(tok, "generated", "auto_increment", "autoincrement"))
|
|
1254
|
+
auto = true;
|
|
1255
|
+
else if (isWord(tok, "as") && isPunct(rest[k + 1], "("))
|
|
1256
|
+
auto = true;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
const declared = words.join(" ");
|
|
1260
|
+
if (words.length === 1 && /^(serial|smallserial|bigserial|serial2|serial4|serial8)$/.test(declared))
|
|
1261
|
+
notNull = auto = true;
|
|
1262
|
+
if (this.dialect === "mysql" && declared === "serial")
|
|
1263
|
+
notNull = auto = true;
|
|
1264
|
+
const where = `${JSON.stringify(table.name)}.${JSON.stringify(name)}`;
|
|
1265
|
+
const column = {
|
|
1266
|
+
name,
|
|
1267
|
+
base: "unknown",
|
|
1268
|
+
notNull,
|
|
1269
|
+
primary,
|
|
1270
|
+
pkNotNull: this.dialect !== "sqlite" || declared === "integer",
|
|
1271
|
+
hasDefault,
|
|
1272
|
+
auto,
|
|
1273
|
+
integer: declared === "integer" && !array
|
|
1274
|
+
};
|
|
1275
|
+
const shown = declared + (array ? "[]" : "");
|
|
1276
|
+
const base = array ? undefined : mapType(this.dialect, declared);
|
|
1277
|
+
if (base)
|
|
1278
|
+
column.base = base;
|
|
1279
|
+
else
|
|
1280
|
+
column.warning = `${this.file}: column ${where} has ${shown ? `type ${JSON.stringify(shown)}, which typegen does not read` : "no type"}; Row types it unknown`;
|
|
1281
|
+
return column;
|
|
1282
|
+
}
|
|
1283
|
+
dropTable(s, from) {
|
|
1284
|
+
let i = this.ifClause(s, from, "if", "exists");
|
|
1285
|
+
for (;; ) {
|
|
1286
|
+
const name = this.name(s, i);
|
|
1287
|
+
if (!name)
|
|
1288
|
+
return;
|
|
1289
|
+
this.schema.tables.delete(this.key(name.display));
|
|
1290
|
+
if (!isPunct(s[name.next], ","))
|
|
1291
|
+
return;
|
|
1292
|
+
i = name.next + 1;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
alterTable(s, from) {
|
|
1296
|
+
let i = this.ifClause(s, from, "if", "exists");
|
|
1297
|
+
if (isWord(s[i], "only"))
|
|
1298
|
+
i++;
|
|
1299
|
+
const name = this.name(s, i);
|
|
1300
|
+
if (!name)
|
|
1301
|
+
return;
|
|
1302
|
+
const key = this.key(name.display);
|
|
1303
|
+
const table = this.schema.tables.get(key);
|
|
1304
|
+
if (!table)
|
|
1305
|
+
return;
|
|
1306
|
+
for (const action of splitTop(s.slice(name.next)))
|
|
1307
|
+
this.action(key, table, action);
|
|
1308
|
+
}
|
|
1309
|
+
action(key, table, a) {
|
|
1310
|
+
const verb = a[0]?.kind === "word" ? a[0].lower : "";
|
|
1311
|
+
if (verb === "add") {
|
|
1312
|
+
let j = 1;
|
|
1313
|
+
if (isWord(a[j], "column"))
|
|
1314
|
+
j++;
|
|
1315
|
+
if (isPunct(a[j], "(")) {
|
|
1316
|
+
const close = closing(a, j);
|
|
1317
|
+
for (const item of splitTop(a.slice(j + 1, close < 0 ? a.length : close)))
|
|
1318
|
+
this.item(table, item);
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
const afterIf = this.ifClause(a, j, "if", "not", "exists");
|
|
1322
|
+
this.item(table, a.slice(afterIf), afterIf !== j);
|
|
1323
|
+
} else if (verb === "drop") {
|
|
1324
|
+
let j = 1;
|
|
1325
|
+
if (isWord(a[j], "constraint", "primary", "foreign", "index", "key", "check", "unique", "partition"))
|
|
1326
|
+
return;
|
|
1327
|
+
if (isWord(a[j], "column"))
|
|
1328
|
+
j++;
|
|
1329
|
+
j = this.ifClause(a, j, "if", "exists");
|
|
1330
|
+
const column = this.name(a, j);
|
|
1331
|
+
if (column)
|
|
1332
|
+
table.columns.delete(this.key(column.display));
|
|
1333
|
+
} else if (verb === "rename") {
|
|
1334
|
+
let j = 1;
|
|
1335
|
+
if (isWord(a[j], "constraint", "index", "key"))
|
|
1336
|
+
return;
|
|
1337
|
+
if (isWord(a[j], "to", "as"))
|
|
1338
|
+
return this.renameTable(key, table, a[j + 1]);
|
|
1339
|
+
if (isWord(a[j], "column"))
|
|
1340
|
+
j++;
|
|
1341
|
+
if (!isWord(a[j + 1], "to", "as"))
|
|
1342
|
+
return this.renameTable(key, table, a[j]);
|
|
1343
|
+
const from = a[j];
|
|
1344
|
+
const to = a[j + 2];
|
|
1345
|
+
if (!from || !to)
|
|
1346
|
+
return;
|
|
1347
|
+
const oldKey = this.key(this.display(from));
|
|
1348
|
+
const column = table.columns.get(oldKey);
|
|
1349
|
+
if (!column)
|
|
1350
|
+
return;
|
|
1351
|
+
const display = this.display(to);
|
|
1352
|
+
const renamed = new Map;
|
|
1353
|
+
for (const [k, value] of table.columns) {
|
|
1354
|
+
if (k === oldKey)
|
|
1355
|
+
renamed.set(this.key(display), {
|
|
1356
|
+
...column,
|
|
1357
|
+
name: display,
|
|
1358
|
+
warning: column.warning?.replace(JSON.stringify(column.name), JSON.stringify(display))
|
|
1359
|
+
});
|
|
1360
|
+
else
|
|
1361
|
+
renamed.set(k, value);
|
|
1362
|
+
}
|
|
1363
|
+
table.columns = renamed;
|
|
1364
|
+
} else if (verb === "modify" || verb === "change" || verb === "alter" && a.some((tok) => isWord(tok, "type", "null"))) {
|
|
1365
|
+
this.warn(`ALTER TABLE ${table.name} ${verb.toUpperCase()} is not read; Row<${JSON.stringify(table.name)}> may differ from the database`);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
renameTable(key, table, to) {
|
|
1369
|
+
if (!to || to.kind !== "word" && to.kind !== "ident")
|
|
1370
|
+
return;
|
|
1371
|
+
const display = this.display(to);
|
|
1372
|
+
this.schema.tables.delete(key);
|
|
1373
|
+
table.name = display;
|
|
1374
|
+
this.schema.tables.set(this.key(display), table);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
function readSchema(dialect, migrations) {
|
|
1378
|
+
const reader = new Reader(dialect);
|
|
1379
|
+
for (const { file, sql } of migrations) {
|
|
1380
|
+
reader.file = file;
|
|
1381
|
+
const pieces = dialect === "mysql" && /^\s*delimiter\s/im.test(sql) ? delimited(sql) : [{ sql, whole: false }];
|
|
1382
|
+
for (const piece of pieces) {
|
|
1383
|
+
const tokens = tokenize(piece.sql, dialect);
|
|
1384
|
+
for (const statement of piece.whole ? [tokens] : statements(tokens))
|
|
1385
|
+
reader.statement(statement);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
return reader.schema;
|
|
1389
|
+
}
|
|
1390
|
+
function warningsOf(schema) {
|
|
1391
|
+
const columns = [...schema.tables.values()].flatMap((table) => [...table.columns.values()]);
|
|
1392
|
+
return [...schema.warnings, ...columns.flatMap((column) => column.warning ? [column.warning] : [])];
|
|
1393
|
+
}
|
|
1394
|
+
var isNullable = (column) => !column.notNull && !(column.primary && column.pkNotNull);
|
|
1395
|
+
var typeOfColumn = (column) => isNullable(column) && column.base !== "unknown" ? `${column.base} | null` : column.base;
|
|
1396
|
+
var isOptionalOnInsert = (column, dialect) => isNullable(column) || column.hasDefault || column.auto || dialect === "sqlite" && column.primary && column.integer;
|
|
1397
|
+
|
|
1398
|
+
// packages/db/src/build/factories.ts
|
|
1399
|
+
var FILE = /^(.+)\.(ts|mts|js|mjs)$/;
|
|
1400
|
+
var IGNORED_FILE = /\.(test|spec)\.[^/]+$|\.d\.m?ts$/;
|
|
1401
|
+
var TABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1402
|
+
var ignored = (name) => name.startsWith("_") || name.startsWith(".");
|
|
1403
|
+
async function entries(dir) {
|
|
1404
|
+
try {
|
|
1405
|
+
return await readdir2(dir, { withFileTypes: true });
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
1408
|
+
return [];
|
|
1409
|
+
throw error;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
function distance(a, b) {
|
|
1413
|
+
let row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
1414
|
+
for (let i = 1;i <= a.length; i++) {
|
|
1415
|
+
const next = [i];
|
|
1416
|
+
for (let j = 1;j <= b.length; j++)
|
|
1417
|
+
next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
1418
|
+
row = next;
|
|
1419
|
+
}
|
|
1420
|
+
return row[b.length];
|
|
1421
|
+
}
|
|
1422
|
+
function nearest(name, known) {
|
|
1423
|
+
let best;
|
|
1424
|
+
for (const table of known) {
|
|
1425
|
+
const at = distance(name, table);
|
|
1426
|
+
if (at <= 2 && (!best || at < best.at))
|
|
1427
|
+
best = { table, at };
|
|
1428
|
+
}
|
|
1429
|
+
return best?.table;
|
|
1430
|
+
}
|
|
1431
|
+
async function scanFactories(hamur, options, dialects) {
|
|
1432
|
+
const { rootDir } = hamur.options;
|
|
1433
|
+
const roots = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)].map((dir) => join4(dir, "db", "factories"));
|
|
1434
|
+
const migrations = await loadMigrations(hamur, options);
|
|
1435
|
+
const problems = [];
|
|
1436
|
+
const found = {};
|
|
1437
|
+
const schemas = new Map;
|
|
1438
|
+
const schemaOf = (connection) => {
|
|
1439
|
+
let schema = schemas.get(connection);
|
|
1440
|
+
if (!schema) {
|
|
1441
|
+
schema = readSchema(dialects[connection] ?? options.connections[connection].dialect, migrations[connection] ?? []);
|
|
1442
|
+
schemas.set(connection, schema);
|
|
1443
|
+
}
|
|
1444
|
+
return schema;
|
|
1445
|
+
};
|
|
1446
|
+
for (const root of roots) {
|
|
1447
|
+
const place = async (connection, dir, folders) => {
|
|
1448
|
+
for (const entry of (await entries(dir)).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1449
|
+
if (ignored(entry.name))
|
|
1450
|
+
continue;
|
|
1451
|
+
const path = join4(dir, entry.name);
|
|
1452
|
+
if (entry.isDirectory()) {
|
|
1453
|
+
if (folders && !Object.hasOwn(options.connections, entry.name))
|
|
1454
|
+
problems.push(`${shown2(rootDir, path)}: db.connections has no connection "${entry.name}"`);
|
|
1455
|
+
continue;
|
|
1456
|
+
}
|
|
1457
|
+
const match = entry.isFile() ? FILE.exec(entry.name) : null;
|
|
1458
|
+
if (!match || IGNORED_FILE.test(entry.name))
|
|
1459
|
+
continue;
|
|
1460
|
+
const table = match[1];
|
|
1461
|
+
if (!Object.hasOwn(options.connections, connection)) {
|
|
1462
|
+
problems.push(`${shown2(rootDir, path)}: db.connections has no connection "${connection}"`);
|
|
1463
|
+
continue;
|
|
1464
|
+
}
|
|
1465
|
+
const files = found[connection] ??= {};
|
|
1466
|
+
const schema = schemaOf(connection);
|
|
1467
|
+
if (!TABLE.test(table) || !schema.tables.has(table)) {
|
|
1468
|
+
const hint = nearest(table, [...schema.tables.keys()]);
|
|
1469
|
+
problems.push(`${shown2(rootDir, path)}: db "${connection}" has no table "${table}"${hint ? ` (did you mean "${hint}"?)` : ""}`);
|
|
1470
|
+
continue;
|
|
1471
|
+
}
|
|
1472
|
+
if (Object.hasOwn(files, table) && files[table].startsWith(root)) {
|
|
1473
|
+
problems.push(`${shown2(rootDir, files[table])} and ${shown2(rootDir, path)} both write the factory of "${table}"`);
|
|
1474
|
+
continue;
|
|
1475
|
+
}
|
|
1476
|
+
if (!Object.hasOwn(files, table))
|
|
1477
|
+
files[table] = path;
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
await place("default", root, true);
|
|
1481
|
+
for (const connection of Object.keys(options.connections)) {
|
|
1482
|
+
if (connection !== "default")
|
|
1483
|
+
await place(connection, join4(root, connection), false);
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
if (problems.length)
|
|
1487
|
+
throw new DiagnosticError6("HAMUR_E5525", problems.join(`
|
|
1488
|
+
`));
|
|
1489
|
+
return Object.fromEntries(Object.entries(found).filter(([, files]) => Object.keys(files).length > 0));
|
|
1490
|
+
}
|
|
1491
|
+
function setupFactories(options, hamur, dialects) {
|
|
1492
|
+
addTemplate4({
|
|
1493
|
+
filename: "db/factories",
|
|
1494
|
+
getContents: async () => {
|
|
1495
|
+
const found = await scanFactories(hamur, options, dialects);
|
|
1496
|
+
const imports = [];
|
|
1497
|
+
const tables = Object.entries(found).map(([connection, files]) => {
|
|
1498
|
+
const members = Object.entries(files).map(([table, file]) => {
|
|
1499
|
+
const name = `factory${imports.length}`;
|
|
1500
|
+
imports.push(`import ${name} from ${JSON.stringify(file)};`);
|
|
1501
|
+
return `${JSON.stringify(table)}: ${name}`;
|
|
1502
|
+
});
|
|
1503
|
+
return `${JSON.stringify(connection)}: { ${members.join(", ")} }`;
|
|
1504
|
+
});
|
|
1505
|
+
return `${imports.join(`
|
|
1506
|
+
`)}
|
|
1507
|
+
export const factories = { ${tables.join(", ")} };
|
|
1508
|
+
`;
|
|
1509
|
+
}
|
|
1510
|
+
});
|
|
1511
|
+
hamur.hooks.hook("build:before", async () => void await scanFactories(hamur, options, dialects));
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
// packages/db/src/build/types.ts
|
|
1515
|
+
import { addTypeTemplate, diagnostic as diagnostic2, useLogger as useLogger3 } from "hamur/kit";
|
|
1516
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
1517
|
+
var key = (name) => IDENTIFIER.test(name) ? name : JSON.stringify(name);
|
|
1518
|
+
function setupTypes(options, hamur, dialects = {}) {
|
|
1519
|
+
addTypeTemplate({
|
|
1520
|
+
filename: "db.d.ts",
|
|
1521
|
+
getContents: async () => {
|
|
1522
|
+
const all = await loadMigrations(hamur, options);
|
|
1523
|
+
const log = useLogger3("hamur");
|
|
1524
|
+
const entries = [];
|
|
1525
|
+
for (const [name, connection] of Object.entries(options.connections)) {
|
|
1526
|
+
const dialect = dialects[name] ?? connection.dialect;
|
|
1527
|
+
const schema = readSchema(dialect, all[name] ?? []);
|
|
1528
|
+
for (const warning of warningsOf(schema))
|
|
1529
|
+
log.warn(diagnostic2("HAMUR_W5519", `db "${name}": ${warning}`));
|
|
1530
|
+
const tables = [...schema.tables.values()].sort((a, b) => a.name.localeCompare(b.name)).map((table) => ` ${key(table.name)}: { ${[...table.columns.values()].map((column) => `${key(column.name)}: ${typeOfColumn(column)}`).join("; ")} };`);
|
|
1531
|
+
const inserts = [...schema.tables.values()].sort((a, b) => a.name.localeCompare(b.name)).map((table) => ` ${key(table.name)}: { ${[...table.columns.values()].map((column) => `${key(column.name)}${isOptionalOnInsert(column, dialect) ? "?" : ""}: ${typeOfColumn(column)}`).join("; ")} };`);
|
|
1532
|
+
const block = (field, lines) => ` ${field}: {${lines.length ? `
|
|
1533
|
+
${lines.join(`
|
|
1534
|
+
`)}
|
|
1535
|
+
` : " "}};`;
|
|
1536
|
+
entries.push(` ${key(name)}: {
|
|
1537
|
+
dialect: ${JSON.stringify(dialect)};
|
|
1538
|
+
${block("tables", tables)}
|
|
1539
|
+
${block("inserts", inserts)}
|
|
1540
|
+
};`);
|
|
1541
|
+
}
|
|
1542
|
+
return `declare module "@hamur/db" {
|
|
1543
|
+
interface HamurDatabases {
|
|
1544
|
+
${entries.join(`
|
|
1545
|
+
`)}
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
export {};
|
|
1549
|
+
`;
|
|
1550
|
+
}
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// packages/db/src/module.ts
|
|
1555
|
+
var DATABASE_ICON = '<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>';
|
|
1556
|
+
var resolvedOptions = new WeakMap;
|
|
1557
|
+
var module_default = defineModule({
|
|
1558
|
+
meta: { name: "db", configKey: "db", hooks: ["db:migrations:dirs"] },
|
|
1559
|
+
async setup(input, hamur) {
|
|
1560
|
+
const options = resolveOptions(input);
|
|
1561
|
+
const dialects = Object.fromEntries(Object.entries(options.connections).map(([name, connection]) => [name, connection.dialect]));
|
|
1562
|
+
await setupConnections(options, hamur);
|
|
1563
|
+
await setupMigrations(options, hamur);
|
|
1564
|
+
await setupQueue(options, hamur);
|
|
1565
|
+
setupTypes(options, hamur, dialects);
|
|
1566
|
+
setupFactories(options, hamur, dialects);
|
|
1567
|
+
resolvedOptions.set(hamur, options);
|
|
1568
|
+
addDevtoolsTab({
|
|
1569
|
+
name: "database",
|
|
1570
|
+
title: "Database",
|
|
1571
|
+
icon: DATABASE_ICON,
|
|
1572
|
+
view: { type: "module", entry: createResolver3(new URL("../../src/module.ts", import.meta.url).href).resolve("./devtools.ts") }
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
});
|
|
1576
|
+
|
|
1577
|
+
// packages/db/src/build/tables.ts
|
|
1578
|
+
async function tableProblem(hamur, { connection = "default", table, columns }) {
|
|
1579
|
+
const options = resolvedOptions.get(hamur);
|
|
1580
|
+
if (!options || !Object.hasOwn(options.connections, connection))
|
|
1581
|
+
return `db.connections has no ${JSON.stringify(connection)}`;
|
|
1582
|
+
const { dialect } = options.connections[connection];
|
|
1583
|
+
const { tables } = readSchema(dialect, (await loadMigrations(hamur, options))[connection] ?? []);
|
|
1584
|
+
const found = tables.get(nameKey(dialect, table));
|
|
1585
|
+
if (!found)
|
|
1586
|
+
return `no migration of ${JSON.stringify(connection)} creates table ${JSON.stringify(table)}`;
|
|
1587
|
+
const missing = columns.find((column) => !found.columns.has(nameKey(dialect, column)));
|
|
1588
|
+
return missing === undefined ? undefined : `table ${JSON.stringify(table)} has no column ${JSON.stringify(missing)}`;
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// packages/db/src/cli.ts
|
|
1592
|
+
var MIGRATION_NAME = /^[a-z0-9_]+$/;
|
|
1593
|
+
async function runDbCommand(args, hamur) {
|
|
1594
|
+
const options = resolvedOptions.get(hamur);
|
|
1595
|
+
if (!options)
|
|
1596
|
+
throw new DiagnosticError7("HAMUR_E5501", "hamur db needs @hamur/db (bun add @hamur/db, then add it to modules)");
|
|
1597
|
+
const { connection, out } = args;
|
|
1598
|
+
if (connection !== undefined && !Object.hasOwn(options.connections, connection)) {
|
|
1599
|
+
throw new DiagnosticError7("HAMUR_E5502", `No database "${connection}": set db.connections.${connection} in hamur.config.ts`);
|
|
1600
|
+
}
|
|
1601
|
+
const names = connection === undefined ? Object.keys(options.connections) : [connection];
|
|
1602
|
+
const all = await loadMigrations(hamur, options);
|
|
1603
|
+
if (args.command === "new") {
|
|
1604
|
+
const { name } = args;
|
|
1605
|
+
if (name === undefined)
|
|
1606
|
+
throw new DiagnosticError7("HAMUR_E5503", "hamur db new needs a migration name (hamur db new add_users)");
|
|
1607
|
+
if (!MIGRATION_NAME.test(name))
|
|
1608
|
+
throw new DiagnosticError7("HAMUR_E5504", `Migration name ${JSON.stringify(name)} may hold only a-z, 0-9 and _`);
|
|
1609
|
+
const target = connection ?? "default";
|
|
1610
|
+
if (!Object.hasOwn(options.connections, target))
|
|
1611
|
+
throw new DiagnosticError7("HAMUR_E5502", `No database "${target}": set db.connections.${target} in hamur.config.ts`);
|
|
1612
|
+
const last = (all[target] ?? []).map((migration) => migration.id).sort(compareIds).at(-1);
|
|
1613
|
+
const next = String(last === undefined ? 1n : BigInt(last) + 1n).padStart(4, "0");
|
|
1614
|
+
const dir = join5(hamur.options.serverDir, "db", "migrations", ...target === "default" ? [] : [target]);
|
|
1615
|
+
const file = join5(dir, `${next}_${name}.sql`);
|
|
1616
|
+
await mkdir2(dir, { recursive: true });
|
|
1617
|
+
await writeFile2(file, `-- ${name}
|
|
1618
|
+
`, { flag: "wx" });
|
|
1619
|
+
out(`Created ${relative3(hamur.options.rootDir, file)}`);
|
|
1620
|
+
return 0;
|
|
1621
|
+
}
|
|
1622
|
+
const databases = openDatabases(hamur, options);
|
|
1623
|
+
try {
|
|
1624
|
+
for (const name of names) {
|
|
1625
|
+
if (options.connections[name].connector === "d1") {
|
|
1626
|
+
out(`db.connections.${name} uses d1; run wrangler d1 migrations apply or list`);
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
const list = all[name] ?? [];
|
|
1630
|
+
if (args.command === "migrate") {
|
|
1631
|
+
const applied = await migrate(databases.use(name), list, {
|
|
1632
|
+
warn: (message) => useLogger4("hamur").warn(message),
|
|
1633
|
+
applied: (migration, ms) => out(`Applied ${migration.id}_${migration.name} (${Math.round(ms)} ms)`)
|
|
1634
|
+
});
|
|
1635
|
+
out(applied.length ? `${applied.length} migration${applied.length === 1 ? "" : "s"} applied to "${name}"` : `No pending migrations on "${name}"`);
|
|
1636
|
+
continue;
|
|
1637
|
+
}
|
|
1638
|
+
if (names.length > 1)
|
|
1639
|
+
out(`${name}:`);
|
|
1640
|
+
const states = await migrationStatus(databases.use(name), list);
|
|
1641
|
+
if (!states.length)
|
|
1642
|
+
out(`No migrations on "${name}"`);
|
|
1643
|
+
for (const state of states)
|
|
1644
|
+
out([`${state.id}_${state.name}`, state.state, ...state.state === "applied" ? [state.appliedAt] : []].join(" "));
|
|
1645
|
+
}
|
|
1646
|
+
} finally {
|
|
1647
|
+
await databases.close();
|
|
1648
|
+
}
|
|
1649
|
+
return 0;
|
|
1650
|
+
}
|
|
1651
|
+
var firstLine = (text) => (text ?? "").split(`
|
|
1652
|
+
`, 1)[0];
|
|
1653
|
+
async function runQueueCommand(args, hamur) {
|
|
1654
|
+
const options = resolvedOptions.get(hamur);
|
|
1655
|
+
const queue = queueOptions(hamur);
|
|
1656
|
+
if (!options || !queue)
|
|
1657
|
+
throw new DiagnosticError7("HAMUR_E5522", 'tasks.queue.driver "db" needs @hamur/db in modules');
|
|
1658
|
+
const databases = openDatabases(hamur, options);
|
|
1659
|
+
try {
|
|
1660
|
+
const table = createQueueTable(() => databases.use(queue.connection), queue);
|
|
1661
|
+
await table.ensure();
|
|
1662
|
+
if (args.command === "retry") {
|
|
1663
|
+
const id = args.id ?? "";
|
|
1664
|
+
const retried = await table.retry(id);
|
|
1665
|
+
if (retried.state === "missing")
|
|
1666
|
+
throw new DiagnosticError7("HAMUR_E5523", `No failed task run ${JSON.stringify(id)} in ${queue.table}`);
|
|
1667
|
+
if (retried.state === "locked")
|
|
1668
|
+
throw new DiagnosticError7("HAMUR_E5524", `Task run ${JSON.stringify(id)} is still locked by a run until ${new Date(retried.until).toISOString()}; retry it after that`);
|
|
1669
|
+
args.out(`Task run ${id} is due again`);
|
|
1670
|
+
return 0;
|
|
1671
|
+
}
|
|
1672
|
+
const rows = await table.failed();
|
|
1673
|
+
if (!rows.length)
|
|
1674
|
+
args.out("No failed task runs");
|
|
1675
|
+
for (const row of rows)
|
|
1676
|
+
args.out([
|
|
1677
|
+
row.id,
|
|
1678
|
+
row.task,
|
|
1679
|
+
`${row.attempts} ${row.attempts === 1 ? "attempt" : "attempts"}`,
|
|
1680
|
+
new Date(row.failedAt).toISOString(),
|
|
1681
|
+
firstLine(row.lastError)
|
|
1682
|
+
].join(" "));
|
|
1683
|
+
return 0;
|
|
1684
|
+
} finally {
|
|
1685
|
+
await databases.close();
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
export {
|
|
1689
|
+
runDbCommand,
|
|
1690
|
+
runQueueCommand,
|
|
1691
|
+
tableProblem
|
|
1692
|
+
};
|