Aerich Documentation

repository·dev·Indexed 22 days ago

https://github.com/tortoise/aerich

A database migrations tool specifically designed for Tortoise ORM, providing functionality similar to Alembic or Django's migration system. Aerich allows users to initialize database schemas, generate and apply migrations, rollback to previous versions, and introspect existing MySQL, Postgres, or SQLite tables to generate TortoiseORM model code. It provides both a CLI and a programmatic interface via the Command class.

Tokens
9.2K
Snippets
49
Records
53
Agent score
77%

What's inside aerich

  1. How to ignore tables in migrations

    dev

    To prevent Aerich from managing a specific table during migrations, set managed = False in the model's Meta class.

    Note: This setting is only recognized by aerich migrate. It is not recognized by tortoise-orm or aerich init-db.

    class MyModel(Model):
        class Meta:
            managed = False
  2. Inspect database tables to TortoiseORM models

    dev

    Aerich can introspect existing MySQL, Postgres, or SQLite tables and generate TortoiseORM model code. This is useful for reverse-engineering schemas.

    Options:

    • -t, --table: Specify a specific table to inspect. If omitted, all tables are inspected.

    Usage:

    • To print all models to stdout: aerich --app models inspectdb
    • To save a specific table to a file: aerich inspectdb -t user > models.py

    Note: Some complex fields like IntEnumField or ForeignKeyField might not be correctly inferred.

    aerich --app models inspectdb
    
    aerich inspectdb -t user > models.py
  3. Install Aerich

    dev

    Install Aerich from PyPI with TOML support using pip. You can also install the latest version directly from GitHub.

    Note: For tortoise-orm>=1.0.0, you can use the built-in CLI for migrations (e.g., python -m tortoise makemigrations) instead of Aerich.

    pip install "aerich[toml]"
    
    # Or from GitHub
    pip install "aerich[toml] @git+https://github.com/tortoise/aerich"
  4. Initialize Aerich configuration

    dev

    Use aerich init to create the configuration file (defaults to pyproject.toml) and the root migration storage location.

    Options:

    • -t, --tortoise-orm: The path to your Tortoise-ORM config module/variable (e.g., settings.TORTOISE_ORM). Required.
    • --location: The migration store location (defaults to ./migrations).
    • -s, --src_folder: Folder of the source, relative to the project root.

    To use a Django-style per-app migration structure, set the location to include the {app} placeholder, for example: --location "./{app}/migrations".

    aerich init -t tests.backends.mysql.TORTOISE_ORM
  5. Configure Aerich for Tortoise-ORM

    dev

    To use Aerich, you must include aerich.models in your Tortoise-ORM configuration under the apps section. This allows Aerich to track migration state.

    If you have only one app in your configuration, the aerich.models entry might be omitted, but it is recommended for clarity.

    TORTOISE_ORM = {
        "connections": {"default": "mysql://root:123456@127.0.0.1:3306/test"},
        "apps": {
            "models": {
                "models": ["tests.models", "aerich.models"],
                "default_connection": "default",
            },
        },
    }
  6. Configure Tortoise-ORM for Aerich

    dev

    To use Aerich, you must include aerich.models in your Tortoise-ORM configuration under the relevant app.

    Note: If you are using multiple databases, you should only include aerich.models in one of your apps. For all other apps, you must specify the app name using the --app flag when running Aerich commands.

    Example configuration:

    TORTOISE_ORM = {
        "connections": {"default": "mysql://root:123456@127.0.0.1:3306/test"},
        "apps": {
            "models": {
                "models": ["tests.models", "aerich.models"],
                "default_connection": "default",
            },
        },
    }
  7. Initialize the database schema

    dev

    Use aerich init-db to generate the initial database schema and create the migration folder for your app.

    If your Tortoise-ORM app is named something other than models, you must specify it using the --app flag.

    aerich init-db
    
    # For a custom app name
    aerich --app other_models init-db
  8. Generate and apply migrations

    dev

    Create a migration file

    Use aerich migrate --name <name> to detect changes in your models and generate a migration script.

    • If Aerich detects a column rename, it will prompt you to confirm the rename (which preserves data) or drop/create (which may lose data).
    • To create an empty migration file for manual writing, use the --empty flag.

    Apply migrations

    Use aerich upgrade to apply all pending migrations to the database.

    Rollback migrations

    Use aerich downgrade to roll back to a previous version. By default, it rolls back the last version (-v -1).

    • -v, --version: Specify the target version integer.
    • -d, --delete: Delete the version files during downgrade.
    • --yes: Skip confirmation prompts.
    # Generate migration
    aerich migrate --name drop_column
    
    # Generate empty migration
    aerich migrate --name add_index --empty
    
    # Apply migrations
    aerich upgrade
    
    # Rollback
    aerich downgrade
  9. How Aerich handles model changes during migration

    dev

    Aerich uses a diffing mechanism to detect changes between the last_version_content and the current new_version_content.

    Supported Change Types:

    • Model Creation/Deletion: Detects new or removed models and generates CREATE TABLE or DROP TABLE statements.
    • Table Renaming: Detects if a model class name changed but the underlying database table name remained the same.
    • Field Changes: Handles additions, removals, and alterations of data fields.
    • Relational Changes:
      • Foreign Keys (FK): Handles adding, dropping, and altering foreign key constraints.
      • One-to-One (O2O): Handles changes to one-to-one relationships.
      • Many-to-Many (M2M): Handles creation and removal of through-tables for M2M relationships.
    • Constraints and Indexes:
      • Manages unique_together constraints.
      • Manages database indexes (addition and removal).

    Limitations:

    • Aerich does not automatically handle on_delete changes for foreign keys or M2M fields; these may require manual SQL intervention.
    • Renaming a model class while simultaneously changing its attributes is not supported and will trigger a warning.
  10. Reset Aerich migration workflow

    dev

    If you encounter issues (e.g., after an Aerich update) where migrate or upgrade fails, you can reset the migration state.

    Warning: This is a destructive process used to reset migrations.

    1. Delete the aerich tables in your database.
    2. Delete the migrations/{app} directory.
    3. Run aerich init-db to start fresh.
  11. Use Aerich programmatically with the `Command` class

    dev

    You can execute Aerich commands outside of the CLI by using the Command class.

    from aerich import Command
    
    # config is your Tortoise-ORM configuration dictionary
    command = Command(tortoise_config=config, app="models")
    await command.init()
    await command.migrate("test")
    from aerich import Command
    
    command = Command(tortoise_config=config, app="models")
    await command.init()
    await command.migrate("test")