Skip to content

Commit 79a5b38

Browse files
DennisAlundCopilot
andcommitted
Resolve D1 database_id at build time via API lookup
The deploy script now runs scripts/resolve-d1-id.js before migrations. It queries wrangler d1 list to find the database_id by name and injects it into wrangler.toml. Skips if database_id is already present. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 25272b1 commit 79a5b38

2 files changed

Lines changed: 48 additions & 1 deletion

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"license": "Apache-2.0",
66
"scripts": {
77
"dev": "wrangler dev",
8-
"deploy": "npm run db:migrate:remote && wrangler deploy",
8+
"deploy": "node scripts/resolve-d1-id.js && npm run db:migrate:remote && wrangler deploy",
99
"wrangler-login": "wrangler login",
1010
"db:create": "wrangler d1 create shrtnr-db",
1111
"db:migrate": "wrangler d1 migrations apply shrtnr-db --local",

scripts/resolve-d1-id.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env node
2+
3+
// Resolves the D1 database_id at build time by querying the Cloudflare API
4+
// via wrangler. Keeps wrangler.toml free of hardcoded database IDs so the
5+
// source repo works for any Cloudflare account.
6+
7+
const { execSync } = require("child_process");
8+
const fs = require("fs");
9+
10+
const configPath = "wrangler.toml";
11+
const toml = fs.readFileSync(configPath, "utf-8");
12+
13+
if (/^\s*database_id\s*=/m.test(toml)) {
14+
process.exit(0);
15+
}
16+
17+
const nameMatch = toml.match(/database_name\s*=\s*"([^"]+)"/);
18+
if (!nameMatch) {
19+
console.error("No database_name found in wrangler.toml");
20+
process.exit(1);
21+
}
22+
const dbName = nameMatch[1];
23+
24+
let databases;
25+
try {
26+
const raw = execSync("npx wrangler d1 list --json 2>/dev/null", {
27+
encoding: "utf-8",
28+
});
29+
const parsed = JSON.parse(raw);
30+
databases = Array.isArray(parsed) ? parsed : [];
31+
} catch {
32+
console.error("Could not list D1 databases. Is wrangler authenticated?");
33+
process.exit(1);
34+
}
35+
36+
const db = databases.find((d) => d.name === dbName);
37+
if (!db) {
38+
console.error(`D1 database "${dbName}" not found in this account.`);
39+
process.exit(1);
40+
}
41+
42+
const updated = toml.replace(
43+
/(database_name\s*=\s*"[^"]+")/,
44+
`$1\ndatabase_id = "${db.uuid}"`,
45+
);
46+
fs.writeFileSync(configPath, updated);
47+
console.log(`Resolved ${dbName}${db.uuid}`);

0 commit comments

Comments
 (0)