-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
66 lines (60 loc) · 2.08 KB
/
db.py
File metadata and controls
66 lines (60 loc) · 2.08 KB
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
import psycopg2
import streamlit as st
@st.cache_resource
def init_connection():
try:
# DEBUGGING: Print what keys exist in secrets
print("Available Secret Keys:", st.secrets.keys())
# Check if "postgres" section exists
if "postgres" in st.secrets:
print("Found [postgres] section in secrets. Connecting to Cloud...")
return psycopg2.connect(
dbname=st.secrets["postgres"]["dbname"],
user=st.secrets["postgres"]["user"],
password=st.secrets["postgres"]["password"],
host=st.secrets["postgres"]["host"],
port=st.secrets["postgres"]["port"]
)
else:
print("⚠️ [postgres] section NOT found. Falling back to Localhost...")
return psycopg2.connect(
dbname="local_lens_db",
user="postgres",
password="postgre",
host="localhost",
port="5432"
)
except Exception as e:
print(f"DB Connection failed: {e}")
st.error(f"DB Connection failed: {e}")
return None
def run_query(query, params=None):
conn = init_connection()
if conn:
try:
import pandas as pd
return pd.read_sql(query, conn, params=params)
except Exception as e:
st.error(f"Query failed: {e}")
return pd.DataFrame()
return pd.DataFrame()
def run_transaction(query, params):
conn = init_connection()
if conn:
try:
with conn.cursor() as cur:
cur.execute(query, params)
conn.commit()
return True
except Exception as e:
conn.rollback()
st.error(f"Transaction failed: {e}")
return False
return False
# --- Data Loaders ---
@st.cache_data(ttl=60)
def get_product_list():
return run_query("SELECT product_id, name, category FROM products ORDER BY name")
@st.cache_data(ttl=60)
def get_store_list():
return run_query("SELECT store_id, name FROM stores ORDER BY name")