![](/img/trans.png)
[英]How to explicitly cast type of array literal in sqlalchemy using postgresql?
[英]Explicitly define type cast for Generic function in sqlalchemy
我们有一个用户定义的数据库 function,如下所示:
CREATE OR REPLACE FUNCTION my_function(ids integer[],
.
.
我打电话给 sqlalchemy:
from sqlalchemy import func
statement = func.my_function(
[1,2,3,4]
)
station_count = await db.execute(statement)
我收到以下错误:
sqlalchemy.exc.ProgrammingError: (sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError) <class 'asyncpg.exceptions.AmbiguousFunctionError'>: function my_function(unknown) is not unique
HINT: Could not choose a best candidate function. You might need to add explicit type casts.
[SQL: SELECT my_function(%s) AS my_function_1]
[parameters: ([1,2,3,4]]
(Background on this error at: https://sqlalche.me/e/14/f405)
我认为这里的问题是关于将列表[1,2,3,4]
转换为integer[]
。 但是,如何在 SQLAlchemy 中调用 function 时将list[int]
显式转换为integer[]
?
问题绝对不是将list[int]
转换为integer[]
,它可能与错误提示的 function 名称不唯一有关。
尝试使用以下方法检查现有功能:
SELECT routine_name
FROM information_schema.routines
WHERE routine_type = 'FUNCTION'
这是将list[int]
传递给具有integer[]
参数的 function 的 MRE。
from sqlalchemy import create_engine, func
engine = create_engine("postgresql+psycopg2://postgres:postgres@localhost:5432/postgres", echo=True, future=True)
with engine.connect() as con:
con.execute(
sa.text(
"""
CREATE FUNCTION my_sum (ns integer[]) RETURNS integer
AS $$ SELECT SUM(t) FROM UNNEST(ns) t $$
LANGUAGE SQL;
"""
)
)
con.commit()
with engine.connect() as con:
stmt = func.my_sum([1, 2, 3, 4])
result = con.execute(stmt).scalar_one()
print(result) # 10
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.