Skip to content

Instantly share code, notes, and snippets.

@mvodep
Created April 12, 2022 04:18
Show Gist options
  • Save mvodep/122e14b91c59043fee98e975dbcbec31 to your computer and use it in GitHub Desktop.
Save mvodep/122e14b91c59043fee98e975dbcbec31 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION walk_graph(param_node_id INTEGER)
RETURNS TABLE (id INTEGER)
LANGUAGE plpgsql
AS $$
DECLARE
var_node_ids INTEGER[] := ARRAY[param_node_id];
var_iteration_node_ids INTEGER[] := ARRAY[param_node_id];
BEGIN
WHILE array_length(var_iteration_node_ids, 1) > 0 LOOP
var_iteration_node_ids := ARRAY(SELECT DISTINCT "to" FROM edges
WHERE "from" = ANY(var_iteration_node_ids)
AND NOT("to" = ANY(var_node_ids)));
var_node_ids := var_node_ids || var_iteration_node_ids;
END LOOP;
RETURN QUERY SELECT unnest(var_node_ids);
END $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment