aerich


Nameaerich JSON
Version 0.9.2 PyPI version JSON
download
home_pageNone
SummaryA database migrations tool for Tortoise ORM.
upload_time2025-10-10 05:53:49
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseNone
keywords migrate tortoise-orm mysql
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Aerich

[![image](https://img.shields.io/pypi/v/aerich.svg?style=flat)](https://pypi.python.org/pypi/aerich)
[![image](https://img.shields.io/github/license/tortoise/aerich)](https://github.com/tortoise/aerich)
[![image](https://github.com/tortoise/aerich/workflows/pypi/badge.svg)](https://github.com/tortoise/aerich/actions?query=workflow:pypi)
[![image](https://github.com/tortoise/aerich/workflows/ci/badge.svg)](https://github.com/tortoise/aerich/actions?query=workflow:ci)
![Python Versions](https://img.shields.io/pypi/pyversions/aerich)

English | [Русский](./README_RU.md)

## Introduction

Aerich is a database migrations tool for TortoiseORM, which is like alembic for SQLAlchemy, or like Django ORM with
it\'s own migration solution.

## Install

Just install from pypi:

```shell
pip install "aerich[toml]"
```

## Quick Start

```shell
> aerich -h

Usage: aerich [OPTIONS] COMMAND [ARGS]...

Options:
  -V, --version      Show the version and exit.
  -c, --config TEXT  Config file.  [default: pyproject.toml]
  --app TEXT         Tortoise-ORM app name.
  -h, --help         Show this message and exit.

Commands:
  downgrade  Downgrade to specified version.
  heads      Show current available heads in migrate location.
  history    List all migrate items.
  init       Init config file and generate root migrate location.
  init-db    Generate schema and generate app migrate location.
  inspectdb  Introspects the database tables to standard output as...
  migrate    Generate migrate changes file.
  upgrade    Upgrade to specified version.
```

## Usage

You need to add `aerich.models` to your `Tortoise-ORM` config first. Example:

```python
TORTOISE_ORM = {
    "connections": {"default": "mysql://root:123456@127.0.0.1:3306/test"},
    "apps": {
        "models": {
            "models": ["tests.models", "aerich.models"],
            "default_connection": "default",
        },
    },
}
```

### Initialization

```shell
> aerich init -h

Usage: aerich init [OPTIONS]

  Init config file and generate root migrate location.

Options:
  -t, --tortoise-orm TEXT  Tortoise-ORM config module dict variable, like
                           settings.TORTOISE_ORM.  [required]
  --location TEXT          Migrate store location.  [default: ./migrations]
  -s, --src_folder TEXT    Folder of the source, relative to the project root.
  -h, --help               Show this message and exit.
```

Initialize the config file and migrations location:

```shell
> aerich init -t tests.backends.mysql.TORTOISE_ORM

Success create migrate location ./migrations
Success write config to pyproject.toml
```

*Note*: aerich will import the config file when running init-db/migrate/upgrade/heads/history commands, so it is better to keep this file simple and clean.

### Init db

```shell
> aerich init-db

Success create app migrate location ./migrations/models
Success generate schema for app "models"
```

If your Tortoise-ORM app is not the default `models`, you must specify the correct app via `--app`,
e.g. `aerich --app other_models init-db`.

### Update models and make migrate

```shell
> aerich migrate --name drop_column

Success migrate 1_202029051520102929_drop_column.py
```

Format of migrate filename is
`{version_num}_{datetime}_{name|update}.py`.

If `aerich` guesses you are renaming a column, it will ask `Rename {old_column} to {new_column} [True]`. You can choose
`True` to rename column without column drop, or choose `False` to drop the column then create. Note that the latter may
lose data.

If you need to manually write migration, you could generate empty file:

```shell
> aerich migrate --name add_index --empty

Success migrate 1_202326122220101229_add_index.py
```

### Upgrade to latest version

```shell
> aerich upgrade

Success upgrade 1_202029051520102929_drop_column.py
```

Now your db is migrated to latest.

### Downgrade to specified version

```shell
> aerich downgrade -h

Usage: aerich downgrade [OPTIONS]

  Downgrade to specified version.

Options:
  -v, --version INTEGER  Specified version, default to last.  [default: -1]
  -d, --delete           Delete version files at the same time.  [default:
                         False]

  --yes                  Confirm the action without prompting.
  -h, --help             Show this message and exit.
```

```shell
> aerich downgrade

Success downgrade 1_202029051520102929_drop_column.py
```

Now your db is rolled back to the specified version.

### Show history

```shell
> aerich history

1_202029051520102929_drop_column.py
```

### Show heads to be migrated

```shell
> aerich heads

1_202029051520102929_drop_column.py
```

### Inspect db tables to TortoiseORM model

Currently `inspectdb` support MySQL & Postgres & SQLite.

```shell
Usage: aerich inspectdb [OPTIONS]

  Introspects the database tables to standard output as TortoiseORM model.

Options:
  -t, --table TEXT  Which tables to inspect.
  -h, --help        Show this message and exit.
```

Inspect all tables and print to console:

```shell
aerich --app models inspectdb
```

Inspect a specified table in the default app and redirect to `models.py`:

```shell
aerich inspectdb -t user > models.py
```

For example, you table is:

```sql
CREATE TABLE `test`
(
    `id`       int            NOT NULL AUTO_INCREMENT,
    `decimal`  decimal(10, 2) NOT NULL,
    `date`     date                                    DEFAULT NULL,
    `datetime` datetime       NOT NULL                 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `time`     time                                    DEFAULT NULL,
    `float`    float                                   DEFAULT NULL,
    `string`   varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL,
    `tinyint`  tinyint                                 DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `asyncmy_string_index` (`string`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_general_ci
```

Now run `aerich inspectdb -t test` to see the generated model:

```python
from tortoise import Model, fields


class Test(Model):
    date = fields.DateField(null=True)
    datetime = fields.DatetimeField(auto_now=True)
    decimal = fields.DecimalField(max_digits=10, decimal_places=2)
    float = fields.FloatField(null=True)
    id = fields.IntField(primary_key=True)
    string = fields.CharField(max_length=200, null=True)
    time = fields.TimeField(null=True)
    tinyint = fields.BooleanField(null=True)
```

Note that this command is limited and can't infer some fields, such as `IntEnumField`, `ForeignKeyField`, and others.

### Multiple databases

```python
tortoise_orm = {
    "connections": {
        "default": "postgres://postgres_user:postgres_pass@127.0.0.1:5432/db1",
        "second": "postgres://postgres_user:postgres_pass@127.0.0.1:5432/db2",
    },
    "apps": {
        "models": {"models": ["tests.models", "aerich.models"], "default_connection": "default"},
        "models_second": {"models": ["tests.models_second"], "default_connection": "second", },
    },
}
```

You only need to specify `aerich.models` in one app, and must specify `--app` when running `aerich migrate` and so on, e.g. `aerich --app models_second migrate`.

## Restore `aerich` workflow

In some cases, such as broken changes from upgrade of `aerich`, you can't run `aerich migrate` or `aerich upgrade`, you
can make the following steps:

1. drop `aerich` table.
2. delete `migrations/{app}` directory.
3. rerun `aerich init-db`.

Note that these actions is safe, also you can do that to reset your migrations if your migration files is too many.

## Use `aerich` in application

You can use `aerich` out of cli by use `Command` class.

```python
from aerich import Command
from aerich.utils import load_tortoise_config

async with Command(tortoise_config=load_tortoise_config(), app='models') as command:
    await command.migrate('test')
    await command.upgrade()
    print(await command.history())
```

## Upgrade/Downgrade with `--fake` option

Marks the migrations up to the latest one(or back to the target one) as applied, but without actually running the SQL to change your database schema.

- Upgrade

```bash
aerich upgrade --fake
aerich --app models upgrade --fake
```
- Downgrade

```bash
aerich downgrade --fake -v 2
aerich --app models downgrade --fake -v 2
```

### Ignore tables

You can tell aerich to ignore table by setting `managed=False` in the `Meta` class, e.g.:
```py
class MyModel(Model):
    class Meta:
        managed = False
```
**Note** `managed=False` does not recognized by `tortoise-orm` and `aerich init-db`, it is only for `aerich migrate`.

## License

This project is licensed under the
[Apache-2.0](https://github.com/long2ice/aerich/blob/master/LICENSE) License.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "aerich",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "migrate, Tortoise-ORM, mysql",
    "author": null,
    "author_email": "long2ice <long2ice@gmail.com>>",
    "download_url": "https://files.pythonhosted.org/packages/c4/60/5d3885f531fab2cecec67510e7b821efc403940ed9eefd034b2c21350f3c/aerich-0.9.2.tar.gz",
    "platform": null,
    "description": "# Aerich\n\n[![image](https://img.shields.io/pypi/v/aerich.svg?style=flat)](https://pypi.python.org/pypi/aerich)\n[![image](https://img.shields.io/github/license/tortoise/aerich)](https://github.com/tortoise/aerich)\n[![image](https://github.com/tortoise/aerich/workflows/pypi/badge.svg)](https://github.com/tortoise/aerich/actions?query=workflow:pypi)\n[![image](https://github.com/tortoise/aerich/workflows/ci/badge.svg)](https://github.com/tortoise/aerich/actions?query=workflow:ci)\n![Python Versions](https://img.shields.io/pypi/pyversions/aerich)\n\nEnglish | [\u0420\u0443\u0441\u0441\u043a\u0438\u0439](./README_RU.md)\n\n## Introduction\n\nAerich is a database migrations tool for TortoiseORM, which is like alembic for SQLAlchemy, or like Django ORM with\nit\\'s own migration solution.\n\n## Install\n\nJust install from pypi:\n\n```shell\npip install \"aerich[toml]\"\n```\n\n## Quick Start\n\n```shell\n> aerich -h\n\nUsage: aerich [OPTIONS] COMMAND [ARGS]...\n\nOptions:\n  -V, --version      Show the version and exit.\n  -c, --config TEXT  Config file.  [default: pyproject.toml]\n  --app TEXT         Tortoise-ORM app name.\n  -h, --help         Show this message and exit.\n\nCommands:\n  downgrade  Downgrade to specified version.\n  heads      Show current available heads in migrate location.\n  history    List all migrate items.\n  init       Init config file and generate root migrate location.\n  init-db    Generate schema and generate app migrate location.\n  inspectdb  Introspects the database tables to standard output as...\n  migrate    Generate migrate changes file.\n  upgrade    Upgrade to specified version.\n```\n\n## Usage\n\nYou need to add `aerich.models` to your `Tortoise-ORM` config first. Example:\n\n```python\nTORTOISE_ORM = {\n    \"connections\": {\"default\": \"mysql://root:123456@127.0.0.1:3306/test\"},\n    \"apps\": {\n        \"models\": {\n            \"models\": [\"tests.models\", \"aerich.models\"],\n            \"default_connection\": \"default\",\n        },\n    },\n}\n```\n\n### Initialization\n\n```shell\n> aerich init -h\n\nUsage: aerich init [OPTIONS]\n\n  Init config file and generate root migrate location.\n\nOptions:\n  -t, --tortoise-orm TEXT  Tortoise-ORM config module dict variable, like\n                           settings.TORTOISE_ORM.  [required]\n  --location TEXT          Migrate store location.  [default: ./migrations]\n  -s, --src_folder TEXT    Folder of the source, relative to the project root.\n  -h, --help               Show this message and exit.\n```\n\nInitialize the config file and migrations location:\n\n```shell\n> aerich init -t tests.backends.mysql.TORTOISE_ORM\n\nSuccess create migrate location ./migrations\nSuccess write config to pyproject.toml\n```\n\n*Note*: aerich will import the config file when running init-db/migrate/upgrade/heads/history commands, so it is better to keep this file simple and clean.\n\n### Init db\n\n```shell\n> aerich init-db\n\nSuccess create app migrate location ./migrations/models\nSuccess generate schema for app \"models\"\n```\n\nIf your Tortoise-ORM app is not the default `models`, you must specify the correct app via `--app`,\ne.g. `aerich --app other_models init-db`.\n\n### Update models and make migrate\n\n```shell\n> aerich migrate --name drop_column\n\nSuccess migrate 1_202029051520102929_drop_column.py\n```\n\nFormat of migrate filename is\n`{version_num}_{datetime}_{name|update}.py`.\n\nIf `aerich` guesses you are renaming a column, it will ask `Rename {old_column} to {new_column} [True]`. You can choose\n`True` to rename column without column drop, or choose `False` to drop the column then create. Note that the latter may\nlose data.\n\nIf you need to manually write migration, you could generate empty file:\n\n```shell\n> aerich migrate --name add_index --empty\n\nSuccess migrate 1_202326122220101229_add_index.py\n```\n\n### Upgrade to latest version\n\n```shell\n> aerich upgrade\n\nSuccess upgrade 1_202029051520102929_drop_column.py\n```\n\nNow your db is migrated to latest.\n\n### Downgrade to specified version\n\n```shell\n> aerich downgrade -h\n\nUsage: aerich downgrade [OPTIONS]\n\n  Downgrade to specified version.\n\nOptions:\n  -v, --version INTEGER  Specified version, default to last.  [default: -1]\n  -d, --delete           Delete version files at the same time.  [default:\n                         False]\n\n  --yes                  Confirm the action without prompting.\n  -h, --help             Show this message and exit.\n```\n\n```shell\n> aerich downgrade\n\nSuccess downgrade 1_202029051520102929_drop_column.py\n```\n\nNow your db is rolled back to the specified version.\n\n### Show history\n\n```shell\n> aerich history\n\n1_202029051520102929_drop_column.py\n```\n\n### Show heads to be migrated\n\n```shell\n> aerich heads\n\n1_202029051520102929_drop_column.py\n```\n\n### Inspect db tables to TortoiseORM model\n\nCurrently `inspectdb` support MySQL & Postgres & SQLite.\n\n```shell\nUsage: aerich inspectdb [OPTIONS]\n\n  Introspects the database tables to standard output as TortoiseORM model.\n\nOptions:\n  -t, --table TEXT  Which tables to inspect.\n  -h, --help        Show this message and exit.\n```\n\nInspect all tables and print to console:\n\n```shell\naerich --app models inspectdb\n```\n\nInspect a specified table in the default app and redirect to `models.py`:\n\n```shell\naerich inspectdb -t user > models.py\n```\n\nFor example, you table is:\n\n```sql\nCREATE TABLE `test`\n(\n    `id`       int            NOT NULL AUTO_INCREMENT,\n    `decimal`  decimal(10, 2) NOT NULL,\n    `date`     date                                    DEFAULT NULL,\n    `datetime` datetime       NOT NULL                 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n    `time`     time                                    DEFAULT NULL,\n    `float`    float                                   DEFAULT NULL,\n    `string`   varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL,\n    `tinyint`  tinyint                                 DEFAULT NULL,\n    PRIMARY KEY (`id`),\n    KEY `asyncmy_string_index` (`string`)\n) ENGINE = InnoDB\n  DEFAULT CHARSET = utf8mb4\n  COLLATE = utf8mb4_general_ci\n```\n\nNow run `aerich inspectdb -t test` to see the generated model:\n\n```python\nfrom tortoise import Model, fields\n\n\nclass Test(Model):\n    date = fields.DateField(null=True)\n    datetime = fields.DatetimeField(auto_now=True)\n    decimal = fields.DecimalField(max_digits=10, decimal_places=2)\n    float = fields.FloatField(null=True)\n    id = fields.IntField(primary_key=True)\n    string = fields.CharField(max_length=200, null=True)\n    time = fields.TimeField(null=True)\n    tinyint = fields.BooleanField(null=True)\n```\n\nNote that this command is limited and can't infer some fields, such as `IntEnumField`, `ForeignKeyField`, and others.\n\n### Multiple databases\n\n```python\ntortoise_orm = {\n    \"connections\": {\n        \"default\": \"postgres://postgres_user:postgres_pass@127.0.0.1:5432/db1\",\n        \"second\": \"postgres://postgres_user:postgres_pass@127.0.0.1:5432/db2\",\n    },\n    \"apps\": {\n        \"models\": {\"models\": [\"tests.models\", \"aerich.models\"], \"default_connection\": \"default\"},\n        \"models_second\": {\"models\": [\"tests.models_second\"], \"default_connection\": \"second\", },\n    },\n}\n```\n\nYou only need to specify `aerich.models` in one app, and must specify `--app` when running `aerich migrate` and so on, e.g. `aerich --app models_second migrate`.\n\n## Restore `aerich` workflow\n\nIn some cases, such as broken changes from upgrade of `aerich`, you can't run `aerich migrate` or `aerich upgrade`, you\ncan make the following steps:\n\n1. drop `aerich` table.\n2. delete `migrations/{app}` directory.\n3. rerun `aerich init-db`.\n\nNote that these actions is safe, also you can do that to reset your migrations if your migration files is too many.\n\n## Use `aerich` in application\n\nYou can use `aerich` out of cli by use `Command` class.\n\n```python\nfrom aerich import Command\nfrom aerich.utils import load_tortoise_config\n\nasync with Command(tortoise_config=load_tortoise_config(), app='models') as command:\n    await command.migrate('test')\n    await command.upgrade()\n    print(await command.history())\n```\n\n## Upgrade/Downgrade with `--fake` option\n\nMarks the migrations up to the latest one(or back to the target one) as applied, but without actually running the SQL to change your database schema.\n\n- Upgrade\n\n```bash\naerich upgrade --fake\naerich --app models upgrade --fake\n```\n- Downgrade\n\n```bash\naerich downgrade --fake -v 2\naerich --app models downgrade --fake -v 2\n```\n\n### Ignore tables\n\nYou can tell aerich to ignore table by setting `managed=False` in the `Meta` class, e.g.:\n```py\nclass MyModel(Model):\n    class Meta:\n        managed = False\n```\n**Note** `managed=False` does not recognized by `tortoise-orm` and `aerich init-db`, it is only for `aerich migrate`.\n\n## License\n\nThis project is licensed under the\n[Apache-2.0](https://github.com/long2ice/aerich/blob/master/LICENSE) License.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A database migrations tool for Tortoise ORM.",
    "version": "0.9.2",
    "project_urls": {
        "documentation": "https://github.com/tortoise/aerich",
        "homepage": "https://github.com/tortoise/aerich",
        "repository": "https://github.com/tortoise/aerich.git"
    },
    "split_keywords": [
        "migrate",
        " tortoise-orm",
        " mysql"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "871a956c6b1e35881bb9835a33c8db1565edcd133f8e45321010489092a0df40",
                "md5": "b13b27150814e7f00e92321d814cc9d5",
                "sha256": "d0f007acb21f6559f1eccd4e404fb039cf48af2689e0669afa62989389c0582d"
            },
            "downloads": -1,
            "filename": "aerich-0.9.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b13b27150814e7f00e92321d814cc9d5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 46451,
            "upload_time": "2025-10-10T05:53:48",
            "upload_time_iso_8601": "2025-10-10T05:53:48.710185Z",
            "url": "https://files.pythonhosted.org/packages/87/1a/956c6b1e35881bb9835a33c8db1565edcd133f8e45321010489092a0df40/aerich-0.9.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c4605d3885f531fab2cecec67510e7b821efc403940ed9eefd034b2c21350f3c",
                "md5": "e4c7fcf3593c22d58c372595ca3d2e6c",
                "sha256": "02d58658714eebe396fe7bd9f9401db3a60a44dc885910ad3990920d0357317d"
            },
            "downloads": -1,
            "filename": "aerich-0.9.2.tar.gz",
            "has_sig": false,
            "md5_digest": "e4c7fcf3593c22d58c372595ca3d2e6c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 74231,
            "upload_time": "2025-10-10T05:53:49",
            "upload_time_iso_8601": "2025-10-10T05:53:49.632221Z",
            "url": "https://files.pythonhosted.org/packages/c4/60/5d3885f531fab2cecec67510e7b821efc403940ed9eefd034b2c21350f3c/aerich-0.9.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-10 05:53:49",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tortoise",
    "github_project": "aerich",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aerich"
}
        
Elapsed time: 3.77932s