'''
These classes define native PostgreSQL geometry types to be used with SQLAlchemy.
'''
from sqlalchemy.types import TypeDecorator, VARCHAR
class PGPolygon(TypeDecorator):
"""Represents the native polygon data type in PostgreSQL (i.e. *not* PostGIS).
Usage::
polygonColumnName = Column('polygon_column_name', PGPolygon)
"""
impl = VARCHAR
def process_bind_param(self, value, dialect):
'''
Take the object and convert it into a string to be entered into the database.
The value should be in the form of a Python list of tuples, e.g.
[ (x1,y1), (x2,y2), (x3,y3), ... ]
'''
if value is not None:
value = "({0})".format(",".join([str(x) for x in value]))
return value
def process_result_value(self, value, dialect):
'''
Take the polygon value from the database and convert it into a list of point tuples.
The incoming format looks like this: '((12,34),(56,78),(90,12))'
'''
if value is not None:
polygon = list()
for point in value[1:-1].split("),("): # also strip outer single quotes
point = point.lstrip("(") # remove extra "(" ")" (first and last elements only)
point = point.rstrip(")")
x, y = point.split(",")
polygon.append((float(x), float(y)))
value = polygon
return value