Skip to content

Instantly share code, notes, and snippets.

@jkominek
Created September 21, 2020 02:22
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 jkominek/df05bd7b2de7dcfaac8106a4a1e705bc to your computer and use it in GitHub Desktop.
Save jkominek/df05bd7b2de7dcfaac8106a4a1e705bc to your computer and use it in GitHub Desktop.
sqlalchemy postgresql poor man's custom types
# I had a fancy custom type in PG, and wanted to use it in
# SQLAlchemy. I didn't care to jump through all of the custom
# type stuff, and the type had an reasonable representation
# to JSON, and PG could convert it to/from JSON very easily.
# So I added cast conversions to PG, and then this special
# type:
class CastToJSONB(sqlalchemy.types.TypeDecorator):
'''A JSON object where we force PostgreSQL to cast our
interactions with the value to JSON. Useful when we've
got a PG data type that is a pain in the ass, but has an
acceptable JSON representation, and appropriate CAST functions
installed into the PG database.
'''
impl = sqlalchemy.types.JSON
def column_expression(self, col):
return cast(col, JSON)
def bind_expression(self, bindparam):
return cast(bindparam, JSON)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment