@@ -145,8 +145,8 @@ def get_connection(self, timeout: float = 5.0):
145145 # CRITICAL: Always return and clean connection
146146 if conn is not None :
147147 try :
148- # Test if connection is still valid
149- # If the connection is closed, this will raise an exception
148+ # Reset connection state (clears DuckDB internal caches)
149+ # Use a simple query to clear any cached results
150150 result = conn .execute ("SELECT 1" ).fetchall ()
151151 del result
152152
@@ -158,31 +158,15 @@ def get_connection(self, timeout: float = 5.0):
158158 if collected > 100 :
159159 logger .debug (f"Connection cleanup: collected { collected } objects" )
160160
161- # Connection is valid, return to pool
162- self .pool .put (conn )
163-
164161 except Exception as e :
165- # Connection is invalid/closed - create a fresh one
166- logger .warning (f"Connection invalid during cleanup ({ e } ), creating fresh connection" )
167- try :
168- # Close the bad connection properly
169- conn .close ()
170- except Exception :
171- pass
172-
173- # Create and return a fresh connection to the pool
174- fresh_conn = duckdb .connect ()
175-
176- # Apply configuration if provided
177- if self .configure_fn :
178- try :
179- self .configure_fn (fresh_conn )
180- except Exception as config_error :
181- logger .error (f"Failed to configure fresh connection: { config_error } " )
182- fresh_conn .close ()
183- raise
184-
185- self .pool .put (fresh_conn )
162+ # If cleanup fails, connection may be closed - don't return it to pool
163+ logger .warning (f"Connection cleanup failed ({ e } ) - connection not returned to pool" )
164+ conn = None # Mark as invalid so we don't return it
165+
166+ finally :
167+ # Always return connection to pool (if still valid)
168+ if conn is not None :
169+ self .pool .put (conn )
186170
187171 def get_metrics (self ) -> Dict [str , Any ]:
188172 """
0 commit comments