-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriggers.sql
More file actions
71 lines (56 loc) · 1.81 KB
/
Copy pathtriggers.sql
File metadata and controls
71 lines (56 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* creating triggers to run in the background so we do not need to query and check for every insertion (automates the process)*/
CREATE OR REPLACE FUNCTION check_email_exists() RETURNS TRIGGER AS $$
BEGIN
IF EXISTS (SELECT 1 FROM users WHERE email = NEW.email) THEN
RAISE EXCEPTION 'Email already exists';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_check_email_exists
BEFORE INSERT ON users
FOR EACH ROW
EXECUTE FUNCTION check_email_exists();
CREATE OR REPLACE FUNCTION check_password() RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF NEW.password = OLD.password THEN
RAISE EXCEPTION 'New password cannot be the same as the previous password';
END IF;
END IF;
IF LENGTH(NEW.password) < 8 THEN
RAISE EXCEPTION 'Password must be at least 8 characters long';
END IF;
IF NEW.password !~ '[a-z]' THEN
RAISE EXCEPTION 'Password must contain at least 1 lowercase letter';
END IF;
IF NEW.password !~ '[A-Z]' THEN
RAISE EXCEPTION 'Password must contain at least 1 uppercase letter';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_check_password
BEFORE INSERT ON users
FOR EACH ROW
EXECUTE FUNCTION check_password();
/* checking before password updates */
CREATE TRIGGER trigger_check_password_before_update
BEFORE UPDATE OF password ON users
FOR EACH ROW
EXECUTE FUNCTION check_password();
CREATE OR REPLACE FUNCTION expenses_amount_check()
RETURNS TRIGGER
AS $$
BEGIN
IF NEW.amount <= 0 THEN
RAISE EXCEPTION 'Amount must be greater than zero';
END IF;
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER expenses_amount_trigger
BEFORE INSERT ON expenses
FOR EACH ROW
EXECUTE FUNCTION expenses_amount_check();