Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A database migrations tool for TortoiseORM, ready to production.

License

NotificationsYou must be signed in to change notification settings

tortoise/aerich

Repository files navigation

imageimageimageimagePython Versions

English |Русский

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:

pip install"aerich[toml]"

Or install the latest version directly fromgithub with thefollowing command:

pip install"aerich[toml] @git+https://github.com/tortoise/aerich"

Quick Start

> aerich -hUsage: 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.  fix-migrations   Fix migration files to include models statefor aerich...  heads      Show current available headsin 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.  init-migrations  Generate app migration folder and your first migration.  inspectdb  Introspects the database tables to standard output as...  migrate    Generate migrate changes file.  upgrade    Upgrade to specified version.

Usage

You need to addaerich.models to yourTortoise-ORM config first. Example:

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

Initialization

> aerich init -hUsage: 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:

> aerich init -t tests.backends.mysql.TORTOISE_ORMSuccess create migrate location ./migrationsSuccess 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.

To apply per app migrations style(like Django), set the location option with a '{app}', such as:--location "./{app}/migrations"

Init db

> aerich init-dbSuccess create app migrate location ./migrations/modelsSuccess generate schemafor app"models"

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

Update models and make migrate

> aerich migrate --name drop_columnSuccess migrate 1_202029051520102929_drop_column.py

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

Ifaerich guesses you are renaming a column, it will askRename {old_column} to {new_column} [True]. You can chooseTrue to rename column without column drop, or chooseFalse to drop the column then create. Note that the latter maylose data.

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

> aerich migrate --name add_index --emptySuccess migrate 1_202326122220101229_add_index.py

Upgrade to latest version

> aerich upgradeSuccess upgrade 1_202029051520102929_drop_column.py

Now your db is migrated to latest.

Downgrade to specified version

> aerich downgrade -hUsage: 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.
> aerich downgradeSuccess downgrade 1_202029051520102929_drop_column.py

Now your db is rolled back to the specified version.

Show history

> aerichhistory1_202029051520102929_drop_column.py

Show heads to be migrated

> aerich heads1_202029051520102929_drop_column.py

Inspect db tables to TortoiseORM model

Currentlyinspectdb support MySQL & Postgres & SQLite.

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:

aerich --app models inspectdb

Inspect a specified table in the default app and redirect tomodels.py:

aerich inspectdb -t user> models.py

For example, you table is:

CREATETABLE `test`(`id`intNOT NULL AUTO_INCREMENT,`decimal`decimal(10,2)NOT NULL,`date`date                                    DEFAULTNULL,`datetime` datetimeNOT NULL                 DEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP,`time`time                                    DEFAULTNULL,`float`    float                                   DEFAULTNULL,`string`varchar(200) COLLATE utf8mb4_general_ci DEFAULTNULL,`tinyint`  tinyint                                 DEFAULTNULL,PRIMARY KEY (`id`),    KEY`asyncmy_string_index` (`string`)) ENGINE= InnoDB  DEFAULT CHARSET= utf8mb4  COLLATE= utf8mb4_general_ci

Now runaerich inspectdb -t test to see the generated model:

fromtortoiseimportModel,fieldsclassTest(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 asIntEnumField,ForeignKeyField, and others.

Multiple databases

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 specifyaerich.models in one app, and must specify--app when runningaerich migrate and so on, e.g.aerich --app models_second migrate.

Restoreaerich workflow

In some cases, such as broken changes from upgrade ofaerich, you can't runaerich migrate oraerich upgrade, youcan make the following steps:

  1. dropaerich table.
  2. deletemigrations/{app} directory.
  3. rerunaerich init-db.

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

Useaerich in application

You can useaerich out of cli by useCommand class.

fromaerichimportCommandfromaerich.utilsimportload_tortoise_configasyncwithCommand(tortoise_config=load_tortoise_config(),app='models')ascommand:awaitcommand.migrate('test')awaitcommand.upgrade()print(awaitcommand.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
aerich upgrade --fakeaerich --app models upgrade --fake
  • Downgrade
aerich downgrade --fake -v 2aerich --app models downgrade --fake -v 2

Ignore tables

You can tell aerich to ignore table by settingmanaged=False in theMeta class, e.g.:

classMyModel(Model):classMeta:managed=False

Notemanaged=False does not recognized bytortoise-orm andaerich init-db, it is only foraerich migrate.

License

This project is licensed under theApache-2.0 License.


[8]ページ先頭

©2009-2025 Movatter.jp