File size: 1,954 Bytes
20852d6
6424951
 
92a832f
6424951
20852d6
6424951
20852d6
6424951
 
 
 
7b3455b
 
20852d6
6424951
 
20852d6
6424951
 
 
 
 
20852d6
6424951
 
 
 
20852d6
 
 
6424951
 
20852d6
6424951
 
20852d6
6424951
20852d6
 
 
 
6424951
20852d6
 
 
 
 
 
7b3455b
 
6424951
 
 
20852d6
 
6424951
 
20852d6
6424951
 
20852d6
6424951
 
20852d6
 
 
 
 
 
 
6424951
20852d6
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
"""Local CSV data management with error handling."""

import logging
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path

import pandas as pd
import streamlit as st

logger = logging.getLogger("streamlit_nba")

# Resolve path relative to this module
CSV_PATH = Path(__file__).resolve().parent.parent.parent / "snowflake_nba.csv"


class DatabaseConnectionError(Exception):
    """Raised when local data file cannot be found or loaded."""

    pass


class QueryExecutionError(Exception):
    """Raised when data query fails."""

    pass


@st.cache_data
def load_data() -> pd.DataFrame:
    """Load and cache the local CSV data.

    Returns:
        DataFrame containing player data

    Raises:
        DatabaseConnectionError: If file cannot be loaded
    """
    if not CSV_PATH.exists():
        logger.error(f"Data file not found: {CSV_PATH}")
        raise DatabaseConnectionError(f"Data file not found: {CSV_PATH}")

    try:
        df = pd.read_csv(CSV_PATH)
        # Ensure column names match expected Snowflake names (uppercase)
        df.columns = [col.upper() for col in df.columns]
        return df
    except Exception as e:
        logger.error(f"Failed to load CSV data: {e}")
        msg = f"Could not load data from {CSV_PATH}: {e}"
        raise DatabaseConnectionError(msg) from e


@contextmanager
def get_connection() -> Generator[pd.DataFrame, None, None]:
    """Context manager for local data access with error handling.

    Yields:
        DataFrame with player data

    Raises:
        DatabaseConnectionError: If data cannot be loaded
    """
    try:
        yield load_data()
    except DatabaseConnectionError as e:
        logger.error(f"Data access error: {e}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error accessing data: {e}")
        raise DatabaseConnectionError(f"Data access failed: {e}") from e
    finally:
        pass