-
-
Couldn't load subscription status.
- Fork 13
Description
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
alembicfolder containing your migration scripts and analembic.iniconfiguration file. -
Configure Alembic:
Open
alembic.iniand set the database URL to your actual database connection string:sqlalchemy.url = <your_database_connection_string>
-
Create a
env.pyfile:In the
alembicfolder, open theenv.pyfile, 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 YourModelReplace
your_modulewith the name of the module containing your SQLModel classes andYourModelwith 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/versionsfolder. -
Review the migration script:
Inspect the generated migration script in the
alembic/versionsfolder 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.