-
Notifications
You must be signed in to change notification settings - Fork 0
/
stored
42 lines (37 loc) · 1.07 KB
/
stored
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
DROP EXTENSION IF EXISTS pgcrypto;
CREATE EXTENSION pgcrypto;
DROP FUNCTION IF EXISTS on_record_insert() CASCADE;
CREATE FUNCTION on_record_insert() RETURNS trigger AS $$
DECLARE
id_sequence VARCHAR;
BEGIN
SELECT TG_ARGV[0] INTO id_sequence;
NEW.id := nextval(id_sequence);
NEW.password := crypt(NEW.password, gen_salt('md5'));
NEW.created_at := now();
NEW.updated_at := now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP FUNCTION IF EXISTS on_record_update() CASCADE;
CREATE FUNCTION on_record_update() RETURNS trigger AS $$
BEGIN
NEW.id := OLD.id;
IF NEW.password = OLD.password THEN
NEW.password := OLD.password;
ELSE
NEW.password := crypt(NEW.password, gen_salt('md5'));
END IF;
NEW.created_at := OLD.created_at;
NEW.updated_at := now();
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER persons_insert
BEFORE INSERT ON persons
FOR EACH ROW
EXECUTE PROCEDURE on_record_insert('person_ids');
CREATE TRIGGER persons_update
BEFORE UPDATE ON persons
FOR EACH ROW
EXECUTE PROCEDURE on_record_update();