Github user ankurdave commented on a diff in the pull request: https://github.com/apache/spark/pull/9089#discussion_r41836429 --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala --- @@ -362,14 +362,35 @@ class Analyzer( j case Some((oldRelation, newRelation)) => val attributeRewrites = AttributeMap(oldRelation.output.zip(newRelation.output)) - val newRight = right transformUp { - case r if r == oldRelation => newRelation - } transformUp { - case other => other transformExpressions { - case a: Attribute => attributeRewrites.get(a).getOrElse(a) + def applyRewrites(plan: LogicalPlan): LogicalPlan = + plan transformUp { + case r if r == oldRelation => newRelation + } transformUp { + case other => other transformExpressions { + case a: Attribute => attributeRewrites.get(a).getOrElse(a) + } } - } - j.copy(right = newRight) + val newRight = applyRewrites(right) + // Also apply the rewrites to foreign keys on the left side, because these are meant to + // reference the right side. + val newLeft = + if (left.keys.nonEmpty) { + left.transform { + case KeyHint(keys, child) => + val newKeys = keys.collect { + case ForeignKey(attr, referencedRelation, referencedAttr) => + ForeignKey( + attr, + applyRewrites(referencedRelation), + attributeRewrites.get(referencedAttr).getOrElse(referencedAttr)) + case other => other + } + KeyHint((keys ++ newKeys).distinct, child) --- End diff -- Good eye! This is to accommodate future self-joins. If we got rid of the old foreign keys, a future self-join would not recognize that the new keys applied to it, because the attributes would have been rewritten. I just added a comment noting this. There's [a unit test](https://github.com/apache/spark/pull/9089/files#diff-09ca3beb9c48d89b5fcf248e48d888ddR261) that covers this (fails if you remove the old keys).
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. --- --------------------------------------------------------------------- To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org For additional commands, e-mail: reviews-h...@spark.apache.org