psycopg / psycopg2

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

cursor.closed=-1 but raises "cursor already closed" #1719

Closed gtavella closed 1 month ago

gtavella commented 1 month ago

Ciao Daniele, what seems like a bug when closing a cursor.

cursor.closed should be 1 when cursor is closed, correct?

The docs don't seem to contain that information, they only say that it's either True or False

before closing the cursor <cursor object at 0x0000016BEA64EA40; closed: 0>

after closing the cursor with cursor.close() <cursor object at 0x0000016BEA64EA40; closed: -1>

however this is what I get:

Traceback (most recent call last): File "C:\Users\giuse\Desktop\assotax\utils\DatabasePipeline\DatabasePipeline.py", line 496, in _run_pipeline_func self.pipeline_func(ctx, self, *args, kw) File "C:\Users\giuse\Desktop\assotax\utils\DatabasePipeline\tesserati.py", line 18, in add step1(pip, ctx.form_orig, File "C:\Users\giuse\Desktop\assotax\utils\DatabasePipeline\DatabasePipeline.py", line 650, in call self.step_func(self, params, kw) File "C:\Users\giuse\Desktop\assotax\utils\DatabasePipeline\tesserati.py", line 78, in step1 results = curs.fetchall() ^^^^^^^^^^^^^^^ psycopg2.InterfaceError: cursor already closed

Context

To provide some custom logic, I have "pipeline" and "pipeline steps" functions.

conn points to the actual psycopg2 connection object

curs = self.this_pipeline.conn.cursor()

and then I simply close the cursor curs.close()

also when opening the cursor, I pass one parameter: {"cursor_factory": psycopg2.extras.RealDictCursor}

that's the only customization I have.

I can assume that the cursor was successfully closed even when I get -1?

Thanks for all the work

dvarrazzo commented 1 month ago

Hello @gtavella

-1 is a C-ism: it is the binary not of a 0 in a signed type in C. So that might leak through Python. Probably that code was written when Python didn't have bool types.

You can safely use if cur.closed and if not cur.closed, regardless of the precise value of the attribute. -1 is a true value anyway.