Solution!!! ENUM type that works with sqlite too

17 views
Skip to first unread message

Ian Charnas

unread,
Apr 22, 2007, 9:33:35 AM4/22/07
to sqlalchemy
I'm sure a lot of us have done something like this, I figured I'd post
it so people can find it in a google search and won't have to write it
and debug it themselves... This is a Type that emulates ENUM for
engines (like sqlite) that don't have a native ENUM type. This
*could* be augmented so that it uses the actual ENUM type for engines
that support it. For those interested, you'd add a "get_col_spec"
method (see other types in sqlalchemy/types.py for details)

class EnumType(Unicode):
"""Basic type that emulates ENUM sql type.

Useful for database engines that don't support ENUM (such as
sqlite).
required 'names' parameter must be a list of strings for this ENUM

"""
def __init__(self, names, *args, **kw):
self.names = names
super(EnumType, self).__init__(*args, **kw)
def convert_bind_param(self, value, engine):
if value is not None and value not in self.names:
raise EnumError("Value(%s) not in Enum(%s)" %
(value, ", ".join(self.names)))
return super(EnumType, self).convert_bind_param(value, engine)

and this is how you'd use it:

customers_table = Table('customer', metadata,
Column('name', String(50)),
Column('frequency', EnumType(names=['Rare', 'Occasional',
'Regular']), default='Rare'),
)

Brett

unread,
Apr 23, 2007, 10:10:21 AM4/23/07
to sqlal...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages