Created
October 30, 2024 17:17
-
-
Save trvswgnr/2407923609561a295b9fa36789f63fa1 to your computer and use it in GitHub Desktop.
query that returns a tree in json (full tree from root or subtree from node n) with RCTE
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 build_tree(parent_id INTEGER DEFAULT NULL) | |
RETURNS JSONB AS $$ | |
DECLARE | |
result JSONB; | |
count INTEGER; | |
BEGIN | |
SELECT COUNT(*) | |
INTO count | |
FROM nodes n | |
WHERE n.parent_id IS NOT DISTINCT FROM $1; | |
WITH children AS ( | |
SELECT | |
n.id, | |
n.name, | |
build_tree(n.id) as child_tree | |
FROM nodes n | |
WHERE n.parent_id IS NOT DISTINCT FROM $1 | |
) | |
SELECT COALESCE( | |
jsonb_agg( | |
jsonb_build_object( | |
'id', name, | |
'children', COALESCE(child_tree, '[]'::jsonb) | |
) | |
), | |
'[]'::jsonb | |
) | |
INTO result | |
FROM children; | |
RETURN result; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment