繁体   English   中英

在 sqlalchemy 中为 Generic function 显式定义类型转换

[英]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

参考:

  1. 数组总和 select 取自https://cwestblog.com/2012/07/18/postgresql-sum-of-an-array/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM