![](/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.