我得到:当使用 psycopg2 执行 poytgis 函数时,没有函数匹配给定的名称和参数类型

I am getting: No function matches the given name and argument types when executing poytgis function with psycopg2

我正在尝试执行一个来自 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):
        # 
        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: function st_centroid(public.geometry) does not exist LINE 3: SELECT ST_Centroid(geom) AS geom, way_id, osm_type, name...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

虽然扩展 postgis 安装在 database world 上。

SELECT * FROM pg_extension;

当我在 pgAdmin 中尝试 运行 这个函数时,它没有问题...

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

安德烈·席尔瓦:

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

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

此外,请确保私人用户在数据库中拥有必要的权限以继续进行分析(请看这里)。

我是这样解决的:

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};
    """