File size: 5,560 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""
Database connection and session management
"""
import os
from urllib.parse import urlparse

from loguru import logger
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.pool import StaticPool
from typing import Generator

from api.models import Base

# Database URL priority:
# 1. NEON_DATABASE_URL_DEV (local development with PostgreSQL)
# 2. NEON_DATABASE_URL (production Neon PostgreSQL)
# 3. DATABASE_URL (backwards compatibility)
# 4. SQLite fallback (no setup required)
DATABASE_URL = os.getenv(
    "NEON_DATABASE_URL_DEV",
    os.getenv(
        "NEON_DATABASE_URL",
        os.getenv(
            "DATABASE_URL",
            "sqlite:///./data/users.db"
        )
    )
)

def sqlalchemy_url(url: str) -> str:
    """The URL the ORM engine uses: PostgreSQL always names the psycopg2 driver.

    SQLAlchemy 2.1 changed the default driver for ``postgresql://`` from psycopg2 to
    psycopg 3, which isn't installed (only ``psycopg2-binary`` is), so an implicit
    driver made ``api.main`` fail at import (#282). ``postgres://`` and
    ``postgresql://`` get ``+psycopg2``; a URL that already names a driver, and
    SQLite, are left as they are.
    """
    for prefix in ("postgres://", "postgresql://"):
        if url.startswith(prefix):
            return "postgresql+psycopg2://" + url[len(prefix):]
    return url


# The asyncpg pools elsewhere read the plain URL; only the ORM engine gets the driver.
if DATABASE_URL.startswith("postgres://"):
    DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)

# ---------------------------------------------------------------------------
# Serving schema (gold/public split).
#
# The warehouse is split into two Postgres schemas in open_navigator:
#   * `public` — ONLY the API-served relations, as views over gold; the
#     person-graph PII is absent and `contact_official` is PII-light. This is
#     what the PUBLIC API serves (default).
#   * `gold`   — the FULL warehouse (incl. the person graph, un-redacted). A
#     PRIVATE/internal API instance reads this by setting API_DB_SCHEMA=gold.
#
# API_DB_SCHEMA names the DATA schema (default `public`). Table references in
# route SQL are UNqualified so they resolve via search_path. The data pools
# (asyncpg) use `search_path = <API_DB_SCHEMA>, public` — the data schema first,
# `public` as the fallback for the operational/ORM tables (user/social_follows/
# prefs) which ALWAYS live in public. The ORM engine below uses `public` FIRST
# so auth tables never get shadowed into gold by create_all.
# See dbt_project/macros/publish_public_serving.sql.
# ---------------------------------------------------------------------------
DB_SCHEMA = os.getenv("API_DB_SCHEMA", "public").strip() or "public"
# NOTE: no spaces in these search_path strings — they feed libpq's `-csearch_path=`
# options below, and libpq splits the options value on whitespace (a space turns
# "public, gold" into the malformed search_path "public,"). Commas only.
#: search_path for raw DATA reads (asyncpg pools): data schema first, public fallback.
DATA_SEARCH_PATH = DB_SCHEMA if DB_SCHEMA == "public" else f"{DB_SCHEMA},public"
#: search_path for the ORM/auth engine: public FIRST so operational tables stay in public.
_ORM_SEARCH_PATH = "public" if DB_SCHEMA == "public" else f"public,{DB_SCHEMA}"

def orm_connect_args(url: str) -> dict:
    """libpq connect args for the ORM/auth engine (#367).

    Pins ``search_path`` (public first) with a startup ``options`` parameter, except
    on a Neon *pooled* endpoint (host contains ``-pooler``): PgBouncer rejects
    startup ``options`` ("unsupported startup parameter in options: search_path"),
    which failed every ORM connection and took sign-in down. There the server
    default ``"$user", public`` already resolves the ORM tables to ``public``.
    """
    host = urlparse(url).hostname or ""
    if "-pooler" in host:
        if _ORM_SEARCH_PATH != "public":
            logger.warning(
                "Neon pooled host {}: search_path pin {!r} not applied (pooler rejects "
                "startup options); ORM tables resolve via the default search_path.",
                host,
                _ORM_SEARCH_PATH,
            )
        return {}
    return {"options": f"-csearch_path={_ORM_SEARCH_PATH}"}


# Create engine
if "sqlite" in DATABASE_URL:
    # SQLite needs special handling for concurrent access
    engine = create_engine(
        DATABASE_URL,
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
else:
    # PostgreSQL configuration
    engine = create_engine(
        sqlalchemy_url(DATABASE_URL),
        pool_pre_ping=True,
        pool_size=10,
        max_overflow=20,
        # Pin the ORM/auth search_path (public-first) so Base.metadata.create_all
        # always targets public even when a private instance serves data from gold.
        connect_args=orm_connect_args(DATABASE_URL),
    )

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


def init_db():
    """Create all tables"""
    Base.metadata.create_all(bind=engine)
    print(f"✅ Database initialized at: {DATABASE_URL}")


def get_db() -> Generator[Session, None, None]:
    """
    Database session dependency for FastAPI
    
    Usage:
        @app.get("/users")
        def get_users(db: Session = Depends(get_db)):
            return db.query(User).all()
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()