vranes commented on code in PR #60611:
URL: https://github.com/apache/spark/pull/60611#discussion_r4614949814


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -87,6 +89,116 @@ case class BinByExec(
   override protected def withNewChildInternal(newChild: SparkPlan): BinByExec =
     copy(child = newChild)
 
+  override def supportCodegen: Boolean = 
conf.getConf(SQLConf.ENABLE_BIN_BY_CODEGEN)
+
+  override def inputRDDs(): Seq[RDD[InternalRow]] = {
+    child.asInstanceOf[CodegenSupport].inputRDDs()
+  }
+
+  override protected def doProduce(ctx: CodegenContext): String = {
+    child.asInstanceOf[CodegenSupport].produce(ctx, this)
+  }
+
+  // Evaluate child expressions once per input row, before expanding it into 
bins.
+  override def usedInputs: AttributeSet = child.outputSet
+
+  // One input row makes many output rows, so each output row needs a copy.
+  override def needCopyResult: Boolean = true
+
+  // The bin loop stops at a LIMIT fused above it.
+  override protected def canCheckLimitNotReached: Boolean = true
+
+  override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row: 
ExprCode): String = {
+    val start = input(bindOrdinal(rangeStart))
+    val end = input(bindOrdinal(rangeEnd))
+    val zone = 
timeZoneId.map(DateTimeUtils.getZoneId).getOrElse(ZoneOffset.UTC)
+    val zoneRef = ctx.addReferenceObj(
+      objName = "zoneId", obj = zone, className = classOf[ZoneId].getName)
+    val formatter = ctx.addReferenceObj(
+      objName = "formatter",
+      obj = TimestampFormatter.getFractionFormatter(zone),
+      className = classOf[TimestampFormatter].getName
+    )
+    val taskContext = ctx.addMutableState(
+      javaType = "TaskContext",
+      variableName = "taskContext",
+      initFunc = v => s"$v = TaskContext.get();",
+      forceInline = true
+    )
+    // A long expansion of one input row checks for a task kill every this 
many bins.
+    val killCheckInterval = 1024
+    val dateTimeUtils = DateTimeUtils.getClass.getName.stripSuffix("$")
+    val errors = QueryExecutionErrors.getClass.getName.stripSuffix("$")
+    val nullRange = ctx.freshName("nullRange")
+    val total = ctx.freshName("total")
+    val bucket = ctx.freshName("bucket")
+    val index = ctx.freshName("index")
+    val nextStart = ctx.freshName("nextStart")
+    val binStart = ctx.freshName("binStart")
+    val binEnd = ctx.freshName("binEnd")
+    val ratio = ctx.freshName("ratio")
+    val hasNext = ctx.freshName("hasNext")
+    val binsSinceKillCheck = ctx.freshName("binsSinceKillCheck")
+    val numOutput = metricTerm(ctx, "numOutputRows")
+
+    val appended = Seq(binStart, binEnd, ratio).zip(appendedAttributes).map {
+      case (value, attr) =>
+        ExprCode(JavaCode.isNullVariable(nullRange), JavaCode.variable(value, 
attr.dataType))
+    }
+    ctx.currentVars = input ++ appended
+    val outputVars = buildOutputExpressions(childLen = input.length, 
ratioNullable = true)
+      .map(_.genCode(ctx))
+
+    s"""
+       |boolean $nullRange = ${start.isNull} || ${end.isNull};
+       |long $total = 0L;
+       |long $index = 0L;
+       |long $nextStart = 0L;
+       |if (!$nullRange) {
+       |  if (${start.value} > ${end.value}) {
+       |    throw (RuntimeException) $errors.binByInvalidRangeError(
+       |      $formatter.format(${start.value}), 
$formatter.format(${end.value}));
+       |  }
+       |  try {
+       |    $total = java.lang.Math.subtractExact(${end.value}, 
${start.value});
+       |    scala.Tuple2 $bucket = 
$dateTimeUtils.timeBucketFromTimestampDTInterval(
+       |      ${binWidthMicros}L, ${start.value}, ${originMicros}L, $zoneRef);
+       |    $index = $bucket._1$$mcJ$$sp();
+       |    $nextStart = $bucket._2$$mcJ$$sp();
+       |  } catch (java.lang.ArithmeticException e) {
+       |    throw $errors.binByOverflowError();
+       |  }
+       |}
+       |boolean $hasNext = true;
+       |int $binsSinceKillCheck = 0;
+       |while ($limitNotReachedCond $hasNext) {

Review Comment:
   Regarding the "Top-level LIMIT can fail with DATETIME_OVERFLOW" from the top 
comment:
   
   Fixed by the same change: the loop returns after the first bin, so it does 
not compute the overflowing boundary.
    'BIN BY returns the bins a LIMIT takes before a later bin boundary 
overflows' runs the example from above and returns one row on both paths.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to