FrostByte/server/migrations/0004_procedures.sql

62 lines
1.6 KiB
PL/PgSQL

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