how to use composite data types (e.g. geomval) in SQLAlchemy?

878 views Asked by At

I'm trying to replicate a nested raw PostGreSQL/PostGIS raster query using SQLAlchemy(0.8)/GeoAlchemy2(0.2.1) and can't figure how to access the components of a geomval data type. It's a compound data type that returns a 'geom' and a 'val'.

Here is the raw query that works:

SELECT (dap).val, (dap).geom
FROM (SELECT ST_DumpAsPolygons(rast) as dap FROM my_raster_table) thing

And the SQLAlchemy query I'm currently working with:

import geoalchemy2 as ga2
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker

metadata = MetaData()
my_raster_table = Table('my_raster_table', metadata,
                  Column('rid', Integer),
                  Column('rast', ga2.Raster))

engine = create_engine(my_conn_str)
session = sessionmaker(engine)()

q = session.query(ga2.func.ST_DumpAsPolygons(my_raster_table.c.rast).label('dap'))

And then I'd like to access that in a subquery, something like this:

q2 = session.query(ga2.func.ST_Area(q.subquery().c.dap.geom))

But that syntax doesn't work, or I wouldn't be posting this question ;). Anyone have ideas? Thanks!

1

There are 1 answers

0
gweedoh565 On BEST ANSWER

The solution ended up being fairly simple:

First, define a custom GeomvalType, inheriting geoalchemy2's CompositeType and specifying a typemap specific to geomval:

class GeomvalType(ga2.types.CompositeType):
    typemap = {'geom':ga2.Geometry('MULTIPOLYGON'),'val':Float}

Next, use type_coerce to cast the ST_DumpAsPolygons result to the GeomvalType in the initial query:

q = session.query(type_coerce(ga2.func.ST_DumpAsPolygons(my_raster_table.c.rast), GeomvalType()).label('dap'))

Finally, access it (successfully!) from the subquery as I was trying to before:

q2 = session.query(ga2.func.ST_Area(q.subquery().c.dap.geom))