tuttle-dev / tuttle

🪰 Tuttle - time and money management for freelancers
GNU General Public License v3.0
61 stars 12 forks source link

Data model migration using alembic #228

Open clstaudt opened 1 year ago

clstaudt commented 1 year ago

To migrate a data model defined with SQLModel to a new version using Alembic, follow these steps:

  1. Install Alembic:

    pip install alembic

  2. Initialize Alembic in your project directory:

    alembic init alembic

    This command will create an alembic folder containing your migration scripts and an alembic.ini configuration file.

  3. Configure Alembic:

    Open alembic.ini and set the database URL to your actual database connection string:

    sqlalchemy.url =

  4. Create a env.py file:

    In the alembic folder, open the env.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 and YourModel with your actual model class names.

    Next, find the following line:

    target_metadata = None

    And change it to:

    target_metadata = SQLModel.metadata

  5. 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 the alembic/versions folder.

  6. 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.

  7. 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.

  8. 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.