File size: 1,150 Bytes
c87f46d
8105596
c87f46d
 
 
 
8105596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87f46d
 
 
8105596
 
 
 
 
 
c87f46d
8105596
 
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
# db.py
import os
import pandas as pd
from sqlalchemy import create_engine
import streamlit as st

def _get_conn_str():
    # HF Spaces: secrets/variables are environment vars
    for key in ("DB_CONNECTION", "DATABASE_URL", "db_connection", "database_url"):
        val = os.environ.get(key)
        if val:
            return val

    # Streamlit Cloud/local: secrets.toml
    try:
        for key in ("db_connection", "DATABASE_URL", "database_url"):
            if key in st.secrets:
                return st.secrets[key]
    except Exception:
        pass

    return None

CONN_STR = _get_conn_str()
engine = create_engine(CONN_STR, pool_pre_ping=True) if CONN_STR else None

def run_query(query: str) -> pd.DataFrame:
    if engine is None:
        st.error(
            "No database connection configured. "
            "Set DB_CONNECTION in your HF Space (Settings → Variables & secrets) "
            "or add db_connection to .streamlit/secrets.toml."
        )
        return pd.DataFrame()
    with engine.connect() as conn:
        # use read_sql_query to be explicit; no trailing comma!
        return pd.read_sql_query(query, conn)