Skip to content

Instantly share code, notes, and snippets.

@mfenniak
Created June 27, 2012 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfenniak/3006798 to your computer and use it in GitHub Desktop.
Save mfenniak/3006798 to your computer and use it in GitHub Desktop.
Plugin that enables unicode decoding for PostgreSQL's CITEXT column type when using psycopg2 and SQLAlchemy
from sqlalchemy.event import listen
def register_citext_type(conn, con_record):
from psycopg2.extensions import new_type, register_type
from contextlib import closing
def cast_citext(in_str, cursor):
if in_str == None:
return None
return unicode(in_str, cursor.connection.encoding)
with closing(conn.cursor()) as c:
c.execute("SELECT pg_type.oid FROM pg_type WHERE typname = 'citext'")
citext_oid = c.fetchone()
if citext_oid != None:
citext_type = new_type(citext_oid, "CITEXT", cast_citext)
register_type(citext_type)
# Replace db.engine with your SQLAlchemy engine
listen(db.engine, "first_connect", register_citext_type)
@manuganji
Copy link

Thank you for posting this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment