psycopg / psycopg2

PostgreSQL database adapter for the Python programming language
https://www.psycopg.org/
Other
3.31k stars 503 forks source link

Incorrect Decimal('Infinity') adaptation #1724

Open hordiienko-v opened 2 weeks ago

hordiienko-v commented 2 weeks ago

Since v14, PostgreSQL NUMERIC type supports Infinity value. But for now, psycopg2 adapts Infinity as 'NaN'::numeric. This can be avoided by creating custom type adapter that wraps decimal value in quotes, but still, adapting to NaN seems like outdated logic.

from decimal import Decimal

from psycopg2 import connect
from psycopg2._psycopg import connection, cursor

if __name__ == "__main__":
    conn: connection
    curr: cursor

    with connect("dbname=test_db user=test_user password=test_user") as conn:
        with conn.cursor() as curr:
            q = curr.mogrify(
                "INSERT INTO test VALUES (%s), (%s)",
                [Decimal("1"), Decimal("Infinity")],
            )
            print(q)
            # b"INSERT INTO test VALUES (1), ('NaN'::numeric)"
dvarrazzo commented 2 weeks ago

Thank you for the report. The solution is probably little enough invasive that we can provide it in the next bugfix release.

Psycopg 3 already does the right thing:

>>> import psycopg.sql
>>> from decimal import Decimal
>>> psycopg.sql.quote(Decimal("Infinity"))
"'Infinity'::numeric"