Skip to content

recursive ctes w/ anon labels don't resolve the anon label in the "WITH" part #6663

Closed
@zzzeek

Description

@zzzeek
Member

this doesnt produce real problems but it looks bad

        parts = table(
            "parts", column("part"), column("sub_part"), column("quantity")
        )

        included_parts = (
            select(
                parts.c.sub_part.label(None),
                parts.c.part.label(None),
                parts.c.quantity,
            )
            .where(parts.c.part == "our part")
            .cte(recursive=True)
        )

        incl_alias = included_parts.alias()
        parts_alias = parts.alias()
        included_parts = included_parts.union(
            select(
                parts_alias.c.sub_part,
                parts_alias.c.part,
                parts_alias.c.quantity,
            ).where(parts_alias.c.part == incl_alias.c[0])
        )

        s = (
            select(
                included_parts.c[0],
                func.sum(included_parts.c.quantity).label("total_quantity"),
            )
            .select_from(
                included_parts.join(
                    parts, included_parts.c[1] == parts.c.part
                )
            )
            .group_by(included_parts.c[0])
        )

will render

WITH RECURSIVE anon_1("%(140408045591184 sub_part)s", "%(140408045590320 part)s", quantity) AS (SELECT parts.sub_part AS sub_part_1, parts.part AS part_1, parts.quantity AS quantity FROM parts WHERE parts.part = :part_2 UNION SELECT parts_1.sub_part AS sub_part, parts_1.part AS part, parts_1.quantity AS quantity FROM parts AS parts_1, anon_1 AS anon_2 WHERE parts_1.part = anon_2.sub_part_1) SELECT anon_1.sub_part_1, sum(anon_1.quantity) AS total_quantity FROM anon_1 JOIN parts ON anon_1.part_1 = parts.part GROUP BY anon_1.sub_part_1

whlie the test above relies on indexed column access that's only in 1.4, this happens in 1.3 also with ORM use cases such as that mentioned in #6661 .

Activity

added this to the 1.4.x milestone on Jun 22, 2021
sqla-tester

sqla-tester commented on Jun 22, 2021

@sqla-tester
Collaborator

Mike Bayer has proposed a fix for this issue in the master branch:

Export deferred columns but not col props; fix CTE labeling https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/2885

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingsql

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @zzzeek@sqla-tester

        Issue actions

          recursive ctes w/ anon labels don't resolve the anon label in the "WITH" part · Issue #6663 · sqlalchemy/sqlalchemy