Skip to content

Commit efec6cb

Browse files
committed
Use pg_isready to check for postgres ready state
1 parent 35fc247 commit efec6cb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

postgres/testcontainers/postgres/__init__.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,15 @@
1111
# License for the specific language governing permissions and limitations
1212
# under the License.
1313
import os
14+
import re
15+
from datetime import UTC, datetime
16+
from time import sleep
1417
from typing import Optional
18+
19+
from testcontainers.core.config import MAX_TRIES, SLEEP_TIME
1520
from testcontainers.core.generic import DbContainer
1621
from testcontainers.core.utils import raise_for_deprecated_parameter
22+
from testcontainers.core.waiting_utils import wait_container_is_ready
1723

1824

1925
class PostgresContainer(DbContainer):
@@ -63,3 +69,27 @@ def get_connection_url(self, host=None) -> str:
6369
password=self.password, dbname=self.dbname, host=host,
6470
port=self.port,
6571
)
72+
73+
@wait_container_is_ready()
74+
def _connect(self) -> None:
75+
count = 0
76+
77+
# ALTERNATE IMPLEMENTATION based on comments from @HofmeisterAn
78+
# expr = re.compile(r'(?P<ts>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z).*')
79+
# timestamp = datetime.now()
80+
while count < MAX_TRIES:
81+
status, _ = self.exec(f"pg_isready -hlocalhost -p{self.port} -U{self.username}")
82+
if status == 0:
83+
return
84+
85+
# ALTERNATE IMPLEMENTATION based on comments from @HofmeisterAn
86+
# stdout = self._container.logs(stderr = False, timestamps = True, since = timestamp)
87+
# lines = stdout.decode("utf-8").split("\n")
88+
# for line in lines:
89+
# if m:= re.match(expr, line):
90+
# timestamp = datetime.fromisoformat(m.groupdict()["ts"]).replace(tzinfo=None)
91+
# if "database system is ready to accept connections" in line:
92+
# return
93+
94+
sleep(SLEEP_TIME)
95+
count += 1

0 commit comments

Comments
 (0)