2023-10-21 00:59:21 +02:00
|
|
|
CREATE TABLE
|
|
|
|
IF NOT EXISTS posts (
|
|
|
|
id INTEGER PRIMARY KEY NOT NULL,
|
|
|
|
user_id INTEGER 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 (user_id) REFERENCES users (id)
|
|
|
|
);
|
|
|
|
|
|
|
|
-- Create a trigger to set created_at and updated_at on INSERT
|
|
|
|
CREATE TRIGGER IF NOT EXISTS set_created_at AFTER INSERT ON posts BEGIN
|
|
|
|
UPDATE posts
|
|
|
|
SET
|
|
|
|
created_at = CURRENT_TIMESTAMP
|
|
|
|
WHERE
|
|
|
|
id = NEW.id;
|
|
|
|
|
|
|
|
END;
|
|
|
|
|
|
|
|
-- Create a trigger to set updated_at on UPDATE
|
|
|
|
CREATE TRIGGER IF NOT EXISTS set_updated_at AFTER
|
|
|
|
UPDATE ON posts BEGIN
|
|
|
|
UPDATE posts
|
|
|
|
SET
|
|
|
|
updated_at = CURRENT_TIMESTAMP
|
|
|
|
WHERE
|
|
|
|
id = NEW.id;
|
|
|
|
|
|
|
|
END;
|
|
|
|
|
|
|
|
create INDEX IF NOT EXISTS posts_user_id_index ON posts (user_id);
|
|
|
|
|
|
|
|
create INDEX IF NOT EXISTS posts_id_index ON posts (id);
|
|
|
|
|
2023-10-21 01:55:07 +02:00
|
|
|
CREATE INDEX idx_created_at_desc ON posts (created_at DESC);
|