Skip to content

Instantly share code, notes, and snippets.

@Xion
Created October 25, 2015 23:02
Show Gist options
  • Save Xion/5564b907e5f4e883511c to your computer and use it in GitHub Desktop.
Save Xion/5564b907e5f4e883511c to your computer and use it in GitHub Desktop.
SQLAlchemy column type for storing Python enums
from enum import Enum
from inspect import isclass
import re
from sqlalchemy.types import TypeDecorator, TypeEngine
__all__ = ['EnumType']
class EnumType(TypeDecorator):
"""Column type for storing Python :class:`Enum` types
by converting them back-and-forth from & to a chosen SQL type.
"""
def __init__(self, enum, impl):
"""Constructor.
:type enum: Python :class:`Enum` subclass
:param impl: Actual SQL type for the database side
"""
if not issubclass(enum, Enum):
raise TypeError(
"argument must be a Python enum class; got %r" % (enum,))
if not ((isclass(impl) and issubclass(impl, TypeEngine))
or isinstance(impl, TypeEngine)):
raise TypeError(
"argument must be an ORM type; got %r" % (impl,))
self.enum = enum
self.impl = impl
def copy(self):
return EnumType(self.enum, self.impl)
def load_dialect_impl(self, dialect):
return dialect.type_descriptor(self.impl)
def process_bind_param(self, value, dialect):
""":type value: ``self.enum``"""
if value is None:
return None
return value.value
def process_result_value(self, value, dialect):
""":type value: ``self.impl``"""
if value is None:
return None
return self.enum(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment