tuttle
tuttle copied to clipboard
Data model migration using alembic
To migrate a data model defined with SQLModel to a new version using Alembic, follow these steps:
-
Install Alembic:
pip install alembic
-
Initialize Alembic in your project directory:
alembic init alembic
This command will create an
alembic
folder containing your migration scripts and analembic.ini
configuration file. -
Configure Alembic:
Open
alembic.ini
and set the database URL to your actual database connection string:sqlalchemy.url = <your_database_connection_string>
-
Create a
env.py
file:In the
alembic
folder, open theenv.py
file, and modify it to import your SQLModel metadata and use it as the Alembic target metadata. Add these lines to the top of the file:from sqlalchemy.ext.asyncio import create_async_engine from sqlmodel import SQLModel from your_module import YourModel
Replace
your_module
with the name of the module containing your SQLModel classes andYourModel
with your actual model class names.Next, find the following line:
target_metadata = None
And change it to:
target_metadata = SQLModel.metadata
-
Create a new migration:
Generate a migration script by running the following command:
alembic revision --autogenerate -m "Your migration message"
Replace
"Your migration message"
with a brief description of the changes being made to the schema. This command will create a new migration script in thealembic/versions
folder. -
Review the migration script:
Inspect the generated migration script in the
alembic/versions
folder to ensure that the generated operations match your intended changes. Modify the script as needed. -
Apply the migration:
Run the following command to apply the migration to your database:
alembic upgrade head
This will update your database schema to the latest version.
-
Manage migrations:
To manage your migrations, you can use additional Alembic commands such as:
- alembic history to view the migration history
- alembic downgrade
to downgrade your schema to a specific revision - alembic current to show the current revision of your schema
For more information, refer to the official Alembic documentation.