Skip to content

Commit 4b06c45

Browse files
fix(db): store table row trigger timestamps in UTC
1 parent c0c20bf commit 4b06c45

3 files changed

Lines changed: 18776 additions & 0 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
CREATE OR REPLACE FUNCTION increment_user_table_row_count()
2+
RETURNS TRIGGER AS $$
3+
DECLARE
4+
updated_count INTEGER;
5+
max_allowed INTEGER;
6+
BEGIN
7+
UPDATE user_table_definitions
8+
SET row_count = row_count + 1,
9+
updated_at = timezone('UTC', now())
10+
WHERE id = NEW.table_id
11+
AND row_count < max_rows
12+
RETURNING row_count, max_rows INTO updated_count, max_allowed;
13+
14+
IF NOT FOUND THEN
15+
SELECT max_rows INTO max_allowed
16+
FROM user_table_definitions
17+
WHERE id = NEW.table_id;
18+
19+
IF NOT FOUND THEN
20+
RAISE EXCEPTION 'Table % not found', NEW.table_id
21+
USING ERRCODE = 'foreign_key_violation';
22+
END IF;
23+
24+
RAISE EXCEPTION 'Maximum row limit (%) reached for table %',
25+
max_allowed, NEW.table_id
26+
USING ERRCODE = 'check_violation';
27+
END IF;
28+
29+
RETURN NEW;
30+
END;
31+
$$ LANGUAGE plpgsql;
32+
--> statement-breakpoint
33+
34+
CREATE OR REPLACE FUNCTION decrement_user_table_row_count()
35+
RETURNS TRIGGER AS $$
36+
BEGIN
37+
UPDATE user_table_definitions
38+
SET row_count = GREATEST(row_count - 1, 0),
39+
updated_at = timezone('UTC', now())
40+
WHERE id = OLD.table_id;
41+
42+
RETURN OLD;
43+
END;
44+
$$ LANGUAGE plpgsql;
45+
--> statement-breakpoint
46+
47+
CREATE OR REPLACE FUNCTION increment_user_table_row_count_stmt()
48+
RETURNS TRIGGER AS $$
49+
BEGIN
50+
UPDATE user_table_definitions d
51+
SET row_count = d.row_count + c.n,
52+
updated_at = timezone('UTC', now())
53+
FROM (
54+
SELECT table_id, count(*)::int AS n
55+
FROM new_rows
56+
GROUP BY table_id
57+
) c
58+
WHERE d.id = c.table_id;
59+
60+
RETURN NULL;
61+
END;
62+
$$ LANGUAGE plpgsql;
63+
--> statement-breakpoint
64+
65+
CREATE OR REPLACE FUNCTION decrement_user_table_row_count_stmt()
66+
RETURNS TRIGGER AS $$
67+
BEGIN
68+
UPDATE user_table_definitions d
69+
SET row_count = GREATEST(d.row_count - c.n, 0),
70+
updated_at = timezone('UTC', now())
71+
FROM (
72+
SELECT table_id, count(*)::int AS n
73+
FROM old_rows
74+
GROUP BY table_id
75+
) c
76+
WHERE d.id = c.table_id;
77+
78+
RETURN NULL;
79+
END;
80+
$$ LANGUAGE plpgsql;

0 commit comments

Comments
 (0)