import sys
import asyncio
import logging
+import warnings
import threading
from types import TracebackType
from typing import Any, AsyncIterator, Callable, Iterator, List, NamedTuple
pgconn.notice_handler = partial(BaseConnection._notice_handler, wself)
pgconn.notify_handler = partial(BaseConnection._notify_handler, wself)
+ def __del__(self) -> None:
+ status = self.pgconn.transaction_status
+ if status == TransactionStatus.UNKNOWN:
+ return
+
+ elif status == TransactionStatus.INTRANS:
+ msg = (
+ f"connection {self} was deleted with an open transaction,"
+ " changes discarded by the server"
+ )
+ else:
+ status = TransactionStatus(status) # in case we got an int
+ msg = f"connection {self} was deleted open in status {status.name}"
+
+ warnings.warn(msg, ResourceWarning)
+
@property
def closed(self) -> bool:
"""`True` if the connection is closed."""
cur.execute("select 1")
+def test_connection_warn_close(dsn, recwarn):
+ conn = Connection.connect(dsn)
+ conn.close()
+ del conn
+ assert not recwarn
+
+ conn = Connection.connect(dsn)
+ del conn
+ assert "IDLE" in str(recwarn.pop(ResourceWarning).message)
+
+ conn = Connection.connect(dsn)
+ conn.execute("select 1")
+ del conn
+ assert "discarded" in str(recwarn.pop(ResourceWarning).message)
+
+ conn = Connection.connect(dsn)
+ try:
+ conn.execute("select wat")
+ except Exception:
+ pass
+ del conn
+ assert "INERROR" in str(recwarn.pop(ResourceWarning).message)
+
+ with Connection.connect(dsn) as conn:
+ pass
+ del conn
+ assert not recwarn
+
+
def test_context_commit(conn, dsn):
with conn:
with conn.cursor() as cur:
await cur.execute("select 1")
+async def test_connection_warn_close(dsn, recwarn):
+ conn = await AsyncConnection.connect(dsn)
+ await conn.close()
+ del conn
+ assert not recwarn
+
+ conn = await AsyncConnection.connect(dsn)
+ del conn
+ assert "IDLE" in str(recwarn.pop(ResourceWarning).message)
+
+ conn = await AsyncConnection.connect(dsn)
+ await conn.execute("select 1")
+ del conn
+ assert "discarded" in str(recwarn.pop(ResourceWarning).message)
+
+ conn = await AsyncConnection.connect(dsn)
+ try:
+ await conn.execute("select wat")
+ except Exception:
+ pass
+ del conn
+ assert "INERROR" in str(recwarn.pop(ResourceWarning).message)
+
+ async with await AsyncConnection.connect(dsn) as conn:
+ pass
+ del conn
+ assert not recwarn
+
+
async def test_context_commit(aconn, dsn):
async with aconn:
async with await aconn.cursor() as cur: