mercredi 4 novembre 2015

python sqlite3 adapter for custom type

I am using sqlite3 for db access in a python module.

I frequently use enums in my python objects. Currently I have to convert my enums into strings before inserting them into the sqlite db. My following attempt to register a generic adapter to make this conversion implicit fails.

def adapt_enum(enum_instance):
    return enum_instance.name

sqlite3.register_adapter(enum.Enum,adapt_enum)

The above implementation results in the following error.

sqlite3.InterfaceError: Error binding parameter 5 - probably unsupported type.

Registering an adapter for each enum, as shown below works fine however

class MyEnum(Enum):
    a = 1
    b = 2

def adapt_my_enum(my_enum_instance):
    return my_enum_instance.name

sqlite3.register_adapter(MyEnum,adapt_my_enum)

The adapter for MyEnum works as expected. But going this way I have to register an adapter for all my enums separately. Is there a way to remove this redundancy?

P.S. I am using python 2.7

Aucun commentaire:

Enregistrer un commentaire