[Sqlalchemy-tickets] Issue #4180: Enum type stores wrong values in DB when aliases are used (zzzeek
Brought to you by:
zzzeek
From: Daniel K. <iss...@bi...> - 2018-02-02 15:38:37
|
New issue 4180: Enum type stores wrong values in DB when aliases are used https://bitbucket.org/zzzeek/sqlalchemy/issues/4180/enum-type-stores-wrong-values-in-db-when Daniel Knell: There is a problem with how SQLAlchemy stores Python Enum types when native enums are disabled and said Enum contains aliases. ```python class Country(enum.Enum): GB = 'gb' FR = 'fr' UK = 'gb' # alias the GB item foo = Table( 'foo', metadata, Column('country', Enum(Country,native_enum=False,create_constraint=False)) ) ``` ```python >>> Country.GB <Country.GB: 'gb'> >>> Country.UK <Country.GB: 'gb'> >>> Country.GB.name 'GB' >>> Country.UK.name 'GB' >>> ``` If you store the value Country.GB in the table foo it will be stored as UK instead of GB. I believe this is caused by flipping the dictionary keys/values in Enum._setup_for_values, instead of using the name param of the enum. https://github.com/zzzeek/sqlalchemy/blob/699272e4dcb9aa71ebbc0d9487fb6de82d3abc2b/lib/sqlalchemy/sql/sqltypes.py#L1357 ```python >>> import enum >>> >>> class Country(enum.Enum): ... GB = 'gb' ... FR = 'fr' ... UK = 'gb' # alias the GB item ... >>> values = list(Country.__members__) >>> objects = [Country.__members__[k] for k in values] >>> dict(zip(values, objects)) {'GB': <Country.GB: 'gb'>, 'FR': <Country.FR: 'fr'>, 'UK': <Country.GB: 'gb'>} >>> dict((value, key) for key, value in _.items()) {<Country.GB: 'gb'>: 'UK', <Country.FR: 'fr'>: 'FR'} >>> ``` https://gist.github.com/danielknell/e3c9c7b65b395a2e295ee8237a70286e |