github-code-scanning[bot] commented on code in PR #13168:
URL: https://github.com/apache/druid/pull/13168#discussion_r1056344932


##########
processing/src/main/java/org/apache/druid/collections/QueueBasedSorter.java:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.collections;
+
+import com.google.common.collect.Iterators;
+import com.google.common.collect.MinMaxPriorityQueue;
+import com.google.common.collect.Ordering;
+import org.apache.druid.java.util.common.ISE;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * This sorter is applicable to two cases:
+ * 1.Result Set Merge
+ * 2.Sort the internal data of segment in the way of delayed materialization
+ */
+public class QueueBasedSorter<T> implements Sorter<T>
+{
+
+  private final MinMaxPriorityQueue<T[]> queue;
+
+  public QueueBasedSorter(int limit, Comparator<T[]> comparator)
+  {
+    this.queue = MinMaxPriorityQueue
+        .orderedBy(Ordering.from(comparator))
+        .maximumSize(limit)
+        .create();
+  }
+
+  public QueueBasedSorter(int limit, Ordering<T[]> ordering)
+  {
+    this.queue = MinMaxPriorityQueue
+        .orderedBy(ordering)
+        .maximumSize(limit)
+        .create();
+  }
+
+  @Override
+  public void add(T[] sorterElement)
+  {
+    try {
+      queue.offer(sorterElement);

Review Comment:
   ## Ignored error status of call
   
   Method add ignores exceptional return value of 
MinMaxPriorityQueue<T\[\]>.offer.
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/3583)



##########
processing/src/test/java/org/apache/druid/query/scan/ScanQueryResultOrderingTest.java:
##########
@@ -303,6 +307,290 @@
     );
   }
 
+  @Test
+  public void testOrderIdAscending()
+  {
+    assertOrderByIdResultsEquals(
+        Druids.newScanQueryBuilder()
+              .dataSource("ds")
+              .intervals(new 
MultipleIntervalSegmentSpec(Collections.singletonList(Intervals.of("2000/P1D"))))
+              .columns(ColumnHolder.TIME_COLUMN_NAME, ID_COLUMN)
+              .orderBy(ImmutableList.of(new ScanQuery.OrderBy(ID_COLUMN, 
ScanQuery.Order.ASCENDING)))
+              .build(),
+        ImmutableList.of(
+            7,
+            8,
+            9,
+            12,
+            22,
+            80,
+            101,
+            111,
+            222,
+            232,
+            333,
+            383,
+            411,
+            444,
+            555,
+            777,
+            808,
+            888,
+            999
+        )
+    );
+  }
+
+  @Test
+  public void testOrderDescending()
+  {
+    assertOrderByIdResultsEquals(
+        Druids.newScanQueryBuilder()
+              .dataSource("ds")
+              .intervals(new 
MultipleIntervalSegmentSpec(Collections.singletonList(Intervals.of("2000/P1D"))))
+              .columns(ColumnHolder.TIME_COLUMN_NAME, ID_COLUMN)
+              .orderBy(ImmutableList.of(new ScanQuery.OrderBy(ID_COLUMN, 
ScanQuery.Order.DESCENDING)))
+              .build(),
+        ImmutableList.of(
+            999,
+            888,
+            808,
+            777,
+            555,
+            444,
+            411,
+            383,
+            333,
+            232,
+            222,
+            111,
+            101,
+            80,
+            22,
+            12,
+            9,
+            8,
+            7
+        )
+    );
+  }
+
+  @Test
+  public void testMultiColumnSort()
+  {
+    assertOrderByMultiColumnResultsEquals(
+        Druids.newScanQueryBuilder()
+              .dataSource("ds")
+              .intervals(new 
MultipleIntervalSegmentSpec(Collections.singletonList(Intervals.of("2000/P1D"))))
+              .columns(ColumnHolder.TIME_COLUMN_NAME, ID_COLUMN, CODE_COLUMN)
+              .orderBy(ImmutableList.of(new ScanQuery.OrderBy(CODE_COLUMN, 
ScanQuery.Order.ASCENDING),
+                                        new ScanQuery.OrderBy(ID_COLUMN, 
ScanQuery.Order.DESCENDING)))
+              .build(),
+        ImmutableList.of(
+            new Object[]{999, "200"},
+            new Object[]{888, "200"},
+            new Object[]{383, "200"},
+            new Object[]{101, "200"},
+            new Object[]{8, "200"},
+            new Object[]{7, "200"},
+            new Object[]{444, "201"},
+            new Object[]{411, "201"},
+            new Object[]{80, "201"},
+            new Object[]{232, "206"},
+            new Object[]{12, "300"},
+            new Object[]{9, "400"},
+            new Object[]{555, "403"},
+            new Object[]{808, "404"},
+            new Object[]{111, "404"},
+            new Object[]{333, "500"},
+            new Object[]{22, "500"},
+            new Object[]{777, "501"},
+            new Object[]{222, "503"}
+        )
+    );
+  }
+
+  private void assertOrderByMultiColumnResultsEquals(final ScanQuery query, 
final List<Object[]> expectedResults)
+  {
+
+    final List<List<Pair<SegmentId, QueryRunner<ScanResultValue>>>> 
serverRunners = new ArrayList<>();
+    for (int i = 0; i <= 
segmentToServerMap.stream().max(Comparator.naturalOrder()).orElse(0); i++) {
+      serverRunners.add(new ArrayList<>());
+    }
+
+    for (int segmentNumber = 0; segmentNumber < segmentToServerMap.size(); 
segmentNumber++) {
+      final SegmentId segmentId = SEGMENTS.get(segmentNumber).getId();
+      final int serverNumber = segmentToServerMap.get(segmentNumber);
+
+      serverRunners.get(serverNumber).add(Pair.of(segmentId, 
segmentRunners.get(segmentNumber)));
+    }
+
+    // Simulates what the Historical servers would do.
+    final List<QueryRunner<ScanResultValue>> mergedServerRunners =
+        serverRunners.stream()
+                     .filter(runners -> !runners.isEmpty())
+                     .map(
+                         runners ->
+                             queryRunnerFactory.getToolchest().mergeResults(
+                                 new QueryRunner<ScanResultValue>()
+                                 {
+                                   @Override
+                                   public Sequence<ScanResultValue> run(
+                                       final QueryPlus<ScanResultValue> 
queryPlus,
+                                       final ResponseContext responseContext
+                                   )
+                                   {
+                                     return queryRunnerFactory.mergeRunners(
+                                         Execs.directExecutor(),
+                                         runners.stream().map(p -> 
p.rhs).collect(Collectors.toList())
+                                     ).run(
+                                         queryPlus.withQuery(
+                                             queryPlus.getQuery()
+                                                      .withQuerySegmentSpec(
+                                                          new 
MultipleSpecificSegmentSpec(
+                                                              runners.stream()
+                                                                     .map(p -> 
p.lhs.toDescriptor())
+                                                                     
.collect(Collectors.toList())
+                                                          )
+                                                      )
+                                         ),
+                                         responseContext
+                                     );
+                                   }
+                                 }
+                             )
+                     )
+                     .collect(Collectors.toList());
+
+    // Simulates what the Broker would do.
+    final QueryRunner<ScanResultValue> brokerRunner = 
queryRunnerFactory.getToolchest().mergeResults(
+        (queryPlus, responseContext) -> {
+          final List<Sequence<ScanResultValue>> sequences =
+              mergedServerRunners.stream()
+                                 .map(runner -> 
runner.run(queryPlus.withoutThreadUnsafeState()))
+                                 .collect(Collectors.toList());
+
+          return new MergeSequence<>(
+              queryPlus.getQuery().getResultOrdering(),
+              Sequences.simple(sequences)
+          );
+        }
+    );
+
+    // Finally: run the query.
+    final List<Object[]> results = runMultiColumnQuery(
+        (ScanQuery) Druids.ScanQueryBuilder.copy(query)
+                                           .limit(limit <= 0 ? 10 : limit)
+                                           .batchSize(batchSize)
+                                           .build()
+                                           .withOverriddenContext(
+                                               ImmutableMap.of(
+                                                   
ScanQueryConfig.CTX_KEY_MAX_ROWS_QUEUED_FOR_ORDERING,
+                                                   maxRowsQueuedForOrdering
+                                               )
+                                           ),
+        brokerRunner
+    );
+
+    Assert.assertEquals(
+        expectedResults.stream().limit(limit <= 0 ? 10 : limit).map(rs -> 
rs[0]).collect(Collectors.toList()),
+        results.stream().map(rs -> rs[0]).collect(Collectors.toList())
+    );
+
+    Assert.assertEquals(
+        expectedResults.stream().limit(limit <= 0 ? 10 : limit).map(rs -> 
rs[1]).collect(Collectors.toList()),
+        results.stream().map(rs -> rs[1]).collect(Collectors.toList())
+    );
+  }
+
+  private void assertOrderByIdResultsEquals(final ScanQuery query, final 
List<Integer> expectedResults)
+  {
+
+    final List<List<Pair<SegmentId, QueryRunner<ScanResultValue>>>> 
serverRunners = new ArrayList<>();
+    for (int i = 0; i <= 
segmentToServerMap.stream().max(Comparator.naturalOrder()).orElse(0); i++) {
+      serverRunners.add(new ArrayList<>());
+    }
+
+    for (int segmentNumber = 0; segmentNumber < segmentToServerMap.size(); 
segmentNumber++) {
+      final SegmentId segmentId = SEGMENTS.get(segmentNumber).getId();
+      final int serverNumber = segmentToServerMap.get(segmentNumber);
+
+      serverRunners.get(serverNumber).add(Pair.of(segmentId, 
segmentRunners.get(segmentNumber)));
+    }
+
+    // Simulates what the Historical servers would do.
+    final List<QueryRunner<ScanResultValue>> mergedServerRunners =
+        serverRunners.stream()
+                     .filter(runners -> !runners.isEmpty())
+                     .map(
+                         runners ->
+                             queryRunnerFactory.getToolchest().mergeResults(
+                                 new QueryRunner<ScanResultValue>()
+                                 {
+                                   @Override
+                                   public Sequence<ScanResultValue> run(
+                                       final QueryPlus<ScanResultValue> 
queryPlus,
+                                       final ResponseContext responseContext
+                                   )
+                                   {
+                                     return queryRunnerFactory.mergeRunners(
+                                         Execs.directExecutor(),
+                                         runners.stream().map(p -> 
p.rhs).collect(Collectors.toList())
+                                     ).run(

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [QueryRunnerFactory.mergeRunners](1) should be avoided because it 
has been deprecated.
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/3580)



##########
processing/src/test/java/org/apache/druid/collections/SorterTests.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.collections;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.guava.Comparators;
+import org.apache.druid.query.scan.ScanQuery;
+
+import javax.annotation.Nonnull;
+import java.util.Comparator;
+import java.util.List;
+
+public class SorterTests
+{
+
+  public void addData(Sorter<Integer> sorter, Integer[] datas)
+  {
+    sorter.add(datas);
+  }
+
+  @Nonnull
+  protected Comparator<Comparable[]> getMultiColumnSorterElementComparator(
+      List<String> orderByDirection,
+      List<Integer> orderByIdxs
+  )
+  {
+    Comparator<Comparable[]> comparator = (o1, o2) -> {
+      for (int i = 0; i < orderByIdxs.size(); i++) {
+        int compare;
+        if 
(ScanQuery.Order.ASCENDING.equals(ScanQuery.Order.fromString(orderByDirection.get(i))))
 {
+          compare = Comparators.<Comparable>naturalNullsFirst()
+                               .compare(o1[orderByIdxs.get(i)], 
o2[orderByIdxs.get(i)]);
+        } else {
+          compare = Comparators.<Comparable>naturalNullsFirst()
+                               .compare(o2[orderByIdxs.get(i)], 
o1[orderByIdxs.get(i)]);
+        }
+        if (compare != 0) {
+          return compare;
+        }
+      }
+      return 0;
+    };
+    return comparator;
+  }
+
+  private Comparable[] getDatas(Comparable... datas)
+  {
+    return datas;
+  }
+
+  protected void singleColumnAscSortDatas(Sorter<Object> sorter, List<Integer> 
expectedValues)
+  {
+    sorter.add(getDatas(1, 1));
+    sorter.add(getDatas(2, 2));
+    sorter.add(getDatas(3, 3));
+    sorter.add(getDatas(4, 4));
+    sorter.add(getDatas(5, 5));
+    sorter.add(getDatas(6, 7));
+    sorter.add(getDatas(7, 8));
+    sorter.add(getDatas(1, 9));
+    sorter.add(getDatas(100, 0));
+    sorter.add(getDatas(1, 1));
+    sorter.add(getDatas(1, 3));
+    sorter.add(getDatas(9, 6));
+    sorter.add(getDatas(11, 6));
+
+    expectedValues.addAll(ImmutableList.of(100, 1, 2, 3, 4));
+  }
+
+  protected void singleColumnAscSortNaturalNullsFirstDatas(Sorter<Object> 
sorter, List<Integer> expectedValues)
+  {
+
+    sorter.add(getDatas(1, 1));
+    sorter.add(getDatas(2, 2));
+    sorter.add(getDatas(3, 3));
+    sorter.add(getDatas(4, 4));
+    sorter.add(getDatas(5, 5));
+    sorter.add(getDatas(6, 7));
+    sorter.add(getDatas(7, 8));
+    sorter.add(getDatas(1, 9));
+    sorter.add(getDatas(100, null));
+    sorter.add(getDatas(1, 1));
+    sorter.add(getDatas(1, 3));
+    sorter.add(getDatas(9, 6));
+    sorter.add(getDatas(11, 6));
+
+    expectedValues.addAll(ImmutableList.of(100, 1, 2, 3, 4));
+  }
+
+  protected void multiColumnSortDatas(Sorter<Object> sorter, List<Integer> 
expectedValues)
+  {
+    sorter.add(getDatas(1, 0, 0, 1));
+    sorter.add(getDatas(2, 0, 0, 2));
+    sorter.add(getDatas(3, 0, 0, 3));
+    sorter.add(getDatas(4, 0, 0, 4));
+    sorter.add(getDatas(5, 0, 3, 5));
+    sorter.add(getDatas(6, 0, 6, 7));
+    sorter.add(getDatas(7, 0, 0, 8));
+    sorter.add(getDatas(1, 0, 0, 9));
+    sorter.add(getDatas(100, 1, 0, 0));
+    sorter.add(getDatas(1, 0, 0, 1));
+    sorter.add(getDatas(1, 0, 0, 3));
+    sorter.add(getDatas(9, 0, 0, 6));
+    sorter.add(getDatas(11, 0, 0, 6));
+
+    expectedValues.addAll(ImmutableList.of(6, 5, 1, 7, 9));
+  }
+
+
+  protected void multiColumnSorWithNullDatas(Sorter<Object> sorter, 
List<Integer> expectedValues)
+  {
+    sorter.add(getDatas(1, 0, 0, 1));
+    sorter.add(getDatas(2, 0, 0, 2));
+    sorter.add(getDatas(3, 0, 0, 3));
+    sorter.add(getDatas(4, 0, 0, 4));
+    sorter.add(getDatas(5, 0, 3, 5));
+    sorter.add(getDatas(6, null, 6, 7));
+    sorter.add(getDatas(7, 0, 0, 8));
+    sorter.add(getDatas(1, 0, 0, 9));
+    sorter.add(getDatas(100, 1, 0, 0));
+    sorter.add(getDatas(1, 0, 0, 1));
+    sorter.add(getDatas(1, 0, 0, 3));
+    sorter.add(getDatas(9, 0, 0, 6));
+    sorter.add(getDatas(11, 0, 0, 6));
+
+    expectedValues.addAll(ImmutableList.of(6, 5, 1, 7));
+  }
+
+  protected void multiColumnSortCalssCastExceptionDatas(Sorter sorter)
+  {
+    sorter.add(getDatas(1, 0, 0, 1));
+    sorter.add(getDatas(2, 0, 0, 2));
+    ISE ise = null;

Review Comment:
   ## Unread local variable
   
   Variable 'ISE ise' is never read.
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/3582)



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