]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix(pool): trade off usage timing precision for robustness
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 6 Oct 2023 12:36:43 +0000 (14:36 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 6 Oct 2023 15:06:33 +0000 (17:06 +0200)
It is unlikely that the statements we shuffled around will fail;
however, let's do the right thing and make sure that, if they do, the
getconn/putconn pair remains matched.

psycopg_pool/psycopg_pool/pool.py
psycopg_pool/psycopg_pool/pool_async.py

index 354cbd77cd504c20d08ca8e5d3831df9b3cc3a5d..a67e29adfc58af9b97a3216d00ca08fa947e067d 100644 (file)
@@ -138,14 +138,14 @@ class ConnectionPool(BasePool[Connection[Any]]):
         in working state, replace it with a new one.
         """
         conn = self.getconn(timeout=timeout)
-        t0 = monotonic()
         try:
+            t0 = monotonic()
             with conn:
                 yield conn
         finally:
+            self.putconn(conn)
             t1 = monotonic()
             self._stats[self._USAGE_MS] += int(1000.0 * (t1 - t0))
-            self.putconn(conn)
 
     def getconn(self, timeout: Optional[float] = None) -> Connection[Any]:
         """Obtain a connection from the pool.
index a03b33d2ff6b9c8e042a5eed1f19107ca3248928..03dd61e1c4b069a35c26cc58c012fcc7ee3c5c48 100644 (file)
@@ -116,14 +116,14 @@ class AsyncConnectionPool(BasePool[AsyncConnection[Any]]):
         self, timeout: Optional[float] = None
     ) -> AsyncIterator[AsyncConnection[Any]]:
         conn = await self.getconn(timeout=timeout)
-        t0 = monotonic()
         try:
+            t0 = monotonic()
             async with conn:
                 yield conn
         finally:
+            await self.putconn(conn)
             t1 = monotonic()
             self._stats[self._USAGE_MS] += int(1000.0 * (t1 - t0))
-            await self.putconn(conn)
 
     async def getconn(self, timeout: Optional[float] = None) -> AsyncConnection[Any]:
         logger.info("connection requested from %r", self.name)