DEV Community

sumandari
sumandari

Posted on

3

Create a trigger in MySQL in SQLAlchemy migration

Create a trigger in MySQL in SQLAlchemy migration with op.execute.

I wanted to have an update in last_update field, every time a user or an admin changed the data directly in the database (without python sqlalchemy). Instead of using signal, I created trigger inside op.execute method

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')
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay