Skip to content

Instantly share code, notes, and snippets.

@maou-shonen
Last active May 9, 2020 06:20
Show Gist options
  • Save maou-shonen/6ce26c6cbe1521dd5ea89a8407db438f to your computer and use it in GitHub Desktop.
Save maou-shonen/6ce26c6cbe1521dd5ea89a8407db438f to your computer and use it in GitHub Desktop.
sqlalchemy BinaryUUID (mysql/mariadb)
from uuid import UUID
from sqlalchemy.types import TypeDecorator
from sqlalchemy.dialects.mysql import BINARY
class BinaryUUID(TypeDecorator):
impl = BINARY(16)
def process_bind_param(self, value, dialect=None):
if not value:
return None
if isinstance(value, UUID):
return value.bytes
else:
raise ValueError('value {} is not a valid UUID'.format(value))
def process_result_value(self, value, dialect=None):
if not value:
return None
else:
return UUID(bytes=value)
from uuid import uuid4
from sqlalchemy import Column
from sqlalchemy.ext.declarative import declarative_base
from .BinaryUUID import BinaryUUID
Base = declarative_base()
from .Base import BinaryUUID
class User(Base):
__tablename__ = 'users'
id = Column(BinaryUUID(), primary_key=True, default=uuid4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment