Created
March 23, 2023 21:26
-
-
Save fwgreen/183eede2e6e6ce82728995e0ad6fd360 to your computer and use it in GitHub Desktop.
Paginating SQL function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION list_paginated_messages_by_priority(p text, o int, l int) | |
RETURNS TABLE(id bigint, sender_name text, recipient_name text, message_title text, current_page bigint, page_count bigint) | |
LANGUAGE SQL | |
BEGIN ATOMIC | |
WITH pagination_meta_data AS ( | |
SELECT *, | |
((ROW_NUMBER () OVER (ORDER BY id) - 1) / $3) + 1 AS current_page, | |
CEILING((COUNT(*) OVER ())::decimal / $3::decimal)::bigint AS page_count | |
FROM ( | |
SELECT *, | |
ROW_NUMBER () OVER (PARTITION BY id ORDER BY id DESC NULLS LAST, id DESC) AS this_rows_number | |
FROM direct_message | |
) sub | |
WHERE this_rows_number = 1 | |
AND $1 = ANY(message_priority::text[]) | |
) | |
SELECT id, | |
(SELECT pn.first_name || ' ' || pn.last_name FROM person pn WHERE sender_id = pn.id) AS sender_name, | |
(SELECT pn.first_name || ' ' || pn.last_name FROM person pn WHERE recipient_id = pn.id) AS recipient_name, | |
message_title, | |
current_page, | |
page_count | |
FROM pagination_meta_data | |
ORDER BY current_page ASC | |
LIMIT $3 | |
OFFSET $2; | |
END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment