From f167cf02f976e7ee45712bfddf89c8b4a9b6ede1 Mon Sep 17 00:00:00 2001 From: Fabrice Lecomte Date: Mon, 26 Aug 2019 00:41:30 +0200 Subject: [PATCH] feature #7: add query "find_comments_by_citizen" --- .../comment/find_comments_by_citizen.sql | 26 +++++++++++++++++++ src/test/sql/comment.sql | 14 +++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 src/main/resources/sql/functions/comment/find_comments_by_citizen.sql diff --git a/src/main/resources/sql/functions/comment/find_comments_by_citizen.sql b/src/main/resources/sql/functions/comment/find_comments_by_citizen.sql new file mode 100644 index 0000000..3f3dccb --- /dev/null +++ b/src/main/resources/sql/functions/comment/find_comments_by_citizen.sql @@ -0,0 +1,26 @@ +create or replace function find_comments_by_citizen( + _citizen_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") + 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 citizen_id = _citizen_id + order by created_at desc, + com.created_at desc + limit "limit" offset "offset" + ) as t; +end; +$$; + +-- drop function if exists find_comments_by_citizen(uuid, int, int); diff --git a/src/test/sql/comment.sql b/src/test/sql/comment.sql index e01bc6a..87ebce1 100644 --- a/src/test/sql/comment.sql +++ b/src/test/sql/comment.sql @@ -26,6 +26,8 @@ declare } $json$; _comment_id uuid; + _selected_comments json; + _selected_comments_total int; begin -- insert user for context select insert_user(created_user) into created_user; @@ -41,7 +43,7 @@ begin select upsert_article(created_article) into created_article; - select comment( + select "comment"( reference => 'article'::regclass, target_id => (created_article->>'id')::uuid, citizen_id => _citizen_id, @@ -52,10 +54,16 @@ begin perform edit_comment( reference => 'article'::regclass, id => _comment_id, - content => 'edited'::text + content => 'edited content'::text ); assert (select count(*) = 1 from "comment"), 'edit comment must not insert new comment'; - assert (select count(*) = 1 from "comment" where content = 'edited'), 'edit comment must not insert new comment'; + assert (select count(*) = 1 from "comment" where content = 'edited content'), 'edit comment must not insert new comment'; + + select resource, total + into _selected_comments, _selected_comments_total + from find_comments_by_citizen(_citizen_id); + assert (_selected_comments_total = 1), 'the number of comments for this citizen must be 1'; + assert (_selected_comments#>>'{0,content}' = 'edited content'), 'the content of first comment for this citizen must be "edited content", "' || (_selected_comments#>>'{0,content}') || '" returned'; -- delete comment and context delete from "comment";