coryd.dev/queries/functions/update_days_read.psql

26 lines
777 B
Text

CREATE OR REPLACE FUNCTION update_days_read()
RETURNS TRIGGER AS $$
DECLARE
pacific_now TIMESTAMPTZ;
pacific_today DATE;
last_read DATE;
BEGIN
SELECT (NOW() AT TIME ZONE 'America/Los_Angeles')::DATE INTO pacific_today;
SELECT COALESCE(last_read_date::DATE, pacific_today - INTERVAL '1 day') INTO last_read FROM reading_streak LIMIT 1;
IF last_read < pacific_today - INTERVAL '1 day' THEN
UPDATE reading_streak
SET days_read = 0, last_read_date = NOW() AT TIME ZONE 'America/Los_Angeles'
WHERE id = 1;
END IF;
IF last_read IS DISTINCT FROM pacific_today THEN
UPDATE reading_streak
SET days_read = days_read + 1, last_read_date = NOW() AT TIME ZONE 'America/Los_Angeles'
WHERE id = 1;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;