From 9b7d1c545e881c70c1ef2c4358937edd3054cd56 Mon Sep 17 00:00:00 2001 From: brendancol Date: Thu, 4 Feb 2021 12:22:19 -0600 Subject: [PATCH] stubbed out postgres utils --- mapshader/io.py | 51 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/mapshader/io.py b/mapshader/io.py index 92ae6d3..9972670 100644 --- a/mapshader/io.py +++ b/mapshader/io.py @@ -8,7 +8,6 @@ from os.path import expanduser - def load_raster(file_path, xmin=None, ymin=None, xmax=None, ymax=None, chunks=None, layername='data'): @@ -41,3 +40,53 @@ def load_raster(file_path, xmin=None, ymin=None, def load_vector(filepath: str): return gpd.read_file(filepath) + + +def has_postgis(): + + from sqlalchemy.exc import OperationalError + + try: + conn = get_postgis_connection() + conn.connect() + return True + except OperationalError: + return False + + +def doesnt_have_postgis(): + return not has_postgis() + + +def get_postgis_connection(): + from sqlalchemy import create_engine + + database = environ.get('PGDATABASE', 'template_postgis') + host = environ.get('PGHOST', '127.0.0.1') + port = environ.get('PGPORT', '5432') + user = environ.get('PGUSER', 'postgres') + password = environ.get('PGPASSWORD', '') + + return create_engine(f"postgresql://{user}:{password}@{host}:{port}/{database}") + + +def get_layer_from_postgis(layername, rows=None, where='1=1', geom_col='geometry'): + + from sqlalchemy import text as normalize_sql + + conn = get_postgis_connection() + + sql = f'SELECT * FROM {layername}' + + if where: + sql += f' WHERE {normalize_sql(where)}' + + if rows: + sql += f' LIMIT {rows}' + + sql += ';' + + df = gpd.GeoDataFrame.from_postgis(sql, + conn, + geom_col=geom_col) + return df