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

Allow embedded use of Aerich #159

Closed manzato closed 3 years ago

manzato commented 3 years ago

Related to #141

@long2ice this is far from complete, but I wanted to share with you the approach I was thinking.

I'm no expert in either Tortoise or Aerich, so please bear with me.

This is the sample program I'm using to call the init_db from inside the application. The application takes care of setting up the DB connection, and providing it to Aerich. In the CLI case, the CLI is in charge of doing that.

import asyncio

from tortoise import Tortoise
from aerich.embed import Aerich

from app.models import Team

db_url = "sqlite:///tmp/dummy.sqlite3"

TORTOISE_ORM = {
    "connections": {"default": db_url},
    "apps": {
        "models": {
            "models": ["app.models", "aerich.models"],
            "default_connection": "default",
        },
    },
}

async def run():
    await Tortoise.init(
        db_url=db_url,
        modules={'models': ['app.models', 'aerich.models']}
    )

    # Generate the schema
    await Tortoise.generate_schemas()

    aerich = Aerich()
    await aerich.init_db()
    await aerich.upgrade()

    print(await Team.all().values_list("name", flat=True))

    await Tortoise.close_connections()

def main():
    asyncio.get_event_loop().run_until_complete(run())

if __name__ == "__main__":
    main()
manzato commented 3 years ago

Please provide any (and all) feedback you can

manzato commented 3 years ago

With these two actions (init_db and upgrade) I think most important use cases are covered for #141 , but let me know what you think