Skip to content

数据库 Seeding

Populate 数据库使用初始 and 测试数据 using seed scripts and fixtures.

你将学到

  • 什么 seeding 是 and 为什么它 是必要 for development
  • 编写 seed scripts 使用 INSERT 语句
  • Using fixtures and faker 库 for 测试数据
  • Idempotent seeding — safe 到运行 repeatedly
  • Seeding for development 对比 production 环境

概念讲解

什么是数据填充?

Seeding 是 the process of populating a database with initial data — reference data, demo data, or test data. When a new developer joins the team, they create the database schema and run the seed script to have a working database with realistic data. Seeding is also used in automated tests to set up a known state before each test run.

Reference Data vs Demo Data

Reference data is required for the application to function — a list of countries, currencies, user roles, or product categories. This data is part of the schema and should be seeded in all environments. Demo data is sample data for development and testing — fake users, sample orders, test products. This should only be seeded in development and staging, never in production.

Writing Seed Scripts

A seed script is typically a SQL file or a program (Node.js, Python) that inserts rows. For reference data, write explicit INSERT statements with known values. For demo data, use a faker library to generate realistic random data — names, emails, addresses, dates. Generate enough data to test pagination, search, and performance (e.g. 10,000 users, 100,000 orders).

Idempotent Seeding

A seed script should be idempotent — safe to run multiple times without creating duplicates. Use INSERT ... ON CONFLICT DO NOTHING (PostgreSQL) or INSERT IGNORE (MySQL) to skip existing rows. Alternatively, start the script with TRUNCATE to clear the table before inserting. Idempotency lets you re-seed after schema changes without manual cleanup.

Seeding in Practice

Most frameworks have a seeding system: Rails uses db/seeds.rb, Django uses data migrations or management commands, Prisma uses prisma db seed, Drizzle ORM has seed scripts. The pattern is the same: define the data in code, run a command, and the database is populated. Keep seed scripts in version control alongside the schema.

示例代码

              -- Reference data: user roles (idempotent)
INSERT INTO roles (name, description) VALUES
  ('admin',    'Full access to all features'),
  ('editor',   'Can edit content'),
  ('viewer',   'Read-only access')
ON CONFLICT (name) DO NOTHING;

-- Reference data: product categories
INSERT INTO categories (name, slug) VALUES
  ('Electronics', 'electronics'),
  ('Books',       'books'),
  ('Clothing',    'clothing')
ON CONFLICT (slug) DO NOTHING;

-- Demo data: sample users (idempotent with fixed IDs)
INSERT INTO users (id, name, email, role_id) VALUES
  (1, 'Ada Lovelace',  '[email protected]',  1),
  (2, 'Alan Turing',   '[email protected]', 2),
  (3, 'Grace Hopper',  '[email protected]', 2)
ON CONFLICT (id) DO UPDATE SET
  name  = EXCLUDED.name,
  email = EXCLUDED.email;

-- Demo data: sample products
INSERT INTO products (name, price, category_id, in_stock) VALUES
  ('Wireless Mouse',  29.99, 1, TRUE),
  ('SQL Book',        39.99, 2, TRUE),
  ('Cotton T-Shirt',  19.99, 3, FALSE)
ON CONFLICT DO NOTHING;
            

Idempotent seed script: 引用数据 (roles, 分类) and demo 数据 (用户, products) using ON CONFLICT 到 avoid duplicates on re-运行.

动手试一试

常见错误

错误写法

运行 demo seed 数据 in production

正确做法

Separate 引用数据 (需要 in 所有环境) 从 demo 数据 (development 仅). Use 环境检查到 prevent demo 数据从 运行 in production.

错误写法

非-idempotent seeds 那个创建 duplicates on re-运行

正确做法

Use ON CONFLICT DO NOTHING or ON CONFLICT DO UPDATE, or TRUNCATE 之前 inserting. Seeds 应该是 safe 到运行多个次数.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误