Select columns from function call in sqlalchemy core

限于喜欢 提交于 2020-06-08 20:03:01

问题


In postgresql I have select col1, col2 from my_function(). How can I do that in sqlalchemy core?

select(func.my_function()) gives the result as a string, but I want a tuple.


回答1:


You'll want to use FunctionElement.alias() and the light weight column():

from sqlalchemy import func, select, column

stmt = select([column('col1'), column('col2')]).\
    select_from(func.my_function().alias())

The documentation specifically mentions Postgresql as a use case for this construct. The above produces:

SELECT col1, col2 
FROM my_function() AS anon_1

Using the parameter _selectable of column() you could also:

In [4]: fn = func.my_function().alias()

In [5]: stmt = select([column('col1', _selectable=fn),
   ...:                column('col2', _selectable=fn)])

In [6]: print(stmt)
SELECT anon_1.col1, anon_1.col2 
FROM my_function() AS anon_1

but since _selectable is left undocumented, this might not be a good idea.



来源:https://stackoverflow.com/questions/43130990/select-columns-from-function-call-in-sqlalchemy-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!