Created
June 30, 2019 17:08
-
-
Save beardedtim/5ff068d10449d5d1622c92cc0251ca77 to your computer and use it in GitHub Desktop.
Querying graph data inside postgres
This file contains hidden or 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
const { Router } = require('express') | |
const Step = new Router() | |
Step.get('/starting_at/:id', async (req, res) => { | |
const { rows } = await db.query(` | |
SELECT * | |
FROM nodes | |
WHERE | |
meta @> '{"starting_states": ["${req.params.id}"]}' | |
`) | |
res.json({ rows }) | |
}) | |
Step.get('/ending_at/:id', async (req, res) => { | |
const { rows } = await db.query(` | |
SELECT * | |
FROM nodes | |
WHERE | |
meta @> '{"ending_states": ["${req.params.id}"]}' | |
`) | |
res.json({ rows }) | |
}) | |
Step.get('/graph/:start/:end', async (req, res) => { | |
const { rows } = await db.query(` | |
WITH RECURSIVE hierarchy AS ( | |
SELECT * | |
FROM nodes | |
WHERE meta @> '{"starting_states": ["${req.params.start}"]}' | |
UNION ALL | |
SELECT N.* | |
FROM nodes as N | |
JOIN hierarchy as H | |
ON (H.meta->'starting_states')::jsonb @> (N.meta->'ending_states')::jsonb | |
WHERE H.meta @> '{"ending_states": ["${req.params.end}"]}' | |
) | |
SELECT * | |
FROM hierarchy | |
ORDER BY created_at | |
`) | |
res.json({ rows }) | |
}) |
This file contains hidden or 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 EXTENSION "uuid-ossp"; | |
CREATE TYPE node_type AS ENUM ('link', 'state', 'step', 'modification', 'other'); | |
CREATE TABLE nodes( | |
id UUID NOT NULL DEFAULT uuid_generate_v4(), | |
title VARCHAR(240) NOT NULL, | |
description TEXT, | |
type node_type NOT NULL DEFAULT 'other', | |
created_at TIMESTAMP NOT NULL DEFAULT NOW(), | |
last_updated TIMESTAMP NOT NULL DEFAULT NOW(), | |
meta JSONB, | |
PRIMARY KEY (id) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment