I have a schema that looks like this:
CREATE TABLE category (
id SERIAL PRIMARY KEY,
parent INTEGER REFERENCES category(id) DEFERRABLE,
name TEXT NOT NULL UNIQUE );
SET CONSTRAINTS ALL DEFERRED;
The rows I have added are:
INSERT INTO category VALUES (1, NULL, 'animal');
INSERT INTO category VALUES (2, 1, 'dog');
INSERT INTO category VALUES (3, 1, 'cat');
INSERT INTO category VALUES (4, 3, 'siamese');
INSERT INTO category VALUES (5, 3, 'persian');
INSERT INTO category VALUES (6, 7, 'scary1');
INSERT INTO category VALUES (7, 6, 'scary2');
I'm trying to figure out how to recursively query this using WITH RECURSIVE to get a result that looks as such:
ids | names
---------+------------------------
{1} | animal
{2,1} | dog, animal
{3,1} | cat, animal
{4,3,1} | siamese, cat, animal
{5,3,1} | persian, cat, animal
{6,7} | scary1, scary2
{7,6} | scary2, scary1
Where ids is an array containing each parent until the root, and where names is a string with each name separated by commas.
I also need to handle the paradox condition without hanging.
Can somebody point me in the right direction?