Added a migration script containing useful functions/procedures

This commit is contained in:
Imbus 2024-03-06 08:06:32 +01:00
parent 5a75e6f9a0
commit 8875ae4a4c

View file

@ -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;