feat(db): 配置 Drizzle ORM 与 PostgreSQL 静态连接池

This commit is contained in:
kennethcheng 2026-04-27 18:43:25 +08:00
parent 8fbf8b239f
commit 577a4379cd
3 changed files with 34 additions and 3 deletions

8
drizzle.config.ts Normal file
View File

@ -0,0 +1,8 @@
import { defineConfig } from "drizzle-kit";
export default {
schema: "./src/db/schema.ts",
out: "./drizzle",
dialect: "postgresql",
dbCredentials: { url: process.env.DATABASE_URL! },
} satisfies Parameters<typeof defineConfig>[0];

View File

@ -1,4 +1,4 @@
{
{
"name": "temp-next",
"version": "0.1.0",
"private": true,
@ -6,7 +6,10 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
"lint": "eslint",
"db:generate": "drizzle-kit generate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio"
},
"dependencies": {
"bcryptjs": "^3.0.3",
@ -28,4 +31,4 @@
"tsx": "^4.21.0",
"typescript": "^5"
}
}
}

20
src/db/index.ts Normal file
View File

@ -0,0 +1,20 @@
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import dotenv from "dotenv";
dotenv.config();
const connectionString = process.env.DATABASE_URL!;
const driver = postgres(connectionString, { max: 1 });
let db: PostgresJsDatabase = drizzle(driver);
if (process.env.NODE_ENV !== "production") {
const g = globalThis as unknown as { drizzleClient: PostgresJsDatabase };
if (!g.drizzleClient) {
g.drizzleClient = db;
}
db = g.drizzleClient;
}
export { db };