-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathschema.sql
More file actions
51 lines (41 loc) · 1.24 KB
/
schema.sql
File metadata and controls
51 lines (41 loc) · 1.24 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
BEGIN;
DROP SCHEMA IF EXISTS fb CASCADE;
CREATE SCHEMA fb;
SET search_path TO fb,"$user",public;
CREATE EXTENSION "uuid-ossp";
CREATE TABLE "user" (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
created timestamptz NOT NULL DEFAULT now(),
full_name text NOT NULL DEFAULT ''
);
CREATE TABLE post (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
created timestamptz NOT NULL DEFAULT now(),
content text NOT NULL DEFAULT '',
"user" uuid REFERENCES "user" NOT NULL
);
CREATE TABLE friendship (
first uuid REFERENCES "user" NOT NULL,
second uuid REFERENCES "user" NOT NULL,
created timestamptz NOT NULL DEFAULT now(),
UNIQUE (first, second)
);
CREATE FUNCTION check_friendship_symmetry() RETURNS TRIGGER AS $$
DECLARE
link friendship;
BEGIN
SELECT * INTO link FROM friendship
WHERE second = NEW.first AND first = NEW.second;
IF NOT FOUND THEN
RAISE EXCEPTION 'Friendships must be INSERTed as pairs.';
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql
SET search_path FROM CURRENT;
CREATE CONSTRAINT TRIGGER friendship_symmetry
AFTER INSERT ON friendship
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
EXECUTE PROCEDURE check_friendship_symmetry();
END;