File size: 1,381 Bytes
8545d23
 
 
 
0da3bd8
8545d23
 
0da3bd8
 
 
8545d23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
from pathlib import Path
from dotenv import load_dotenv
from .models import Base

# Load environment variables
load_dotenv()

# Calculate absolute path to backend/test.db
# __file__ is backend/src/database.py
# parent is backend/src
# parent.parent is backend
BASE_DIR = Path(__file__).resolve().parent.parent
DB_PATH = BASE_DIR / "test.db"

# Make DATABASE_URL optional - use SQLite in-memory if not provided
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
    # Use absolute path to ensure we hit the correct file regardless of CWD
    DATABASE_URL = f"sqlite:///{DB_PATH}"

print(f"--- Database Configuration ---")
print(f"Using Database URL: {DATABASE_URL}")
print(f"Absolute DB Path: {DB_PATH}")
print(f"DB File Exists: {DB_PATH.exists()}")
print(f"------------------------------")

try:
    engine = create_engine(DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    database_available = True
except Exception as e:
    print(f"Database connection failed: {e}")
    print("Running without database support")
    engine = None
    SessionLocal = None
    database_available = False

def get_db():
    if not database_available:
        return None
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()