从 sqlalchemy core 中的函数调用中选择列

Hat*_*sut 6 python sql postgresql stored-procedures sqlalchemy

在 postgresql 中我有select col1, col2 from my_function(). 我怎样才能在 sqlalchemy 核心中做到这一点?

select(func.my_function())将结果作为字符串给出,但我想要一个元组。

Ilj*_*ilä 7

您会想要使用FunctionElement.alias()轻量级column()

from sqlalchemy import func, select, column

stmt = select([column('col1'), column('col2')]).\
    select_from(func.my_function().alias())
Run Code Online (Sandbox Code Playgroud)

该文档特别提到 Postgresql 作为此构造的用例。上面的结果是:

SELECT col1, col2 
FROM my_function() AS anon_1
Run Code Online (Sandbox Code Playgroud)

使用参数_selectablecolumn()还可以:

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
Run Code Online (Sandbox Code Playgroud)

但由于_selectable没有记录,这可能不是一个好主意。