1+ import asyncio
2+ import os
3+ import sys
4+ from sqlalchemy .ext .asyncio import create_async_engine
5+ from sqlalchemy import text
6+
7+ # Add current directory to path to find 'app'
8+ sys .path .append (os .getcwd ())
9+
10+ display_url = "UNKNOWN"
11+
12+ try :
13+ from app .config import settings
14+ url = settings .POSTGRES_URL
15+ # Mask password for display
16+ if "@" in url :
17+ display_url = url .split ("@" )[1 ]
18+ user_part = url .split ("@" )[0 ]
19+ if ":" in user_part :
20+ display_url = f"{ user_part .split (':' )[0 ]} :****@{ display_url } "
21+ else :
22+ display_url = f"{ user_part } @{ display_url } "
23+ else :
24+ display_url = url
25+
26+ print (f"Checking connection to: { display_url } " )
27+ except Exception as e :
28+ print (f"Could not load settings: { e } " )
29+ url = os .environ .get ("POSTGRES_URL" )
30+ print (f"Using URL from env: { url } " )
31+
32+ if not url :
33+ print ("Error: POSTGRES_URL not set!" )
34+ sys .exit (1 )
35+
36+ async def check ():
37+ print ("-" * 50 )
38+ print ("Starting connection test..." )
39+ try :
40+ # Create engine
41+ engine = create_async_engine (url , echo = False )
42+
43+ # Try to connect
44+ async with engine .connect () as conn :
45+ result = await conn .execute (text ("SELECT 1" ))
46+ val = result .scalar ()
47+ print (f"SUCCESS: Database returned { val } " )
48+
49+ # Check database name
50+ result_db = await conn .execute (text ("SELECT current_database()" ))
51+ db_name = result_db .scalar ()
52+ print (f"Connected to database: { db_name } " )
53+
54+ await engine .dispose ()
55+ print ("-" * 50 )
56+ print ("✅ DATABASE CONNECTION HEALTHY" )
57+
58+ except Exception as e :
59+ print ("-" * 50 )
60+ print (f"❌ CONNECTION FAILED" )
61+ print (f"Error type: { type (e ).__name__ } " )
62+ print (f"Error message: { e } " )
63+ print ("-" * 50 )
64+
65+ if __name__ == "__main__" :
66+ asyncio .run (check ())
0 commit comments