File size: 2,010 Bytes
c09e844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Database Configuration and Session Management

Supports BOTH SQLite (local) and PostgreSQL (production on Render)

"""
import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path

# ============================================
# HYBRID DATABASE SUPPORT
# ============================================
# Priority:
# 1. Use DATABASE_URL from environment (Render PostgreSQL)
# 2. Fallback to SQLite for local development

DATABASE_URL = os.getenv("DATABASE_URL")

if DATABASE_URL:
    # CRITICAL FIX FOR RENDER:
    # Render provides URLs starting with 'postgres://'
    # but SQLAlchemy 1.4+ requires 'postgresql://'
    if DATABASE_URL.startswith("postgres://"):
        DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
    
    print(f"πŸš€ Production Mode: Using PostgreSQL")
    
    # PostgreSQL: No need for check_same_thread
    engine = create_engine(
        DATABASE_URL,
        pool_pre_ping=True,  # Verify connections before using
        pool_recycle=300,    # Recycle connections every 5 minutes
    )
else:
    # Local development: Use SQLite
    print(f"πŸ”§ Development Mode: Using SQLite")
    
    # Create database directory
    db_dir = Path("app/database")
    db_dir.mkdir(parents=True, exist_ok=True)
    
    DATABASE_URL = "sqlite:///./app/database/rating_prediction.db"
    
    # SQLite: Needs check_same_thread=False for FastAPI
    engine = create_engine(
        DATABASE_URL, 
        connect_args={"check_same_thread": False}
    )

# Create session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Base class for all models
Base = declarative_base()

def get_db():
    """

    Dependency to get database session

    Used in FastAPI route dependencies

    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()