netlify-db

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Netlify 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 ORM
Prerequisites: logged into Netlify CLI and site linked (
netlify link
).
bash
npm install @netlify/neon
netlify db init    # 配置数据库并设置Drizzle ORM
前提条件:已登录Netlify CLI并关联站点(执行
netlify link
)。

Raw SQL via @netlify/neon

通过@netlify/neon执行原生SQL

@netlify/neon
wraps
@neondatabase/serverless
. No connection string needed — it auto-configures.
typescript
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/serverless
,无需连接字符串——它会自动完成配置。
typescript
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
db:generate
, then
db:migrate
.
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"
  }
}
工作流程:修改数据库结构,执行
db:generate
,然后执行
db:migrate

Deploy 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

环境变量

  • NETLIFY_DATABASE_URL
    — Auto-set by Netlify when database is provisioned
  • Retrieve manually:
    netlify env:get NETLIFY_DATABASE_URL
  • NETLIFY_DATABASE_URL
    —— 配置数据库后由Netlify自动设置
  • 手动获取:
    netlify env:get NETLIFY_DATABASE_URL

Local Development

本地开发

Run
netlify dev
or use
@netlify/vite-plugin
to get database access locally. Use
netlify dev:exec
to run migration commands with the proper environment.
运行
netlify dev
或使用
@netlify/vite-plugin
即可在本地访问数据库。使用
netlify dev:exec
执行迁移命令,可确保环境配置正确。