3 ms·
In this case it's hard to make something fancy :) from sqlbind import WHERE, FIELDS, join_fragments q = Q() # a QueryParams factory fields = []
by bvrmn 2y ago
In this case it's hard to make something fancy :)
from sqlbind import WHERE, FIELDS, join_fragments
q = Q() # a QueryParams factory
fields = []
joins = []
filters = []
if some_condition:
fields.append('sub_table.field')
joins.append('INNER JOIN sub_table ON (subid)')
filters.append(q.sub_table.date > since)
sql = f'''\
SELECT {FIELDS('table.field', *fields)}
FROM table
{join_fragments(' ', joins)}
{WHERE(*filters)}
'''
Personally I prefer this explicitness to ORM for complex queries which include recursive or multiple joins to the same table.
But I agree ORM shines with simple joins especially if models include proper relationship and there is no need to specify 'ON' condition every time.
- murkt 2y agoWhenever we do recursive, or really long queries (not often), we’re dropping to basically raw SQL with sqlalchemy.text(). It’s really a lot to keep it wholly in SQLAlchemy: write a complex query in SQL, convert to SQLA, and remember how all the moving parts should be connected. Should be much easier now with LLMs, though :)