]> Untitled Git - lemmy.git/blob - migrations/2019-03-30-212058_create_post_view/up.sql
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / migrations / 2019-03-30-212058_create_post_view / up.sql
1 -- Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
2 create or replace function hot_rank(
3   score numeric,
4   published timestamp without time zone)
5 returns integer as $$
6 begin
7   -- hours_diff:=EXTRACT(EPOCH FROM (timezone('utc',now()) - published))/3600
8   return floor(10000*log(greatest(1,score+3)) / power(((EXTRACT(EPOCH FROM (timezone('utc',now()) - published))/3600) + 2), 1.8))::integer;
9 end; $$
10 LANGUAGE plpgsql;
11
12 create view post_view as
13 with all_post as
14 (
15   select        
16   p.*,
17   (select name from user_ where p.creator_id = user_.id) as creator_name,
18   (select name from community where p.community_id = community.id) as community_name,
19   (select removed from community c where p.community_id = c.id) as community_removed,
20   (select count(*) from comment where comment.post_id = p.id) as number_of_comments,
21   coalesce(sum(pl.score), 0) as score,
22   count (case when pl.score = 1 then 1 else null end) as upvotes,
23   count (case when pl.score = -1 then 1 else null end) as downvotes,
24   hot_rank(coalesce(sum(pl.score) , 0), p.published) as hot_rank
25   from post p
26   left join post_like pl on p.id = pl.post_id
27   group by p.id
28 )
29
30 select
31 ap.*,
32 u.id as user_id,
33 coalesce(pl.score, 0) as my_vote,
34 (select cf.id::bool from community_follower cf where u.id = cf.user_id and cf.community_id = ap.community_id) as subscribed,
35 (select pr.id::bool from post_read pr where u.id = pr.user_id and pr.post_id = ap.id) as read,
36 (select ps.id::bool from post_saved ps where u.id = ps.user_id and ps.post_id = ap.id) as saved
37 from user_ u
38 cross join all_post ap
39 left join post_like pl on u.id = pl.user_id and ap.id = pl.post_id
40
41 union all
42
43 select 
44 ap.*,
45 null as user_id,
46 null as my_vote,
47 null as subscribed,
48 null as read,
49 null as saved
50 from all_post ap
51 ;