DEV Community

Cover image for Recursive tree queries in Drizzle without raw SQL
Sabira Khan
Sabira Khan

Posted on

Recursive tree queries in Drizzle without raw SQL

I'm not sure.. when was the last time I posted here.. its prolly been years.. but I built something that was long overdue, and had to share.
So, most apps have at least one tree hiding in a table. Product categories, comment threads, folders, org charts. They usually look like this:

export const categories = pgTable('categories', {
  id: serial('id').primaryKey(),
  parentId: integer('parent_id').references((): AnyPgColumn => categories.id),
  name: text('name').notNull(),
})
Enter fullscreen mode Exit fullscreen mode

Storing a tree this way is easy. Reading it back is where it gets awkward. "Give me every subcategory of Clothing, however deep it goes" needs a recursive query, and Drizzle does not have a builder for that yet. The feature request has been open since 2023.

The hand-written version

You can do it today with the sql template and a WITH RECURSIVE CTE:

const rows = await db.execute(sql`
  WITH RECURSIVE tree AS (
    SELECT c.*, 1 AS depth, CAST(c.id AS TEXT) AS path
    FROM categories c
    WHERE c.parent_id = ${clothingId}

    UNION ALL

    SELECT c.*, t.depth + 1, t.path || '/' || c.id
    FROM categories c
    JOIN tree t ON c.parent_id = t.id
  )
  SELECT * FROM tree ORDER BY depth, path
`)
Enter fullscreen mode Exit fullscreen mode

Yes, it works, but then you lose most of what you picked Drizzle for:

  • No types. rows is unknown[]. You cast it and hope the schema still matches.
  • No column mapping. You get parent_id, not parentId. Timestamps come back as strings on some drivers.
  • No composition. You cannot join this to products or add .where() and .limit() with the query builder. Every variation is another SQL string.
  • No cycle protection. If bad data makes a category its own grandparent, this query runs until the database stops it.
  • Different syntax per database. String concatenation and casts differ between Postgres, SQLite and MySQL.

And you will write a second version for ancestors (breadcrumbs), and a third for the whole forest.. like, come on.

With drizzle-tree

I wrote drizzle-tree to handle this once. You describe the tree:

import { defineTree } from 'drizzle-tree/pg'

const categoryTree = defineTree(categories, {
  id: categories.id,
  parentId: categories.parentId,
})
Enter fullscreen mode Exit fullscreen mode

Then query it:

const rows = await categoryTree.findDescendants(db, clothingId)
// [
//   { id: 2, parentId: 1, name: 'Shirts', depth: 1, path: '1/2' },
//   { id: 3, parentId: 2, name: 'Linen shirts', depth: 2, path: '1/2/3' },
// ]
Enter fullscreen mode Exit fullscreen mode

rows is typed from your schema, with depth and path added. Keys are camelCase and dates are Date objects, as with any other Drizzle query.

Breadcrumbs are the same call in the other direction:

const trail = await categoryTree.findAncestors(db, linenShirtsId, { includeSelf: true })
Enter fullscreen mode Exit fullscreen mode

And if you want a nested object for a sidebar menu:

const menu = categoryTree.nest(await categoryTree.findForest(db))
// [{ id: 1, name: 'Clothing', children: [{ id: 2, name: 'Shirts', children: [...] }] }]
Enter fullscreen mode Exit fullscreen mode

It composes with the query builder

This is the part I cared about most. descendants(), ancestors() and forest() return a CTE that you pass to db.with(), so it behaves like a table:

const sub = categoryTree.descendants({ of: clothingId })

const products = await db
  .with(sub)
  .select({ title: productsTable.title, category: sub.name, depth: sub.depth })
  .from(sub)
  .innerJoin(productsTable, eq(productsTable.categoryId, sub.id))
  .orderBy(sub.depth)
  .limit(20)
Enter fullscreen mode Exit fullscreen mode

That gives you every product anywhere under Clothing, paginated, in one query.

The details that usually get skipped

  • Cycles. Each query checks the path it has walked and stops before visiting a node twice. Bad data cannot make it loop forever.
  • Multi-tenant trees. where runs at every level of the walk, so the walk never leaves one tenant: where: eq(categories.tenantId, tenantId).
  • Depth limits. maxDepth: 2 stops after two levels, which is useful for "show children and grandchildren only".
  • Three databases. PostgreSQL, SQLite and MySQL 8, each from its own entry point (drizzle-tree/pg, /sqlite, /mysql). CI tests drizzle-orm 0.40 through 1.0.0-rc.6 on Node 20, 22 and 24.

Try it

npm install drizzle-tree
Enter fullscreen mode Exit fullscreen mode

The idea / inspo comes from laravel-adjacency-list, which has been the standard way to do this in Laravel's Eloquent for years. (And its one of my favorite repos)
I wanted the same thing in TypeScript :)

The repo is sabira-khan/drizzle-tree.
If you store trees in a different shape, such as closure tables or materialized paths, I'd like to hear about it in the issues.

Happy building!

Top comments (0)