Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Walk a graph

Keep links between things as rows of a graph table, then find everything reachable from one node and the shortest path between two.

A table of links, such as which card waits on which, answers one step at a time. Finding everything a card waits on, through any number of steps, takes a recursive query that a graph table writes for you.

Find every node a node reaches

Add graph to a table’s options, naming the column each link starts from and the column it goes to. Each row is then one link, and Luna indexes the links both ways.

import { defineLuna, t, table } from "luna";

export const Board = defineLuna({
  name: "Board",
  key: { id: t.string() },
  schema: {
    deps: table(
      { card: t.int(), blocker: t.int() },
      {
        primaryKey: ["card", "blocker"],
        graph: { from: "card", to: "blocker" },
      },
    ),
  },
  handlers: (h) => ({
    block: h(
      { args: { card: t.int(), blocker: t.int() } },
      (ctx, { card, blocker }) => void ctx.db.deps.upsert({ card, blocker }),
    ),
    waitsOn: h({ args: { card: t.int() }, query: true }, (ctx, { card }) =>
      ctx.db.deps.traverse(card),
    ),
  }),
});

traverse(start) follows the links out of start and returns each node it reaches once, as { node, depth }. depth counts the links from start, and nodes come back nearest first. start itself is left out.

With links from card 1 to 2, from 2 to 3 and from 1 to 3, waitsOn for card 1 returns 2 and 3, both at depth 1.

direction picks which way to follow links: "out" by default, "in" against them, or "both".

holdsUp: h({ args: { card: t.int() }, query: true }, (ctx, { card }) =>
  ctx.db.deps.traverse(card, { direction: "in", depth: 3 }),
),

Following links in finds every card that waits on this one.

Limit how far a walk goes

Option Does
depth Follows at most this many links from start. 10 by default, at most 100
limit Returns at most this many nodes. 1,000 by default

Find the shortest path

path(from, to) returns the nodes of a shortest chain of links from one node to the other, both ends included. It returns null when no chain is short enough.

chain: h(
  { args: { from: t.int(), to: t.int() }, query: true },
  (ctx, { from, to }) => ctx.db.deps.path(from, to),
),

maxDepth sets the longest chain it tries, 6 links by default and at most 12. With direction: "both", a chain may also follow links backwards.

Next steps

  • Define tables covers primary keys and the other table options.
  • Run SQL writes recursive queries of your own when a walk needs more.
  • ctx.db lists the options of traverse and path.

Was this page helpful?