From 8875ae4a4cf25c5d1e11c45265facfe772322b85 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 6 Mar 2024 08:06:32 +0100 Subject: [PATCH] Added a migration script containing useful functions/procedures --- server/migrations/0004_procedures.sql | 62 +++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 server/migrations/0004_procedures.sql diff --git a/server/migrations/0004_procedures.sql b/server/migrations/0004_procedures.sql new file mode 100644 index 0000000..0708073 --- /dev/null +++ b/server/migrations/0004_procedures.sql @@ -0,0 +1,62 @@ +-- Description: This file creates the procedures and functions for adding users, posts, and comments. +-- Functions are commonly used for SELECT queries, while procedures are used for INSERT, UPDATE, and DELETE queries. +-- None of these seem to play very nice with sqlx for now, but they will surely be useful in the future. + +-- Procedure for adding a user +CREATE OR REPLACE PROCEDURE add_user( + IN username_param TEXT, + IN password_param TEXT +) +LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO users (username, password) + VALUES (username_param, password_param); +END; +$$; + +-- Procedure for adding a post +CREATE OR REPLACE PROCEDURE add_post( + IN user_id_param BIGINT, + IN content_param TEXT +) +LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO posts (user_id, content) + VALUES (user_id_param, content_param); +END; +$$; + +-- Procedure for adding a comment +CREATE OR REPLACE PROCEDURE add_comment( + IN parent_post_id_param BIGINT, + -- IN parent_comment_id_param BIGINT, + IN author_user_id_param BIGINT, + IN content_param TEXT +) +LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO comments (parent_post_id, author_user_id, content) + VALUES (parent_post_id_param, author_user_id_param, content_param); +END; +$$; + +-- Function for getting comments +CREATE OR REPLACE FUNCTION get_comments( + IN parent_post_id_param BIGINT, + IN limit_param BIGINT, + IN offset_param BIGINT +) +RETURNS SETOF comments AS $$ +BEGIN + RETURN QUERY + SELECT * + FROM comments + WHERE parent_post_id = parent_post_id_param + ORDER BY created_at DESC + LIMIT limit_param + OFFSET offset_param; +END; +$$ LANGUAGE plpgsql;