I have a problem with SQLAlchemy and aliases. I'm trying to do a self-join on a table called Task but SQLAlchemy confuses my aliased table with the non-aliased.
My query is much more complex but this is a simplified version:
baseTask = aliased(model.Task)
query = model.session.query(model.Task.name)\
.select_from(baseTask)\
.join((model.Task, model.Task.taskid==baseTask.taskid))
The resulting query looks like this:
SELECT task_1.name
FROM task AS task_1 INNER JOIN task ON task_1.taskid = task_1.taskid
As you can see it confuses the un-aliased table with the aliased task_1, both in the select and the join condition.
By using an alias on both of the tables it works:
baseTask = aliased(model.Task)
task = aliased(model.Task)
query = model.session.query(task.name)\
.select_from(baseTask)\
.join((task, task.taskid==baseTask.taskid))
This gives the desired result:
SELECT task_1.name
FROM task AS task_2 INNER JOIN task AS task_1 ON task_1.taskid = task_2.taskid
When I use alias on both tables it doesn't confuse them and the resulting query is exactly what I want. The problem is that for various reasons I cannot use alias on the table I join to, this is due to the application design where a dynamically generate queries.
I'm using SQLAlchemy 0.6.8 and I've tried to upgrade to 0.7.9 but I still got this issue. Any ideas on how to solve this?