快速开始
sh
pnpm add drizzle-orm pg dotenv
pnpm add -D drizzle-kit tsx @types/pg目录结构
📦 <project root>
├ 📂 drizzle
├ 📂 src
│ ├ 📂 db
│ │ └ 📜 schema.ts
│ └ 📜 index.ts
├ 📜 .env
├ 📜 drizzle.config.ts
├ 📜 package.json
└ 📜 tsconfig.jsonsh
DATABASE_URL=postgresql://qin:1@192.168.1.4:5432/db1ts
import "dotenv/config";
import { drizzle } from "drizzle-orm/node-postgres";
// You can specify any property from the node-postgres connection options
const db = drizzle({
connection: {
connectionString: process.env.DATABASE_URL!,
ssl: true,
},
});ts
import { integer, pgTable, varchar } from "drizzle-orm/pg-core";
export const usersTable = pgTable("users", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
name: varchar({ length: 255 }).notNull(),
age: integer().notNull(),
email: varchar({ length: 255 }).notNull().unique(),
});ts
import "dotenv/config";
import { defineConfig } from "drizzle-kit";
export default defineConfig({
out: "./drizzle",
schema: "./src/db/schema.ts",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});drizzle.config.ts 是 drizzle-kit 的配置文件
drizzle-kit 是开发工具箱,比如是基于 schema 生成数据库迁移文件