-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase_setup.sql
81 lines (63 loc) · 2.22 KB
/
database_setup.sql
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';
CREATE DATABASE pdforum 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
CREATE TABLE "users" (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
bio TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
password BYTEA NOT NULL,
salt BYTEA NOT NULL
);
-- Create the table for posts
CREATE TABLE "posts" (
id SERIAL PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES users(id),
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
likes INTEGER NOT NULL DEFAULT 0
);
-- create the table for likes
create table "likes" (
id serial primary key,
author_id integer not null references users(id),
post_id integer not null references posts(id),
unique (author_id, post_id)
);
-- Create a function that adds a certain amount to the likes for a post
CREATE FUNCTION modify_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
CREATE FUNCTION increment_likes() RETURNS TRIGGER
AS $$ BEGIN
PERFORM modify_likes(NEW.post_id, 1);
RETURN NEW;
END $$
LANGUAGE plpgsql;
-- Trigger function for decrementing the like count
CREATE FUNCTION decrement_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
CREATE TRIGGER increment_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
CREATE TRIGGER decrement_likes_on_delete
AFTER DELETE ON likes
FOR EACH ROW
EXECUTE FUNCTION decrement_likes();