Fetch table values using alembic and update to another table.

前端 未结 3 748
广开言路
广开言路 2021-02-07 00:43

I have oauth secret and oauth key in client table. Now I moving them to oauth credentials table which will be created during

3条回答
  •  醉梦人生
    2021-02-07 01:27

    You can create a DBSession with sqlalchemy engine bind, then you can avoid use SQL query.

    from myapp.models import Client, ClientCredential
    from alembic import op, context
    import sqlalchemy as sa
    
    
    def upgrade():
        ### commands auto generated by Alembic - please adjust! ###
        url = context.config.get_main_option("sqlalchemy.url")
        engine = sa.create_engine(url)
        DBSession.configure(bind=engine)
    
        op.create_table(
            'client_credential',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('created_at', sa.DateTime(), nullable=False),
            sa.Column('updated_at', sa.DateTime(), nullable=False),
            sa.Column('client_id', sa.Integer(), nullable=False),
            sa.Column('key', sa.String(length=22), nullable=False),
            sa.Column('secret', sa.String(length=44), nullable=False),
            sa.Column('is_active', sa.Boolean(), nullable=False),
            sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
            sa.PrimaryKeyConstraint('id'),
            sa.UniqueConstraint('key'))
        # Here I need to copy data from table A to newly created Table.
        # Now Client table will not have secret and key attributes
        clients = [
            {'secret': client.secret,
             'key': client.key,
             'is_active': True,
             'client_id': client.id,
             'created_at': sa.func.now(),
             'updated_at': sa.func.now()}
            for client in Client.query.all()]
        op.bulk_insert(ClientCredential, clients)
        #Also replaced above two lines with
        #connection = op.get_bind()
        #print connection.execute(Client, Client.query.all())
        op.drop_column(u'client', u'secret')
        op.drop_column(u'client', u'key')
    

提交回复
热议问题