Hoi Mike, On Wednesday, November 14, 2018 at 11:30:18 PM UTC+1, Mike Bayer wrote: > > I have some big ideas for the baked concept which may or may not > impact this area as well. But they are only ideas for now, I have > many explicit SQLAlchemy tasks that I have to get done before I can > try to explore that stuff. > > Interesting, do you have anything written down?
The baked query concept is a nice starting point but has some shortcomings, in particular with respect to parameters. So we created a WrappedBakedQuery to deal with this. To give an idea how this works: class FooQuery(WrappedBakedQuery): def initial_query(self, session): return session.query(Foo) def filter_by_id(self, id_): self += lambda q: q.filter(Foo.id==bindparam('foo_id')) self |= {'foo_id': id_} # Details omitted, we actually return a copy here return self def filter_by_name(self, name): self += lambda q: q.filter(Foo.name==bindparam('foo_name')) self |= {'foo_name': name} return self This allows us to write code like: query = FooQuery(session) if params['id'] is not None: query = query.filter_by_id(params['id']) if params['name'] is not None: query = query.filter_by_name(params['name']) query = query.join_to_bar() result = query.all() And have all the query compilation cached. All the query stuff can be put near the model so your code isn't covered with fragments of SQLAlchemy. I have no idea if this pattern is common, but it works well for us. The naming of the bind parameters is a bit clunky though, haven't thought of a good way around that. And you end up with lots of steps which may be a performance issue (which motivated by original question) but we're going to measure that before claiming it's an actual problem. The Bakery can cache actual Query objects, that's what spoil() does, so it seems like a small step. And exception handling is a bit annoying, with all errors appearing at the point the query is executed, rather than where the fragment is added. OTOH, it doesn't seem smart to try and to magic with tracebacks for something that shouldn't really happen in production code. I'm not sure what the state of the art is w.r.t. baked queries, but I hope this gives an idea of how we use it. Have a nice day, Martijn -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at https://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.