Comments table draft
This commit is contained in:
parent
f10234b72f
commit
f3cab87592
1 changed files with 51 additions and 0 deletions
51
server/migrations_pg/0003_comments_table.sql
Normal file
51
server/migrations_pg/0003_comments_table.sql
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
CREATE TABLE IF NOT EXISTS comments (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
parent_post_id BIGINT NOT NULL,
|
||||||
|
parent_comment_id BIGINT,
|
||||||
|
author_user_id BIGINT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
upvotes INTEGER NOT NULL DEFAULT 0,
|
||||||
|
downvotes INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (parent_post_id) REFERENCES posts (id),
|
||||||
|
FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
|
||||||
|
FOREIGN KEY (author_user_id) REFERENCES users (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Create a function to set created_at and updated_at on INSERT
|
||||||
|
CREATE OR REPLACE FUNCTION comments_set_timestamps_on_insert() RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.created_at = NOW();
|
||||||
|
NEW.updated_at = NOW();
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- Create a trigger to call the function after INSERT
|
||||||
|
CREATE TRIGGER comments_set_timestamps_on_insert
|
||||||
|
BEFORE INSERT ON posts
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION set_timestamps_on_insert();
|
||||||
|
|
||||||
|
-- Create a function to set updated_at on UPDATE
|
||||||
|
CREATE OR REPLACE FUNCTION comments_set_updated_at() RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.updated_at = NOW();
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- Create a trigger to call the function after UPDATE
|
||||||
|
CREATE TRIGGER comments_set_updated_at
|
||||||
|
BEFORE UPDATE ON posts
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION comments_set_updated_at();
|
||||||
|
|
||||||
|
CREATE INDEX comments_parent_post_id_index ON comments (parent_post_id);
|
||||||
|
CREATE INDEX comments_parent_comment_id_index ON comments (parent_comment_id);
|
||||||
|
CREATE INDEX comments_user_id_index ON comments (author_user_id);
|
||||||
|
|
||||||
|
-- CREATE INDEX posts_user_id_index ON posts (user_id);
|
||||||
|
-- CREATE INDEX posts_id_index ON posts (id);
|
||||||
|
-- CREATE INDEX idx_created_at_desc ON posts (created_at DESC);
|
Loading…
Reference in a new issue