netlify-db
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNetlify DB
Netlify DB
Netlify DB provisions a managed Neon Postgres database automatically. No Neon account required.
Netlify DB 会自动配置托管的 Neon Postgres 数据库,无需拥有 Neon 账户。
When to Use DB vs Blobs
何时使用DB vs Blobs
Use Netlify DB when:
- Storing structured, relational data
- Data will grow over time
- Need queries, filtering, joins, or aggregations
Use Netlify Blobs instead when:
- Storing files (images, documents, exports)
- A handful of records with no growth expectation
- Simple key-value storage with no relational needs
- Want zero dependencies beyond
@netlify/blobs
See the netlify-blobs skill for Blobs usage.
使用Netlify DB的场景:
- 存储结构化、关联型数据
- 数据会随时间增长
- 需要执行查询、筛选、关联或聚合操作
改用Netlify Blobs的场景:
- 存储文件(图片、文档、导出文件等)
- 仅少量记录且无增长预期
- 仅需简单键值存储,无关联需求
- 希望除外无其他依赖
@netlify/blobs
如需了解Blobs的使用方法,请查看netlify-blobs技能文档。
Setup
配置步骤
bash
npm install @netlify/neon
netlify db init # Provisions database and sets up Drizzle ORMPrerequisites: logged into Netlify CLI and site linked ().
netlify linkbash
npm install @netlify/neon
netlify db init # 配置数据库并设置Drizzle ORM前提条件:已登录Netlify CLI并关联站点(执行)。
netlify linkRaw SQL via @netlify/neon
通过@netlify/neon执行原生SQL
@netlify/neon@neondatabase/serverlesstypescript
import { neon } from "@netlify/neon";
const sql = neon();
const users = await sql("SELECT * FROM users");
await sql("INSERT INTO users (name) VALUES ($1)", ["Jane"]);
await sql("UPDATE users SET name = $1 WHERE id = $2", ["Jane", 1]);
await sql("DELETE FROM users WHERE id = $1", [1]);@netlify/neon@neondatabase/serverlesstypescript
import { neon } from "@netlify/neon";
const sql = neon();
const users = await sql("SELECT * FROM users");
await sql("INSERT INTO users (name) VALUES ($1)", ["Jane"]);
await sql("UPDATE users SET name = $1 WHERE id = $2", ["Jane", 1]);
await sql("DELETE FROM users WHERE id = $1", [1]);Drizzle ORM Integration
Drizzle ORM集成
For most projects, use Drizzle ORM on top of Netlify DB.
对于大多数项目,建议在Netlify DB之上使用Drizzle ORM。
drizzle.config.ts
drizzle.config.ts
typescript
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
dbCredentials: { url: process.env.NETLIFY_DATABASE_URL! },
schema: "./db/schema.ts",
out: "./migrations",
migrations: { prefix: "timestamp" }, // Avoids conflicts across branches
});typescript
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
dbCredentials: { url: process.env.NETLIFY_DATABASE_URL! },
schema: "./db/schema.ts",
out: "./migrations",
migrations: { prefix: "timestamp" }, // 避免跨分支冲突
});db/index.ts
db/index.ts
typescript
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";
import * as schema from "./schema";
const sql = neon(process.env.NETLIFY_DATABASE_URL!);
export const db = drizzle(sql, { schema });
export * from "./schema";typescript
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";
import * as schema from "./schema";
const sql = neon(process.env.NETLIFY_DATABASE_URL!);
export const db = drizzle(sql, { schema });
export * from "./schema";Schema Example
结构示例
typescript
// db/schema.ts
import { integer, pgTable, varchar, text, boolean, timestamp } from "drizzle-orm/pg-core";
export const items = pgTable("items", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
title: varchar({ length: 255 }).notNull(),
description: text(),
isActive: boolean("is_active").notNull().default(true),
createdAt: timestamp("created_at").defaultNow(),
updatedAt: timestamp("updated_at").defaultNow(),
});
export type Item = typeof items.$inferSelect;
export type NewItem = typeof items.$inferInsert;typescript
// db/schema.ts
import { integer, pgTable, varchar, text, boolean, timestamp } from "drizzle-orm/pg-core";
export const items = pgTable("items", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
title: varchar({ length: 255 }).notNull(),
description: text(),
isActive: boolean("is_active").notNull().default(true),
createdAt: timestamp("created_at").defaultNow(),
updatedAt: timestamp("updated_at").defaultNow(),
});
export type Item = typeof items.$inferSelect;
export type NewItem = typeof items.$inferInsert;Query Patterns
查询模式
typescript
import { db, items } from "../db";
import { eq } from "drizzle-orm";
const all = await db.select().from(items);
const [one] = await db.select().from(items).where(eq(items.id, id)).limit(1);
const [created] = await db.insert(items).values({ title: "New" }).returning();
const [updated] = await db.update(items).set({ title: "Updated" }).where(eq(items.id, id)).returning();
await db.delete(items).where(eq(items.id, id));typescript
import { db, items } from "../db";
import { eq } from "drizzle-orm";
const all = await db.select().from(items);
const [one] = await db.select().from(items).where(eq(items.id, id)).limit(1);
const [created] = await db.insert(items).values({ title: "New" }).returning();
const [updated] = await db.update(items).set({ title: "Updated" }).where(eq(items.id, id)).returning();
await db.delete(items).where(eq(items.id, id));Migrations
数据迁移
json
{
"scripts": {
"db:generate": "drizzle-kit generate",
"db:migrate": "netlify dev:exec drizzle-kit migrate",
"db:push": "netlify dev:exec drizzle-kit push",
"db:studio": "netlify dev:exec drizzle-kit studio"
}
}Workflow: modify schema, run , then .
db:generatedb:migratejson
{
"scripts": {
"db:generate": "drizzle-kit generate",
"db:migrate": "netlify dev:exec drizzle-kit migrate",
"db:push": "netlify dev:exec drizzle-kit push",
"db:studio": "netlify dev:exec drizzle-kit studio"
}
}工作流程:修改数据库结构,执行,然后执行。
db:generatedb:migrateDeploy Preview Branching
部署预览分支功能
Netlify DB supports branching — production branch gets the production database, all other branches and deploy previews get a separate preview branch. Develop and test migrations on preview, merge to main, then apply to production.
Netlify DB支持分支功能——生产分支对应生产数据库,其他所有分支和部署预览都有独立的预览分支。可在预览环境开发并测试迁移,合并到主分支后再应用到生产环境。
Environment Variables
环境变量
- — Auto-set by Netlify when database is provisioned
NETLIFY_DATABASE_URL - Retrieve manually:
netlify env:get NETLIFY_DATABASE_URL
- —— 配置数据库后由Netlify自动设置
NETLIFY_DATABASE_URL - 手动获取:
netlify env:get NETLIFY_DATABASE_URL
Local Development
本地开发
Run or use to get database access locally. Use to run migration commands with the proper environment.
netlify dev@netlify/vite-pluginnetlify dev:exec运行或使用即可在本地访问数据库。使用执行迁移命令,可确保环境配置正确。
netlify dev@netlify/vite-pluginnetlify dev:exec