|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +from buildpg import render, Renderer |
| 4 | +from fastapi import APIRouter, Request, Response |
| 5 | +from timvt.resources.enums import MimeTypes |
| 6 | +from titiler.core.models.mapbox import TileJSON |
| 7 | +from asyncpg import UndefinedTableError |
| 8 | +from enum import Enum |
| 9 | +from macrostrat.utils import get_logger |
| 10 | +from macrostrat.database.utils import format as format_sql |
| 11 | + |
| 12 | +print_sql_statements = False |
| 13 | + |
| 14 | +router = APIRouter() |
| 15 | +log = get_logger("uvicorn.error") |
| 16 | + |
| 17 | +__here__ = Path(__file__).parent |
| 18 | + |
| 19 | + |
| 20 | +class FeatureType(str, Enum): |
| 21 | + """Feature types.""" |
| 22 | + |
| 23 | + polygons = "polygons" |
| 24 | + lines = "lines" |
| 25 | + points = "points" |
| 26 | + |
| 27 | + |
| 28 | +@router.get( |
| 29 | + "/{slug}/tilejson.json", |
| 30 | + response_model=TileJSON, |
| 31 | + responses={200: {"description": "Return a tilejson"}}, |
| 32 | + response_model_exclude_none=True, |
| 33 | +) |
| 34 | +async def tilejson( |
| 35 | + request: Request, |
| 36 | + slug: str, |
| 37 | +): |
| 38 | + """Return TileJSON document.""" |
| 39 | + url_path = request.url_for( |
| 40 | + "tile", **{"slug": slug, "z": "{z}", "x": "{x}", "y": "{y}"} |
| 41 | + ) |
| 42 | + |
| 43 | + tile_endpoint = str(url_path) |
| 44 | + |
| 45 | + bounds_query = f""" |
| 46 | + SELECT geom FROM sources.{slug}_polygons |
| 47 | + UNION |
| 48 | + SELECT geom FROM sources.{slug}_lines |
| 49 | + UNION |
| 50 | + SELECT geom FROM sources.{slug}_points |
| 51 | + """ |
| 52 | + |
| 53 | + sql = get_bounds(bounds_query, geometry_column="geom") |
| 54 | + pool = request.app.state.pool |
| 55 | + async with pool.acquire() as con: |
| 56 | + bounds = await con.fetchval(sql) |
| 57 | + |
| 58 | + return { |
| 59 | + "minzoom": 0, |
| 60 | + "maxzoom": 18, |
| 61 | + "name": slug, |
| 62 | + "bounds": bounds, |
| 63 | + "tiles": [tile_endpoint], |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | +@router.get("/{slug}/{z}/{x}/{y}") |
| 68 | +async def tile( |
| 69 | + request: Request, |
| 70 | + slug: str, |
| 71 | + z: int, |
| 72 | + x: int, |
| 73 | + y: int, |
| 74 | +): |
| 75 | + |
| 76 | + # if feature_type != FeatureType.polygons: |
| 77 | + # return Response(status_code=404, content="Only polygons are supported for now") |
| 78 | + |
| 79 | + """Get a tile from the tileserver.""" |
| 80 | + pool = request.app.state.pool |
| 81 | + |
| 82 | + data = b"" |
| 83 | + success = False |
| 84 | + for layer in FeatureType: |
| 85 | + try: |
| 86 | + data += await get_layer(pool, slug, layer, z=z, x=x, y=y) |
| 87 | + success = True |
| 88 | + except UndefinedTableError: |
| 89 | + pass |
| 90 | + if not success: |
| 91 | + return Response(status_code=404, content=f"No tables found for {slug}") |
| 92 | + |
| 93 | + kwargs = {} |
| 94 | + kwargs.setdefault("media_type", MimeTypes.pbf.value) |
| 95 | + return Response(data, **kwargs) |
| 96 | + |
| 97 | + |
| 98 | +async def get_layer(pool, slug, layer: FeatureType, **params): |
| 99 | + async with pool.acquire() as con: |
| 100 | + table_name = f"{slug}_{layer}" |
| 101 | + alias = "s" |
| 102 | + column_dict = await get_table_columns(con, table_name, schema="sources") |
| 103 | + log.debug("Columns: %s", column_dict) |
| 104 | + columns = [ |
| 105 | + format_column(k, v, cast_empty_strings=True, table_alias=alias) |
| 106 | + for k, v in column_dict.items() |
| 107 | + if k != "geom" |
| 108 | + ] |
| 109 | + columns.append("tile_layers.tile_geom(s.geom, :envelope) AS geometry") |
| 110 | + |
| 111 | + joins = None |
| 112 | + if layer == FeatureType.polygons: |
| 113 | + joins = [ |
| 114 | + "LEFT JOIN macrostrat.intervals i0 ON s.b_interval = i0.id", |
| 115 | + "LEFT JOIN macrostrat.intervals i1 ON s.t_interval = i1.id", |
| 116 | + ] |
| 117 | + |
| 118 | + b_age = "i0.age_bottom" |
| 119 | + t_age = "i1.age_top" |
| 120 | + # Eventually we will allow b_age and t_age to be set directly |
| 121 | + # b_age = "coalesce(s.b_age, i0.age_bottom)" |
| 122 | + # t_age = "coalesce(s.t_age, i1.age_top)" |
| 123 | + columns += [ |
| 124 | + b_age + "::float AS b_age", |
| 125 | + t_age + "::float AS t_age", |
| 126 | + _color_subquery(b_age, t_age, "color"), |
| 127 | + ] |
| 128 | + |
| 129 | + return await run_layer_query( |
| 130 | + con, |
| 131 | + f"sources.{table_name}", |
| 132 | + columns, |
| 133 | + joins=joins, |
| 134 | + table_alias=alias, |
| 135 | + layer_name=f"{layer}", |
| 136 | + **params, |
| 137 | + ) |
| 138 | + |
| 139 | + |
| 140 | +string_data_types = [ |
| 141 | + "character varying", |
| 142 | + "text", |
| 143 | +] |
| 144 | + |
| 145 | + |
| 146 | +def format_column( |
| 147 | + col, data_type, table_alias=None, cast_empty_strings=False, name=None |
| 148 | +): |
| 149 | + val = _wrap_with_quotes(col) |
| 150 | + if name is None: |
| 151 | + name = val |
| 152 | + if table_alias is not None: |
| 153 | + val = f"{table_alias}.{val}" |
| 154 | + if cast_empty_strings and data_type in string_data_types: |
| 155 | + val = f"NULLIF({val}, '')::text" |
| 156 | + return f"{val} AS {name}" |
| 157 | + |
| 158 | + |
| 159 | +def _color_subquery(b_age, t_age, alias): |
| 160 | + return f"""( |
| 161 | + SELECT interval_color |
| 162 | + FROM macrostrat.intervals |
| 163 | + WHERE age_top <= {t_age} AND age_bottom >= {b_age} |
| 164 | + ORDER BY age_bottom - age_top |
| 165 | + LIMIT 1 |
| 166 | + ) AS {alias}""" |
| 167 | + |
| 168 | + |
| 169 | +async def run_layer_query( |
| 170 | + con, |
| 171 | + table_name, |
| 172 | + columns, |
| 173 | + *, |
| 174 | + joins=None, |
| 175 | + layer_name="default", |
| 176 | + table_alias=None, |
| 177 | + **params, |
| 178 | +): |
| 179 | + _cols = ", ".join(columns) |
| 180 | + query = f"SELECT {_cols} FROM {table_name}" |
| 181 | + if table_alias: |
| 182 | + query += f" AS {table_alias}" |
| 183 | + |
| 184 | + if joins: |
| 185 | + query += "\n" + "\n".join(joins) |
| 186 | + |
| 187 | + query = extend_sql(query) |
| 188 | + params = dict(layer_name=layer_name, **params) |
| 189 | + |
| 190 | + if print_sql_statements: |
| 191 | + log.debug( |
| 192 | + "Running query:\n%s\nParameters: %s", |
| 193 | + format_sql(query, reindent=True), |
| 194 | + params, |
| 195 | + ) |
| 196 | + |
| 197 | + q, p = render(query, **params) |
| 198 | + |
| 199 | + return await con.fetchval(q, *p) |
| 200 | + |
| 201 | + |
| 202 | +def _wrap_with_quotes(col): |
| 203 | + if col[0] == '"' and col[-1] == '"': |
| 204 | + col = col[1:-1] |
| 205 | + if '"' in col: |
| 206 | + col = col.replace('"', '""') |
| 207 | + return '"' + col + '"' |
| 208 | + |
| 209 | + |
| 210 | +def extend_sql(sql): |
| 211 | + q = sql.strip() |
| 212 | + if q.endswith(";"): |
| 213 | + q = q[:-1] |
| 214 | + |
| 215 | + # Replace the envelope with the function call. Kind of awkward. |
| 216 | + q = q.replace(":envelope", "tile_utils.envelope(:x, :y, :z)") |
| 217 | + |
| 218 | + # Wrap with MVT creation |
| 219 | + return f"WITH feature_query AS ({q}) SELECT ST_AsMVT(feature_query, :layer_name, 4096, 'geometry') FROM feature_query" |
| 220 | + |
| 221 | + |
| 222 | +def get_bounds(base_query, geometry_column="geometry"): |
| 223 | + return f"""WITH b AS ( |
| 224 | + SELECT ST_Union(a.{geometry_column}::box2d)::box2d env |
| 225 | + FROM ({base_query}) a |
| 226 | + ) |
| 227 | + SELECT ARRAY[ST_XMin(env), ST_YMin(env), ST_XMax(env), ST_YMax(env)] |
| 228 | + FROM b; |
| 229 | + """ |
| 230 | + |
| 231 | + |
| 232 | +async def get_table_columns(con, table, schema="sources"): |
| 233 | + base_sql = f""" |
| 234 | + SELECT column_name, data_type |
| 235 | + FROM information_schema.columns |
| 236 | + WHERE table_name = :table |
| 237 | + AND table_schema = :schema; |
| 238 | + """ |
| 239 | + |
| 240 | + q, p = render(base_sql, table=table, schema=schema) |
| 241 | + res = await con.fetch(q, *p) |
| 242 | + if len(res) == 0: |
| 243 | + raise UndefinedTableError(f"Table {schema}.{table} not found") |
| 244 | + |
| 245 | + return {i[0]: i[1] for i in res} |
| 246 | + |
| 247 | + |
| 248 | +def register_map_ingestion_routes(app): |
| 249 | + app.include_router(router, tags=["Map ingestion"], prefix="/ingestion") |
0 commit comments