diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index e3415ff5a..dc9924dc9 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -1355,7 +1355,7 @@ private func prefetch( // useless, and we only need to select pivot columns: let originRelation = originRelation .unorderedUnlessLimited() // only preserve ordering in the CTE if limited - .removingChildrenForPrefetchedAssociations() + .removingPrefetchedAssociations() .selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection }) let originCTE = CommonTableExpression( named: "grdb_base", diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index aa106a319..4d9a8d30c 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -120,10 +120,10 @@ public struct _SQLAssociation { let reversedSteps = zip(steps, steps.dropFirst()) .map { (step, nextStep) in // Intermediate steps are not selected, and including(all:) - // children are useless: + // children can't impact the destination relation: let relation = step.relation .selectOnly([]) - .removingChildrenForPrefetchedAssociations() + .removingPrefetchedAssociations() // Don't interfere with user-defined keys that could be added later let key = step.key.with { diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index e4c687bf5..4bd764e29 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -530,11 +530,18 @@ extension SQLRelation { } } - func removingChildrenForPrefetchedAssociations() -> Self { - filteringChildren { - switch $0.kind { - case .all, .bridge: return false - case .oneRequired, .oneOptional: return true + /// Return a relation without any `.all` and `.bridge` children, recursively. + func removingPrefetchedAssociations() -> Self { + with { + $0.children = $0.children.compactMapValues { child in + switch child.kind { + case .all, .bridge: + return nil + case .oneRequired, .oneOptional: + return child.with { + $0.relation = $0.relation.removingPrefetchedAssociations() + } + } } } }