MagicStack / asyncpg

A fast PostgreSQL Database Client Library for Python/asyncio.
Apache License 2.0
6.88k stars 399 forks source link

SELECT query to database returns wrong decimal values. #1160

Closed JavaProgswing closed 2 months ago

JavaProgswing commented 3 months ago

I have this postgres table:

    version float4,
    releaseurl varchar(128),
    releaseinfo varchar(128),
    timestamp int4,

where version is the primary key.

I use this select request to fetch the latest version SELECT version, releaseinfo, timestamp FROM ... ORDER BY version DESC LIMIT 1

it returns me 3.0999999046325684 in asyncpg python. yet the database has no such value, I was guessing perhaps a precision error on that and it was getting 3.1.

Cuz the database does have 3.1 and when i use the same query on java JDBC, it does return 3.1

thomas-mckay commented 3 months ago

Probably a precision error when converting to a Python float: https://magicstack.github.io/asyncpg/current/usage.html#id3

Try casting to decimal in your query, see if it changes.

On a side-note, though related if I understand your table correctly, I'd suggest using a fixed-length array of integers for version numbers. Even if you're absolutely sure you'll never have values like 3.14.2, a version number is not a float (or a decimal). And comparison becomes natural with an array of ints:

JavaProgswing commented 3 months ago

Oh yep having a list of integers is definitely better. I'll do that.

I'll try casting and see if it works. Cuz was working normally in a other python library.

JavaProgswing commented 2 months ago

Yep, works when casting to text.