clintropolis commented on code in PR #16740:
URL: https://github.com/apache/druid/pull/16740#discussion_r1689555698


##########
processing/src/main/java/org/apache/druid/query/groupby/ResultRowObjectMapperDecoratorUtil.java:
##########
@@ -0,0 +1,236 @@
+/*
+ * 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.druid.query.groupby;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import org.apache.druid.data.input.Row;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.jackson.JacksonUtils;
+import org.apache.druid.query.dimension.DimensionSpec;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.NullableTypeStrategy;
+import org.apache.druid.segment.column.ValueType;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.List;
+
+public class ResultRowObjectMapperDecoratorUtil
+{
+  public static ObjectMapper decorateObjectMapper(
+      final ObjectMapper baseObjectMapper,
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final JsonDeserializer<ResultRow> deserializer = 
getDeserializer(baseObjectMapper, query, groupByQueryConfig);
+    final JsonSerializer<ResultRow> serializer = getSerializer(query, 
groupByQueryConfig);
+    if (deserializer == null && serializer == null) {
+      return baseObjectMapper;
+    }
+
+    final ObjectMapper decoratedObjectMapper = baseObjectMapper.copy();
+    class GroupByResultRowModule extends SimpleModule
+    {
+      private GroupByResultRowModule()
+      {
+        if (serializer != null) {
+          addSerializer(ResultRow.class, serializer);
+        }
+        if (deserializer != null) {
+          addDeserializer(ResultRow.class, deserializer);
+        }
+      }
+    }
+    decoratedObjectMapper.registerModule(new GroupByResultRowModule());
+    return decoratedObjectMapper;
+  }
+
+  @Nullable
+  private static JsonDeserializer<ResultRow> getDeserializer(
+      final ObjectMapper objectMapper,
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final boolean resultAsArray = 
query.context().getBoolean(GroupByQueryConfig.CTX_KEY_ARRAY_RESULT_ROWS, false);
+    final boolean intermediateCompatMode = 
groupByQueryConfig.isIntermediateResultAsMapCompat();
+    final boolean arrayBasedRows = resultAsArray && !intermediateCompatMode;
+    final boolean dimensionsRequireConversion = query.getDimensions()
+                                                     .stream()
+                                                     .anyMatch(
+                                                         dimensionSpec -> 
dimensionRequiresConversion(dimensionSpec.getOutputType())
+                                                     );
+
+    if (arrayBasedRows && !dimensionsRequireConversion) {
+      // We can assume ResultRow are serialized and deserialized as arrays. No 
need for special decoration,
+      // and we can save the overhead of making a copy of the ObjectMapper
+      return null;
+    } else if (!arrayBasedRows && !dimensionsRequireConversion) {
+      // Have to deserialize map based rows, however don't have to deserialize 
the dimensions individually
+      // Deserializer that can deserialize either array- or map-based rows.
+      return new JsonDeserializer<ResultRow>()
+      {
+        @Override
+        public ResultRow deserialize(final JsonParser jp, final 
DeserializationContext ctxt) throws IOException
+        {
+          if (jp.isExpectedStartObjectToken()) {
+            final Row row = jp.readValueAs(Row.class);
+            return ResultRow.fromLegacyRow(row, query);
+          } else {
+            return ResultRow.of(jp.readValueAs(Object[].class));
+          }
+        }
+      };
+
+    } else {
+      // Have to deserialize the dimensions carefully
+      return new JsonDeserializer<ResultRow>()
+      {
+        final JavaType[] javaTypes = createJavaTypesForResultRow(query);
+
+        @Override
+        public ResultRow deserialize(final JsonParser jp, final 
DeserializationContext ctxt) throws IOException
+        {
+          if (jp.isExpectedStartObjectToken()) {
+            final Row row = jp.readValueAs(Row.class);
+            final ResultRow resultRow = ResultRow.fromLegacyRow(row, query);
+
+            final List<DimensionSpec> queryDimensions = query.getDimensions();
+            for (int i = 0; i < queryDimensions.size(); ++i) {
+              if 
(dimensionRequiresConversion(queryDimensions.get(i).getOutputType())) {
+                final int dimensionIndexInResultRow = 
query.getResultRowDimensionStart() + i;
+                resultRow.set(
+                    dimensionIndexInResultRow,
+                    objectMapper.convertValue(
+                        resultRow.get(dimensionIndexInResultRow),
+                        javaTypes[dimensionIndexInResultRow]
+                    )
+                );
+              }
+            }
+
+            return resultRow;
+          } else {
+            if (!jp.isExpectedStartArrayToken()) {
+              throw DruidException.defensive("Expected start token, received 
[%s]", jp.currentToken());
+            }
+
+            Object[] objectArray = new 
Object[query.getResultRowSizeWithPostAggregators()];
+            int index = 0;
+
+            while (jp.nextToken() != JsonToken.END_ARRAY) {
+              objectArray[index] = 
JacksonUtils.readObjectUsingDeserializationContext(jp, ctxt, javaTypes[index]);
+              ++index;
+            }
+
+            return ResultRow.of(objectArray);
+          }
+        }
+      };
+    }
+  }
+
+  @Nullable
+  private static JsonSerializer<ResultRow> getSerializer(
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final boolean resultAsArray = 
query.context().getBoolean(GroupByQueryConfig.CTX_KEY_ARRAY_RESULT_ROWS, false);
+    final boolean intermediateCompatMode = 
groupByQueryConfig.isIntermediateResultAsMapCompat();
+    final boolean arrayBasedRows = resultAsArray && !intermediateCompatMode;
+    if (arrayBasedRows) {
+      return null;
+    } else {
+      if (resultAsArray) {
+        return new JsonSerializer<ResultRow>()
+        {
+          @Override
+          public void serialize(ResultRow resultRow, JsonGenerator 
jsonGenerator, SerializerProvider serializerProvider)
+              throws IOException
+          {
+            JacksonUtils.writeObjectUsingSerializerProvider(jsonGenerator, 
serializerProvider, resultRow.getArray());
+          }
+        };
+
+      } else {
+        return new JsonSerializer<ResultRow>()
+        {
+          @Override
+          public void serialize(ResultRow resultRow, JsonGenerator 
jsonGenerator, SerializerProvider serializerProvider)
+              throws IOException
+          {
+            JacksonUtils.writeObjectUsingSerializerProvider(
+                jsonGenerator,
+                serializerProvider,
+                resultRow.toMapBasedRow(query)
+            );
+          }
+        };
+      }
+    }
+  }
+
+  private static boolean dimensionRequiresConversion(final ColumnType 
dimensionType)
+  {
+    return dimensionType.is(ValueType.COMPLEX) && 
!ColumnType.NESTED_DATA.equals(dimensionType);
+  }
+
+  private static JavaType[] createJavaTypesForResultRow(final GroupByQuery 
groupByQuery)

Review Comment:
   ah i see, inside the version that takes a class its going to call 
typeFactory.constructType anyway, :+1:



##########
processing/src/main/java/org/apache/druid/query/groupby/ResultRowObjectMapperDecoratorUtil.java:
##########
@@ -0,0 +1,236 @@
+/*
+ * 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.druid.query.groupby;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import org.apache.druid.data.input.Row;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.jackson.JacksonUtils;
+import org.apache.druid.query.dimension.DimensionSpec;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.NullableTypeStrategy;
+import org.apache.druid.segment.column.ValueType;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.util.List;
+
+public class ResultRowObjectMapperDecoratorUtil
+{
+  public static ObjectMapper decorateObjectMapper(
+      final ObjectMapper baseObjectMapper,
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final JsonDeserializer<ResultRow> deserializer = 
getDeserializer(baseObjectMapper, query, groupByQueryConfig);
+    final JsonSerializer<ResultRow> serializer = getSerializer(query, 
groupByQueryConfig);
+    if (deserializer == null && serializer == null) {
+      return baseObjectMapper;
+    }
+
+    final ObjectMapper decoratedObjectMapper = baseObjectMapper.copy();
+    class GroupByResultRowModule extends SimpleModule
+    {
+      private GroupByResultRowModule()
+      {
+        if (serializer != null) {
+          addSerializer(ResultRow.class, serializer);
+        }
+        if (deserializer != null) {
+          addDeserializer(ResultRow.class, deserializer);
+        }
+      }
+    }
+    decoratedObjectMapper.registerModule(new GroupByResultRowModule());
+    return decoratedObjectMapper;
+  }
+
+  @Nullable
+  private static JsonDeserializer<ResultRow> getDeserializer(
+      final ObjectMapper objectMapper,
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final boolean resultAsArray = 
query.context().getBoolean(GroupByQueryConfig.CTX_KEY_ARRAY_RESULT_ROWS, false);
+    final boolean intermediateCompatMode = 
groupByQueryConfig.isIntermediateResultAsMapCompat();
+    final boolean arrayBasedRows = resultAsArray && !intermediateCompatMode;
+    final boolean dimensionsRequireConversion = query.getDimensions()
+                                                     .stream()
+                                                     .anyMatch(
+                                                         dimensionSpec -> 
dimensionRequiresConversion(dimensionSpec.getOutputType())
+                                                     );
+
+    if (arrayBasedRows && !dimensionsRequireConversion) {
+      // We can assume ResultRow are serialized and deserialized as arrays. No 
need for special decoration,
+      // and we can save the overhead of making a copy of the ObjectMapper
+      return null;
+    } else if (!arrayBasedRows && !dimensionsRequireConversion) {
+      // Have to deserialize map based rows, however don't have to deserialize 
the dimensions individually
+      // Deserializer that can deserialize either array- or map-based rows.
+      return new JsonDeserializer<ResultRow>()
+      {
+        @Override
+        public ResultRow deserialize(final JsonParser jp, final 
DeserializationContext ctxt) throws IOException
+        {
+          if (jp.isExpectedStartObjectToken()) {
+            final Row row = jp.readValueAs(Row.class);
+            return ResultRow.fromLegacyRow(row, query);
+          } else {
+            return ResultRow.of(jp.readValueAs(Object[].class));
+          }
+        }
+      };
+
+    } else {
+      // Have to deserialize the dimensions carefully
+      return new JsonDeserializer<ResultRow>()
+      {
+        final JavaType[] javaTypes = createJavaTypesForResultRow(query);
+
+        @Override
+        public ResultRow deserialize(final JsonParser jp, final 
DeserializationContext ctxt) throws IOException
+        {
+          if (jp.isExpectedStartObjectToken()) {
+            final Row row = jp.readValueAs(Row.class);
+            final ResultRow resultRow = ResultRow.fromLegacyRow(row, query);
+
+            final List<DimensionSpec> queryDimensions = query.getDimensions();
+            for (int i = 0; i < queryDimensions.size(); ++i) {
+              if 
(dimensionRequiresConversion(queryDimensions.get(i).getOutputType())) {
+                final int dimensionIndexInResultRow = 
query.getResultRowDimensionStart() + i;
+                resultRow.set(
+                    dimensionIndexInResultRow,
+                    objectMapper.convertValue(
+                        resultRow.get(dimensionIndexInResultRow),
+                        javaTypes[dimensionIndexInResultRow]
+                    )
+                );
+              }
+            }
+
+            return resultRow;
+          } else {
+            if (!jp.isExpectedStartArrayToken()) {
+              throw DruidException.defensive("Expected start token, received 
[%s]", jp.currentToken());
+            }
+
+            Object[] objectArray = new 
Object[query.getResultRowSizeWithPostAggregators()];
+            int index = 0;
+
+            while (jp.nextToken() != JsonToken.END_ARRAY) {
+              objectArray[index] = 
JacksonUtils.readObjectUsingDeserializationContext(jp, ctxt, javaTypes[index]);
+              ++index;
+            }
+
+            return ResultRow.of(objectArray);
+          }
+        }
+      };
+    }
+  }
+
+  @Nullable
+  private static JsonSerializer<ResultRow> getSerializer(
+      final GroupByQuery query,
+      final GroupByQueryConfig groupByQueryConfig
+  )
+  {
+    final boolean resultAsArray = 
query.context().getBoolean(GroupByQueryConfig.CTX_KEY_ARRAY_RESULT_ROWS, false);
+    final boolean intermediateCompatMode = 
groupByQueryConfig.isIntermediateResultAsMapCompat();
+    final boolean arrayBasedRows = resultAsArray && !intermediateCompatMode;

Review Comment:
   not a blocker, but i wonder if we still need this config...



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