Skip to content

Instantly share code, notes, and snippets.

@cairabbit
Last active April 15, 2024 16:03
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cairabbit/d64fccf7cf2abe180e69c843706f46c7 to your computer and use it in GitHub Desktop.
Save cairabbit/d64fccf7cf2abe180e69c843706f46c7 to your computer and use it in GitHub Desktop.
SqlAlchemy CTE recursive sample
from sqlalchemy.orm import sessionmaker, relationship, aliased
from sqlalchemy import cast, Integer, Text, Column, ForeignKey, literal, null
from sqlalchemy.sql import column, label
class Catalog(Base):
__tablename__ = 'catalog'
id = Column(String, primary_key=True)
parentid = Column(String, ForeignKey('catalog.id'))
name = Column(String)
parent = relationship("Catalog", remote_side=[id])
hierarchy = session.query(
Catalog, literal(0).label('level'))\
.filter(Catalog.parentid == null())\
.cte(name="hierarchy", recursive=True)
parent = aliased(hierarchy, name="p")
children = aliased(Catalog, name="c")
hierarchy = hierarchy.union_all(
session.query(
children,
(parent.c.level + 1).label("level"))
.filter(children.parentid == parent.c.id))
result = session.query(Catalog, hierarchy.c.level)\
.select_entity_from(hierarchy).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment