diff --git a/src/MySQLdb/_mysql.c b/src/MySQLdb/_mysql.c index 8d832bfd..813a872c 100644 --- a/src/MySQLdb/_mysql.c +++ b/src/MySQLdb/_mysql.c @@ -327,8 +327,22 @@ _mysql_ResultObject_Initialize( &_mysql_ConnectionObject_Type, &conn, &use, &conv)) return -1; - self->conn = (PyObject *) conn; - Py_INCREF(conn); + /* A result keeps its original connection and buffering mode until deallocation. */ + bool already_initialized; +#ifdef Py_GIL_DISABLED + Py_BEGIN_CRITICAL_SECTION(self); +#endif + already_initialized = self->conn != NULL; + if (!already_initialized) { + self->conn = Py_NewRef(conn); + } +#ifdef Py_GIL_DISABLED + Py_END_CRITICAL_SECTION(); +#endif + if (already_initialized) { + PyErr_SetString(_mysql_ProgrammingError, "Result is already initialized"); + return -1; + } self->use = use; if (BEGIN_CONNECTION_LOCK(conn) < 0) { return -1; @@ -2587,13 +2601,14 @@ static void _mysql_ResultObject_dealloc( _mysql_ResultObject *self) { - PyObject *conn = self->conn; PyObject_GC_UnTrack((PyObject *)self); - if (conn != NULL) { + /* Only an unbuffered result may need to read remaining rows from the connection. */ + bool lock_connection = self->use && self->result != NULL && self->conn != NULL; + if (lock_connection) { BEGIN_RESULT_CONNECTION_LOCK(self); } mysql_free_result(self->result); - if (conn != NULL) { + if (lock_connection) { END_RESULT_CONNECTION_LOCK(self); } _mysql_ResultObject_clear(self); diff --git a/tests/test_connection.py b/tests/test_connection.py index 790eecc8..ea6a1e46 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1,13 +1,14 @@ import enum import threading import time +from concurrent.futures import ThreadPoolExecutor import pytest from configdb import connection_factory, connection_kwargs from MySQLdb._exceptions import ProgrammingError from MySQLdb.connections import Connection -from MySQLdb.constants import CLIENT +from MySQLdb.constants import CLIENT, FIELD_TYPE @pytest.fixture @@ -168,6 +169,41 @@ def run_slow_query(): assert thread_error is None +@pytest.mark.parametrize("use", [False, True]) +def test_result_rejects_reinitialization(conn, use): + conn.query("SELECT 1 UNION ALL SELECT 2 ORDER BY 1") + result = conn.use_result() if use else conn.store_result() + with pytest.raises(ProgrammingError, match="already initialized"): + result.__init__(conn, not use) + + assert result.fetch_row() == ((1,),) + del result # Leave the second row for cleanup. + conn.query("SELECT 3") + assert conn.store_result().fetch_row() == ((3,),) + + +def test_stored_result_dealloc_while_connection_locked(conn): + stored = [] + + def store_result(): + conn.query("SELECT 1") + stored.append(conn.store_result()) + + with ThreadPoolExecutor(max_workers=1) as executor: + # On free-threaded CPython, drop the last reference on its owning thread. + executor.submit(store_result).result() + + def convert(value): + # fetch_row holds the connection lock while calling this converter. + executor.submit(stored.clear).result(timeout=5) + return int(value) + + conn.converter[FIELD_TYPE.NEWDECIMAL] = convert + conn.query("SELECT CAST(2 AS DECIMAL(1,0))") + assert conn.use_result().fetch_row() == ((2,),) + assert not stored + + def test_result_concurrent_use_raises(conn): """While fetch_row holds the connection lock streaming a slow result, any other access from a second thread must raise ProgrammingError immediately."""