File size: 1,754 Bytes
953f021
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
HireSense AI — Database Setup
SQLAlchemy engine, session factory, and initialization.
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

from backend.config import settings

# Create engine — check_same_thread=False needed for SQLite with FastAPI
engine = create_engine(
    settings.DATABASE_URL,
    connect_args={"check_same_thread": False},
    echo=False,
)

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

# Base class for all models
Base = declarative_base()


def init_db():
    """Create all database tables. Called on app startup."""
    # Import all models so they register with Base.metadata
    from backend.models import candidate, team, job  # noqa: F401

    Base.metadata.create_all(bind=engine)

    # Lightweight migrations for columns added after a table already existed
    _ensure_columns()

    # Seed default job postings (open application + sample roles)
    db = SessionLocal()
    try:
        job.seed_jobs(db)
    finally:
        db.close()


def _ensure_columns():
    """Add columns introduced after initial table creation (SQLite-safe)."""
    from sqlalchemy import inspect, text

    insp = inspect(engine)
    try:
        cols = [c["name"] for c in insp.get_columns("candidate_analyses")]
    except Exception:
        return
    if "status" not in cols:
        with engine.begin() as conn:
            conn.execute(text(
                "ALTER TABLE candidate_analyses ADD COLUMN status VARCHAR(32) DEFAULT 'applied'"
            ))


def get_db():
    """Dependency that provides a database session and closes it after use."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()