Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475527569


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/UDAFAccumulator.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.queryengine.execution.aggregation;
+
+import org.apache.iotdb.commons.udf.service.UDFManagementService;
+import org.apache.iotdb.commons.udf.utils.UDFDataTypeTransformer;
+import org.apache.iotdb.db.queryengine.plan.expression.Expression;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.statistics.Statistics;
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.read.common.block.column.ColumnBuilder;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.State;
+import org.apache.iotdb.udf.api.UDAF;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameterValidator;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.ZoneId;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+public class UDAFAccumulator implements Accumulator {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(UDAFAccumulator.class);
+
+  private final String functionName;
+  private final UDAFConfigurations configurations;
+
+  private State state;
+
+  private UDAF udaf;
+
+  public UDAFAccumulator(
+      String functionName,
+      List<Expression> childrenExpressions,
+      TSDataType childrenExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    this.functionName = functionName;
+    this.configurations = new UDAFConfigurations(ZoneId.systemDefault());
+
+    List<String> childExpressionStrings =
+        childrenExpressions.stream()
+            .map(Expression::getExpressionString)
+            .collect(Collectors.toList());
+    beforeStart(
+        childExpressionStrings,
+        Collections.singletonList(childrenExpressionDataTypes),
+        attributes,
+        isInputRaw);
+  }
+
+  private void beforeStart(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    reflectAndValidateUDF(childExpressions, childExpressionDataTypes, 
attributes, isInputRaw);
+    configurations.check();
+  }
+
+  private void reflectAndValidateUDF(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    udaf = (UDAF) UDFManagementService.getInstance().reflect(functionName);
+    state = udaf.createState();
+
+    final UDFParameters parameters =
+        new UDFParameters(
+            childExpressions,
+            
UDFDataTypeTransformer.transformToUDFDataTypeList(childExpressionDataTypes),
+            attributes);
+
+    // Only validate for raw input
+    // There is no need to validate for partial input
+    if (isInputRaw) {
+      try {
+        // Double validates in workers
+        udaf.validate(new UDFParameterValidator(parameters));
+      } catch (Exception e) {
+        onError("validate(UDFParameterValidator)", e);
+      }
+    }
+
+    try {
+      udaf.beforeStart(parameters, configurations);
+    } catch (Exception e) {
+      onError("beforeStart(UDFParameters, UDAFConfigurations)", e);
+    }
+  }
+
+  @Override
+  public void addInput(Column[] columns, BitMap bitMap) {
+    udaf.addInput(state, columns, bitMap);
+  }
+
+  @Override
+  public void addIntermediate(Column[] partialResult) {
+    checkArgument(partialResult.length == 1, "partialResult of UDAF should be 
1");
+    if (partialResult[0].isNull(0)) {
+      return;
+    }
+
+    State otherState = udaf.createState();
+    Binary otherStateBinary = partialResult[0].getBinary(0);
+    otherState.deserialize(otherStateBinary.getValues());
+
+    udaf.combineState(state, otherState);
+  }
+
+  // Currently, UDAF does not support optimization
+  // by statistics in TsFile
+  @Override
+  public void addStatistics(Statistics statistics) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  // Currently, query engine won't generate
+  // Final -> Final AggregationStep for UDAF
+  @Override
+  public void setFinal(Column finalResult) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  @Override
+  public void outputIntermediate(ColumnBuilder[] columnBuilders) {
+    checkArgument(columnBuilders.length == 1, "partialResult of UDAF should be 
1");
+
+    byte[] bytes = state.serialize();

Review Comment:
   I think NULL value here is just to save some space. While all built-in 
aggregators use additional field (like `initResult`) to indicate whether the 
state is initialized, we can't force users to do so. For simplicity, we just 
serialize the whole state object into binary.
   
   The problem is, some built-in aggregators will append NULL in columnBuilder 
if the state is uninitialized, and the NULL value would be skipped in 
`addIntermediate()` and `removeIntermediate()` method. Since UDAF won't produce 
NULL intermediate output, shall we remove the **skip the NULL logic** in both 
methods?
   
   IMHO, if the logic is removed and UT/IT is still passed, we can consider to 
safely apply this change.
   
   



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