Skip to content

Instantly share code, notes, and snippets.

@cowbert
Last active January 30, 2019 00:31
Show Gist options
  • Save cowbert/15ed84cef4c25861b8b05ab33811ece8 to your computer and use it in GitHub Desktop.
Save cowbert/15ed84cef4c25861b8b05ab33811ece8 to your computer and use it in GitHub Desktop.
from uuid import UUID as py_UUID
from sqlalchemy.dialects.postgresql import BYTEA as pg_BYTEA
from sqlalchemy.dialects.oracle import RAW as ora_RAW
from sqlalchemy.types import TypeDecorator, BINARY
class sqla_type_UUID(TypeDecorator):
impl = BINARY
def __init__(self):
self.impl.length = 16
super(sqla_type_UUID, self).__init__(length=self.impl.length)
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(pg_BYTEA(self.impl.length))
elif dialect.name == 'oracle':
return dialect.type_descriptor(ora_RAW(self.impl.length))
def process_bind_param(self, value, dialect=None):
# PY None => SQL null
if not value:
return None
try:
# passed a UUID object
return value.bytes
except AttributeError:
# maybe I submitted a string of hex characters
try:
return py_UUID(value).bytes
except ValueError:
raise ValueError(
'value {} is not a valid representation of a UUID object'.format(value)
) from None
def process_result_value(self, value, dialect=None):
if value:
# SQL binary => PY UUID
return py_UUID(bytes=value)
# SQL null => None
return None
import uuid
from sqlalchemy import Column, String, Integer, DateTime, Text
from sqlalchemy.ext.declarative import declarative_base
from sqla_uuid import sqla_type_UUID
Base = declarative_base()
class ModelUUID(Base):
__tablename__ = "mytable"
uuid = Column(sqla_type_UUID, primary_key=True)
short_text = Column(String(40))
long_text = Column(Text)
anint = Column(Integer)
ts = Column(DateTime)
# default on object create, pre-insert
def __init__(self, *args, **kwargs):
if 'uuid' not in kwargs:
self.uuid = uuid.uuid4()
super().__init__(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment