diff --git a/src/main/resources/sql/functions/comment/find_comments_by_parent.sql b/src/main/resources/sql/functions/comment/find_comments_by_parent.sql new file mode 100644 index 0000000..b419995 --- /dev/null +++ b/src/main/resources/sql/functions/comment/find_comments_by_parent.sql @@ -0,0 +1,26 @@ +create or replace function find_comments_by_parent( + _parent_id uuid, + "limit" int default 50, + "offset" int default 0, + out resource json, + out total int +) language plpgsql as +$$ +begin + select json_agg(t), (select count(id) from "comment" com where com.parents_ids @> array[_parent_id]) + into resource, total + from ( + select + com.*, + json_build_object('id', com.target_id) as target, + find_citizen_by_id(com.citizen_id) as citizen + from "comment" as com + where com.parents_ids @> array[_parent_id] + order by com.parents_ids nulls first, created_at desc, + com.created_at desc + limit "limit" offset "offset" + ) as t; +end; +$$; + +-- drop function if exists find_comments_by_parent(uuid, int, int); diff --git a/src/test/sql/comment.sql b/src/test/sql/comment.sql index 77b2182..257ae62 100644 --- a/src/test/sql/comment.sql +++ b/src/test/sql/comment.sql @@ -31,6 +31,7 @@ declare _selected_comments json; _selected_comments_total int; _find_comments_by_target_result json; + _find_comments_by_parent_result json; begin -- insert user for context select insert_user(created_user) into created_user; @@ -110,6 +111,13 @@ begin assert (_find_comments_by_target_result#>>'{1,content}') = 'God not exist', 'the second content must contain "God not exist", "' || (_find_comments_by_target_result#>>'{1,content}') || '" returned'; assert (_find_comments_by_target_result#>>'{2,content}') = 'are you really sure ?', 'the third content must contain "are you really sure ?", "' || (_find_comments_by_target_result#>>'{2,content}') || '" returned'; + select resource into _find_comments_by_parent_result + from find_comments_by_parent((_find_comments_by_target_result#>>'{0,id}')::uuid); + assert json_array_length(_find_comments_by_parent_result) = 2, + 'the result should contain 2 comment, ' || json_array_length(_find_comments_by_parent_result) || ' returned'; + assert (_find_comments_by_parent_result#>>'{0,content}') = 'God not exist', 'the second content must contain "God not exist", "' || (_find_comments_by_parent_result#>>'{0,content}') || '" returned'; + assert (_find_comments_by_parent_result#>>'{1,content}') = 'are you really sure ?', 'the third content must contain "are you really sure ?", "' || (_find_comments_by_parent_result#>>'{1,content}') || '" returned'; + -- delete comment and context delete from "comment"; delete from article;