Skip to content

Commit 3c7b1e7

Browse files
authored
fix: address security issue with longest streak pg function (#129)
1 parent 6373f36 commit 3c7b1e7

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
set check_function_bodies = off;
2+
3+
CREATE OR REPLACE FUNCTION public.get_longest_streak(habit_identifier integer)
4+
RETURNS TABLE(habit_id integer, streak_start date, streak_end date, streak_length integer)
5+
LANGUAGE plpgsql
6+
SET search_path TO ''
7+
AS $function$
8+
BEGIN
9+
RETURN QUERY
10+
WITH consecutive_days AS (
11+
SELECT
12+
o.habit_id,
13+
o.day,
14+
o.day - INTERVAL '1 day' * ROW_NUMBER() OVER (PARTITION BY o.habit_id ORDER BY o.day) AS streak_id
15+
FROM public.occurrences o
16+
WHERE o.habit_id = habit_identifier
17+
),
18+
streaks AS (
19+
SELECT
20+
o.habit_id::INT,
21+
MIN(o.day) AS streak_start,
22+
MAX(o.day) AS streak_end,
23+
COUNT(*)::INT AS streak_length
24+
FROM consecutive_days o
25+
GROUP BY o.habit_id, o.streak_id
26+
)
27+
SELECT o.habit_id, o.streak_start, o.streak_end, o.streak_length
28+
FROM streaks o
29+
ORDER BY o.streak_length DESC
30+
LIMIT 1;
31+
END;
32+
$function$
33+
;
34+
35+

0 commit comments

Comments
 (0)