BIT 0 represented as '\x00'

1.5k Views Asked by At

In a database table I have a column defined as: enter image description here

Using this query: query = text( "SELECT * FROM %s WHERE " % "aTable" "%s=%s AND " % ("done", 0) )

    result = engine.execute(query)
    row = result.fetchone()

when I call print row['done'] then I get '\x00'.

For generation of tables I sqlacodegen which generated the done columns as this:

Column('done', BIT(1), nullable=False),

Am I missing some configuration in SqlAlchemy? I don't want to convert the hex to int everywhere I am goint to use a BIT column.

EDIT So the problem is not with sqlalchemy but it seems that pymysql is to blame.

2

There are 2 best solutions below

0
mabe02 On

Try to have a look to this chapter of the Python documentation.

However, in your case, it might be enough something like ord to convert your hex:

>>> a = b'\x00' 
>>> a
'\x00'
>>> str(a)
'\x00'
>>> ord(a)
0
>>> ord('\x5f')
95
0
Amio.io On

The solution is to override the BIT column converter and pass it to connection of pyMysql:

from pymysql import converters
converions = converters.conversions
converions[FIELD_TYPE.BIT] = lambda x: False if '\x00' else True
return pymysql.connect(
        conv=converions,
        ...
    )