Cyril N.
Cyril N.

Reputation: 39859

SQLAlchemy TypeDecorator for BigInteger returns Decimal?

I'm trying to create a Type converter on SQLAlchemy that takes a BIGINTEGER from the database, and converts it to a Base64 value.

The problem is that, for some reasons, the value coming from the database is not an int, but a decimal.Decimal. I suspect this is linked to the BigInteger class I use (from the MySQL dialect instead of the BIGINT from SQLAlchemy because I need to set the unsigned parameter).

Any idea how to get the value from the database as int and not as decimal.Decimal ?

Here's my current implementation:

class B64ID(types.TypeDecorator):
    impl = BIGINT  # from sqlalchemy.dialects.mysql import BIGINT

    def __init__(self, prefix):
        self.prefix = prefix
        self.impl.unsigned = True
        types.TypeDecorator.__init__(self, unsigned=self.impl.unsigned)

    def process_bind_param(self, value, dialect=None):
        return int(base64.b64decode(value.encode()))

    def process_result_value(self, value, dialect=None):
        print(value, value.__class__)  # Here, in some case, the class is decimal.Decimal!
        return base64.b64encode(str(value).encode()).decode()

How can I define that the value coming from the database is not a decimal.Decimal, but an int ?

Upvotes: 0

Views: 529

Answers (1)

nullUser
nullUser

Reputation: 1833

BIGINT is returned to you as a python int, not a Decimal. The problem is likely that you didn't actually create the database column as a BIGINT.

Upvotes: 1

Related Questions