Skip to content

add support for enums in sqlalchemy ChoiceType #240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion graphene_sqlalchemy/converter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from enum import EnumMeta

from singledispatch import singledispatch
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
Expand Down Expand Up @@ -163,7 +165,12 @@ def convert_enum_to_enum(type, column, registry=None):
@convert_sqlalchemy_type.register(ChoiceType)
def convert_choice_to_enum(type, column, registry=None):
name = "{}_{}".format(column.table.name, column.name).upper()
return Enum(name, type.choices)
if isinstance(type.choices, EnumMeta):
# type.choices may be Enum/IntEnum, in ChoiceType both presented as EnumMeta
# do not use from_enum here because we can have more than one enum column in table
return Enum(name, list((v.name, v.value) for v in type.choices))
else:
return Enum(name, type.choices)


@convert_sqlalchemy_type.register(ScalarListType)
Expand Down
26 changes: 26 additions & 0 deletions graphene_sqlalchemy/tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,32 @@ def test_should_choice_convert_enum():
assert graphene_type._meta.enum.__members__["en"].value == "English"


def test_should_enum_choice_convert_enum():
class TestEnum(enum.Enum):
es = u"Spanish"
en = u"English"

field = get_field(ChoiceType(TestEnum, impl=types.String()))
graphene_type = field.type
assert issubclass(graphene_type, graphene.Enum)
assert graphene_type._meta.name == "MODEL_COLUMN"
assert graphene_type._meta.enum.__members__["es"].value == "Spanish"
assert graphene_type._meta.enum.__members__["en"].value == "English"


def test_should_intenum_choice_convert_enum():
class TestEnum(enum.IntEnum):
one = 1
two = 2

field = get_field(ChoiceType(TestEnum, impl=types.String()))
graphene_type = field.type
assert issubclass(graphene_type, graphene.Enum)
assert graphene_type._meta.name == "MODEL_COLUMN"
assert graphene_type._meta.enum.__members__["one"].value == 1
assert graphene_type._meta.enum.__members__["two"].value == 2


def test_should_columproperty_convert():
field = get_field_from_column(column_property(
select([func.sum(func.cast(id, types.Integer))]).where(id == 1)
Expand Down