@@ -48,6 +48,11 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
4848 return NULL ;
4949 }
5050
51+ #ifdef Py_GIL_DISABLED
52+ // Bound the number of statements waiting to be finalized.
53+ pysqlite_pending_stmts_finalize (connection -> pending_stmts );
54+ #endif
55+
5156 sqlite3 * db = connection -> db ;
5257 int max_length = sqlite3_limit (db , SQLITE_LIMIT_SQL_LENGTH , -1 );
5358 if (size > max_length ) {
@@ -98,6 +103,12 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
98103
99104 self -> st = stmt ;
100105 self -> is_dml = is_dml ;
106+ #ifdef Py_GIL_DISABLED
107+ assert (connection -> pending_stmts != NULL );
108+ self -> pending = connection -> pending_stmts ;
109+ _Py_atomic_add_ssize (& self -> pending -> refcnt , 1 );
110+ self -> next_pending = NULL ;
111+ #endif
101112
102113 PyObject_GC_Track (self );
103114 return self ;
@@ -112,6 +123,8 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
112123 return NULL ;
113124}
114125
126+ #ifndef Py_GIL_DISABLED
127+
115128static void
116129stmt_dealloc (PyObject * op )
117130{
@@ -134,6 +147,168 @@ stmt_dealloc(PyObject *op)
134147 Py_DECREF (tp );
135148}
136149
150+ #else // Py_GIL_DISABLED
151+
152+ /*
153+ * Finalizing a statement needs the mutex of its database connection. If
154+ * another thread is using the connection, that mutex can be held for a long
155+ * time: for example, while sqlite3_step() waits in the busy handler for a
156+ * file lock. If the thread that deallocates the statement is the one holding
157+ * that file lock (through another connection), blocking on the mutex stalls
158+ * both threads until the busy timeout expires. On the free-threaded build
159+ * this happens in normal use: when a thread that does not own the statement
160+ * drops the last reference (e.g. evicts it from the statement cache), the
161+ * decref is queued and the owning thread deallocates the statement later, at
162+ * an arbitrary point. So stmt_dealloc() must not wait for the mutex.
163+ *
164+ * Instead, the dead statement is put on a list shared with the connection and
165+ * is finalized only if the mutex can be taken without blocking. Statements
166+ * left on the list are finalized the next time the connection prepares or
167+ * executes a statement, or when it is closed. Delaying sqlite3_finalize() is
168+ * harmless: the statement has normally been reset already and holds no locks.
169+ */
170+
171+ pysqlite_pending_stmts *
172+ pysqlite_pending_stmts_new (void )
173+ {
174+ pysqlite_pending_stmts * pending = PyMem_Calloc (1 , sizeof (* pending ));
175+ if (pending == NULL ) {
176+ PyErr_NoMemory ();
177+ return NULL ;
178+ }
179+ pending -> refcnt = 1 ;
180+ return pending ;
181+ }
182+
183+ static void
184+ pending_stmts_decref (pysqlite_pending_stmts * pending )
185+ {
186+ if (_Py_atomic_add_ssize (& pending -> refcnt , -1 ) == 1 ) {
187+ assert (pending -> head == NULL );
188+ PyMem_Free (pending );
189+ }
190+ }
191+
192+ /* Finalize a dead statement and free it. If 'mutex' is not NULL, it is the
193+ * mutex of the statement's database, held by the caller; it is released. */
194+ static void
195+ stmt_destroy (pysqlite_Statement * self , sqlite3_mutex * mutex )
196+ {
197+ PyTypeObject * tp = Py_TYPE (self );
198+ int rc ;
199+ // Release the database mutex before re-attaching the thread state: a
200+ // thread waiting for that mutex may be attached.
201+ Py_BEGIN_ALLOW_THREADS
202+ rc = sqlite3_finalize (self -> st );
203+ sqlite3_mutex_leave (mutex );
204+ Py_END_ALLOW_THREADS
205+ self -> st = NULL ;
206+ if (rc != SQLITE_OK ) {
207+ pysqlite_state * state = PyType_GetModuleState (tp );
208+ PyErr_SetString (state -> InternalError , "cannot finalize statement" );
209+ PyErr_FormatUnraisable ("Exception ignored in stmt_dealloc()" );
210+ }
211+ pending_stmts_decref (self -> pending );
212+ tp -> tp_free (self );
213+ Py_DECREF (tp );
214+ }
215+
216+ static void
217+ stmt_destroy_list (pysqlite_Statement * head )
218+ {
219+ while (head != NULL ) {
220+ pysqlite_Statement * next = head -> next_pending ;
221+ stmt_destroy (head , NULL );
222+ head = next ;
223+ }
224+ }
225+
226+ /* Finalize the statements waiting on the list. The caller must be using the
227+ * connection, so that waiting for the database mutex is fine. */
228+ void
229+ pysqlite_pending_stmts_finalize (pysqlite_pending_stmts * pending )
230+ {
231+ if (_Py_atomic_load_ptr_relaxed (& pending -> head ) == NULL ) {
232+ return ;
233+ }
234+ PyMutex_Lock (& pending -> mutex );
235+ pysqlite_Statement * head = pending -> head ;
236+ _Py_atomic_store_ptr_relaxed (& pending -> head , NULL );
237+ PyMutex_Unlock (& pending -> mutex );
238+ stmt_destroy_list (head );
239+ }
240+
241+ /* Called when the connection is closed: finalize the waiting statements and
242+ * drop the connection's reference. After that nothing can hold the database
243+ * mutex for long, so statements deallocated later are finalized directly. */
244+ void
245+ pysqlite_pending_stmts_close (pysqlite_pending_stmts * pending )
246+ {
247+ PyMutex_Lock (& pending -> mutex );
248+ pending -> closed = 1 ;
249+ pysqlite_Statement * head = pending -> head ;
250+ _Py_atomic_store_ptr_relaxed (& pending -> head , NULL );
251+ PyMutex_Unlock (& pending -> mutex );
252+ stmt_destroy_list (head );
253+ pending_stmts_decref (pending );
254+ }
255+
256+ static void
257+ stmt_dealloc (PyObject * op )
258+ {
259+ pysqlite_Statement * self = _pysqlite_Statement_CAST (op );
260+ PyObject_GC_UnTrack (op );
261+
262+ pysqlite_pending_stmts * pending = self -> pending ;
263+ if (self -> st == NULL ) {
264+ // Empty statement (no SQL): nothing to finalize.
265+ stmt_destroy (self , NULL );
266+ return ;
267+ }
268+ PyMutex_Lock (& pending -> mutex );
269+ if (pending -> closed ) {
270+ PyMutex_Unlock (& pending -> mutex );
271+ stmt_destroy (self , NULL );
272+ return ;
273+ }
274+ // Keep the list alive for the loop below. This must be done before the
275+ // statement is put on the list: once it is there, another thread can
276+ // destroy it and close the connection, dropping the last references.
277+ _Py_atomic_add_ssize (& pending -> refcnt , 1 );
278+ self -> next_pending = pending -> head ;
279+ _Py_atomic_store_ptr_relaxed (& pending -> head , self );
280+ PyMutex_Unlock (& pending -> mutex );
281+
282+ // Finalize the statements on the list (normally just this one) for as
283+ // long as the database mutex is free. Taking the list lock again after
284+ // each one also picks up statements added by threads that found the
285+ // database mutex held by us.
286+ for (;;) {
287+ PyMutex_Lock (& pending -> mutex );
288+ pysqlite_Statement * stmt = pending -> head ;
289+ sqlite3_mutex * mutex = NULL ;
290+ if (stmt != NULL ) {
291+ // The database stays valid while the statement is on the list.
292+ mutex = sqlite3_db_mutex (sqlite3_db_handle (stmt -> st ));
293+ if (sqlite3_mutex_try (mutex ) == SQLITE_OK ) {
294+ _Py_atomic_store_ptr_relaxed (& pending -> head ,
295+ stmt -> next_pending );
296+ }
297+ else {
298+ stmt = NULL ;
299+ }
300+ }
301+ PyMutex_Unlock (& pending -> mutex );
302+ if (stmt == NULL ) {
303+ break ;
304+ }
305+ stmt_destroy (stmt , mutex );
306+ }
307+ pending_stmts_decref (pending );
308+ }
309+
310+ #endif // Py_GIL_DISABLED
311+
137312/*
138313 * Strip leading whitespace and comments from incoming SQL (null terminated C
139314 * string) and return a pointer to the first non-whitespace, non-comment
0 commit comments