netlify-database

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Netlify Database

Netlify Database

Netlify Database is the managed Postgres product built into the Netlify platform. It is GA and is the default choice for any dynamic data in a Netlify project.
Install
@netlify/database
and Netlify auto-provisions a Postgres database for the site at deploy time. Each deploy preview gets its own isolated branch forked from production data. No Neon account, connection-string wiring, or claim flow — the database is a first-class Netlify primitive.
Netlify Database 是Netlify平台内置的托管Postgres产品,已GA,是Netlify项目中处理任何动态数据的默认选择。
安装
@netlify/database
后,Netlify会在部署时自动为站点配置一个Postgres数据库。每个部署预览都会获得一个独立分支,从生产环境数据分叉而来。无需Neon账户、连接字符串配置或申领流程——数据库是Netlify的原生核心组件。

Database vs Blobs

数据库 vs Blobs

Use Netlify Database for anything dynamic:
  • Any user-generated or app-generated records (posts, comments, orders, sessions, audit logs)
  • Structured data that will grow, be queried, or be joined
  • Key-value-style data read or written by application code at runtime
Use Netlify Blobs only for file and asset storage: images, documents, exports, uploads, cached binary artifacts. Do not use Blobs as a dynamic data store — reach for Database instead. See
netlify-blobs/SKILL.md
.
Netlify Database 适用于所有动态数据场景:
  • 用户生成或应用生成的记录(帖子、评论、订单、会话、审计日志)
  • 会增长、需查询或关联的结构化数据
  • 应用代码在运行时读写的键值型数据
Netlify Blobs 仅用于文件和资产存储:图片、文档、导出文件、上传内容、缓存二进制工件。请勿将Blobs用作动态数据存储——此时应使用Database。详情请参阅
netlify-blobs/SKILL.md

CRITICAL: Install Drizzle from the
@beta
dist-tag

重要提示:从
@beta
标签安装Drizzle

The Netlify Database adapter for Drizzle ORM currently only exists on the
beta
release line of
drizzle-orm
. Install both
drizzle-orm
and
drizzle-kit
from the
@beta
dist-tag:
bash
npm install drizzle-orm@beta
npm install -D drizzle-kit@beta
The default
latest
versions do not include the
drizzle-orm/netlify-db
adapter and will fail. If
drizzle-kit generate
errors about being outdated, or the
drizzle-orm/netlify-db
import fails to resolve, the install is missing
@beta
.
The
@beta
tag only affects the installed version — imports are written as
drizzle-orm
,
drizzle-orm/pg-core
, and
drizzle-orm/netlify-db
without modification.
Netlify Database的Drizzle ORM适配器目前仅存在于
drizzle-orm
的beta版本分支中。请同时从
@beta
标签安装
drizzle-orm
drizzle-kit
bash
npm install drizzle-orm@beta
npm install -D drizzle-kit@beta
默认的
latest
版本不包含
drizzle-orm/netlify-db
适配器,会导致运行失败。如果
drizzle-kit generate
提示版本过时,或
drizzle-orm/netlify-db
导入无法解析,说明安装时未添加
@beta
标签。
@beta
标签仅影响安装版本——导入语句仍写为
drizzle-orm
drizzle-orm/pg-core
drizzle-orm/netlify-db
,无需修改。

CRITICAL: Use the Netlify CLI for database operations

重要提示:使用Netlify CLI进行数据库操作

The CLI ships a complete database surface under
netlify database
(alias:
netlify db
) that replaces hand-rolled scripts and direct API/UI work. Reach for these commands first before writing custom tooling. Requires Netlify CLI 26.0.0+ — if a
netlify database
subcommand isn't recognized, run
npm install -g netlify-cli@latest
.
Full reference is in Netlify CLI commands below.
Netlify CLI在
netlify database
(别名:
netlify db
)命令下提供完整的数据库操作能力,可替代手动编写的脚本和直接的API/UI操作。在编写自定义工具之前,请优先使用这些命令。要求Netlify CLI 26.0.0+——如果
netlify database
子命令无法识别,请运行
npm install -g netlify-cli@latest
更新。
完整命令参考请见下方的Netlify CLI数据库命令

CRITICAL: Never apply migrations to a Netlify-hosted database

重要提示:切勿向Netlify托管的数据库应用迁移

The only database you ever apply migrations to yourself is the local development DB. For any Netlify-hosted database — production or a deploy preview branch — Netlify applies migrations automatically during the deploy. Your job is to create migration files and commit them. The deploy does the rest.
This means:
  • Use
    netlify database migrations apply
    for the local DB. Do NOT run
    drizzle-kit migrate
    against
    NETLIFY_DB_URL
    in any context.
  • Do NOT run
    drizzle-kit push
    at all. Generate a migration and let the deploy apply it.
  • Do NOT run raw DDL (
    CREATE
    ,
    ALTER
    ,
    DROP
    ,
    TRUNCATE
    ) via
    netlify database connect
    ,
    psql
    , or any other direct connection. Schema changes go through migration files; out-of-band DDL drifts the migration history from the actual schema.
  • Do NOT export
    NETLIFY_DB_URL
    from a preview or production context and run a client against it. Migrations drift the moment anything touches the schema out-of-band.
The one documented exception is a one-time data import during a provider switch — see
references/migration-from-extension.md
. Outside that specific flow, the rule is absolute: schema changes go through migration files, migration files get applied by the deploy.
你唯一需要手动应用迁移的数据库是本地开发数据库。对于任何Netlify托管的数据库——生产环境或部署预览分支——Netlify会在部署过程中自动应用迁移。你的工作仅需创建迁移文件并提交,部署流程会完成剩下的操作。
这意味着:
  • 使用
    netlify database migrations apply
    操作本地数据库。在任何环境下,都不要针对
    NETLIFY_DB_URL
    运行
    drizzle-kit migrate
  • 完全不要运行
    drizzle-kit push
    。生成迁移文件后,让部署流程自动应用即可。
  • 不要通过
    netlify database connect
    psql
    或任何其他直接连接方式执行原始DDL语句(
    CREATE
    ALTER
    DROP
    TRUNCATE
    )。 schema变更必须通过迁移文件进行;非常规的DDL操作会导致迁移历史与实际schema不一致。
  • 不要从预览或生产环境导出
    NETLIFY_DB_URL
    并使用客户端连接操作。任何非常规的schema变更都会导致迁移历史偏移。
唯一的例外情况是提供商切换时的一次性数据导入——请参阅
references/migration-from-extension.md
。除此特定流程外,规则是绝对的:schema变更必须通过迁移文件进行,迁移文件由部署流程自动应用。

Not the legacy "Netlify DB" extension

并非旧版"Netlify DB"扩展

The older Netlify DB extension (Beta) is deprecated. It is a separate product and must not be confused with Netlify Database. Do not recommend or install it for new projects.
Netlify Database (GA, recommended)Netlify DB extension (deprecated Beta)
Package
@netlify/database
@netlify/neon
Env var
NETLIFY_DB_URL
NETLIFY_DATABASE_URL
Setup
netlify database init
or install the package — auto-provisioned at deploy
Historically
netlify db init
on older CLI versions, with a claim into the user's Neon account; that flow is no longer reachable from the current CLI
StatusGADeprecated; new creation blocked as of April 2026
If an existing project is already using the
@netlify/neon
extension, keep it working and encourage the user to switch. See
references/legacy-extension.md
for recognition and coexistence, and
references/migration-from-extension.md
for the full switching process (also covers switching from other external Postgres providers).
旧版Netlify DB扩展(Beta版)已废弃。它是一个独立产品,切勿与Netlify Database混淆。请勿向新项目推荐或安装该扩展。
Netlify Database(GA,推荐)Netlify DB扩展(已废弃Beta版)
@netlify/database
@netlify/neon
环境变量
NETLIFY_DB_URL
NETLIFY_DATABASE_URL
设置方式
netlify database init
或安装包——部署时自动配置
历史上通过旧版CLI执行
netlify db init
,需申领用户的Neon账户;当前CLI已不再支持该流程
状态GA已废弃;2026年4月起禁止创建新实例
如果现有项目已在使用
@netlify/neon
扩展,请保持其运行并鼓励用户切换。识别与共存方法请参阅
references/legacy-extension.md
,完整切换流程请参阅
references/migration-from-extension.md
(也涵盖从其他外部Postgres提供商切换的场景)。

Provisioning

资源配置

The fastest path is
netlify database init
— an interactive setup that installs
@netlify/database
, lets the user pick Drizzle or raw SQL, writes
drizzle.config.ts
if needed, scaffolds a starter migration, applies it locally, and runs a sample query end-to-end:
bash
netlify database init           # interactive
netlify database init --yes     # accept defaults — for CI/agents
If you'd rather wire things up by hand, install the package directly:
bash
npm install @netlify/database
Either way, presence of
@netlify/database
in the dependency tree triggers provisioning on the next deploy. A database can also be created manually from the Netlify UI before first deploy.
最快的配置方式是执行
netlify database init
——交互式设置流程会安装
@netlify/database
(若选择则同时安装Drizzle)、编写
drizzle.config.ts
(如需)、生成初始迁移文件、在本地应用迁移,并运行示例查询完成端到端验证:
bash
netlify database init           # 交互式模式
netlify database init --yes     # 接受默认设置——适用于CI/自动化代理
如果你更喜欢手动配置,可以直接安装包:
bash
npm install @netlify/database
无论哪种方式,依赖树中存在
@netlify/database
都会触发下一次部署时的数据库配置。也可以在首次部署前,通过Netlify UI手动创建数据库。

Drizzle ORM (recommended path)

Drizzle ORM(推荐方案)

Drizzle is the recommended way to work with Netlify Database. Prefer Drizzle over writing raw SQL or hand-editing migration files — manual migrations are an edge case (see
references/migrations.md
).
Drizzle是操作Netlify Database的推荐方式。优先使用Drizzle而非编写原始SQL或手动编辑迁移文件——手动迁移属于边缘场景(请参阅
references/migrations.md
)。

Install

安装

bash
npm install @netlify/database drizzle-orm@beta
npm install -D drizzle-kit@beta
bash
npm install @netlify/database drizzle-orm@beta
npm install -D drizzle-kit@beta

Schema file

Schema文件

Create
db/schema.ts
. Define all tables here using Drizzle's schema builder.
typescript
// db/schema.ts
import { boolean, pgTable, serial, text, timestamp, varchar } from "drizzle-orm/pg-core";

export const items = pgTable("items", {
  id: serial().primaryKey(),
  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;
Use snake_case strings for column names (
"is_active"
,
"created_at"
) to match Postgres conventions. Drizzle variable names can be camelCase.
创建
db/schema.ts
,使用Drizzle的schema构建器定义所有表。
typescript
// db/schema.ts
import { boolean, pgTable, serial, text, timestamp, varchar } from "drizzle-orm/pg-core";

export const items = pgTable("items", {
  id: serial().primaryKey(),
  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;
列名使用蛇形命名法(
"is_active"
"created_at"
)以匹配Postgres惯例。Drizzle变量名可以使用驼峰命名法。

Drizzle client

Drizzle客户端

Create
db/index.ts
. The adapter on
drizzle-orm/netlify-db
picks the right driver for the runtime automatically.
typescript
// db/index.ts
import { drizzle } from "drizzle-orm/netlify-db";
import * as schema from "./schema";

export const db = drizzle({ schema });
The connection is configured automatically — no connection string needed. If your project uses native ESM with
.js
extensions on relative imports (
from "./schema.js"
), keep that style consistent here.
创建
db/index.ts
drizzle-orm/netlify-db
上的适配器会自动为运行时选择合适的驱动。
typescript
// db/index.ts
import { drizzle } from "drizzle-orm/netlify-db";
import * as schema from "./schema";

export const db = drizzle({ schema });
连接会自动配置——无需连接字符串。如果项目使用原生ESM且相对导入需要
.js
扩展名(如
from "./schema.js"
),请在此保持一致的风格。

Drizzle Kit config

Drizzle Kit配置

Create
drizzle.config.ts
at the project root. Set
out
to
netlify/database/migrations
— that's the directory the deploy applies migrations from:
typescript
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  dialect: "postgresql",
  schema: "./db/schema.ts",
  out: "netlify/database/migrations",
  migrations: { prefix: "timestamp" },
});
Default to
migrations: { prefix: "timestamp" }
.
Drizzle Kit's default sequential indices (
0000_
,
0001_
, …) collide whenever two pieces of work generate migrations in parallel — this happens to teams and to solo developers iterating on multiple branches. Timestamp prefixes keep filenames unique and order stable. If a project is already established on sequential prefixes, leave it alone, but expect collisions when working in parallel.
在项目根目录创建
drizzle.config.ts
。将
out
设置为
netlify/database/migrations
——这是部署流程应用迁移文件的目录:
typescript
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  dialect: "postgresql",
  schema: "./db/schema.ts",
  out: "netlify/database/migrations",
  migrations: { prefix: "timestamp" },
});
默认使用
migrations: { prefix: "timestamp" }
Drizzle Kit默认的序号前缀(
0000_
0001_
……)会在并行生成迁移时发生冲突——团队协作或开发者在多分支迭代时都会遇到这种情况。时间戳前缀可确保文件名唯一且顺序稳定。如果项目已使用序号前缀,可保持不变,但并行工作时需注意冲突问题。

Package scripts

包脚本

json
{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:migrate": "netlify database migrations apply"
  }
}
  • db:generate
    writes a new migration file under
    netlify/database/migrations/
    from the current schema.
  • db:migrate
    applies pending migrations to the local development database only, via the CLI. Hosted migrations (preview branches, production) are applied by the deploy — never by this script.
json
{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:migrate": "netlify database migrations apply"
  }
}
  • db:generate
    根据当前schema在
    netlify/database/migrations/
    目录下生成新的迁移文件。
  • db:migrate
    仅将待处理迁移应用到本地开发数据库,通过CLI执行。托管数据库(预览分支、生产环境)的迁移由部署流程处理——切勿使用此脚本操作。

Schema-change workflow

Schema变更流程

  1. Edit
    db/schema.ts
    .
  2. npm run db:generate
    — writes a new file into
    netlify/database/migrations/
    .
  3. Review the SQL.
  4. npm run db:migrate
    — applies it to the local development DB for testing.
  5. Commit the schema change and migration file together and push. The deploy applies the migration to the preview branch, then to production on publish.
  1. 编辑
    db/schema.ts
  2. 执行
    npm run db:generate
    ——在
    netlify/database/migrations/
    目录下生成新文件。
  3. 审查SQL内容。
  4. 执行
    npm run db:migrate
    ——将迁移应用到本地开发数据库进行测试。
  5. 同时提交schema变更和迁移文件并推送。部署流程会将迁移应用到预览分支,发布时再应用到生产环境。

Query patterns

查询示例

typescript
import { db } from "./db";
import { items } from "./db/schema";
import { eq, desc } from "drizzle-orm";

// Select all
const all = await db.select().from(items);

// Select with condition
const [one] = await db.select().from(items).where(eq(items.id, id)).limit(1);

// Ordering and limit
const recent = await db.select().from(items).orderBy(desc(items.createdAt)).limit(10);

// Insert
const [created] = await db.insert(items).values({ title: "New" }).returning();

// Update
const [updated] = await db.update(items).set({ title: "Updated" }).where(eq(items.id, id)).returning();

// Delete
await db.delete(items).where(eq(items.id, id));
Full migration workflow, expand-and-contract for breaking schema changes, and production DML migrations are in
references/migrations.md
.
typescript
import { db } from "./db";
import { items } from "./db/schema";
import { eq, desc } 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 recent = await db.select().from(items).orderBy(desc(items.createdAt)).limit(10);

// 插入数据
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));
完整的迁移流程、破坏性schema变更的扩展与收缩方法,以及生产环境DML迁移,请参阅
references/migrations.md

Native driver (when Drizzle isn't a fit)

原生驱动(不适用Drizzle时)

When a project wants raw SQL, uses a different query builder (Kysely, etc.), or has a library that needs a
pg.Pool
, use the native driver exposed by
@netlify/database
.
bash
npm install @netlify/database
typescript
import { getDatabase } from "@netlify/database";

const db = getDatabase();

// Tagged template — parameters are safely bound, not interpolated
const users = await db.sql`SELECT * FROM users WHERE active = ${true}`;

// Insert with RETURNING
const [user] = await db.sql`
  INSERT INTO users (name, email)
  VALUES (${name}, ${email})
  RETURNING *
`;

// Bulk insert
const rows = db.sql.values([
  ["Ada", "ada@example.com"],
  ["Bob", "bob@example.com"],
]);
await db.sql`INSERT INTO users (name, email) VALUES ${rows}`;
Transactions go through
db.pool
so
BEGIN
, the queries, and
COMMIT
/
ROLLBACK
all run on the same connection:
typescript
import { getDatabase } from "@netlify/database";

const db = getDatabase();
const client = await db.pool.connect();
try {
  await client.query("BEGIN");
  await client.query("INSERT INTO users (name, email) VALUES ($1, $2)", [name, email]);
  await client.query("INSERT INTO posts (author_id, title) VALUES ($1, $2)", [id, title]);
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();
}
For third-party tools that need a raw connection string, import
getConnectionString
from
@netlify/database
— but prefer
getDatabase()
for application code.
当项目需要使用原始SQL、其他查询构建器(如Kysely),或依赖库需要
pg.Pool
时,可使用
@netlify/database
提供的原生驱动。
bash
npm install @netlify/database
typescript
import { getDatabase } from "@netlify/database";

const db = getDatabase();

// 模板字符串语法——参数会安全绑定,而非直接插值
const users = await db.sql`SELECT * FROM users WHERE active = ${true}`;

// 带RETURNING的插入
const [user] = await db.sql`
  INSERT INTO users (name, email)
  VALUES (${name}, ${email})
  RETURNING *
`;

// 批量插入
const rows = db.sql.values([
  ["Ada", "ada@example.com"],
  ["Bob", "bob@example.com"],
]);
await db.sql`INSERT INTO users (name, email) VALUES ${rows}`;
事务通过
db.pool
执行,确保
BEGIN
、查询语句和
COMMIT
/
ROLLBACK
都在同一个连接上运行:
typescript
import { getDatabase } from "@netlify/database";

const db = getDatabase();
const client = await db.pool.connect();
try {
  await client.query("BEGIN");
  await client.query("INSERT INTO users (name, email) VALUES ($1, $2)", [name, email]);
  await client.query("INSERT INTO posts (author_id, title) VALUES ($1, $2)", [id, title]);
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();
}
对于需要原始连接字符串的第三方工具,可从
@netlify/database
导入
getConnectionString
——但应用代码优先使用
getDatabase()

Manual migrations

手动迁移

With the native driver, scaffold migration files via the CLI:
bash
netlify database migrations new -d "create users table"
This creates
netlify/database/migrations/<prefix>_<slug>/migration.sql
and prompts for the numbering scheme if it can't be detected from existing files. Open the file and write the SQL. The CLI auto-detects an existing scheme; for new projects it'll ask — choose
timestamp
unless you have a reason not to.
You can also write the file by hand if you prefer. Two layouts are supported:
  • Flat:
    netlify/database/migrations/<prefix>_<slug>.sql
  • Subdirectory:
    netlify/database/migrations/<prefix>_<slug>/migration.sql
    (what
    migrations new
    produces)
In both,
<prefix>
is digits (timestamp like
20260417143022
or sequential like
0001
) and
<slug>
is lowercase letters, numbers, hyphens, or underscores. Files apply in lexicographic order. See
references/migrations.md
.
Once a migration has been applied to any database, never modify it — roll forward with a new migration instead.
使用原生驱动时,可通过CLI生成迁移文件:
bash
netlify database migrations new -d "create users table"
这会创建
netlify/database/migrations/<prefix>_<slug>/migration.sql
,如果无法从现有文件检测到编号方案,会提示用户选择。打开文件并编写SQL。CLI会自动检测现有方案;新项目会提示选择——除非有特殊原因,否则选择
timestamp
你也可以手动编写文件,支持两种结构:
  • 扁平结构:
    netlify/database/migrations/<prefix>_<slug>.sql
  • 子目录结构:
    netlify/database/migrations/<prefix>_<slug>/migration.sql
    migrations new
    命令生成的结构)
两种结构中,
<prefix>
为数字(如时间戳
20260417143022
或序号
0001
),
<slug>
为小写字母、数字、连字符或下划线。文件按字典序应用。详情请参阅
references/migrations.md
一旦迁移已应用到任何数据库,切勿修改——需通过新的迁移文件向前兼容。

Connection — don't reach for the env var

连接方式——不要直接使用环境变量

NETLIFY_DB_URL
is set automatically across builds, functions, edge functions, and local dev. Use the
getDatabase()
/
getConnectionString()
helpers above rather than reading it directly — only reach for the raw env var for third-party tools that demand a bare string.
NETLIFY_DB_URL
is intentionally different from the legacy extension's
NETLIFY_DATABASE_URL
. The two coexist so a project mid-migration doesn't break. Don't rename between them.
NETLIFY_DB_URL
会在构建、函数、边缘函数和本地开发环境中自动设置。请使用上述
getDatabase()
/
getConnectionString()
工具函数,而非直接读取环境变量——仅在第三方工具要求提供纯字符串时,才使用原始环境变量。
NETLIFY_DB_URL
与旧版扩展的
NETLIFY_DATABASE_URL
有意区分。两者可共存,避免迁移中的项目出现故障。请勿在两者间重命名。

Preview branching

预览分支

Each deploy preview runs against its own database branch forked from production data. Schema and data changes in a preview do not affect production until the branch is merged and published. This means:
  • Migrations run against the preview branch first — failures fail the preview, not production.
  • Ad-hoc edits in a preview (via the Netlify UI data browser or a direct client) do not propagate to production. Always express production changes as migrations.
每个部署预览都会运行在独立的数据库分支上,该分支从生产环境数据分叉而来。预览分支中的schema和数据变更,在分支合并并发布前不会影响生产环境。这意味着:
  • 迁移会先在预览分支上运行——失败会导致预览部署失败,不会影响生产环境。
  • 在预览分支中的临时编辑(通过Netlify UI数据浏览器或直接客户端)不会同步到生产环境。生产环境变更必须始终通过迁移文件表达。

Production data changes — write a DML migration

生产环境数据变更——编写DML迁移

When a user asks for data changes that should land in production (seed data, backfills, one-off cleanups, CSV imports), do not connect to the production database and run queries. Generate a DML migration in
netlify/database/migrations/
(SQL
INSERT
/
UPDATE
/
DELETE
, or a Drizzle-generated equivalent). Tell the user you created a data migration and that merging to production will apply it. Let them verify in the preview branch first.
If the request is ambiguous ("update this record"), confirm that the user wants a production migration rather than a preview-only edit. See
references/migrations.md
.
当用户需要对生产环境进行数据变更(种子数据、回填、一次性清理、CSV导入)时,不要连接到生产数据库并直接运行查询。在
netlify/database/migrations/
目录下生成DML迁移文件(SQL的
INSERT
/
UPDATE
/
DELETE
语句,或Drizzle生成的等效内容)。告知用户你已创建数据迁移,合并到生产环境分支时会自动应用。让他们先在预览分支中验证。
如果需求不明确(如"更新这条记录"),请确认用户需要的是生产环境迁移,而非仅预览分支的临时编辑。详情请参阅
references/migrations.md

Netlify CLI commands for Netlify Database

Netlify CLI数据库命令

The CLI ships a complete database surface under
netlify database
(alias:
netlify db
). Requires CLI 26.0.0+. Most commands accept
--json
for machine-readable output — useful when scripting or reading results from an agent.
Netlify CLI在
netlify database
(别名:
netlify db
)命令下提供完整的数据库操作能力,要求CLI 26.0.0+。大多数命令支持
--json
参数以输出机器可读格式——适用于脚本或自动化代理读取结果。

netlify database init

netlify database init

Interactive bootstrap: installs
@netlify/database
(and Drizzle if chosen), writes
drizzle.config.ts
, scaffolds and applies a starter migration, and runs a sample query. Use
--yes
for non-interactive mode.
交互式引导流程:安装
@netlify/database
(若选择则同时安装Drizzle)、编写
drizzle.config.ts
、生成并应用初始迁移文件、运行示例查询。使用
--yes
参数进入非交互式模式。

netlify database status

netlify database status

Reports whether the database is enabled, whether
@netlify/database
is installed, the connection string for the active branch, and the applied/pending/missing/out-of-order migrations. Defaults to the local development database — pass
--branch <name>
to target a remote preview or production branch.
bash
netlify database status                          # local
netlify database status --branch my-feature      # remote branch
netlify database status --json
netlify database status --show-credentials       # include username/password in connection string
报告数据库是否启用、
@netlify/database
是否已安装、当前分支的连接字符串,以及已应用/待处理/缺失/顺序错误的迁移。默认针对本地开发数据库——传递
--branch <name>
参数可指定远程预览或生产分支。
bash
netlify database status                          # 本地数据库
netlify database status --branch my-feature      # 远程分支
netlify database status --json
netlify database status --show-credentials       # 在连接字符串中包含用户名/密码

netlify database connect

netlify database connect

Connects to the database. Defaults to an interactive REPL — for agent and script use, always pass
--query
for one-shot execution:
bash
undefined
连接到数据库。默认进入交互式REPL——对于自动化代理和脚本,请始终传递
--query
参数执行单次查询:
bash
undefined

List tables

列出所有表

netlify database connect --query "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"
netlify database connect --query "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"

Inspect columns

查看列信息

netlify database connect --query "SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name = 'items'"
netlify database connect --query "SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name = 'items'"

JSON output

JSON格式输出

netlify database connect --query "SELECT * FROM items LIMIT 10" --json
netlify database connect --query "SELECT * FROM items LIMIT 10" --json

Get connection details only (no query)

仅获取连接详情(不执行查询)

netlify database connect --json

**Never run DDL (`CREATE`, `ALTER`, `DROP`, `TRUNCATE`) through `netlify database connect`, `psql`, or any other direct connection.** Schema changes go through migration files — out-of-band DDL drifts the migration history from the actual schema.
netlify database connect --json

**切勿通过`netlify database connect`、`psql`或任何其他直接连接方式执行DDL语句(`CREATE`、`ALTER`、`DROP`、`TRUNCATE`)。** schema变更必须通过迁移文件进行——非常规的DDL操作会导致迁移历史与实际schema不一致。

netlify database migrations new

netlify database migrations new

Scaffolds a new migration file as
netlify/database/migrations/<prefix>_<slug>/migration.sql
. Auto-detects the numbering scheme from existing files; prompts when undetermined.
bash
netlify database migrations new -d "add users table"
netlify database migrations new -d "add users table" --scheme timestamp
生成新的迁移文件,路径为
netlify/database/migrations/<prefix>_<slug>/migration.sql
。自动从现有文件检测编号方案;无法检测时会提示用户选择。
bash
netlify database migrations new -d "add users table"
netlify database migrations new -d "add users table" --scheme timestamp

netlify database migrations apply

netlify database migrations apply

Applies pending migrations to the local development database. The CLI does not apply migrations to the local DB automatically when
netlify dev
starts — you run this command yourself when you're ready. Hosted databases (preview branches, production) are handled by the deploy.
bash
netlify database migrations apply
netlify database migrations apply --to <name>   # apply up to a specific migration
将待处理迁移应用到本地开发数据库。启动
netlify dev
时,CLI不会自动应用本地数据库迁移——需手动运行此命令。托管数据库(预览分支、生产环境)的迁移由部署流程处理。
bash
netlify database migrations apply
netlify database migrations apply --to <name>   # 应用到指定迁移为止

netlify database migrations pull

netlify database migrations pull

Downloads migration files from a remote branch (defaults to
production
) and overwrites local files. Useful when local migration history has drifted from production — for example, after another contributor shipped a migration you don't have locally.
bash
netlify database migrations pull                  # from production
netlify database migrations pull --branch staging # from a specific branch
netlify database migrations pull --branch         # from your current local git branch
netlify database migrations pull --force          # skip the overwrite confirmation
从远程分支(默认
production
)下载迁移文件并覆盖本地文件。适用于本地迁移历史与生产环境不一致的场景——例如,其他贡献者已发布你本地未有的迁移。
bash
netlify database migrations pull                  # 从生产环境拉取
netlify database migrations pull --branch staging # 从指定分支拉取
netlify database migrations pull --branch         # 从当前本地Git分支拉取
netlify database migrations pull --force          # 跳过覆盖确认

netlify database migrations reset

netlify database migrations reset

Deletes local migration files that have not yet been applied to the target database. Applied migrations and their data are left alone — the command can't undo something already applied.
Typical use: you generated a migration, realized it was wrong, and want to start over. Run
reset
, update
db/schema.ts
, then
npm run db:generate
produces a fresh migration.
bash
netlify database migrations reset                  # against local dev DB
netlify database migrations reset --branch <name>  # against a remote branch
删除尚未应用到目标数据库的本地迁移文件。已应用的迁移及其数据会保留——此命令无法撤销已应用的迁移。
典型场景:你生成了一个迁移,发现有误,想重新开始。运行
reset
,更新
db/schema.ts
,然后执行
npm run db:generate
生成新的迁移文件。
bash
netlify database migrations reset                  # 针对本地开发数据库
netlify database migrations reset --branch <name>  # 针对远程分支

netlify database reset

netlify database reset

Wipes the local development database — drops all schemas and tables. Only affects the local DB; never touches preview branches or production. Use this when you want to replay all migrations from scratch.
bash
netlify database reset
清空本地开发数据库——删除所有schema和表。仅影响本地数据库;绝不会触及预览分支或生产环境。适用于需要重新运行所有迁移的场景。
bash
netlify database reset

Iterating on migrations

迁移迭代

When a migration you generated needs to change, what you do depends on whether it's been applied anywhere yet:
  • Already applied to any database (local dev DB, a preview branch, or production) → treat as immutable. Roll forward with a new migration that applies the correction.
  • Only on disk (not yet applied anywhere) → don't edit the SQL or snapshot files by hand. Run
    netlify database migrations reset
    , update
    db/schema.ts
    , then re-run
    npm run db:generate
    . Hand-editing desyncs Drizzle Kit's internal state and tends to produce broken migrations on the next generate.
当你生成的迁移需要修改时,操作方式取决于它是否已应用到任何数据库:
  • 已应用到任何数据库(本地开发数据库、预览分支或生产环境)→ 视为不可变。需通过新的迁移文件向前兼容,修正问题。
  • 仅存在于磁盘(尚未应用到任何数据库)→ 不要手动编辑SQL或快照文件。运行
    netlify database migrations reset
    ,更新
    db/schema.ts
    ,然后重新执行
    npm run db:generate
    生成新的迁移文件。手动编辑会导致Drizzle Kit内部状态不同步,下次生成时可能产生损坏的迁移。

Local development

本地开发

netlify dev
runs the project against a local Postgres-compatible database — no remote connection, no risk of touching production. Use
netlify database migrations apply
to apply pending migrations locally,
netlify database connect
to query, and
netlify database reset
to wipe and replay. See
references/local-dev.md
.
netlify dev
会在本地兼容Postgres的数据库上运行项目——无需远程连接,不会有触及生产环境的风险。使用
netlify database migrations apply
在本地应用待处理迁移,
netlify database connect
执行查询,
netlify database reset
清空并重新运行所有迁移。详情请参阅
references/local-dev.md

Common mistakes

常见错误

  1. Forgetting the
    @beta
    dist-tag.
    drizzle-orm
    and
    drizzle-kit
    must be installed as
    @beta
    . The
    latest
    releases lack the
    drizzle-orm/netlify-db
    adapter.
  2. Wrong migration output directory. Drizzle Kit defaults to
    drizzle/
    . Set
    out: "netlify/database/migrations"
    in
    drizzle.config.ts
    — migrations outside that directory are not applied by the deploy.
  3. Writing raw
    CREATE TABLE
    when using Drizzle.
    The schema file is the source of truth. Define tables in
    db/schema.ts
    and generate migrations.
  4. Running
    drizzle-kit migrate
    or
    push
    against a hosted DB.
    Never. The deploy applies migrations. For local, use
    netlify database migrations apply
    instead.
  5. Using
    netlify database connect
    to change schema.
    Schema changes go through migration files — never DDL through
    connect
    or any direct connection.
  6. Misunderstanding
    netlify database migrations reset
    .
    It only deletes unapplied files. It cannot undo an applied migration — for that, roll forward with a new migration.
  7. Assuming
    netlify dev
    applies migrations automatically.
    It doesn't — only the deploy does. Run
    netlify database migrations apply
    locally yourself.
  1. 忘记添加
    @beta
    标签。
    drizzle-orm
    drizzle-kit
    必须安装
    @beta
    版本。
    latest
    版本缺少
    drizzle-orm/netlify-db
    适配器。
  2. 迁移输出目录错误。 Drizzle Kit默认输出到
    drizzle/
    。需在
    drizzle.config.ts
    中设置
    out: "netlify/database/migrations"
    ——该目录外的迁移不会被部署流程应用。
  3. 使用Drizzle时编写原始
    CREATE TABLE
    语句。
    schema文件是唯一可信源。需在
    db/schema.ts
    中定义表,然后生成迁移文件。
  4. 针对托管数据库运行
    drizzle-kit migrate
    push
    绝对禁止。迁移由部署流程自动应用。本地数据库请使用
    netlify database migrations apply
  5. 使用
    netlify database connect
    修改schema。
    schema变更必须通过迁移文件进行——绝不要通过
    connect
    或任何直接连接执行DDL语句。
  6. 误解
    netlify database migrations reset
    它仅删除未应用的文件,无法撤销已应用的迁移——如需撤销,需通过新的迁移文件向前兼容。
  7. 认为
    netlify dev
    会自动应用迁移。
    不会——只有部署流程会自动应用。需手动运行
    netlify database migrations apply
    处理本地数据库。