2

I'm working on a project where I need to attach some custom triggers to a table that's defined using SQLAlchemy, and controlled using Alembic.

Right now, I have a simple loop that attaches a after_create event to each declarative table class:

trigger_on = [
    Series,
    Tags,
    Genres,
    Author,
    Illustrators,
    AlternateNames,
    Translators,
    Releases,
    Language,
    Covers,
]
def iife_capture(func, param):
    def callee(table, connection, **kwargs):
        return func(connection, param)
    return callee

for classDefinition in trigger_on:
    event.listen(
        classDefinition.__table__,
        'after_create',
        iife_capture(create_trigger, classDefinition)
        )

Effectively, I'm defining an immediately invoked function to capture the passed parameters, that returns a function that calls create_trigger on the table classDefinition. This part actually works fine, and if I manually execute create_all(), everything is fine.

However, if I create the table via alembic, the after_create calls don't seem to be actually called.

The other SE question here looks to actually be describing a similar issue. I tried attaching the events to sqlalchemy.Table, rather then the individual tables, but it wound up causing them all to execute after only one table was created, which fails because the create_trigger function specifically attaches things to the table it's called against.

How can I call a function after the creation of each table (or all the tables, either could work)?

Basically, I want to be able to do my complete DB setup just by using alembic, rather then the horribly messy apparatus I have now.

Community
  • 1
  • 1
Fake Name
  • 5,556
  • 5
  • 44
  • 66

0 Answers0