- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase_setup.sql
More file actions
Latest commit
81 lines (63 loc) · 2.22 KB
/
Copy pathdatabase_setup.sql
File metadata and controls
81 lines (63 loc) · 2.22 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
70
71
72
73
74
75
76
77
78
79
80
81
-- PDForum PSQL database setup
-- Ideally you just run this once to set it up, but you never know
-- Create a user and a database
CREATE ROLE pdforum LOGIN PASSWORD 'secret';
CREATEDATABASEpdforum ENCODING 'UTF8' OWNER pdforum;
-- Now actually enter the context of the database (I don't know how else to
-- describe it) before running the rest of the commands.
-- Create the table for users
CREATETABLE "users" (
id SERIALPRIMARY KEY,
username TEXT UNIQUE NOT NULL,
bio TEXTNOT NULL DEFAULT '',
created_at TIMESTAMPTZNOT NULL DEFAULT now(),
password BYTEANOT NULL,
salt BYTEANOT NULL
);
-- Create the table for posts
CREATETABLE "posts" (
id SERIALPRIMARY KEY,
author_id INTEGERNOT NULLREFERENCES users(id),
content TEXTNOT NULL,
created_at TIMESTAMPTZNOT NULL DEFAULT now(),
likes INTEGERNOT NULL DEFAULT 0
);
-- create the table for likes
createtable "likes" (
id serialprimary key,
author_id integernot nullreferences users(id),
post_id integernot nullreferences posts(id),
unique (author_id, post_id)
);
-- Create a function that adds a certain amount to the likes for a post
CREATEFUNCTIONmodify_likes(post_id INTEGER, change INTEGER) RETURNS INTEGER
AS $$
UPDATE posts
SET likes = likes + change
WHERE id = post_id
RETURNING likes
$$ LANGUAGE SQL;
-- Trigger function for incrementing the like count
CREATEFUNCTIONincrement_likes() RETURNS TRIGGER
AS $$ BEGIN
PERFORM modify_likes(NEW.post_id, 1);
RETURN NEW;
END $$
LANGUAGE plpgsql;
-- Trigger function for decrementing the like count
CREATEFUNCTIONdecrement_likes() RETURNS TRIGGER
AS $$ BEGIN
PERFORM modify_likes(OLD.post_id, -1);
RETURN NEW;
END $$
LANGUAGE plpgsql;
-- Trigger to increment likes for the post after adding a like
CREATETRIGGERincrement_likes_on_insert
AFTER INSERT ON likes
FOR EACH ROW
EXECUTE FUNCTION increment_likes();
-- Trigger to decrement likes for the post after adding a like
CREATETRIGGERdecrement_likes_on_delete
AFTER DELETEON likes
FOR EACH ROW
EXECUTE FUNCTION decrement_likes();