sqlalchemy: Accessing Query.selectable causes RecursionError in "before_compile" event listener

I posted a question on StackOverflow pertaining to what I’m actually trying to accomplish with the before_compile event listener. In the course of experimenting while waiting for an answer, I made some headway but eventually got stuck.

It seems as though attempting to access virtually any attribute or property of the Query object passed into the registered event handler causes the interpreter to throw a recursion error. I can get at the Query object’s attributes if I attach a debugger and set a break point on the function entry, so I know that it at least appears to have all of the attributes that I’d like to modify prior to compilation, I just can’t… do anything with them.

I’ve tried to dig into this and the best I can tell is that accessing certain attributes causes the event handler to be fired again? Either that or there are multiple circular references between the various things that comprise the Query objects attributes and properties.

The full explanation of why I’d like to do so is in the StackOverflow link above, but the much condensed version is that I’m stuck supporting a very silly DB design that breaks out what should be one table into ~28 different tables that all share the same layout. Due to other entangled complications, SQLAlchemy’s table inheritance recipes don’t feel like the best option. The best thing I can think of would be to utilize an event listener to modify emitted queries prior to their compilation and set the correct table name for the record that’s being requested.

What did I miss in the documentation about how the before_compile event works?

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 20 (11 by maintainers)

Most upvoted comments

@gordthompson and @zzzeek I think I’ve got it figured out. Thank you both profusely for your help.

If anyone else runs into a similar issue, I’ve posted a gist detailing the solution I worked out here.