@@ -33,9 +33,15 @@ CREATE INDEX vote_id_idx ON vote_results (vote_id);
3333DROP INDEX IF EXISTS idx_vote_results_vote_choice;
3434CREATE INDEX idx_vote_results_vote_choice ON vote_results (vote_id, choice);
3535
36+ DROP INDEX IF EXISTS idx_vote_results_vote_choice_priority;
37+ CREATE INDEX idx_vote_results_vote_choice_priority ON vote_results (vote_id, choice, priority);
38+
39+ DROP INDEX IF EXISTS idx_votes_created_time;
40+ CREATE INDEX idx_votes_created_time ON votes (created_time DESC );
41+
3642
3743drop function if exists get_votes_with_results;
38- create or replace function get_votes_with_results ()
44+ create or replace function get_votes_with_results (order_by text default ' recent ' )
3945 returns table (
4046 id BIGINT ,
4147 title text ,
@@ -49,21 +55,40 @@ create or replace function get_votes_with_results()
4955 priority int
5056 )
5157as $$
58+ with results as (
59+ SELECT
60+ v .id ,
61+ v .title ,
62+ v .description ,
63+ v .created_time ,
64+ v .creator_id ,
65+ v .is_anonymous ,
66+ COALESCE(SUM (CASE WHEN r .choice = 1 THEN 1 ELSE 0 END), 0 ) AS votes_for,
67+ COALESCE(SUM (CASE WHEN r .choice = - 1 THEN 1 ELSE 0 END), 0 ) AS votes_against,
68+ COALESCE(SUM (CASE WHEN r .choice = 0 THEN 1 ELSE 0 END), 0 ) AS votes_abstain,
69+ COALESCE(SUM (r .priority ), 0 )::float / GREATEST(COALESCE(SUM (CASE WHEN r .choice = 1 THEN 1 ELSE 0 END), 1 ), 1 ) * 100 / 3 AS priority
70+ FROM votes v
71+ LEFT JOIN vote_results r ON v .id = r .vote_id
72+ GROUP BY v .id
73+ )
5274SELECT
53- v .id ,
54- v .title ,
55- v .description ,
56- v .created_time ,
57- v .creator_id ,
58- v .is_anonymous ,
59- COALESCE(SUM (CASE WHEN r .choice = 1 THEN 1 ELSE 0 END), 0 ) AS votes_for,
60- COALESCE(SUM (CASE WHEN r .choice = - 1 THEN 1 ELSE 0 END), 0 ) AS votes_against,
61- COALESCE(SUM (CASE WHEN r .choice = 0 THEN 1 ELSE 0 END), 0 ) AS votes_abstain,
62- coalesce(SUM (r .priority ), 0 ) AS priority
63- FROM votes v
64- LEFT JOIN vote_results r ON v .id = r .vote_id
65- GROUP BY v .id
66- ORDER BY v .created_time DESC ;
75+ id,
76+ title,
77+ description,
78+ created_time,
79+ creator_id,
80+ is_anonymous,
81+ votes_for,
82+ votes_against,
83+ votes_abstain,
84+ priority
85+ FROM results
86+ ORDER BY
87+ CASE WHEN order_by = ' recent' THEN created_time END DESC ,
88+ CASE WHEN order_by = ' mostVoted' THEN (votes_for + votes_against + votes_abstain) END DESC ,
89+ CASE WHEN order_by = ' mostVoted' THEN created_time END DESC ,
90+ CASE WHEN order_by = ' priority' THEN priority END DESC ,
91+ CASE WHEN order_by = ' priority' THEN created_time END DESC ;
6792$$ language sql stable;
6893
6994
0 commit comments