How do I execute inserts and updates in an Alembic upgrade script?

前端 未结 3 405
滥情空心
滥情空心 2020-11-29 16:05

I need to alter data during an Alembic upgrade.

I currently have a \'players\' table in a first revision:

def upgrade():
    op.create_table(\'player         


        
3条回答
  •  醉话见心
    2020-11-29 16:35

    I recommend using SQLAlchemy core statements using an ad-hoc table, as detailed in the official documentation, because it allows the use of agnostic SQL and pythonic writing and is also self-contained. SQLAlchemy Core is the best of both worlds for migration scripts.

    Here is an example of the concept:

    from sqlalchemy.sql import table, column
    from sqlalchemy import String
    from alembic import op
    
    account = table('account',
        column('name', String)
    )
    op.execute(
        account.update().\\
        where(account.c.name==op.inline_literal('account 1')).\\
            values({'name':op.inline_literal('account 2')})
            )
    
    # If insert is required
    from sqlalchemy.sql import insert
    from sqlalchemy import orm
    
    session = orm.Session(bind=bind)
    bind = op.get_bind()
    
    data = {
        "name": "John",
    }
    ret = session.execute(insert(account).values(data))
    # for use in other insert calls
    account_id = ret.lastrowid
    

提交回复
热议问题