xuzifu666 commented on code in PR #5178:
URL: https://github.com/apache/calcite/pull/5178#discussion_r3784580059


##########
core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java:
##########
@@ -2491,12 +2490,84 @@ protected FirstLastValueImplementor(SeekType seekType) {
         AggResultContext result) {
       WinAggResultContext winResult = (WinAggResultContext) result;
 
+      final boolean ignoreNulls =
+          info instanceof WinAggContext && ((WinAggContext) 
info).ignoreNulls();
+      if (ignoreNulls) {
+        return implementResultIgnoreNulls(info, winResult);
+      }
+
       return Expressions.condition(winResult.hasRows(),
           winResult.rowTranslator(
               winResult.computeIndex(Expressions.constant(0), seekType))
               .translate(winResult.rexArguments().get(0), info.returnType()),
           getDefaultValue(info.returnType()));
     }
+
+    /**
+     * Implements FIRST_VALUE / LAST_VALUE with IGNORE NULLS by scanning the
+     * frame (forward for FIRST_VALUE, backward for LAST_VALUE) and returning
+     * the first non-null argument value, or the default value if all rows in
+     * the frame are null (or the frame is empty).
+     */
+    private Expression implementResultIgnoreNulls(AggContext info,
+        WinAggResultContext winResult) {
+      final Type returnType = info.returnType();
+      final RexNode arg = winResult.rexArguments().get(0);
+
+      // Use a boxed type internally so that a NULL comparison is always valid,
+      // even when the (frame-guaranteed non-empty) return type is a primitive.
+      // The surrounding window implementation converts the result back to the
+      // declared return type.
+      final Type boxType = Types.box(returnType);
+
+      final ParameterExpression res =
+          Expressions.parameter(0, boxType,
+              winResult.currentBlock().newName(
+                  seekType == SeekType.START ? "first_value" : "last_value"));
+      winResult.currentBlock().add(Expressions.declare(0, res, NULL_EXPR));

Review Comment:
   Yes, the NULL_EXPR passed to Expressions.declare initializes res to null, 
which is the default value returned when the frame is empty or every row in the 
frame is null. This matches the behavior in the non-IGNORE NULLS path, where 
getDefaultValue(info.returnType()) also produces null for these functions. I 
kept the code as-is because the surrounding Javadoc now explicitly says "or 
null if all rows in the frame are null", so the intent should be clear from the 
documentation.



-- 
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]

Reply via email to