与 Drizzle 的数据库连接
Drizzle ORM 通过数据库驱动程序在你的数据库上运行 SQL 查询。
index.ts
schema.ts
import { drizzle } from "drizzle-orm/node-postgres"
import { users } from "./schema"
const db = drizzle(process.env.DATABASE_URL);
const usersCount = await db.$count(users);
┌──────────────────────┐
│ db.$count(users) │ <--- drizzle query
└──────────────────────┘
│ ʌ
select count(*) from users -│ │
│ │- [{ count: 0 }]
v │
┌─────────────────────┐
│ node-postgres │ <--- database driver
└─────────────────────┘
│ ʌ
01101000 01100101 01111001 -│ │
│ │- 01110011 01110101 01110000
v │
┌────────────────────┐
│ Database │
└────────────────────┘
Drizzle 会在后台创建一个 node-postgres 驱动程序实例,你可以在必要时通过 db.$client
访问该实例。
import { drizzle } from "drizzle-orm/node-postgres"
const db = drizzle(process.env.DATABASE_URL);
const pool = db.$client;
// above is equivalent to
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
const db = drizzle({ client: pool });
Drizzle 的设计使其与所有边缘计算或无服务器运行时原生兼容,无论你何时需要访问无服务器数据库,都能轻松上手。 - 我们已经为你准备好了
Neon HTTP
Neon with websockets
Vercel Postgres
PlanetScale HTTP
Cloudflare d1
import { drizzle } from "drizzle-orm/neon-http";
const db = drizzle(process.env.DATABASE_URL);
是的,我们支持特定于运行时的驱动程序,例如 Bun SQLite 或 Expo SQLite:
import { drizzle } from "drizzle-orm/bun-sqlite"
const db = drizzle(); // <--- will create an in-memory db
const db = drizzle("./sqlite.db");
import { drizzle } from "drizzle-orm/expo-sqlite";
import { openDatabaseSync } from "expo-sqlite";
const expo = openDatabaseSync("db.db");
const db = drizzle(expo);
数据库连接 URL
如果你不熟悉数据库连接 URL 的概念,请参考这里。
postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname
└──┘ └───────┘ └─────────────────────────────────────────────┘ └────┘
ʌ ʌ ʌ ʌ
role -│ │ │- hostname │- database
│
│- password
后续步骤
欢迎查看每个驱动程序的文档
PostgreSQL drivers
MySQL drivers
SQLite drivers
Native SQLite
Others