Alembic Migrations
🚀 Managing Database Migrations with Alembic
Alembic is a lightweight database migration tool used to manage schema changes over time.
Cognee uses Alembic for database schema migrations. This guide shows you how to handle migrations in your Cognee application.
Running Migrations
To migrate your database to the latest version, go to your cognee directory and execute:
alembic upgrade head
To revert to a previous migration, use:
alembic downgrade -1
You can also migrate to a specific migration using its revision ID:
alembic upgrade <revision_id>
Check the current migration version with:
alembic current
or
SELECT * FROM alembic_version;
in your postgres instance.
Creating Migration Scripts
Automatic Migrations
Alembic can automatically generate migrations by comparing your database schema with SQLAlchemy models:
alembic revision --autogenerate -m "Your migration message"
This command generates a migration script in the alembic/versions
directory, containing schema changes based on your SQLAlchemy models.
You can also find the existing migrations between different versions in the same directory.
Handling Manual Adjustments
Sometimes Alembic cannot automatically detect certain schema changes. This typically happens for example when:
- Renaming a column
- Adding/Changing enum values
- Complex data transformations
- Custom SQL commands
In these scenarios, you’ll need to manually edit the generated migration script to define the exact changes.
Example of manually adjusting a migration script:
revision: str = "8057ae7329c2" # Unique identifier for the migration
down_revision: Union[str, None] = None # Previous migration revision ID
branch_labels: Union[str, Sequence[str], None] = None # Optional labels for migration branching
depends_on: Union[str, Sequence[str], None] = None # Specify migrations that must run prior
def upgrade():
op.alter_column('user', 'fullname', new_column_name='full_name')
def downgrade():
op.alter_column('user', 'full_name', new_column_name='fullname')
Explanation:
revision
: A unique identifier automatically generated by Alembic, representing this migration script.down_revision
: Indicates the migration script this one builds upon. Set toNone
if this is the initial migration.branch_labels
: Allows assigning labels to support branching in complex migration scenarios.depends_on
: Specifies dependencies, ensuring migrations run in the correct order if they depend on others.
Reviewing Migration History
Check your migration history easily with:
alembic history
This will list all migrations with their revision IDs and descriptions.
Configuration
Alembic is configured to work seamlessly with your cognee .env
file.
Best Practices
- Always review auto-generated migration scripts before applying.
- Keep migration files version-controlled.
- Regularly back up your database before performing major schema migrations.