Skip to content

Instantly share code, notes, and snippets.

Last active May 10, 2016 09:19
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
# How to use PG Point type in SQAlchemy
# Most of the code comes from here:
import re
import sqlalchemy
import psycopg2
from psycopg2.extensions import adapt, register_adapter, AsIs
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def adapt_point(point):
return AsIs("'(%s, %s)'" % (adapt(point.x), adapt(point.y)))
def cast_point(value, cur):
if value is None:
return None
# Convert from (f1, f2) syntax using a regular expression.
m = re.match(r"\(([^)]+),([^)]+)\)", value)
if m:
return Point(float(, float(
raise psycopg2.InterfaceError("bad point representation: %r" % value)
def register_point_type(engine):
register_adapter(Point, adapt_point)
rs = engine.execute("SELECT NULL::point")
point_oid = rs.cursor.description[0][1]
POINT = psycopg2.extensions.new_type((point_oid,), "POINT", cast_point)
engine = sqlalchemy.create_engine(
if __name__ == '__main__':
create table t (
p point
engine.execute("insert into t values (%s)", Point(1, 2))
print(dict(engine.execute("select * from t").fetchone()))
engine.execute('drop table t')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment