Alembic ile Veritabanı Geçişleri
Alembic kullanarak SQLAlchemy şemanızı zaman içinde güvenle geliştirin: geçişleri başlatın, düzeltmeleri otomatik oluşturun ve değişiklikleri bir FastAPI projesinde uygulayın veya geri alın.
Alembic ile Veritabanı Geçişleri, CoddyKit'te ücretsiz bir FastAPI Backend Development Bootcamp dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, FastAPI Backend Development Bootcamp öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. FastAPI Backend Development Bootcamp kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Alembic ile Veritabanı Geçişleri” dersi ücretsiz mi?
Evet — “Alembic ile Veritabanı Geçişleri” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve FastAPI Backend Development Bootcamp kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. FastAPI Backend Development Bootcamp kursu toplamda 4 dersten oluşur.
“Alembic ile Veritabanı Geçişleri” dersinde ne öğreneceğim?
Alembic kullanarak SQLAlchemy şemanızı zaman içinde güvenle geliştirin: geçişleri başlatın, düzeltmeleri otomatik oluşturun ve değişiklikleri bir FastAPI projesinde uygulayın veya geri alın. FastAPI Backend Development Bootcamp ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
FastAPI Backend Development Bootcamp öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te FastAPI Backend Development Bootcamp, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“Alembic ile Veritabanı Geçişleri” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu FastAPI Backend Development Bootcamp dersinde kod yazıp çalıştırabilir miyim?
Evet. Her FastAPI Backend Development Bootcamp dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- SQLAlchemy ORM Temelleri
- FastAPI'yi PostgreSQL'e Bağlama
- SQLAlchemy ile CRUD İşlemleri
- Alembic ile Veritabanı Geçişleri