I am trying to execute a function which comes from an extension (postgis
) with psycopg2
.
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]))
This gives me
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.
The extension postgis
is installe on the database world
though.
SELECT * FROM pg_extension;
When I try to run this function in pgAdmin
, it works without a problem...
This is the solution https://gis.stackexchange.com/questions/324386/psycopg2-programmingerror-function-does-not-exist
Andre Silva:
All calls to PostGIS functions must be schema qualified: schema_name.function (source). To bypass writing the schema every time a PostGIS function is used, map the schema where PostGIS is (probably public) to the search_path (see here). As admin:
ALTER DATABASE <database_name> SET search_path TO schema1,schema2;
Moreover, make sure the private user has the necessary privileges in the database to proceed with the analysis (take a look here).
I solved it like this:
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};
"""