Created
October 25, 2015 23:02
-
-
Save Xion/5564b907e5f4e883511c to your computer and use it in GitHub Desktop.
SQLAlchemy column type for storing Python enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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