Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 869
tanay Avatar asked Dec 11 '25 23:12

tanay


1 Answers

Looks like the easier way is to build the adaptation into the Enum itself:

class SqliteEnum(enum.Enum):
    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return self.name

and then use SqliteEnum as the base for your other Enum classes.

like image 56
Ethan Furman Avatar answered Dec 13 '25 13:12

Ethan Furman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!