auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Block makeBlock(int positionCount, boolean includeNulls, boolean[] nulls, long[] values) { Block block = new Int128ArrayBlock(positionCount, Optional.ofNullable(includeNulls ? nulls : null), values); return block; }

Target:
nit: inline `block` variable
Source:
public void testBytes() { // Single tinyint column assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex WHERE ship_day < 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day > 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day is null"); // Two tinyint columns assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day = 1 AND ship_month = 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_month is null"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_day is not null AND ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day > 15 AND ship_month < 5 AND (ship_day + ship_month) < 20"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day_month[2] = 12"); assertQueryUsingH2Cte("SELECT ship_day_month_nulls FROM lineitem_ex WHERE ship_day_month_nulls[1] is NOT NULL AND ship_day_month[1] > 3"); }

Target:
I expect this query to fail because ship_day_month_nulls column doesn't exist
Source:
private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, true, null, 0, false); }

Target:
Why do we change the `organized` argument from `false` to `true`?
Source:
public void start() { log.info("ShardOrganizationManager start, enabled: %s, started: %s", enabled, started); if (!enabled || started.getAndSet(true)) { log.info("ShardOrganizationManager return"); return; } startDiscovery(); }

Target:
I don't think we need this log. Same for the next one.
Source:
public void testTriggerBucketBalancer() { assertUpdate("CREATE TABLE test_bucket_balancer (c1 bigint, c2 bigint)"); assertUpdate("INSERT INTO test_bucket_balancer VALUES (1, 1), (1, 2), (1, 3), (1, 4), (11, 1), (11, 2)", 6); assertUpdate("CALL system.trigger_bucket_balancer()"); assertUpdate("DROP TABLE test_bucket_balancer"); }

Target:
I think we don't need to create a table for this test. Just call the procedure and see if it fails.
Source:
public void testCreateTableWithUnsupportedType() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); try { ConnectorTableMetadata raptorMetadata = buildTable(ImmutableMap.of(), tableMetadataBuilder(DEFAULT_TEST_ORDERS) .column("orderkey", BIGINT) .column("rowtype", RowType.withDefaultFieldNames(ImmutableList.of(BIGINT)))); metadata.createTable(SESSION, raptorMetadata, false); fail(); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } }

Target:
Let's put this together with the previous line ```java ConnectorTableMetadata raptorMetadata = buildTable(ImmutableMap.of(), tableMetadataBuilder(DEFAULT_TEST_ORDERS) ...
Source:
public void setup() { for (int i = 0; i < POSITIONS_PER_PAGE; i++) { longValues[i] = random.nextLong(); ids[i] = random.nextInt(POSITIONS_PER_PAGE / 10); positions[i] = i; if (i % 7 == 0) { nulls[i] = true; } } }

Target:
nit: what about ```java nulls[i] = i % 7 == 0 ``` ?
Source:
synchronized Map<QueryId, Map<String, Long>> getTaggedMemoryAllocations() { return taggedMemoryAllocations.keySet().stream() .collect(toImmutableMap(identity(), queryId -> getTaggedMemoryAllocations(queryId))); }

Target:
`this:: getTaggedMemoryAllocations`
Source:
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<RowExpression> context) { RowExpression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(new SymbolReference(node.getSemiJoinOutput().getName()))) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); }

Target:
SymbolReference is an issue
Source:
public void readFully(long position, byte[] buffer) throws IOException { }

Target:
`throws IOException` is not needed. Same for other `readFully`s
Source:
public int getHeight() { return levelOffsets.length; }

Target:
this method is not used
Source:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } return new AnalyzedExpressionRewriter(session, metadata, sqlParser, symbolAllocator.getTypes()).rewriteWith(Visitor::new, expression); }

Target:
If `apply` is added, the `testCorrelatedExistsSubqueries` will fail. It seems like `ExpressionAnalyzer` are having trouble analyze subquery ( For example, `EXISTIS ( SELECT ...)`). This has been a long standing issue though. The current solution is do the `Desugar` again after correlated subqueries are replaced with plan nodes. This is an issue might worth dig into, but likely outside the scope of this PR.
Source:
protected UnweightedReservoirSampleStateStrategy(UnweightedReservoirSampleStateStrategy other) { reservoir = other.reservoir.clone(); }

Target:
make this private
Source:
public static void output(@AggregationState DifferentialEntropyState state, BlockBuilder out) { DifferentialEntropyStateStrategy strategy = state.getStrategy(); double result = strategy == null ? Double.NaN : strategy.calculateEntropy(); DOUBLE.writeDouble(out, result); }

Target:
I'd inline result variable: `DOUBLE.writeDouble(out, strategy == null ? Double.NaN : strategy.calculateEntropy());`
Source:
public void setStrategy(DifferentialEntropyStateStrategy strategy) { requireNonNull(strategy, "strategy is null"); this.strategy = strategy; }

Target:
nit: combine with assignment `this.strategy = requireNonNull(strategy, "strategy is null");`
Source:
public Operator createOperator(DriverContext driverContext) { OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, PartitionedOutputOperator.class.getSimpleName()); return new PartitionedOutputOperator( operatorContext, sourceTypes, pagePreprocessor, partitionFunction, partitionChannels, partitionConstants, replicatesAnyRow, nullChannel, outputBuffer, serdeFactory, maxMemory, SystemSessionProperties.isOptimizedRepartitioningEnabled(operatorContext.getSession())); }

Target:
static import
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); if (page.getPositionCount() == 0) { return; } page = pagePreprocessor.apply(page); if (useOptmizedPartitionedOutputOperator) { partitionFunction.ariaPartitionPage(page); } else { partitionFunction.partitionPage(page); } operatorContext.recordOutput(page.getSizeInBytes(), page.getPositionCount()); // We use getSizeInBytes() here instead of getRetainedSizeInBytes() for an approximation of // the amount of memory used by the pageBuilders, because calculating the retained // size can be expensive especially for complex types. long partitionsSizeInBytes = partitionFunction.getSizeInBytes(); // We also add partitionsInitialRetainedSize as an approximation of the object overhead of the partitions. systemMemoryContext.setBytes(partitionsSizeInBytes + partitionsInitialRetainedSize); }

Target:
- don't use `aria` in the code - partitionPageOptimized ?
Source:
private static void setupLogging() { Logging logging = Logging.initialize(); logging.setLevel("org.apache.parquet.hadoop", WARN); logging.setLevel("parquet.hadoop", WARN); logging.setLevel("org.glassfish.jersey.internal.inject.Providers", ERROR); logging.setLevel("com.facebook.presto.server.PluginManager", WARN); logging.setLevel("io.airlift.bootstrap.LifeCycleManager", WARN); logging.setLevel("com.facebook.presto.security.AccessControlManager", WARN); logging.setLevel("org.eclipse.jetty.server.handler.ContextHandler", WARN); logging.setLevel("org.eclipse.jetty.server.AbstractConnector", WARN); }

Target:
perhaps, arrange these lines in alphabetical order: ``` logging.setLevel("com.facebook.presto.security.AccessControlManager", WARN); logging.setLevel("com.facebook.presto.server.PluginManager", WARN); logging.setLevel("io.airlift.bootstrap.LifeCycleManager", WARN); logging.setLevel("org.apache.parquet.hadoop", WARN); logging.setLevel("org.eclipse.jetty.server.handler.ContextHandler", WARN); logging.setLevel("org.eclipse.jetty.server.AbstractConnector", WARN); logging.setLevel("org.glassfish.jersey.internal.inject.Providers", ERROR); logging.setLevel("parquet.hadoop", WARN); logging.setLevel("parquet.hadoop", WARN); ```
Source:
public void partitionPage(Page page) { populatePositionsForEachPartition(page); int channelCount = page.getChannelCount(); for (int i = 0; i < channelCount; i++) { decodedBlocks[i] = decodeBlock(flattener, page.getBlock(i)); } for (int i = 0; i < partitionData.length; i++) { partitionData[i].appendRows(decodedBlocks, fixedWidthRowSize, variableWidthChannels, outputBuffer); } }

Target:
channelCount -> decodedBlocks.length for consistency with the next loop
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(() -> directReader.close()); closer.register(() -> dictionaryReader.close()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
nit ```java closer.register(directReader::close); closer.register(dictionaryReader::close);
Source:
public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding) throws IOException { ColumnEncoding.ColumnEncodingKind kind = encoding.get(streamDescriptor.getStreamId()) .getColumnEncoding(streamDescriptor.getSequence()) .getColumnEncodingKind(); if (kind == DIRECT || kind == DIRECT_V2 || kind == DWRF_DIRECT) { currentReader = directReader; } else if (kind == DICTIONARY) { currentReader = dictionaryReader; } else { throw new IllegalArgumentException("Unsupported encoding " + kind); } currentReader.startStripe(dictionaryStreamSources, encoding); }

Target:
I think this would be better expressed as a switch statement
Source:
private MergeQuantileDigestFunction() { super(NAME, QDIGEST, StatisticalDigestStateFactory.createQuantileDigestFactory()); }

Target:
nits: static import
Source:
private MergeTDigestFunction() { super(NAME, TDIGEST, StatisticalDigestStateFactory.createTDigestFactory()); }

Target:
nits: static import
Source:
public void initTestAggregationFunction() { typeRegistry = new TypeRegistry(); functionManager = new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); session = testSessionBuilder().build(); }

Target:
Is this a necessary change?
Source:
protected TestHivePushdownFilterQueries() { super(() -> createQueryRunner()); }

Target:
nit: `super(TestHivePushdownFilterQueries::createQueryRunner);`
Source:
public static CallExpression call(FunctionManager functionManager, String name, Type returnType, List<RowExpression> arguments) { FunctionHandle functionHandle = functionManager.lookupFunction(name, fromTypes(arguments.stream().map(RowExpression::getType).collect(toImmutableList()))); return new CallExpression(name, functionHandle, returnType, arguments); }

Target:
- this should delegate to `call` two functions above. - also, here `name` would be a bit confusing from `displayName`. Maybe @rongrong could provide suggestion.
Source:
public static Optional<HashComputation> computeHash(Iterable<VariableReferenceExpression> fields, FunctionManager functionManager) { requireNonNull(fields, "fields is null"); List<VariableReferenceExpression> variables = ImmutableList.copyOf(fields); if (variables.isEmpty()) { return Optional.empty(); } return Optional.of(new HashComputation(fields, functionManager)); }

Target:
this could be private
Source:
private HashComputation(Iterable<VariableReferenceExpression> fields, FunctionManager functionManager) { requireNonNull(fields, "fields is null"); requireNonNull(functionManager, "functionManager is null"); this.fields = ImmutableList.copyOf(fields); this.functionManager = functionManager; checkArgument(!this.fields.isEmpty(), "fields can not be empty"); }

Target:
inline requireNonNull with this.
Source:
private Function<RowExpression, Optional<RowExpression>> translateGroupIdVariables(GroupIdNode node) { return variable -> { checkArgument(variable instanceof VariableReferenceExpression, "Expect VariableReferenceExpression"); if (node.getAggregationArguments().contains(variable)) { return Optional.of(variable); } if (node.getCommonGroupingColumns().contains(variable)) { return Optional.of((node.getGroupingColumns().get(variable))); } return Optional.empty(); }; }

Target:
@highker , @hellium01 , would you mind also taking a look at `AddExchange` ? -- it's basically a template parameter change.
Source:
public AbstractTupleDomainFilter(boolean nullAllowed) { this.nullAllowed = nullAllowed; }

Target:
I guess what we want here is an effectively sealed class, which Java doesn't have native support for. But we can mimic it by reducing the visibility of the constructor by making this and child constructors private, and exposing factory for creation.
Source:
private boolean verifyAggregationOrderBy(Optional<OrderingScheme> orderingScheme, Optional<OrderBy> expectedSortOrder) { if (orderingScheme.isPresent() && expectedSortOrder.isPresent()) { return verifyAggregationOrderBy(orderingScheme.get(), expectedSortOrder.get()); } return orderingScheme.isPresent() == expectedSortOrder.isPresent(); }

Target:
static?
Source:
private TableStatistics pruneStatistics(TableStatistics tableStatistics, Set<ColumnHandle> desiredColumns) { Map<ColumnHandle, ColumnStatistics> columnStatistics = tableStatistics.getColumnStatistics() .entrySet().stream() .filter(entry -> desiredColumns.contains(entry.getKey())) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); return new TableStatistics(tableStatistics.getRowCount(), columnStatistics); }

Target:
nit: put in on the previous line
Source:
FixedDoubleHistogram(FixedDoubleHistogram other) { this(other.bucketCount, other.min, other.max); for (int i = 0; i < bucketCount; ++i) { weights[i] = other.weights[i]; } }

Target:
I feel that we normally don't do this in Presto but explicitly create a new object with old parameters.
Source:
public void teardown() { closeQuietly(handle); mySqlServer.close(); }

Target:
`closeQuietly(mySqlServer, handle)`
Source:
private PrestoException invalidSubfieldPath() { return new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid subfield path: '%s'", path)); }

Target:
maybe have `index` encoded in the error message to denote where it goes wrong, which I assume `toString()` is for that purpose? So it will be ```java format("Invalid subfield path: '%s'", this) ```
Source:
private void assertInvalidPath(String path) { SubfieldTokenizer tokenizer = new SubfieldTokenizer(path); try { ImmutableList<PathElement> pathElements = Streams.stream(tokenizer).collect(toImmutableList()); fail("Expected failure"); } catch (PrestoException e) { // this is expected assertTrue(e.getMessage().startsWith("Invalid subfield path: ")); } }

Target:
nit: `Streams.stream(tokenizer).collect(toImmutableList());` is good enough. (Assignment to `pathElements` is not necessary)
Source:
private boolean isLambda(RowExpression rowExpression) { if (isExpression(rowExpression)) { return castToExpression(rowExpression) instanceof LambdaExpression; } return rowExpression instanceof LambdaDefinitionExpression; }

Target:
Can this be a static method? Another similar methods is `MultipleDistinctAggregationToMarkDistinct#toSymbol`. Should they be put in a Util class? @highker
Source:
public void testNot() { assertOptimizedEquals("not true", "false"); assertOptimizedEquals("not false", "true"); assertOptimizedEquals("not null", "null"); assertOptimizedEquals("not 1=1", "false"); assertOptimizedEquals("not 1=BIGINT '1'", "false"); assertOptimizedEquals("not 1!=1", "true"); assertOptimizedEquals("not unbound_long=1", "not unbound_long=1"); assertOptimizedEquals("not unbound_long=(1+1)", "not unbound_long=2"); assertOptimizedEquals("cast(json_parse(unbound_string) as map(varchar, varchar))", "cast(json_parse(unbound_string) as map(varchar, varchar))"); assertOptimizedEquals("cast(json_parse(unbound_string) as array(varchar))", "cast(json_parse(unbound_string) as array(varchar))"); assertOptimizedEquals("cast(json_parse(unbound_string) as row(bigint, varchar))", "cast(json_parse(unbound_string) as row(bigint, varchar))"); }

Target:
why these are in `testNot`? -- Also it doesn't seem to perform the optimization?
Source:
public static Slice createHll(@SqlType(StandardTypes.BIGINT) long value) { HyperLogLog hll = HyperLogLog.newInstance(ApproximateCountDistinctAggregation.standardErrorToBuckets(ApproximateSetAggregation.DEFAULT_STANDARD_ERROR)); hll.add(value); return hll.serialize(); }

Target:
I would add some static imports: `HyperLogLog hll = HyperLogLog.newInstance(standardErrorToBuckets(DEFAULT_STANDARD_ERROR));`
Source:
private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle( new ConnectorId("test"), new TestingTableHandle(), TestingTransactionHandle.create(), Optional.of(TestingHandle.INSTANCE)), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column"))); return createFragment(planNode); }

Target:
Same here, should we use `Optional.empty()`?
Source:
private PagesSerde createPagesSerdeInternal(Optional<SpillCipher> spillCipher) { Optional<Compressor> compressor; Optional<Decompressor> decompressor; if (compressionEnabled) { compressor = Optional.of(new Lz4Compressor()); decompressor = Optional.of(new Lz4Decompressor()); } else { compressor = Optional.empty(); decompressor = Optional.empty(); } return new PagesSerde(blockEncodingSerde, compressor, decompressor, spillCipher); }

Target:
The original code style in this method is better: ``` private PagesSerde createPagesSerdeInternal(Optional<SpillCipher> spillCipher) { if (compressionEnabled) { return new PagesSerde(blockEncodingSerde, Optional.of(new Lz4Compressor()), Optional.of(new Lz4Decompressor()), spillCipher); } return new PagesSerde(blockEncodingSerde, Optional.empty(), Optional.empty(), spillCipher); } ```
Source:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } else { return key; } }

Target:
drop unnecessary `else`. ``` private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; } ```
Source:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; }

Target:
Are you expecting destroy() to be called concurrently with this method? If so, the value of `key` visible to different threads may not be the same and the value of key.isDestroyed() may change after this check.
Source:
long adjustValue(int offsetIndex, long value) { if (inDictionaryStream != null) { return inDictionaryFlags[offsetIndex] ? dictionary[(int) value] : value; } return dictionary[(int) value]; }

Target:
private
Source:
protected void ensureValuesCapacity(int capacity, boolean includeNulls) { if (values == null) { values = new int[capacity]; } else if (values == null || values.length < capacity) { values = resize(values, capacity); if (valueIsNull != null) { valueIsNull = resize(valueIsNull, capacity); } } if (includeNulls && valueIsNull == null) { valueIsNull = new boolean[values.length]; } }

Target:
this check should be removed now
Source:
int adjustValue(long value, int offsetIndex) { if (inDictionaryStream != null && !inDictionaryFlags[offsetIndex]) { return toIntExact(value + stripeDictionarySize); } return toIntExact(value); }

Target:
adjustValue method needs to be marked as `private`
Source:
public void testLength() { double length = 4350866.6362; // Empty linestring returns null assertLength("LINESTRING EMPTY", null); // Linestring with one point has length 0 assertLength("LINESTRING (0 0)", 0.0); // Linestring with only one distinct point has length 0 assertLength("LINESTRING (0 0, 0 0, 0 0)", 0.0); // ST_Length is equivalent to sums of ST_DISTANCE between points in the LineString assertLength("LINESTRING (-71.05 42.36, -87.62 41.87, -122.41 37.77)", length); // Linestring has same length as its reverse assertLength("LINESTRING (-122.41 37.77, -87.62 41.87, -71.05 42.36)", length); // Path north pole -> south pole -> north pole should be roughly the circumference of the Earth assertLength("LINESTRING (0.0 90.0, 0.0 -90.0, 0.0 90.0)", 4.003e7); // Empty multi-linestring returns null assertLength("MULTILINESTRING (EMPTY)", null); // Multi-linestring with one path is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77))", length); // Multi-linestring with two disjoint paths has length equal to sum of lengths of lines assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87, -122.41 37.77), (-73.05 42.36, -89.62 41.87, -124.41 37.77))", 2 * length); // Multi-linestring with adjacent paths is equivalent to a single linestring assertLength("MULTILINESTRING ((-71.05 42.36, -87.62 41.87), (-87.62 41.87, -122.41 37.77))", length); }

Target:
nit: move this variable closer to its first usage
Source:
public FunctionHandle lookupFunction(QualifiedName name, List<TypeSignatureProvider> parameterTypes) { return staticFunctionNamespace.resolveFunction(name, parameterTypes); }

Target:
Call `lookupFunction` here.
Source:
public SimpleFilterProjectSemiJoinStatsRule(StatsNormalizer normalizer, FilterStatsCalculator filterStatsCalculator, FunctionManager functionManager) { super(normalizer); this.filterStatsCalculator = requireNonNull(filterStatsCalculator, "filterStatsCalculator can not be null"); this.logicalRowExpressions = new LogicalRowExpressions(requireNonNull(functionManager, "functionManager can not be null")); this.functionResolution = new StandardFunctionResolution(functionManager); }

Target:
Nit: Move requireNonNull in out of this statement.
Source:
public void notifyAllLifespansFinishedExecution() { checkState(groupedExecution); state = State.FINISHED; splitSource.close(); whenFinishedOrNewLifespanAdded.set(null); }

Target:
What does "finished" mean in `whenFinishedOrNewLifespanAdded`? It seems to mean scheduling finished for ungrouped execution and execution finished for grouped execution?
Source:
public List<Type> getTypeParameters() { List<Type> parameters = new ArrayList<>(argumentTypes.size() + 1); argumentTypes.stream() .forEach(parameters::add); parameters.add(returnType); return unmodifiableList(parameters); }

Target:
same line
Source:
ChecksumResult(long rowCount, Map<String, Object> checksums) { for (Object checksum : checksums.values()) { checkArgument( checksum == null || checksum instanceof Long || checksum instanceof Double || checksum instanceof SqlVarbinary, "checksum can only be one of (null, Long, Double, SqlVarbinary), found %s", checksum == null ? "null" : checksum.getClass().getName()); } this.rowCount = rowCount; this.checksums = unmodifiableMap(requireNonNull(checksums, "checksums is null")); }

Target:
`requireNonNull(checksums)` should go to the top because we would have already accessed it in `checksum.values()`
Source:
public void testCastOperatorsExistForCoercions() { Set<Type> types = getStandardPrimitiveTypes(); for (Type sourceType : types) { for (Type resultType : types) { if (typeRegistry.canCoerce(sourceType, resultType) && sourceType != UNKNOWN && resultType != UNKNOWN) { try { functionManager.lookupCast(CastType.CAST, sourceType.getTypeSignature(), resultType.getTypeSignature()); } catch (OperatorNotFoundException e) { fail(format("'%s' -> '%s' coercion exists but there is no cast operator", sourceType, resultType)); } } } } }

Target:
Probably static import?
Source:
static List<HiveSplit> drainSplits(HiveSplitSource source) throws Exception { ImmutableList.Builder<HiveSplit> splits = ImmutableList.builder(); while (!source.isFinished()) { source.getNextBatch(NOT_PARTITIONED, 100).get() .getSplits().stream() .map(HiveSplit.class::cast) .forEach(splits::add); } return splits.build(); }

Target:
Usually we just put tests in `TestBackgroundHiveSplitLoaderForBucketedTables.java` into this `TestBackgroundHiveSplitLoader.java` class. In this specific case, I understand the tests and other helper methods in `TestBackgroundHiveSplitLoaderForBucketedTables.java` are very specific and may not suit for general purposed `TestBackgroundHiveSplitLoader.java`. But a preferred approach might just be refactoring these methods into a helper class like `HvieSplitTestHelper` (this name is just made up)
Source:
public Plan getLogicalPlan(Session session, Statement statement, List<Expression> parameters, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { // analyze statement Analysis analysis = analyze(session, statement, parameters, warningCollector); // plan statement LogicalPlanner logicalPlanner = new LogicalPlanner(session, planOptimizers, idAllocator, metadata, sqlParser, statsCalculator, costCalculator, warningCollector); return logicalPlanner.plan(analysis); }

Target:
It might be better to put `idAllocator` as the last parameter since we have a default value from overloaded `getLogicalPlan`.
Source:
public LocalMemoryManager(NodeMemoryConfig config) { requireNonNull(config, "config is null"); configureMemoryPools(config, Runtime.getRuntime().maxMemory()); }

Target:
What do you think about using a telescoping constructor since one is a prefix of the other? ``` @Inject public LocalMemoryManager(NodeMemoryConfig config) { this(config, Runtime.getRuntime().maxMemory()); } ```
Source:
public static Boolean equal(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice right) { if (left == null) { return right == null; } if (right == null) { return false; } return deserialize(left).Equals(deserialize(right)); }

Target:
No need for the explicit null checks here. The parameters are not marked as `@SqlNullable`, so the engine will apply the default semantics when null is found
Source:
public void enqueue(Lifespan lifespan, int partitionNumber, List<SerializedPage> pages) { requireNonNull(lifespan, "lifespan is null"); checkState(partitionNumber == 0, "Expected partition number to be zero"); checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback has to be set before starting enqueue data"); enqueue(lifespan, pages); }

Target:
Ditto about checks. I don't think we need to duplicate them.
Source:
public void setNoMorePagesForLifespan(Lifespan lifespan) { noMorePagesForLifespan.add(requireNonNull(lifespan, "lifespan is null")); }

Target:
nit: move the null check to previous line (for readability)
Source:
static EquatableValueSet of(Type type, Object first, Object... rest) { LinkedHashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1); set.add(ValueEntry.create(type, first)); for (Object value : rest) { set.add(ValueEntry.create(type, value)); } return new EquatableValueSet(type, true, set); }

Target:
Keep the declaration as `HashSet`
Source:
private LocationHandle createLocationHandle(HdfsContext context, ConnectorSession session, Path targetPath, boolean isExistingTable) { if (shouldUseTemporaryDirectory(session, context, targetPath)) { Path writePath = createTemporaryPath(session, context, hdfsEnvironment, targetPath); return new LocationHandle(targetPath, writePath, isExistingTable, STAGE_AND_MOVE_TO_TARGET_DIRECTORY); } else { return new LocationHandle(targetPath, targetPath, isExistingTable, isExistingTable ? DIRECT_TO_TARGET_EXISTING_DIRECTORY : DIRECT_TO_TARGET_NEW_DIRECTORY); } }

Target:
I would do ```java else if (isExistingTable) { return new LocationHandle(targetPath, targetPath, true, DIRECT_TO_TARGET_EXISTING_DIRECTORY); } else { return new LocationHandle(targetPath, targetPath, false, DIRECT_TO_TARGET_NEW_DIRECTORY); } ``` so there are 3 branches, and easier to follow (at least for myself :) )
Source:
public static BlockBuilder quantileBoundsToArray(double lowerQuantile, double upperQuantile) { QuantileDigestFunctions.validateQuantileRange(lowerQuantile, upperQuantile); BlockBuilder blockBuilder = DOUBLE.createBlockBuilder(null, 2); DOUBLE.writeDouble(blockBuilder, lowerQuantile); DOUBLE.writeDouble(blockBuilder, upperQuantile); return blockBuilder; }

Target:
You can static import `validateQuantileRange`
Source:
public static Double digestToTruncatedMean(QuantileDigest digest, List<Long> bounds, QuantileDigest.MiddleFunction middleFunction) { if (bounds.get(0).equals(bounds.get(1))) { return null; } else { return digest.getHistogram(bounds, middleFunction).get(1).getMean(); } }

Target:
I would remove the else and just return.
Source:
public static void input(@AggregationState DigestAndPercentileArrayState state, @SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.DOUBLE) double lowerQuantile, @SqlType(StandardTypes.DOUBLE) double upperQuantile) { ApproximateDoublePercentileArrayAggregations.input(state, value, ApproximateLongTruncatedMeanAggregations.quantileBoundsToArray(lowerQuantile, upperQuantile)); }

Target:
I would static import `quantileBoundsToArray`.
Source:
public Block split(@TypeParameter("map<varchar,varchar>") Type mapType, @SqlType(StandardTypes.VARCHAR) Slice string, @SqlType(StandardTypes.VARCHAR) Slice entryDelimiter, @SqlType(StandardTypes.VARCHAR) Slice keyValueDelimiter) { return splitToMap(pageBuilder, mapType, string, entryDelimiter, keyValueDelimiter, null); }

Target:
Why don't you use `Optional` instead of null here?
Source:
public Block split( @TypeParameter("map<varchar,varchar>") Type mapType, @SqlType(StandardTypes.VARCHAR) Slice string, @SqlType(StandardTypes.VARCHAR) Slice entryDelimiter, @SqlType(StandardTypes.VARCHAR) Slice keyValueDelimiter, @SqlType("function(varchar, varchar, varchar, varchar)") DuplicateKeyResolutionLambda function) { return splitToMap(pageBuilder, mapType, string, entryDelimiter, keyValueDelimiter, function); }

Target:
ditto about adding `requireNonNull`.
Source:
public static void assertWarnings(QueryRunner queryRunner, Session session, @Language("SQL") String sql, List<WarningCode> expectedWarnings) { Set<WarningCode> warnings = queryRunner.execute(session, sql).getWarnings().stream() .map(PrestoWarning::getWarningCode) .collect(toImmutableSet()); for (WarningCode warningCode : expectedWarnings) { if (!warnings.contains(warningCode)) { fail("Expected warning: " + warningCode); } } }

Target:
nit: does this need to be public?
Source:
public WriteContext init(final Configuration configuration) { schema = MessageTypeParser.parseMessageType(configuration.get("parquet.hive.schema")); return new WriteContext(schema, new HashMap<>()); }

Target:
static import `parseMessageType`
Source:
private static void assertTimestampCorrect(String timestampString) { Timestamp timestamp = Timestamp.valueOf(timestampString); NanoTime nanoTime = NanoTimeUtils.getNanoTime(timestamp, false); ByteBuffer buffer = ByteBuffer.wrap(nanoTime.toBinary().getBytes()); long decodedTimestampMillis = getTimestampMillis(Binary.fromConstantByteBuffer(buffer)); assertEquals(decodedTimestampMillis, timestamp.getTime()); }

Target:
static import `fromConstantByteBuffer`.
Source:
ObjectMetadata getS3ObjectMetadata(Path path) throws IOException { String bucketName = getBucketName(uri); String key = keyFromPath(path); ObjectMetadata s3ObjectMetadata = getS3ObjectMetadata(path, bucketName, key); if (s3ObjectMetadata == null && !key.isEmpty()) { // check if key is not a "directory" verify(!key.endsWith(PATH_SEPARATOR), "Expected key to not end with %s", PATH_SEPARATOR); return getS3ObjectMetadata(path, bucketName, key + PATH_SEPARATOR); } return s3ObjectMetadata; }

Target:
We don't need this check, since `keyFromPath()` is guaranteed never to return a key with a trailing slash. `URI` guarantees that paths are normalized (no double slashes) and `keyFromPath()` strips off any trailing slash. Having this check here is confusing because the reader has to puzzle over how this would be possible.
Source:
public Object randomValue() { return (boolean) ThreadLocalRandom.current().nextBoolean(); }

Target:
nit: redundant casting
Source:
public Object[][] inputSequences() { return new Object[][] { {true}, {false}, {true, true, true}, {false, false, false}, {true, false, true, false}, }; }

Target:
add `{},`
Source:
public void testNoInput() { List<Object> booleanList = new ArrayList<>(); assertCount(ImmutableList.of(), 0, 0); }

Target:
unused variable
Source:
public Builder setBaseDataDir(Optional<Path> baseDataDir) { requireNonNull(baseDataDir, "baseDataDir is null"); this.baseDataDir = baseDataDir; return this; }

Target:
@yingsu00 This can be shorted to `this.baseDataDir = requireNonNull(baseDataDir, "baseDataDir is null");`
Source:
private RetryDriver retry() { return RetryDriver.retry() .exponentialBackoff( this.minBackoffDelay, this.maxBackoffDelay, this.maxRetryTime, this.scaleFactor) .maxAttempts(this.maxRetries + 1) .exceptionMapper(exceptionMapper) .stopOn(PrestoException.class); }

Target:
Please remove `this` from these field references as they aren't needed. We only use them when required, or sometimes for all assignments in the constructor (to be consistent with the assignments where it is required).
Source:
public void tearDown() { try (Closer closer = Closer.create()) { // Closer is documented to mimic try-with-resource, which implies close will happen in reverse order. // first close the cients, then clear the map closer.register(clients::clear); for (Entry<String, TransportClient> entry : clients.entrySet()) { closer.register(entry.getValue()); } closer.register(() -> executor.shutdown()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
closer.register(executor::shutdown);
Source:
private ConnectorTableMetadata getTableMetadata(SchemaTableName tableName) { ElasticsearchTableDescription table = client.getTable(tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return null; } return new ConnectorTableMetadata(tableName, client.getColumnMetadata(table)); }

Target:
Update this method to return `Optional<ConnectorTableMetadata>`
Source:
private SearchResponse getSearchResponse(ElasticsearchQueryBuilder queryBuilder) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime, 2.0) .run("searchRequest", () -> { return queryBuilder.buildScrollSearchRequest() .execute() .actionGet(requestTimeout.toMillis()); }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
nit: you can use an expression lambda here and on L214 (remove curly braces).
Source:
private List<ColumnMetadata> loadColumns(ElasticsearchTableDescription table) { if (table.getColumns().isPresent()) { return buildMetadata(table.getColumns().get()); } List<ElasticsearchColumn> columns = buildColumns(table); return buildMetadata(columns); }

Target:
inline columns
Source:
public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector) { requireNonNull(plan, "plan is null"); requireNonNull(session, "session is null"); requireNonNull(symbolAllocator, "symbolAllocator is null"); requireNonNull(types, "types is null"); return SimplePlanRewriter.rewriteWith(new Rewriter(), plan); }

Target:
nit: Only `plan` parameter is used. I don't think you need to check anything but `plan` with the `requireNonNull`.
Source:
public static PlanMatchPattern semiJoin(String sourceSymbolAlias, String filteringSymbolAlias, String outputAlias, PlanMatchPattern source, PlanMatchPattern filtering) { return node(SemiJoinNode.class, source, filtering).with(new SemiJoinMatcher(sourceSymbolAlias, filteringSymbolAlias, outputAlias, Optional.empty())); }

Target:
reuse overloaded `semiJoin` method here passing distribution type as `Optional.empty()`
Source:
public String toString() { return toStringHelper(this) .add("filteringSymbolAlias", filteringSymbolAlias) .add("sourceSymbolAlias", sourceSymbolAlias) .add("outputAlias", outputAlias) .add("distributionType", distributionType.orElse(null)) .toString(); }

Target:
Just `distributionType`. It is somehow confusing to put `null` here. It would imply that the `distributionType` field is set to `null`, but not to `Optional.empty()`.
Source:
public Result apply(SemiJoinNode semiJoinNode, Captures captures, Context context) { JoinDistributionType joinDistributionType = getJoinDistributionType(context.getSession()); switch (joinDistributionType) { case AUTOMATIC: return Result.ofPlanNode(getCostBasedDistributionType(semiJoinNode, context)); case PARTITIONED: return Result.ofPlanNode(semiJoinNode.withDistributionType(PARTITIONED)); case BROADCAST: return Result.ofPlanNode(semiJoinNode.withDistributionType(REPLICATED)); default: throw new UnsupportedOperationException("Unknown join_distribution_type: " + joinDistributionType); } }

Target:
`UnsupportedOperationException` should be used when the entire operation (method) is not supported. You can use here either `IllegalArgumentException` or `VerifyException`
Source:
private static int megabytes(int size) { return toIntExact(new DataSize(size, DataSize.Unit.MEGABYTE).toBytes()); }

Target:
static import?
Source:
public ToIntFunction<ConnectorSplit> getSplitBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { return value -> ((HiveSplit) value).getBucketNumber() .orElseThrow(() -> new IllegalStateException("Bucket number not set in split")); }

Target:
nit: "in a split"
Source:
public void add(Block block, int position) { requireNonNull(block, "block must not be null"); checkArgument(position >= 0, "position must be >= 0"); if (block.isNull(position)) { if (!containsNullElement) { containsNullElement = true; } } // null is added to both elementBlock and the blockPositionByHash hash table only once. // Adding it to elementBlock makes getBlock() being able to be called multiple times. // Adding it to hash table avoids changes in rehash() int hashPosition = getHashPositionOfElement(block, position); if (blockPositionByHash.get(hashPosition) == EMPTY_SLOT) { addNewElement(hashPosition, block, position); } }

Target:
This if-statement looks redundant -- we can just set `containsNullElement` to be true.
Source:
private void addNewElement(int hashPosition, Block block, int position) { elementType.appendTo(block, position, elementBlock); if (elementBlock.getSizeInBytes() - initialElementBlockSizeInBytes > FOUR_MEGABYTES) { throw new PrestoException( EXCEEDED_FUNCTION_MEMORY_LIMIT, format("The input to %s is too large. More than %s of memory is needed to hold the intermediate hash set.\n", functionName, MAX_FUNCTION_MEMORY)); } blockPositionByHash.set(hashPosition, elementBlock.getPositionCount() - 1); // increase capacity, if necessary if (++size >= maxFill) { rehash(); } }

Target:
"++x >= y" does't seem to be used in Presto code base. I would just put `size++` right after line 156.
Source:
public PlanNodeCostEstimate visitSpatialJoin(SpatialJoinNode node, Void context) { return calculateJoinCost( node, node.getLeft(), node.getRight(), Objects.equals(node.getDistributionType(), SpatialJoinNode.DistributionType.REPLICATED)); }

Target:
`node.getDistributionType() == SpatialJoinNode.DistributionType.REPLICATED`
Source:
private static boolean isSerdeSupported(Properties schema) { String serdeName = getDeserializerClassName(schema); if (!SUPPORTED_SERDES.contains(serdeName)) { return false; } return true; }

Target:
`return SUPPORTED_SERDES.contains(serdeName);`
Source:
private static String buildColumns(List<HiveColumnHandle> columns) { if (columns == null || columns.isEmpty()) { return EMPTY_STRING; } return columns.stream().map(HiveColumnHandle::getName).collect(Collectors.joining(",")); }

Target:
``` return columns.stream() .map(HiveColumnHandle::getName) .collect(Collectors.joining(",")); ```
Source:
S3SelectRecordCursor( Configuration configuration, Path path, RecordReader recordReader, long totalBytes, Properties splitSchema, List<HiveColumnHandle> columns, DateTimeZone hiveStorageTimeZone, TypeManager typeManager) { super(configuration, path, recordReader, totalBytes, updateSplitSchema(splitSchema, columns), columns, hiveStorageTimeZone, typeManager); }

Target:
Make this public, since the constructor is logically part of the public API for the class. Access is controlled at the class level. If we wanted to later make the class public, we wouldn't need to change the access of the constructor.
Source:
public void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket) { checkArgument(!isNullOrEmpty(host), "Expected non empty host"); checkArgument(!isNullOrEmpty(databaseName), "Expected non empty databaseName"); checkArgument(!isNullOrEmpty(awsAccessKey), "Expected non empty awsAccessKey"); checkArgument(!isNullOrEmpty(awsSecretKey), "Expected non empty awsSecretKey"); checkArgument(!isNullOrEmpty(writableBucket), "Expected non empty writableBucket"); super.setup(host, port, databaseName, awsAccessKey, awsSecretKey, writableBucket, true); }

Target:
Remove all these `checkArgument` since they are performed in the parent classes. It is expected that whoever is using an argument will validate it as appropriate. If it's just being passed through, we generally leave it alone (rather than duplicating all the validations).
Source:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { try { return getCompressionCodec((TextInputFormat) inputFormat, path) .map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec)) .orElse(true); } catch (IllegalAccessException e) { LOG.error(e, "Failed to find compressionCodec for inputFormat: %s", inputFormat.getClass().getName()); return false; } } return false; }

Target:
We should never get `IllegalAccessException` as that's a bug (we forgot to call `setAccessible`) or something is wrong with the JVM. Let's catch it in `getCompressionCodec()` and rethrow as `RuntimeException` or `PrestoException(GENERIC_INTERNAL_ERROR, ...)`
Source:
public ElasticsearchTableHandle( @JsonProperty("schemaName") String schemaName, @JsonProperty("tableName") String tableName) { this.schemaTableName = new SchemaTableName(requireNonNull(schemaName.toLowerCase(ENGLISH), "schemaName is null"), requireNonNull(tableName.toLowerCase(ENGLISH), "tableName is null")); }

Target:
This is hard to read, please move out the non-null checks.
Source:
protected String toSqlType(Type type) { if (VARBINARY.equals(type)) { return "bytea"; } else if (JSON.equals(type)) { return "jsonb"; } return super.toSqlType(type); }

Target:
`else` is rendudant
Source:
public Signature getCoercion(Type fromType, Type toType) { try { return globalFunctionNamespace.getCoercion(fromType, toType); } catch (PrestoException e) { if (!(e instanceof OperatorNotFoundException)) { throw e; } } throw new OperatorNotFoundException(OperatorType.CAST, ImmutableList.of(fromType.getTypeSignature()), toType.getTypeSignature()); }

Target:
I believe this can be simplified to ```java catch (OperatorNotFoundException e) { throw new OperatorNotFoundException(...); }
Source:
private static boolean isOperator(Signature signature) { for (OperatorType operator : OperatorType.values()) { if (signature.getName().equals(FunctionUtils.mangleOperatorName(operator))) { return true; } } return false; }

Target:
static import
Source:
private FunctionRegistry createFunctionRegistry(TypeRegistry typeManager) { BlockEncodingManager blockEncodingManager = new BlockEncodingManager(typeManager); FeaturesConfig featuresConfig = new FeaturesConfig(); FunctionManager functionManager = new FunctionManager(typeManager, blockEncodingManager, featuresConfig); return new FunctionRegistry(typeManager, blockEncodingManager, new FeaturesConfig(), functionManager); }

Target:
We create multiple `FeaturesConfig`s in this method (another one is created on L299).
Source:
private ExecutionFailureInfo rewriteTransportFailure(ExecutionFailureInfo executionFailureInfo) { if (executionFailureInfo.getRemoteHost() != null && failureDetector.getState(executionFailureInfo.getRemoteHost()) == GONE) { return new ExecutionFailureInfo( executionFailureInfo.getType(), executionFailureInfo.getMessage(), executionFailureInfo.getCause(), executionFailureInfo.getSuppressed(), executionFailureInfo.getStack(), executionFailureInfo.getErrorLocation(), REMOTE_HOST_GONE.toErrorCode(), executionFailureInfo.getRemoteHost()); } else { return executionFailureInfo; } }

Target:
unnecessary else
Source:
public static int computeTruncatedLength(Slice slice, int offset, int length, int maxCodePointCount, boolean isCharType) { int truncatedLength = length; if (isCharType) { // truncate the characters and then remove the trailing white spaces truncatedLength = byteCountWithoutTrailingSpace(slice, offset, length, maxCodePointCount); } else if (maxCodePointCount >= 0 && length > maxCodePointCount) { truncatedLength = byteCount(slice, offset, length, maxCodePointCount); } return truncatedLength; }

Target:
You can just return directly from here... which would make the else redundant (and return directly from the next block).
Source:
public static void main(String[] args) throws Throwable { // assure the benchmarks are valid before running BenchmarkData data = new BenchmarkData(); data.setup(); new BenchmarkDictionaryBlockGetSizeInBytes().getSizeInBytes(data); Options options = new OptionsBuilder() .verbosity(VerboseMode.NORMAL) .warmupMode(WarmupMode.INDI) .include(".*" + BenchmarkDictionaryBlockGetSizeInBytes.class.getSimpleName() + ".*") .build(); new Runner(options).run(); }

Target:
`WarmupMode.INDI` is already the default warmup mode, so no need to specify it.
Source:
public int hashCode() { return Objects.hash(storageFormat, location, bucketProperty, skewed, serdeParameters); }

Target:
can you have the fields in the same order here as in toString and equals? ie `skewed` is first there
Source:
public PolymorphicScalarFunctionBuilder choice(Function<ChoiceBuilder, ChoiceBuilder> choiceSpecification) { ChoiceBuilder choiceBuilder = new ChoiceBuilder(clazz, signature); choiceSpecification.apply(choiceBuilder); PolymorphicScalarFunctionChoice choice = choiceBuilder.build(); choices.add(choice); return this; }

Target:
`choices.add(choiceBuilder.build());`
Source:
public PolymorphicScalarFunctionChoice build() { if (argumentProperties.isEmpty()) { argumentProperties = Collections.nCopies(signature.getArgumentTypes().size(), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)); } return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups); }

Target:
static import `nCopies`
Source:
public PolymorphicScalarFunctionChoice build() { if (argumentProperties == null || argumentProperties.isEmpty()) { argumentProperties = nCopies(signature.getArgumentTypes().size(), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)); } return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups.build()); }

Target:
I recommend removing ` || argumentProperties.isEmpty()`. I believe that makes more sense from a semantic perspective. Logically, `argumentProperties` should not be populated if it is set (even if empty). Even though it wouldn't hurt here because repopulating it will still yield an empty list, it's confusing and arguably incorrect.
Source:
private void assertMultiPoint(String expectedWkt, String... pointWkts) { assertFunction(format("ST_MultiPoint(array[%s])", ImmutableList.copyOf(pointWkts).stream() .map(wkt -> wkt.equalsIgnoreCase("null") ? "null" : format("ST_GeometryFromText('%s')", wkt)) .collect(Collectors.joining(","))), GEOMETRY, expectedWkt); }

Target:
The formatting is off. It's really hard to read and figure out what lines up with what.