psycopg / psycopg2

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

AsyncCursor.execute exception messages are unhelpful #1750

Closed allComputableThings closed 4 weeks ago

allComputableThings commented 4 weeks ago
query =  Composed([SQL('INSERT INTO '), Identifier('user'), SQL(' ( '), Identifier('first_name'), SQL(', '), Identifier('last_name'), SQL(' ) VALUES ( %%s, %%s);')])
params = ['a', 'b']
acursor.execute(query, params)   # AsyncCursor

>>
  File "/home/sir/venv/py3/lib/python3.10/site-packages/psycopg/_cursor_base.py", line 195, in _execute_gen
    pgq = self._convert_query(query, params)
  File "/home/sir/venv/py3/lib/python3.10/site-packages/psycopg/_cursor_base.py", line 455, in _convert_query
    pgq.convert(query, params)
  File "/home/sir/venv/py3/lib/python3.10/site-packages/psycopg/_queries.py", line 82, in convert
    len(bquery) <= MAX_CACHED_STATEMENT_LENGTH
TypeError: object of type 'Composed' has no len()

but...

conn = psycopg2.connect(self.params.conn_str)
c = conn.cursor()
c.execute(query, params)

psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: ... INTO "user" ( "first_name", "last_name" ) VALUES ( %s, %s);                
dvarrazzo commented 4 weeks ago

I don't understand your examples. They give different error messages to me, as %%s are not valid parameters.

It is not a Python practice to inspect the types of the argument upfront and throw error messages if the type is not what expected. The custom is to pass arguments to the function assuming that the user knows what they are doing (duck typing). If you want to catch type errors you can use a linter such as Mypy.