Skip to content

Instantly share code, notes, and snippets.

@tlaitinen
Last active April 4, 2017 07:31
Show Gist options
  • Select an option

  • Save tlaitinen/aa5070b3580cd36aa65750c9d4a12a5b to your computer and use it in GitHub Desktop.

Select an option

Save tlaitinen/aa5070b3580cd36aa65750c9d4a12a5b to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION choose_other(x bigint, y bigint, z bigint) RETURNS bigint AS
$$
SELECT CASE x
WHEN y THEN z
ELSE y
END
$$ LANGUAGE SQL;
CREATE OR REPLACE FUNCTION node_connected_component(node_id bigint) RETURNS SETOF bigint AS
$$
WITH RECURSIVE n(id, path) AS (
VALUES (node_id, ARRAY[node_id])
UNION
SELECT
choose_other(n.id, l.src_node_id, l.dst_node_id),
n.path || ARRAY[choose_other(n.id, l.src_node_id, l.dst_node_id)]
FROM n, link AS l
WHERE
NOT choose_other(n.id, l.src_node_id, l.dst_node_id) = ANY (n.path)
AND l.active
AND (l.src_node_id = n.id OR l.dst_node_id = n.id)
) SELECT id from n;
$$ LANGUAGE SQL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment