Github user sameeragarwal commented on a diff in the pull request: https://github.com/apache/spark/pull/14866#discussion_r76884744 --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala --- @@ -933,6 +936,45 @@ object CombineLimits extends Rule[LogicalPlan] { } /** + * Check if there any cartesian products between joins of any type in the optimized plan tree. + * Throw an error if a cartesian product is found without an explicit cross join specified. + * This rule is effectively disabled if the CROSS_JOINS_ENABLED flag is true. + * + * This rule must be run AFTER the ReorderJoin rule since the join conditions for each join must be + * collected before checking if it is a cartesian product. If you have + * SELECT * from R, S where R.r = S.s, + * the join between R and S is not a cartesian product and therefore should be allowed. + * The predicate R.r = S.s is not recognized as a join condition until the ReorderJoin rule. + */ +case class CheckCartesianProducts(conf: CatalystConf) + extends Rule[LogicalPlan] with PredicateHelper { + /** + * Check if a join specified by left, right and condition is a cartesian product. Returns true if + * there are no join conditions involving references from both left and right. + */ + def isCartesianProduct(left: LogicalPlan, right: LogicalPlan, condition: Option[Expression]) + : Boolean = { + val conditions = condition.map(splitConjunctivePredicates).getOrElse(Nil) + !conditions.map(_.references).exists(refs => refs.exists(left.outputSet.contains) + && refs.exists(right.outputSet.contains)) + } + + def apply(plan: LogicalPlan): LogicalPlan = + if (conf.allowCartesianProduct) { + plan + } else plan transform { + case j @ Join(left, right, Inner(false) | LeftOuter | RightOuter | FullOuter, condition) + if isCartesianProduct(left, right, condition) => + throw new AnalysisException( + s"""Detected cartesian product for ${j.joinType.sql} join between logical plans + |${left.treeString(false).trim} + |and + |${right.treeString(false).trim} + |Use a CROSS JOIN to allow cartesian products between these relations""".stripMargin) --- End diff -- Should we also talk about the conf flag here?
--- 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