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
带 Websockets 的 Neon
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:[email protected]/dbname
└──┘ └───────┘ └─────────────────────────────────────────────┘ └────┘
ʌ ʌ ʌ ʌ
role -│ │ │- hostname │- database
│
│- password
下一步
欢迎查看各个驱动的文档
PostgreSQL 驱动
MySQL 驱动
SQLite 驱动
原生 SQLite
其他