Using Alembic API from inside application code

前端 未结 8 923
夕颜
夕颜 2020-12-08 04:06

I am using SQLite as an application file format (see here for why you would want to do this) for my PySide-based desktop application. That is, when a user uses my app, their

8条回答
  •  遥遥无期
    2020-12-08 04:52

    This is a very broad question, and actually implementing your idea will be up to you, but it is possible.

    You can call Alembic from your Python code without using the commands, since it's implemented in Python too! You just need to recreate what the commands are doing behind the scenes.

    Admittedly, the docs aren't in very good shape since these are still relatively early releases of the library, but with a little digging you will find the following:

    1. Create a Config
    2. Use the Config to create a ScriptDirectory
    3. Use the Config and the ScriptDirectory to create an EnvironmentContext
    4. Use the EnvironmentContext to create a MigrationContext
    5. Most commands use some combination of methods from Config and MigrationContext

    I've written an extension to provide this programmatic Alembic access to a Flask-SQLAlchemy database. The implementation is tied to Flask and Flask-SQLAlchemy, but it should be a good place to start. See Flask-Alembic here.

    Regarding your last point about how to create new databases, you can either use Alembic to create the tables, or you can use metadata.create_all() then alembic stamp head (or equivalent python code). I recommend always using the migration path to create the tables, and ignoring the raw metadata.create_all().

    I don't have any experience with cx_freeze, but it should be fine as long as the migrations are included in the distribution and the path to that directory in the code is correct.

提交回复
热议问题