I'm trying to pull out composite columns from tiger.geocode function in python using sqlalchemy.
In pure sql form this looks like this:
SELECT
g.rating
,ST_X(g.geomout) As lon
,ST_Y(g.geomout) As lat
,(addy).address As stno
,(addy).streetname As street
,(addy).streettypeabbrev As styp
,(addy).location As city
,(addy).stateabbrev As st
,(addy).zip
FROM geocode(pagc_normalize_address('1 Capitol Square Columbus OH 43215')) As g
;
This produces the following output:
# rating lon lat stno street styp city st zip
1 17 -82.99782603089086 39.96172588526335 1 Capital St Columbus OH 43215
The issue I'm faced with is how to reference composite columns when querying the object from sqlalchemy (rating, lon, lat, stno, street, styp, city, st, zip)?
Please and Thank you.
SQLAlchemy doesn't support set returning functions directly, but its
FunctionElement
s are consideredFromClause
s, which means you can already treat them as tables; we just need to add the ability to select a particular column from the function. Fortunately, this is straightforward (although not obvious):Subclassing from
GenericFunction
has the added benefit of registering thegeocode
function globally so thatfunc.geocode
will work as expected.Unfortunately this doesn't quite work. There seems to be a bug that makes
g.c.addy.address
syntax not work on recent versions of SQLAlchemy. We can fix it real quick (although this should really be fixed in sqlalchemy_utils):Now it works: