Skip to content

Instantly share code, notes, and snippets.

@frmichetti
Created June 9, 2022 21:24
Show Gist options
  • Save frmichetti/1c8e4a5f9d091908f111a6c565deb291 to your computer and use it in GitHub Desktop.
Save frmichetti/1c8e4a5f9d091908f111a6c565deb291 to your computer and use it in GitHub Desktop.
Hierarchic Self-Referential Data (fixed)
create extension intarray ;
CREATE TABLE messages (
created_at timestamp DEFAULT now(),
reply_to int REFERENCES messages,
id int PRIMARY KEY
GENERATED BY DEFAULT AS IDENTITY,
content text,
CHECK (reply_to <> id)
);
CREATE INDEX ON messages (reply_to, id);
INSERT INTO messages ( reply_to, id, content )
VALUES
( null, 1, 'SYN'),
( 1, 2, 'SYN-ACK'),
( 2, 3, 'ACK'),
( null, 4, 'We should give free advertising to PLAN EXPLORER'),
( 4, 5, 'Admins should disclose their affiliations with products'),
( 5, 6, 'BANNNN'),
( 4, 7, 'Plan Explorer only works on one database'),
( 7, 8, 'BANNNN'),
( 4, 9, 'Plan Explorer does not support Linux'),
( 9, 10, 'BANNNN'),
( 4, 11, 'Plan Explorer only does what decent databases already do'),
( 11, 12, 'BANNNN');
WITH RECURSIVE t(reply_to, id, content, root, level)
AS (
SELECT reply_to, id, content, ARRAY[id], 0
FROM messages
WHERE reply_to IS NULL
UNION ALL
SELECT messages.reply_to, messages.id, messages.content, root | ARRAY[messages.id], t.level+1
FROM t
JOIN messages
ON (messages.reply_to = t.id)
)
SELECT * FROM t
ORDER BY root;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment