Add local_subscribers field to CommunityAggregates

struct and schema
This commit is contained in:
İsmail Karslı 2023-11-15 23:55:00 +03:00
parent e2bf2ce530
commit f22d602a10
No known key found for this signature in database
GPG key ID: A28872907CA1BE93
4 changed files with 98 additions and 0 deletions

View file

@ -59,6 +59,7 @@ pub struct CommunityAggregates {
pub users_active_half_year: i64,
#[serde(skip)]
pub hot_rank: f64,
pub local_subscribers: i64,
}
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Default)]

View file

@ -198,6 +198,7 @@ diesel::table! {
users_active_month -> Int8,
users_active_half_year -> Int8,
hot_rank -> Float8,
local_subscribers -> Int8,
}
}

View file

@ -0,0 +1,35 @@
ALTER TABLE community_aggregates
DROP COLUMN local_subscribers;
CREATE OR REPLACE FUNCTION community_aggregates_subscriber_count ()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF (TG_OP = 'INSERT') THEN
UPDATE
community_aggregates
SET
subscribers = subscribers + 1
FROM
community
WHERE
community.id = community_id
AND community.local
AND community_id = NEW.community_id;
ELSIF (TG_OP = 'DELETE') THEN
UPDATE
community_aggregates
SET
subscribers = subscribers - 1
FROM
community
WHERE
community.id = community_id
AND community.local
AND community_id = OLD.community_id;
END IF;
RETURN NULL;
END
$$;

View file

@ -0,0 +1,61 @@
-- Couldn't find a way to put local_subscribers right after subscribers
ALTER TABLE community_aggregates
ADD COLUMN local_subscribers int8 NOT NULL DEFAULT 0;
-- update initial value
UPDATE
community_aggregates
SET
local_subscribers = (
SELECT
COUNT(*)
FROM
community_follower
WHERE
community_follower.community_id = community_aggregates.community_id
AND community_follower.person_id IN (
SELECT
id
FROM
person
WHERE
local
)
)
;
CREATE OR REPLACE FUNCTION community_aggregates_subscriber_count ()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF (TG_OP = 'INSERT') THEN
UPDATE
community_aggregates
SET
subscribers = subscribers + 1,
local_subscribers = local_subscribers + 1
FROM
community
WHERE
community.id = community_id
AND community.local
AND community_id = NEW.community_id;
ELSIF (TG_OP = 'DELETE') THEN
UPDATE
community_aggregates
SET
subscribers = subscribers - 1,
local_subscribers = local_subscribers - 1
FROM
community
WHERE
community.id = community_id
AND community.local
AND community_id = OLD.community_id;
END IF;
RETURN NULL;
END
$$;