Overview
SmartEat AI uses Alembic for database migrations. Alembic tracks schema changes through version-controlled migration scripts, allowing you to evolve the database structure safely across environments.Prerequisites
Before working with migrations, ensure:- PostgreSQL database is running
- Database connection string is configured in
.env - All model changes are committed to SQLAlchemy models in
backend/app/models/
Configuration
Alembic configuration is defined in two files:alembic.ini
Located atbackend/alembic.ini, this file contains Alembic settings:
env.py
Located atbackend/alembic/env.py, this file configures how Alembic connects to your database:
The
DATABASE_URL is automatically read from your environment variables, so you don’t need to hardcode database credentials.Common Migration Commands
View Migration History
Check the current migration state and history:Creating New Migrations
When you modify database models, create a new migration:Modify your models
Edit the SQLAlchemy models in
backend/app/models/. For example, adding a field to the User model:Generate migration
Use Alembic’s autogenerate feature to detect changes:This creates a new migration file in
backend/alembic/versions/ with a revision ID and timestamp.Review the migration
Open the generated file in
backend/alembic/versions/ and verify the changes:Always review autogenerated migrations. Alembic may miss some changes or generate suboptimal SQL. Edit the migration if needed.
Applying Migrations
Upgrade to the latest version:Rolling Back Migrations
Downgrade one migration:Be careful with downgrades in production! Rolling back migrations can result in data loss, especially if columns or tables are dropped.
Migration File Structure
Migration files follow this structure:Manual Migrations
For complex schema changes, create a blank migration and write custom logic:Common Operations
Adding a Column
Creating a Table
Adding an Index
Modifying a Column
Best Practices
Important migration guidelines:
- Always review autogenerated migrations before applying
- Test migrations in development before production
- Keep migrations small and focused on single changes
- Never edit applied migrations - create new ones instead
- Write descriptive migration messages
- Always implement both
upgrade()anddowngrade()functions - Backup your database before running migrations in production
Troubleshooting
Migration out of sync
If Alembic reports the database is out of sync:Multiple heads detected
If you have branching migration history:Reset database completely
To start fresh (development only):Migration Workflow
Review migration file
Open the generated file in
backend/alembic/versions/ and verify the SQL operationsSee Also
- Database Schema - Understanding the database structure
- Seeding Data - Populating the database with initial data
- Alembic Documentation - Official Alembic docs
