tortoise / aerich

A database migrations tool for TortoiseORM, ready to production.
https://github.com/tortoise/aerich
Apache License 2.0
820 stars 94 forks source link

Upgrade to specified version, the specified is not suitable #183

Closed panla closed 2 years ago

panla commented 3 years ago

it can only upgrade to the latest version and can`t upgrade to the designative version,

@cli.command(help="Upgrade to specified version.")
@click.option(
    "--name",
    required=False,
    help="Migrate SQL File, ./migrations/master/10_20210803180848_add_users.sql or 10_20210803180848_add_users.sql"
)
@click.pass_context
@coro
async def upgrade(ctx: Context, name: str = None):
    """upgrade

    Upgrade to specified version
    """

    config = ctx.obj["config"]
    app = ctx.obj["app"]
    migrated = False

    ############################################################
    if not name:
        version_files = Migrate.get_all_version_files()
    else:

        file_path = Path(name)
        if not file_path.exists or file_path.name not in Migrate.get_all_version_files():
            click.secho("No this migrate file found", fg=Color.red)
            return
        version_files = [file_path.name]

    for version_file in version_files:
        ############################################################
        try:
            exists = await Aerich.exists(version=version_file, app=app)
        except OperationalError:
            exists = False
        if not exists:
            async with in_transaction(get_app_connection_name(config, app)) as conn:
                file_path = Path(Migrate.migrate_location, version_file)
                content = get_version_content_from_file(file_path)
                upgrade_query_list = content.get("upgrade")
                for upgrade_query in upgrade_query_list:
                    await conn.execute_script(upgrade_query)
                await Aerich.create(
                    version=version_file, app=app, content=get_models_describe(app),
                )
            click.secho(f"Success upgrade {version_file}", fg=Color.green)
            migrated = True
    if not migrated:
        click.secho("No upgrade items found", fg=Color.yellow)