Created
September 21, 2020 02:22
-
-
Save jkominek/df05bd7b2de7dcfaac8106a4a1e705bc to your computer and use it in GitHub Desktop.
sqlalchemy postgresql poor man's custom types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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