olirice / alembic_utils

An alembic/sqlalchemy extension for migrating sql views, functions, triggers, and policies
MIT License
193 stars 42 forks source link

Is it possible to create PGTrigger in all the table by expanding declarative_base? #131

Closed hidetatz closed 1 month ago

hidetatz commented 1 month ago

Hi, I'm new to the alembic, am trying to create updated_at column in every table managed by alembic, in our database.

Because we are using PostgreSQL, we need to use PostgreSQL trigger to auto-update updated_at. I found I can create trigger and integrate it in automigrate python script using PGTrigger.

Because I want to add this trigger in every table also, I don't want to write PGTrigger manually but automatically create it. Is it possible to expand sqlalchemy declarative_base to achieve this?

Specifically, now I have something like this:

tg_update_system_updated_at_users = PGTrigger(
    schema="public",
    signature="tg_update_system_updated_at",
    on_entity="public.users",
    definition="""
        BEFORE UPDATE ON "users"
        FOR EACH ROW EXECUTE FUNCTION function_update_system_updated_at();
    """,
)

register_entities([tg_update_system_updated_at_users])

I want to make it:

tg_update_system_updated_at = PGTrigger(
    schema="public",
    signature="tg_update_system_updated_at",
    on_entity="public.{table name here}",
    definition="""
        BEFORE UPDATE ON "{table name here}"
        FOR EACH ROW EXECUTE FUNCTION function_update_system_updated_at();
    """,
)

register_entities([tg_update_system_updated_at])

Is it even possible, if yes how can I do this?

hidetatz commented 1 month ago

Sorry, it has been resolved.