【问题标题】:I am getting: No function matches the given name and argument types when executing poytgis function with psycopg2我得到:使用 psycopg2 执行 poytgis 函数时,没有函数与给定的名称和参数类型匹配
【发布时间】:2022-11-07 19:06:39
【问题描述】:

我正在尝试使用psycopg2 执行来自扩展(postgis)的函数。

import psycopg2

AFRICA = "africa"
ANTARCTICA = "antarctica"
ASIA = "asia"
AUSTRALIA_OCEANIA = "australia-oceania"
CENTRAL_AMERICA = "central-america"
EUROPE = "europe"
NORTH_AMERICA = "north-america"
SOUTH_AMERICA = "south-america"

SCHEMAS = [AFRICA, ANTARCTICA, ASIA, AUSTRALIA_OCEANIA,
           CENTRAL_AMERICA, EUROPE, NORTH_AMERICA, SOUTH_AMERICA]

def createCentroidTableFromPolygon(fromTable, toTable):
    return f"""
        CREATE TABLE IF NOT EXISTS {toTable} AS
        SELECT ST_Centroid(geom) AS geom, way_id, osm_type, name FROM {fromTable};
    """

for schema in SCHEMAS:    
    conn = psycopg2.connect(
        host='localhost',
        database='world',
        user="postgres",
        password="postgres",
        port=5432,
        options=f"-c search_path={schema}"
    )

    for i, table in enumerate(TABLES):
        # https://stackoverflow.com/questions/57116846/run-postgresql-functions-in-python-and-gets-error
        with conn:
            with conn.cursor() as cursor:
                # this works!
                cursor.execute(f"""SELECT * FROM {table} LIMIT 10""")
                print(cursor.fetchall())

                # this throws an error
                cursor.execute(createCentroidTableFromPolygon(
                table, FROM_POLY_TABLES[i]))

这给了我

psycopg2.errors.UndefinedFunction:函数 st_centroid(public.geometry) 不存在 第 3 行:选择 ST_Centroid(geom) 作为 geom、way_id、osm_type、名称...
提示:没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。

扩展名postgis 安装在database world 上。

SELECT * FROM pg_extension;

当我尝试在pgAdmin 中运行此功能时,它可以正常工作...

【问题讨论】:

标签: python postgresql postgis psycopg2


【解决方案1】:

这是解决方案https://gis.stackexchange.com/questions/324386/psycopg2-programmingerror-function-does-not-exist

安德烈席尔瓦:

所有对 PostGIS 函数的调用都必须是模式限定的:schema_name.function (source)。 要绕过每次使用 PostGIS 函数时写入架构,请将 PostGIS 所在的架构(可能是公共的)映射到 search_path(参见此处)。作为管理员:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

此外,请确保私人用户在数据库中具有进行分析所需的权限(查看here)。

我是这样解决的:

def createCentroidTableFromPolygon(fromTable, toTable):
    return f"""
    CREATE TABLE IF NOT EXISTS {toTable} AS
    SELECT public.ST_Centroid(geom) AS geom, way_id, osm_type, name FROM {fromTable};
    """

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 1970-01-01
    • 2016-07-07
    • 2013-08-20
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多