-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrizzle.config.ts
More file actions
68 lines (60 loc) · 1.79 KB
/
Copy pathdrizzle.config.ts
File metadata and controls
68 lines (60 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import fs from "node:fs";
import path from "node:path";
import { config } from "dotenv";
import { defineConfig } from "drizzle-kit";
let dbConfig: ReturnType<typeof defineConfig>;
if (process.env.ENVIRONMENT === "production") {
config({ path: "./.prod.vars" });
dbConfig = defineConfig({
schema: "./src/db/schema.ts",
out: "./drizzle/migrations",
dialect: "sqlite",
driver: "d1-http",
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "",
databaseId: process.env.CLOUDFLARE_DATABASE_ID ?? "",
token: process.env.CLOUDFLARE_D1_TOKEN ?? "",
},
});
} else {
config({ path: "./.dev.vars" });
const localD1DB = getLocalD1DB();
if (!localD1DB) {
process.exit(1);
}
dbConfig = defineConfig({
schema: "./src/db/schema.ts",
out: "./drizzle/migrations",
dialect: "sqlite",
dbCredentials: {
url: localD1DB,
},
});
}
export default dbConfig;
function getLocalD1DB() {
try {
const basePath = path.resolve(".wrangler");
const files = fs
.readdirSync(basePath, { encoding: "utf-8", recursive: true })
.filter((f) => f.endsWith(".sqlite"));
// In case there are multiple .sqlite files, we want the most recent one.
files.sort((a, b) => {
const statA = fs.statSync(path.join(basePath, a));
const statB = fs.statSync(path.join(basePath, b));
return statB.mtime.getTime() - statA.mtime.getTime();
});
const dbFile = files[0];
if (!dbFile) {
throw new Error(`.sqlite file not found in ${basePath}`);
}
const url = path.resolve(basePath, dbFile);
return url;
} catch (err) {
if (err instanceof Error) {
console.log(`Error resolving local D1 DB: ${err.message}`);
} else {
console.log(`Error resolving local D1 DB: ${err}`);
}
}
}