-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQUICK_SQL_FIX.sql
More file actions
76 lines (70 loc) · 2.45 KB
/
QUICK_SQL_FIX.sql
File metadata and controls
76 lines (70 loc) · 2.45 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
67
68
69
70
71
72
73
74
75
-- QUICK COPY-PASTE FIX for Supabase Dashboard
-- This fixes the "column streak_days does not exist" error
-- Step 1: Drop the old broken function
DROP FUNCTION IF EXISTS public.get_user_stats(uuid) CASCADE;
-- Step 2: Create the fixed function
CREATE OR REPLACE FUNCTION public.get_user_stats(user_id_param uuid)
RETURNS json
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
result JSON;
current_streak_val INTEGER;
longest_streak_val INTEGER;
BEGIN
-- Get streak data from streaks table (instead of non-existent profiles.streak_days)
SELECT
COALESCE(MAX(current_count), 0),
COALESCE(MAX(longest_count), 0)
INTO current_streak_val, longest_streak_val
FROM streaks
WHERE user_id = user_id_param;
-- Build the complete stats JSON
SELECT json_build_object(
'total_milestones', COUNT(*),
'completed_milestones', COUNT(*) FILTER (WHERE is_completed = true),
'current_streak', current_streak_val,
'longest_streak', longest_streak_val,
'total_prayer_points', COUNT(*) FILTER (WHERE prayer_points IS NOT NULL),
'total_reflections', COUNT(*) FILTER (WHERE type = 'reflection'),
'milestones_by_category', (
SELECT json_object_agg(category, count)
FROM (
SELECT category, COUNT(*) as count
FROM milestones
WHERE user_id = user_id_param
GROUP BY category
) t
),
'milestones_by_month', (
SELECT json_object_agg(month, count)
FROM (
SELECT
TO_CHAR(DATE_TRUNC('month', TO_TIMESTAMP(start_timestamp / 1000)), 'YYYY-MM') as month,
COUNT(*) as count
FROM milestones
WHERE user_id = user_id_param
GROUP BY DATE_TRUNC('month', TO_TIMESTAMP(start_timestamp / 1000))
ORDER BY month DESC
LIMIT 12
) t
),
'average_completion_time', (
SELECT AVG(EXTRACT(EPOCH FROM (TO_TIMESTAMP(completed_at / 1000.0) - TO_TIMESTAMP(start_timestamp / 1000.0))) / 86400.0)
FROM milestones
WHERE user_id = user_id_param
AND is_completed = true
AND completed_at IS NOT NULL
)
) INTO result
FROM milestones
WHERE user_id = user_id_param;
RETURN COALESCE(result, '{}'::JSON);
END;
$$;
-- Grant permissions to ensure function is visible to PostgREST
GRANT EXECUTE ON FUNCTION public.get_user_stats(uuid) TO authenticated;
GRANT EXECUTE ON FUNCTION public.get_user_stats(uuid) TO anon;
GRANT EXECUTE ON FUNCTION public.get_user_stats(uuid) TO service_role;