Skip to content

Commit 9529979

Browse files
committed
add get_connection function
1 parent 617d38a commit 9529979

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

postgrestq/task_queue.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
Sequence,
1515
)
1616

17-
from psycopg import sql, connect
17+
from psycopg import sql, connect, Connection
1818

1919
# supported only from 3.11 onwards:
2020
# from datetime import UTC
@@ -69,19 +69,28 @@ def __init__(
6969
# called when ttl <= 0 for a task
7070
self.ttl_zero_callback = ttl_zero_callback
7171

72-
self.connect()
72+
self.conn = self.connect()
7373
if create_table:
7474
self._create_queue_table()
7575

7676
if reset:
7777
self._reset()
7878

79+
def get_connection(self):
80+
connection = connect(self._dsn)
81+
with connection.cursor() as cur:
82+
cur.execute("SELECT 1+1")
83+
cur.fetchone()
84+
85+
return connection
86+
7987
def connect(self) -> None:
8088
"""
8189
Establish a connection to Postgres.
8290
If a connection already exists, it's overwritten.
8391
"""
84-
self.conn = connect(self._dsn)
92+
if self.conn is None or self.conn.closed:
93+
self.conn = self.get_connection()
8594

8695
def _create_queue_table(self) -> None:
8796
"""

0 commit comments

Comments
 (0)