ترحيلات قواعد البيانات باستخدام Alembic
طوّر مخطط SQLAlchemy بأمان مع مرور الوقت باستخدام Alembic: هيّئ الترحيلات، وأنشئ المراجعات تلقائيًا، وطبّق التغييرات أو تراجع عنها في مشروع FastAPI.
ترحيلات قواعد البيانات باستخدام Alembic درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 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 alembicPointing 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.metadataSetting 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 headRolling Back
Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.
alembic downgrade -1Revision 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 headand reverted withdowngrade. - Followed best practices for reviewing and sequencing migrations.
الأسئلة الشائعة
هل درس «ترحيلات قواعد البيانات باستخدام Alembic» مجاني؟
نعم — نص درس «ترحيلات قواعد البيانات باستخدام Alembic» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «ترحيلات قواعد البيانات باستخدام Alembic»؟
طوّر مخطط SQLAlchemy بأمان مع مرور الوقت باستخدام Alembic: هيّئ الترحيلات، وأنشئ المراجعات تلقائيًا، وطبّق التغييرات أو تراجع عنها في مشروع FastAPI. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 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 يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- أساسيات ORM في SQLAlchemy
- ربط FastAPI بـ PostgreSQL
- عمليات CRUD باستخدام SQLAlchemy
- ترحيلات قواعد البيانات باستخدام Alembic