Skip to content

Instantly share code, notes, and snippets.

@hendawy
Created August 9, 2017 11:42
Show Gist options
  • Save hendawy/308362107a000d06621413ca057fa078 to your computer and use it in GitHub Desktop.
Save hendawy/308362107a000d06621413ca057fa078 to your computer and use it in GitHub Desktop.
from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID
import uuid
class GUID(TypeDecorator):
"""Platform-independent GUID type.
Uses PostgreSQL's UUID type, otherwise uses
CHAR(36), storing as stringified hex values.
"""
impl = CHAR
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(UUID())
else:
return dialect.type_descriptor(CHAR(36))
def process_bind_param(self, value, dialect):
if value is None:
return value
elif dialect.name == 'postgresql':
return str(value)
else:
if not isinstance(value, uuid.UUID):
return str(uuid.UUID(value))
else:
# hexstring
return str(value)
def process_result_value(self, value, dialect):
if value is None:
return value
else:
return uuid.UUID(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment