Skip to content

Instantly share code, notes, and snippets.

@Xion Xion/sqla_enum.py
Created Oct 25, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.