File size: 1,086 Bytes
7785f49
c71e312
7785f49
c71e312
 
7785f49
c71e312
7785f49
 
c71e312
7785f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c71e312
 
7785f49
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
# src/expon/shared/infrastructure/database.py
import os
from urllib.parse import urlparse
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.pool import QueuePool

# No tocamos tu .env; lo carga main.py. Aquí solo leemos.
DATABASE_URL = (os.getenv("DATABASE_URL") or "").strip()

# Forzamos driver psycopg2 si usas "postgresql://"
if DATABASE_URL.startswith("postgresql://"):
    DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+psycopg2://", 1)

# Si el host es Azure, fuerza SSL sin tocar tu .env
connect_args = {}
try:
    netloc = urlparse(DATABASE_URL).netloc
    if "azure.com" in netloc:
        connect_args["sslmode"] = "require"
except Exception:
    pass

engine = create_engine(
    DATABASE_URL,
    connect_args=connect_args,
    poolclass=QueuePool,
    pool_pre_ping=True,   # detecta conexiones rotas
    pool_recycle=1800,    # recicla a los 30 min
    pool_size=5,
    max_overflow=5,
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()