From 7914b6491b31e07d2aa0313a97a0ded27627da07 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Fri, 5 Aug 2022 17:25:05 -0400 Subject: deep compare CTEs before considering them conflicting Fixed issue where referencing a CTE multiple times in conjunction with a polymorphic SELECT could result in multiple "clones" of the same CTE being constructed, which would then trigger these two CTEs as duplicates. To resolve, the two CTEs are deep-compared when this occurs to ensure that they are equivalent, then are treated as equivalent. Fixes: #8357 Change-Id: I1f634a9cf7a6c4256912aac1a00506aecea3b0e2 (cherry picked from commit 85fa363c846f4ed287565c43c32e2cca29470e25) --- lib/sqlalchemy/sql/compiler.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'lib/sqlalchemy/sql/compiler.py') diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index 330f3c3bc..c9b6ba670 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -2708,10 +2708,19 @@ class SQLCompiler(Compiled): del self.level_name_by_cte[existing_cte_reference_cte] else: - raise exc.CompileError( - "Multiple, unrelated CTEs found with " - "the same name: %r" % cte_name - ) + # if the two CTEs are deep-copy identical, consider them + # the same, **if** they are clones, that is, they came from + # the ORM or other visit method + if ( + cte._is_clone_of is not None + or existing_cte._is_clone_of is not None + ) and cte.compare(existing_cte): + is_new_cte = False + else: + raise exc.CompileError( + "Multiple, unrelated CTEs found with " + "the same name: %r" % cte_name + ) if not asfrom and not is_new_cte: return None -- cgit v1.2.1