MCPcopy Create free account
hub / github.com/sqlalchemy/sqlalchemy / cte

Method cte

lib/sqlalchemy/orm/query.py:654–715  ·  view source on GitHub ↗

r"""Return the full SELECT statement represented by this :class:`_query.Query` represented as a common table expression (CTE). Parameters and usage are the same as those of the :meth:`_expression.SelectBase.cte` method; see that method for further details. H

(
        self,
        name: Optional[str] = None,
        recursive: bool = False,
        nesting: bool = False,
    )

Source from the content-addressed store, hash-verified

652 return stmt.subquery(name=name)
653
654 def cte(
655 self,
656 name: Optional[str] = None,
657 recursive: bool = False,
658 nesting: bool = False,
659 ) -> CTE:
660 r"""Return the full SELECT statement represented by this
661 :class:`_query.Query` represented as a common table expression (CTE).
662
663 Parameters and usage are the same as those of the
664 :meth:`_expression.SelectBase.cte` method; see that method for
665 further details.
666
667 Here is the `PostgreSQL WITH
668 RECURSIVE example
669 <https://www.postgresql.org/docs/current/static/queries-with.html>`_.
670 Note that, in this example, the ``included_parts`` cte and the
671 ``incl_alias`` alias of it are Core selectables, which
672 means the columns are accessed via the ``.c.`` attribute. The
673 ``parts_alias`` object is an :func:`_orm.aliased` instance of the
674 ``Part`` entity, so column-mapped attributes are available
675 directly::
676
677 from sqlalchemy.orm import aliased
678
679
680 class Part(Base):
681 __tablename__ = "part"
682 part = Column(String, primary_key=True)
683 sub_part = Column(String, primary_key=True)
684 quantity = Column(Integer)
685
686
687 included_parts = (
688 session.query(Part.sub_part, Part.part, Part.quantity)
689 .filter(Part.part == "our part")
690 .cte(name="included_parts", recursive=True)
691 )
692
693 incl_alias = aliased(included_parts, name="pr")
694 parts_alias = aliased(Part, name="p")
695 included_parts = included_parts.union_all(
696 session.query(
697 parts_alias.sub_part, parts_alias.part, parts_alias.quantity
698 ).filter(parts_alias.part == incl_alias.c.sub_part)
699 )
700
701 q = session.query(
702 included_parts.c.sub_part,
703 func.sum(included_parts.c.quantity).label("total_quantity"),
704 ).group_by(included_parts.c.sub_part)
705
706 .. seealso::
707
708 :meth:`_sql.Select.cte` - v2 equivalent method.
709
710 """ # noqa: E501
711 return (

Calls 2

enable_eagerloadsMethod · 0.95