Alias an sqlalchemy.text object

Viewed 1048

Im trying to allow users to input query in the UI and then add it to the FROM clause of my sqlalchemy. After seeing the from_self function on the query object in the docs, I tried:

Query.from_statement(text("select * from test_table")).from_self()

and:

alias(text("select * from test_table"), name="some_name")

and:

text("select * from test_table").label(name="some_name")

None of these worked. Im trying to get a query like this:

(SELECT * FROM test_table) AS some_name
1 Answers

After a lot of hassling, found a way to do so like this:

alias(TextAsFrom(text("SELECT * FROM test_table"), columns), name='some_name')

This is possible due to the TextAsFrom that can be found deep in the docs here. One con to this method is that you must provide column objects for this to work (you can see the columns variable in my code.) I worked around this by querying the table only for the columns and then creating a column object for each column in the table.

Cheers.

Related