FastAPI Backend Development Bootcamp · บทเรียน

การย้ายฐานข้อมูลด้วย Alembic

พัฒนาสคีมา SQLAlchemy อย่างปลอดภัยเมื่อเวลาผ่านไปด้วย Alembic ตั้งค่าการย้าย สร้างการแก้ไขโดยอัตโนมัติ และนำการเปลี่ยนแปลงไปใช้หรือย้อนกลับในโครงการ FastAPI

บทเรียน 4 จาก 413 ขั้นตอน

การย้ายฐานข้อมูลด้วย Alembic เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Migrations

Your database schema changes as your app grows: new columns, tables, and indexes. Migrations are versioned, repeatable scripts that evolve the schema without losing data. Alembic is the standard tool for SQLAlchemy.

create_all Is Not Enough

Base.metadata.create_all() creates missing tables but never alters existing ones. It cannot add a column to a populated table or track history. Production needs real migrations.

Installing and Initializing

Install Alembic and scaffold its folder. This creates an alembic/ directory and alembic.ini.

pip install alembic
alembic init alembic

Pointing Alembic at Your Models

In alembic/env.py, set target_metadata to your SQLAlchemy Base.metadata so autogenerate can compare models to the live schema.

from app.database import Base
from app import models  # ensure models are imported

target_metadata = Base.metadata

Setting the Database URL

Configure the connection string. Reading it from an env var keeps secrets out of source control.

import os
config.set_main_option('sqlalchemy.url', os.environ['DATABASE_URL'])

Autogenerating a Revision

Alembic compares your models to the database and writes a migration script with the differences.

alembic revision --autogenerate -m 'add email to users'

Anatomy of a Migration

Each script has upgrade() and downgrade(). Upgrade applies the change; downgrade reverses it. Always review autogenerated code before running it.

def upgrade():
    op.add_column('users', sa.Column('email', sa.String(), nullable=True))

def downgrade():
    op.drop_column('users', 'email')

Applying Migrations

Run upgrade head to apply all pending migrations up to the latest revision.

alembic upgrade head

Rolling Back

Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.

alembic downgrade -1

Revision Chain Mental Model

Migrations form a linked list: each revision records its down_revision. Alembic walks the chain to know what to apply. Here is the idea in plain Python.

revisions = [
    {'id': 'a1', 'down': None},
    {'id': 'b2', 'down': 'a1'},
    {'id': 'c3', 'down': 'b2'},
]
order = []
cur = 'c3'
by_id = {r['id']: r for r in revisions}
while cur:
    order.append(cur)
    cur = by_id[cur]['down']
print(list(reversed(order)))

Migration Best Practices

Keep migrations safe:

  • Review autogenerated scripts; they miss some changes (e.g. column renames).
  • Run migrations in CI/CD before deploying code.
  • Make additive changes first, remove old columns in a later release.
  • Never edit an already-applied migration; create a new one.

Quick Check

Why is Base.metadata.create_all() insufficient for evolving a production schema?

Recap

You added safe schema evolution:

  • Initialized Alembic and wired it to your models and DB URL.
  • Autogenerated revisions with upgrade() / downgrade().
  • Applied with upgrade head and reverted with downgrade.
  • Followed best practices for reviewing and sequencing migrations.
เริ่มต้นได้ฟรี

เรียนรู้ FastAPI Backend Development Bootcamp ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
21
บทเรียน
84

คำถามที่พบบ่อย

บทเรียน “การย้ายฐานข้อมูลด้วย Alembic” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การย้ายฐานข้อมูลด้วย Alembic” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การย้ายฐานข้อมูลด้วย Alembic”

พัฒนาสคีมา SQLAlchemy อย่างปลอดภัยเมื่อเวลาผ่านไปด้วย Alembic ตั้งค่าการย้าย สร้างการแก้ไขโดยอัตโนมัติ และนำการเปลี่ยนแปลงไปใช้หรือย้อนกลับในโครงการ FastAPI คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การย้ายฐานข้อมูลด้วย Alembic” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐาน ORM ของ SQLAlchemy
  2. การเชื่อมต่อ FastAPI กับ PostgreSQL
  3. การทำงาน CRUD ด้วย SQLAlchemy
  4. การย้ายฐานข้อมูลด้วย Alembic
← กลับไปที่ FastAPI Backend Development Bootcamp