数据库迁移 Script
你将构建什么
级数的 迁移 scripts 那个开始使用基础用户表 and evolve 它 over three versions: 添加列, 创建索引, and 添加新 表.
学习目标
- 编写上 and 下迁移 scripts
- Use ALTER TABLE 到添加 and 移除列
- 创建索引 in 迁移
- 理解如何 Schema evolve over 时间
前置要求
- CREATE TABLE 语法
- ALTER TABLE 基础
- 理解的 索引
步骤
- 1
迁移 001: 创建用户表
编写初始迁移那个创建基础用户表 使用 id, name, and email.
代码-- Migration 001: Initial users table -- Up CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL ); -- Down DROP TABLE users;预期结果
用户表 是创建使用 three 基础列.
- 2
迁移 002: 添加 timestamps and 唯一 email
In 其次迁移, 添加 created_at and updated_at 列, and 添加唯一 constraint on email.
代码-- Migration 002: Add timestamps and unique email -- Up ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT NOW(); ALTER TABLE users ADD COLUMN updated_at TIMESTAMP DEFAULT NOW(); ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email); -- Down ALTER TABLE users DROP CONSTRAINT users_email_unique; ALTER TABLE users DROP COLUMN updated_at; ALTER TABLE users DROP COLUMN created_at;预期结果
Two timestamp 列 and 唯一 constraint 是添加.
- 3
迁移 003: 添加索引 and profiles 表
In 第三迁移, 创建索引 on email for 快 lookups, and 添加 profiles 表链接到 用户.
代码-- Migration 003: Add email index and profiles -- Up CREATE INDEX idx_users_email ON users(email); CREATE TABLE profiles ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), bio TEXT, avatar_url TEXT ); -- Down DROP TABLE profiles; DROP INDEX idx_users_email;预期结果
索引 and related profiles 表是 创建.
- 4
验证最终 Schema
之后所有迁移, 验证 Schema 通过描述用户表 and inserting 用户使用 profile.
代码-- Check the schema \d users -- Insert a user and profile INSERT INTO users (name, email) VALUES ('Ada', '[email protected]'); INSERT INTO profiles (user_id, bio) VALUES (1, 'Mathematician and programmer'); -- Query with join SELECT u.name, u.email, p.bio FROM users u LEFT JOIN profiles p ON p.user_id = u.id;预期结果
最终 Schema 有所有列, constraints, and 索引从 迁移.
- 5
添加索引优化查询
为频繁查询的列创建索引,提升查询性能。索引是数据库性能优化的首要手段,但需注意写操作的开销。
代码-- Create indexes on frequently filtered columns CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_orders_user_id ON orders(user_id); CREATE INDEX idx_orders_created_at ON orders(created_at DESC); -- Verify the index is used EXPLAIN SELECT * FROM orders WHERE user_id = 42;预期结果
EXPLAIN 输出显示使用 idx_orders_user_id 索引扫描而非全表扫描。
自己动手试试
你学到了什么
你 wrote versioned 迁移 scripts 使用上 and 下方向, evolving Schema over 时间 — 相同方法 used 通过 Flyway, Alembic, Prisma Migrate, and other 迁移 tools.
相关资源
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。