Spaces:
Running

File size: 3,390 Bytes
4b10b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from sqlalchemy import create_engine, event, exc, text
from sqlalchemy.orm import sessionmaker, scoped_session

from app.core.config import settings
from app.core.logger import get_logger

logger = get_logger(__name__)

# Main database engine
raw_db_url = settings.DATABASE_URL
if not raw_db_url or "sqlite" in raw_db_url:
    raise ValueError("A valid PostgreSQL DATABASE_URL must be configured in the environment")

db_url = raw_db_url.strip()

# 1. Normalize deprecated postgres:// to postgresql://
if db_url.startswith("postgres://"):
    db_url = db_url.replace("postgres://", "postgresql://", 1)

# 2. Check available drivers
has_psycopg3 = False
try:
    import psycopg  # noqa: F401
    has_psycopg3 = True
except ImportError:
    pass

has_psycopg2 = False
try:
    import psycopg2.extras
    psycopg2.extras.register_uuid()
    logger.info("Successfully registered psycopg2 UUID adapter")
    has_psycopg2 = True
except Exception as e:
    logger.warning(f"Failed to register psycopg2 UUID adapter: {e}")

# 3. Ensure compatible driver dialect is specified in URL
if db_url.startswith("postgresql+psycopg://") and not has_psycopg3:
    logger.warning("psycopg (v3) not found; falling back to postgresql+psycopg2://")
    db_url = db_url.replace("postgresql+psycopg://", "postgresql+psycopg2://", 1)
elif db_url.startswith("postgresql://") and not db_url.startswith("postgresql+"):
    if not has_psycopg3 and has_psycopg2:
        logger.info("Explicitly routing postgresql:// to postgresql+psycopg2://")
        db_url = db_url.replace("postgresql://", "postgresql+psycopg2://", 1)

engine = create_engine(
    db_url,
    pool_pre_ping=True,
    pool_size=5,
    max_overflow=5,
    pool_recycle=3600,
    connect_args={"connect_timeout": 10},
    echo=False,
)


# Event listener to log connection issues
@event.listens_for(engine, "connect")
def receive_connect(dbapi_conn, connection_record):
    logger.info("Database connection established")


@event.listens_for(engine, "checkout")
def receive_pool_checkout(dbapi_conn, connection_record, connection_proxy):
    connection_record.info['checkout_time'] = __import__('time').time()


@event.listens_for(engine, "checkin")
def receive_pool_checkin(dbapi_conn, connection_record):
    checkout_time = connection_record.info.get('checkout_time')
    if checkout_time:
        duration = __import__('time').time() - checkout_time
        if duration > 5.0:
            logger.warning(f"Long database connection held for {duration:.2f}s")


SessionLocal = scoped_session(
    sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=engine,
    )
)


import time

def get_db_session():
    """
    Returns a scoped SQLAlchemy session. Retries on connection failure.
    """
    max_retries = 3
    retry_delay = 2
    
    for attempt in range(max_retries):
        try:
            session = SessionLocal()
            session.execute(text("SELECT 1"))
            return session
        except Exception as e:
            if attempt < max_retries - 1:
                logger.warning(f"Database connection attempt {attempt + 1} failed, retrying...: {e}")
                if 'session' in locals():
                    session.close()
                time.sleep(retry_delay)
            else:
                logger.error(f"Database connection failed after {max_retries} attempts: {e}")
                raise