Spaces:
Runtime error

File size: 3,405 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Supabase initialization and migration"""

from src.api.supabase_client import get_db
from src.utils.logging import get_logger

logger = get_logger(__name__)

INIT_SQL = """
-- Create profiles table if not exists
CREATE TABLE IF NOT EXISTS public.profiles (
    id uuid PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
    email text NOT NULL,
    full_name text,
    avatar_url text,
    role text DEFAULT 'user' CHECK (role IN ('admin', 'user')),
    created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
    updated_at timestamp with time zone DEFAULT timezone('utc'::text, now())
);

-- Enable RLS on profiles
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;

-- Drop existing policies to avoid conflicts
DROP POLICY IF EXISTS "Public profiles are viewable by everyone" ON public.profiles;
DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles;

-- Create policies
CREATE POLICY "Public profiles are viewable by everyone"
    ON public.profiles FOR SELECT
    USING (true);

CREATE POLICY "Users can insert their own profile"
    ON public.profiles FOR INSERT
    WITH CHECK (auth.uid() = id);

CREATE POLICY "Users can update own profile"
    ON public.profiles FOR UPDATE
    USING (auth.uid() = id);

-- Function to handle user creation
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
BEGIN
    INSERT INTO public.profiles (id, email, full_name, role)
    VALUES (
        NEW.id,
        NEW.email,
        NEW.raw_user_meta_data->>'full_name',
        COALESCE(NEW.raw_user_meta_data->>'role', 'user')
    );
    RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Drop existing trigger to avoid conflicts
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;

-- Trigger for new user
CREATE TRIGGER on_auth_user_created
    AFTER INSERT ON auth.users
    FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
"""


def init_supabase_tables():
    """Initialize Supabase tables if they don't exist"""
    try:
        db = get_db()
        
        # Execute initialization SQL
        # Note: This uses RPC to execute SQL, or we can use the REST API
        # For now, we'll just check if the table exists
        
        try:
            _ = db.table("profiles").select("count", count="exact").limit(1).execute()
            logger.info("supabase_init: profiles table already initialized")
            return True
        except Exception as exc:
            if "profiles" in str(exc).lower() or "PGRST205" in str(exc):
                logger.warning(
                    "supabase_init: profiles table missing — run supabase_setup.sql in the "
                    "Supabase SQL Editor"
                )
                return False
            raise

    except Exception:
        logger.exception("supabase_init: initialization error")
        return False


def check_supabase_connection():
    """Check if Supabase connection is working"""
    try:
        db = get_db()
        # Try to get auth settings
        db.auth.get_session()
        return True
    except Exception as exc:
        # Logged at INFO since absence is normal in dev (Supabase optional).
        logger.info(
            "supabase_init: connection check failed",
            extra={"error": str(exc)[:200]},
        )
        return False