I am trying to generate dynamic sql queries based on certain conditions in SQLAlchemy. I have a model that is gets queried constantly based on different conditions
The code goes like this:
condition 1:
allowed_names = ['a', 'b', 'c']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')
condition 2:
allowed_names = ['x', 'y', 'z']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')
I get results of the query the following way:
res = Parent.filter(Parent.parent_id.in_([1, 2, 3])).limit(100).offset(1).all()
If I run the query based on condition 1 first and run the query based on condition 2 again without stopping the program, it returns results based on query 1 since it ran first. After printing out the sql query that gets executed, I figured out that it only runs the condition that was executed first.
Does SQLALchemy cache the string query? I noticed the old value of allowed_names in the filter condition in the query
[cached since 7.236s ago] {'name_1_1': 'a', 'name_1_2': 'b', 'name_1_3': 'c'}
Am I missing something here, or is it a SQLAlchemy bug??