简体   繁体   English

使用 sqlalchemy 引擎通过代码手动运行 alembic 操作

[英]Run alembic operations manually by code, using an sqlalchemy engine

I invested some time to understand Alemic, how I could run migrations manually without any setup.我花了一些时间来了解 Alemic,了解如何在没有任何设置的情况下手动运行迁移。 Due to some reasons we need that, we need to be able to execute operations manually without init, ini files or execution context.由于我们需要的某些原因,我们需要能够在没有 init、ini 文件或执行上下文的情况下手动执行操作。

Here is my result:这是我的结果:

import sqlalchemy

from alembic.migration import MigrationContext
from alembic.operations import Operations


# Connection
connection_string = 'postgres://xx:@localhost/xxdb'
engine = sqlalchemy.create_engine(connection_string.replace('postgres://', 'postgresql://'))

# Create migration context
mc = MigrationContext.configure(engine.connect())

# Creation operations object
ops = Operations(mc)


# Add column
try:
    ops.add_column('record', sqlalchemy.Column('new_column', sqlalchemy.String))
except Exception as ex:
    print(ex)

# Create table
try:
    ops.create_table('new_table', [
        sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
        sqlalchemy.Column('name', sqlalchemy.String)
    ])
except Exception as ex:
    print(ex)

It lets you run any alembic operation without needing all the stuff around.它可以让你运行任何 alembic 操作而不需要周围的所有东西。 I just wanted to share that, since it's really hard to get complete examples about it online.我只是想分享一下,因为很难在网上找到完整的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM