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