File size: 1,172 Bytes
954551b
 
 
 
 
 
 
 
216da3b
 
954551b
 
 
 
 
216da3b
 
 
 
954551b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from dotenv import load_dotenv

load_dotenv()

# Load from environment variable – set this in your .env file
# Handle empty string or missing variable gracefully
DATABASE_URL = os.getenv("DATABASE_URL") or "postgresql://user:password@localhost/facerecog"

# Neon postgres URLs use "postgres://" but SQLAlchemy needs "postgresql://"
if DATABASE_URL.startswith("postgres://"):
    DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)

# Ensure we don't pass an empty string to create_engine
if not DATABASE_URL or DATABASE_URL.strip() == "":
    DATABASE_URL = "postgresql://user:password@localhost/facerecog"

engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,  # reconnect if connection dropped (important for Neon)
    pool_size=5,
    max_overflow=10,
)

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


def get_db():
    """FastAPI dependency: yields a DB session and closes it after use."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()