File size: 1,551 Bytes
6e8d513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Database service for Supabase connection"""

import logging
from supabase import create_client, Client
from config import SUPABASE_URL, SUPABASE_KEY

logger = logging.getLogger(__name__)


class DatabaseService:
    """Service for managing Supabase database connection"""
    
    def __init__(self):
        self.client: Client | None = None
        self.connected = False
    
    def connect(self):
        """Initialize Supabase client connection"""
        if self.connected and self.client:
            logger.info("Database already connected")
            return
        
        if not SUPABASE_URL or not SUPABASE_KEY:
            raise ValueError("SUPABASE_URL and SUPABASE_KEY must be set in environment variables")
        
        try:
            logger.info("Connecting to Supabase...")
            self.client = create_client(SUPABASE_URL, SUPABASE_KEY)
            self.connected = True
            logger.info("✓ Successfully connected to Supabase")
        except Exception as e:
            logger.error(f"Error connecting to Supabase: {str(e)}")
            raise RuntimeError(f"Failed to connect to Supabase: {str(e)}")
    
    def get_client(self) -> Client:
        """Get Supabase client instance"""
        if not self.connected or not self.client:
            self.connect()
        return self.client
    
    def is_connected(self) -> bool:
        """Check if database is connected"""
        return self.connected and self.client is not None


# Initialize singleton instance
database_service = DatabaseService()