45 lines
No EOL
1.5 KiB
PL/PgSQL
45 lines
No EOL
1.5 KiB
PL/PgSQL
CREATE TABLE IF NOT EXISTS comments (
|
|
id SERIAL PRIMARY KEY NOT NULL,
|
|
parent_post_id BIGINT NOT NULL,
|
|
-- parent_comment_id BIGINT,
|
|
author_user_id BIGINT NOT NULL,
|
|
content TEXT NOT NULL,
|
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
FOREIGN KEY (parent_post_id) REFERENCES posts (id) ON DELETE CASCADE,
|
|
-- FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
|
|
FOREIGN KEY (author_user_id) REFERENCES users (id) ON DELETE CASCADE
|
|
);
|
|
|
|
-- 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); |