Modify data as part of an alembic upgrade

后端 未结 3 603
长情又很酷
长情又很酷 2020-12-14 16:55

I would like to modify some database data as part of an alembic upgrade.

I thought I could just add any code in the upgrade of my migration, but the following fails:

3条回答
  •  被撕碎了的回忆
    2020-12-14 17:52

    It is difficult to understand what exactly you are trying to achieve from the code excerpt your provided. But I'll try to guess. So the following answer will be based on my guess.

    Line 4 - you import things (DBSession, SmsDelivery, SmsMessagePart) form your modules and then you are trying to operate with these objects like you do in your application.

    The error shows that SmsDelivery is a mapper object - so it is pointing to some table. mapper objects should bind to valid sqlalchemy connection.

    Which tells me that you skipped initialization of DB objects (connection and binding this connection to mapper objects) like you normally do in your application code.

    DBSession looks like SQLAlchemy session object - it should have connection bind too.

    Alembic already has connection ready and open - for making changes to db schema you are requesting with op.* methods.

    So there should be way to get this connection.

    According to Alembic manual op.get_bind() will return current Connection bind:
    For full interaction with a connected database, use the “bind” available from the context:

    from alembic import op
    connection = op.get_bind()
    

    So you may use this connection to run your queries into db.

    PS. I would assume you wanted to perform some modifications to data in your table. You may try to formulate this modification into one update query. Alembic has special method for executing such changes - so you would not need to deal with connection.
    alembic.operations.Operations.execute

    execute(sql, execution_options=None)
    

    Execute the given SQL using the current migration context.

    In a SQL script context, the statement is emitted directly to the output stream. There is no return result, however, as this function is oriented towards generating a change script that can run in “offline” mode.

    Parameters: sql – Any legal SQLAlchemy expression, including:

    • a string a sqlalchemy.sql.expression.text() construct.
    • a sqlalchemy.sql.expression.insert() construct.
    • a sqlalchemy.sql.expression.update(),
    • sqlalchemy.sql.expression.insert(), or
    • sqlalchemy.sql.expression.delete() construct. Pretty much anything that’s “executable” as described in SQL Expression Language Tutorial.

提交回复
热议问题