在sqlalchemy迁移中的mysql中创建触发器
#python #mysql #sqlalchemy

使用op.ectute。

我想在last_update字段中进行更新,每当用户或管理员直接在数据库中更改数据时(没有Python Sqlalchemy)。我没有使用信号,而是在op.execute方法中创建触发器

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('new_table',
        sa.Column('no_id', sa.Integer(), nullable=False),
        sa.Column('car', sa.Integer(), nullable=False),
        sa.Column('house', sa.Integer(), nullable=False),
        sa.Column('tier_id', sa.Integer(), nullable=False),
        sa.Column('last_updated', sa.TIMESTAMP(), nullable=True),
        sa.Column('timestamp', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
        sa.ForeignKeyConstraint(['no_id'], ['companies.company_id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['tier_id'], ['tiers.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('no_id')
    )
    op.execute('''
        CREATE TRIGGER tier_after_insert_trigger
        BEFORE UPDATE ON tier_table
        FOR EACH ROW
        BEGIN
            SET NEW.last_updated = CURRENT_TIMESTAMP();
        END;
    ''')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute('DROP TRIGGER IF EXISTS tier_after_insert_trigger')
    op.drop_table('new_table')