auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Class<? extends ArrayAggregationState> getGroupedStateClass() { if (mode == NEW) { return GroupArrayAggregationState.class; } if (mode == LEGACY) { return LegacyArrayAggregationGroupState.class; } throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, format("Unexpected group enum type %s", mode)); }

Target:
Use `switch` instead of `if`s
Source:
public DecimalStatistics(BigDecimal minimum, BigDecimal maximum, long decimalSizeInBytes) { checkArgument(minimum == null || maximum == null || minimum.compareTo(maximum) <= 0, "minimum is not less than maximum"); this.minimum = minimum; this.maximum = maximum; int retainedSizeInBytes = 0; if (minimum != null) { retainedSizeInBytes += BIG_DECIMAL_INSTANCE_SIZE + decimalSizeInBytes; } if (maximum != null) { retainedSizeInBytes += BIG_DECIMAL_INSTANCE_SIZE + decimalSizeInBytes; } this.retainedSizeInBytes = retainedSizeInBytes + INSTANCE_SIZE; }

Target:
at some point we should switch this to our decimal library which can represent these as two longs
Source:
public static double stXMax(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { Envelope envelope = deserializeEnvelope(input); if (envelope == null) { return 0.0; } return envelope.getXMax(); }

Target:
- please squash the commits - fix commit message. `Optimize Min Max geospatial functions` is too generic, instead please describe what you changed which resulted with better performance of min max geospatial functions.
Source:
public double simpleGeometry(BenchmarkData data) { return GeoFunctions.stXMin(data.simpleGeometry); }

Target:
static import `stXMin`.
Source:
public void setup() throws IOException { complexGeometry = GeoFunctions.stGeometryFromText(Slices.utf8Slice(loadPolygon("large_polygon.txt"))); simpleGeometry = GeoFunctions.stGeometryFromText(Slices.utf8Slice("POLYGON ((1 1, 4 1, 1 4))")); }

Target:
static import `stGeometryFromText` and `utf8Slice`.
Source:
public void acknowledgeTaskResults(TaskId taskId, OutputBufferId bufferId, long sequenceId) { requireNonNull(taskId, "taskId is null"); requireNonNull(bufferId, "bufferId is null"); Preconditions.checkArgument(sequenceId >= 0, "sequenceId is negative"); tasks.getUnchecked(taskId).acknowledgeTaskResults(bufferId, sequenceId); }

Target:
static import
Source:
public List<Expression> rewrite(List<Expression> items, Context<C> context) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (Expression expression : items) { builder.add(rewrite(expression, context.get())); } return builder.build(); }

Target:
This should probably be `private`.
Source:
public void start() { DateTime now = DateTime.now(); executionStartTime.compareAndSet(null, now); startNanos.compareAndSet(0, System.nanoTime()); startFullGcCount.compareAndSet(0, gcMonitor.getMajorGcCount()); startFullGcTimeNanos.compareAndSet(0, gcMonitor.getMajorGcTime().roundTo(NANOSECONDS)); // always update last execution start time lastExecutionStartTime.set(now); }

Target:
0 is not a reasonable initial value for these two fields. Use -1 instead. I would imagine that these two values will stay at 0 for a long time after VM start.
Source:
public void testValues() { assertQuery("VALUES 1, 2, 3, 4"); assertQuery("VALUES 1, 3, 2, 4 ORDER BY 1", "SELECT * FROM (VALUES 1, 3, 2, 4) ORDER BY 1"); assertQuery("VALUES (1.1, 2, 'foo'), (sin(3.3), 2+2, 'bar')"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) ORDER BY 1", "VALUES (sin(3.3), 2+2), (1.1, 2)"); assertQuery("VALUES (1.1, 2), (sin(3.3), 2+2) LIMIT 1", "VALUES (1.1, 2)"); assertQuery("SELECT * FROM (VALUES (1.1, 2), (sin(3.3), 2+2))"); assertQuery( "SELECT * FROM (VALUES (1.1, 2), (sin(3.3), 2+2)) x (a, b) LEFT JOIN (VALUES (1.1, 2), (1.1, 2+2)) y (a, b) USING (a)", "VALUES (1.1, 2, 4), (1.1, 2, 2), (sin(3.3), 4, NULL)"); assertQuery("SELECT 1.1 in (VALUES (1.1), (2.2))", "VALUES (TRUE)"); assertQuery("" + "WITH a AS (VALUES (1.1, 2), (sin(3.3), 2+2)) " + "SELECT * FROM a", "VALUES (1.1, 2), (sin(3.3), 2+2)"); // implicity coersions assertQuery("VALUES 1, 2.2, 3, 4.4"); assertQuery("VALUES (1, 2), (3.3, 4.4)"); assertQuery("VALUES true, 1.0 in (1, 2, 3)"); }

Target:
If these queries are covered by `TestJoinUsing`, then maybe we could remove them from here?
Source:
public void cleanup() throws IOException { getMetastoreClient(TEST_DB_NAME).dropDatabase(TEST_DB_NAME); deleteRecursively(tempDir.toPath(), ALLOW_INSECURE); }

Target:
Nice fix!
Source:
private void assertColumnList(List<com.amazonaws.services.glue.model.Column> actual, List<Column> expected) { if (expected == null) { assertNull(actual); } assertEquals(actual.size(), expected.size()); for (int i = 0; i < expected.size(); i++) { assertColumn(actual.get(i), expected.get(i)); } }

Target:
I think all these `assert` methods can be static
Source:
private void assertColumnList(List<Column> actual, List<com.amazonaws.services.glue.model.Column> expected) { if (expected == null) { assertNull(actual); } assertEquals(actual.size(), expected.size()); for (int i = 0; i < expected.size(); i++) { assertColumn(actual.get(i), expected.get(i)); } }

Target:
Same here, see if these can be static
Source:
public void testNoFrom() { assertQuery("SELECT 1 + 2, 3 + 4", "SELECT 1 + 2, 3 + 4"); }

Target:
`expected` and `actual` SQLs are now same, use simpler `assertQuery` overload
Source:
protected TestQueryPlanDeterminism() { super(TestQueryPlanDeterminism::createLocalQueryRunner, FeatureSelection.all().without(ENGINE_ONLY).build()); }

Target:
really? not the other way around (e.g: include engine/planner only) features?
Source:
public TestDistributedQueriesNoHashGeneration() { super(() -> createQueryRunner(ImmutableMap.of(), ImmutableMap.of("optimizer.optimize-hash-generation", "false")), FeatureSelection.all().without(ENGINE_ONLY).build()); }

Target:
maybe we could make shortcut for: `FeatureSelection.all().without(ENGINE_ONLY).build()`?
Source:
protected AbstractTestIntegrationSmokeTest(QueryRunnerSupplier supplier) { super(supplier, FeatureSelection.all()); }

Target:
nit: `AbstractTestIntegrationSmokeTest` doesn't make use of feature selection (if it did, a constructor accepting feature selection would be needed). Therefore the superclass (`AbstractTestQueryFramework`) should still provide a constructor that doesn't require passing feature selection.
Source:
public StreamProperties visitSort(SortNode node, List<StreamProperties> inputProperties) { StreamProperties sourceProperties = Iterables.getOnlyElement(inputProperties); if (sourceProperties.isSingleStream()) { // stream is only sorted if sort operator is executed without parallelism return StreamProperties.ordered(); } else { return sourceProperties; } }

Target:
maybe it should be in a `checkState` as currently it would mean that there is a bug somewhere, no point of having parallel sort without a merge
Source:
private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix) { if (prefix.getTableName() == null) { return listTables(session, prefix.getSchemaName()); } return ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); }

Target:
What if `schemaName` is `null` here?
Source:
public boolean needsInput() { return !finishing && lookupSourceProviderFuture.isDone() && spillInProgress.isDone() && probe == null && outputPage == null && !isLookupSourceEmpty(); }

Target:
Check this right after `lookupSourceProviderFuture.isDone()`... or better yet, don't check it here at all, check in `tryFetchLookupSourceProvider`
Source:
public boolean isFinished() { boolean finished = (this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null) || isLookupSourceEmpty(); // if finished drop references so memory is freed early if (finished) { close(); } return finished; }

Target:
Instead of inspecting repeatedly whether lookup source is empty, you could leverage the fact that this information doesn't change, ever. So, instead of this change (and instead of introducing the `isLookupSourceEmpty` method), you can inspect `lookupSource` only once, in `tryFetchLookupSourceProvider`, and set `finishing` flag when the LS is empty.
Source:
public void testStatsCalculatorUsesLayout() { assertPlan("SELECT orderstatus FROM orders WHERE orderstatus = 'P'", anyTree( node(TableScanNode.class) .withStats(PlanNodeStatsEstimate.builder() .setOutputRowCount(new Estimate(363.0)) .setOutputSizeInBytes(unknownValue()) .build()))); assertPlan("SELECT orderstatus FROM orders WHERE orderkey = 42", anyTree( node(TableScanNode.class) .withStats(PlanNodeStatsEstimate.builder() .setOutputRowCount(new Estimate(15000.0)) .setOutputSizeInBytes(unknownValue()) .build()))); }

Target:
it looks unrelated
Source:
public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaSystemMemoryInBytes = currentSystemMemory - previousSystemMemory; previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaSystemMemoryInBytes); }

Target:
The existing code was unnecessarily roundabout. It can be simplified. Here, we have the absolute number, and we turn it into delta. In `QueryStateMachine.updateMemoryUsage`, it takes the delta, and converts it back to absolute value.
Source:
public List<String> setUGI(String userName, List<String> groupNames) { groupNames.add(userName); return groupNames; }

Target:
why do you modify input `paratemeter`. Maybe instead of this please return a copied list.
Source:
protected BaseRuleTest() { this(TpchConnectorFactory.DEFAULT_PREDICATE_PUSHDOWN_ENABLED); }

Target:
from testing point of view, using explicit `false` (or whatever this is) would be better. i.e., if tpch connector decides to change its default, should presto tests change their behavior and coverage?
Source:
private void checkNotHoldsLock(Object lock) { checkState(!Thread.holdsLock(lock), "Cannot execute this method while holding a lock"); }

Target:
make it `static`
Source:
public long getEstimatedSizeInBytes() { long hashMemorySizeInBytes = groupByHash == null ? 0 : groupByHash.getEstimatedSize(); return INSTANCE_SIZE + memorySizeInBytes + hashMemorySizeInBytes + groupedRows.sizeOf() + pageReferences.sizeOf() + emptyPageReferenceSlots.getEstimatedSizeInBytes(); }

Target:
groupByHash is never null
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); Block sourceBlock = page.getBlock(setChannel); Page sourcePage = hashChannel.isPresent() ? new Page(sourceBlock, page.getBlock(hashChannel.get())) : new Page(sourceBlock); unfinishedWork = channelSetBuilder.addPage(sourcePage); processUnfinishedWork(); channelSetBuilder.updateMemoryReservation(); }

Target:
How many times per page `OperatorContext#setMemoryReservation` is being called now?
Source:
public Work<?> addPage(Page page) { // Just add the page to the pending work, which will be processed later. Work<?> work = hash.addPage(page); return work; }

Target:
inline: ```java return hash.addPage(page);
Source:
public boolean needsInput() { // Since SetBuilderOperator doesn't produce any output, the getOutput() // method may never be called. We need to handle any unfinished work // before addInput() can be called again. if (unfinishedWork.isPresent() && !processUnfinishedWork()) { return false; } return !finished; }

Target:
inline: ```java return !finished && (!unfinishedWork.isPresent() || processUnfinishedWork());
Source:
public int partitions() { lock.readLock().lock(); try { return partitions.length; } finally { lock.readLock().unlock(); } }

Target:
`partitions.length` is final, because `partitions` is final, so this doesn't need the lock. Are you adding this to get a code analysis tool happy?
Source:
protected static ReadMapping dateReadMapping() { return longReadMapping(DATE, (resultSet, columnIndex) -> { // JDBC returns a date using a timestamp at midnight in the JVM timezone long localMillis = resultSet.getDate(columnIndex).getTime(); // Convert it to a midnight in UTC long utcMillis = ISOChronology.getInstance().getZone().getMillisKeepLocal(UTC, localMillis); // convert to days return MILLISECONDS.toDays(utcMillis); }); }

Target:
These should also be public, as connectors which extend the base one won't be in the same package.
Source:
public static long fromUnixTime(@SqlType(StandardTypes.DOUBLE) double unixTime, @SqlType(StandardTypes.BIGINT) long hoursOffset, @SqlType(StandardTypes.BIGINT) long minutesOffset) { int offset = toIntExact(hoursOffset * 60 + minutesOffset); TimeZoneKey timeZoneKey; try { timeZoneKey = getTimeZoneKeyForOffset(offset); } catch (IllegalArgumentException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid offset: %d", offset), e); } return packDateTimeWithZone(Math.round(unixTime * 1000), timeZoneKey); }

Target:
You can do without `format` here: `"Invalid offset: " + offset`
Source:
private Iterator<Page> readPages() { checkState(writable, "Repeated reads are disallowed to prevent potential resource leaks"); writable = false; try { InputStream input = targetFile.newInputStream(); Closeable resources = closer.register(input); Iterator<Page> pages = PagesSerdeUtil.readPages(serde, new InputStreamSliceInput(input, BUFFER_SIZE)); return PrestoIterators.closeWhenExhausted(pages, resources); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Failed to read spilled pages", e); } }

Target:
`resources` is now just `input`. Remove the variable: ``` InputStream input = closer.register(targetFile.newInputStream()); ```
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.close(); revocableLocalMemoryContext.close(); systemLocalMemoryContext.close(); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }

Target:
Why not `closer.register(...::close)`, as above?
Source:
public synchronized ListenableFuture<?> updateUserMemory(long delta) { if (delta >= 0) { if (queryMemoryContext.getUserMemory() + delta > maxMemory) { throw exceededLocalLimit(succinctBytes(maxMemory)); } return memoryPool.reserve(queryId, delta); } memoryPool.free(queryId, -delta); return NOT_BLOCKED; }

Target:
`private`
Source:
public TaskContext addTaskContext(TaskStateMachine taskStateMachine, Session session, boolean verboseStats, boolean cpuTimerEnabled) { MemoryTrackingContext taskMemoryContext; synchronized (this) { taskMemoryContext = queryMemoryContext.newMemoryTrackingContext(); } TaskContext taskContext = TaskContext.createTaskContext( this, taskStateMachine, notificationExecutor, yieldExecutor, session, taskMemoryContext, verboseStats, cpuTimerEnabled); taskContexts.put(taskStateMachine.getTaskId(), taskContext); return taskContext; }

Target:
`queryMemoryContext` is `final` and `@ThreadSafe`. What is this synchronization for?
Source:
public boolean trySetBytes(long bytes) { boolean result = delegate.trySetBytes(bytes); if (peakMemory.isPresent()) { peakMemory.get().accumulateAndGet(delegate.getBytes(), Math::max); } return result; }

Target:
You can spare this call when `!result`
Source:
public synchronized long getReservedRevocableBytes() { return operatorMemoryContext.getRevocableMemory(); }

Target:
remove `synchronized`
Source:
static long addExact(long usedBytes, long bytes) { try { return Math.addExact(usedBytes, bytes); } catch (ArithmeticException e) { throw new RuntimeException(String.format("Overflow detected. usedBytes: %d, bytes: %d", usedBytes, bytes), e); } }

Target:
static import `format`
Source:
public OutputBufferMemoryManager(long maxBufferedBytes, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor) { requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"); checkArgument(maxBufferedBytes > 0, "maxBufferedBytes must be > 0"); this.maxBufferedBytes = maxBufferedBytes; this.systemMemoryContextSupplier = Suppliers.memoize(() -> systemMemoryContextSupplier.get()); this.notificationExecutor = requireNonNull(notificationExecutor, "notificationExecutor is null"); notFull = SettableFuture.create(); notFull.set(null); }

Target:
nit: `Suppliers.memoize(systemMemoryContextSupplier::get)`
Source:
public void failQuery(QueryId queryId, Throwable cause) { requireNonNull(queryId, "queryId is null"); requireNonNull(cause, "cause is null"); log.warn(cause, "Fail query %s", queryId); QueryExecution query = queries.get(queryId); if (query != null) { query.fail(cause); } }

Target:
Query %s failed. Also, I'm pretty sure we already log failures somewhere? Or if we don't, that there's a good reason for that.
Source:
private static DataSize.Unit valueOfUnit(String unitString) { for (DataSize.Unit unit : DataSize.Unit.values()) { if (unit.getUnitString().equals(unitString)) { return unit; } } throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unit string must be one of [B, kB, MB, GB, TB, PB]"); }

Target:
static import `DataSize.Unit`
Source:
public static Slice succinctDuration(@SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.VARCHAR) Slice unit) { try { Duration duration = Duration.succinctDuration(value, valueOfTimeUnit(unit.toStringUtf8())); return utf8Slice(duration.toString()); } catch (IllegalArgumentException e) { // When value is negative, NaN, etc. throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } }

Target:
It's good practice to only wrap the relevant code that can throw with try/catch: ``` Duration duration; try { duration = Duration.succinctDuration(value, valueOfTimeUnit(unit.toStringUtf8())); } catch (IllegalArgumentException e) { // When value is negative, NaN, etc. throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } return utf8Slice(duration.toString()); ```
Source:
public static Slice hmacMd5( @SqlType(StandardTypes.VARBINARY) Slice slice, @SqlType(StandardTypes.VARBINARY) Slice key) { return Slices.wrappedBuffer(Hashing.hmacMd5(key.getBytes()).hashBytes(slice.getBytes()).asBytes()); }

Target:
static import `wrappedBuffer`
Source:
private void bindLowMemoryKiller(String name, Class<? extends LowMemoryKiller> clazz) { install(installModuleIf( MemoryManagerConfig.class, config -> name.equals(config.getLowMemoryKillerPolicy()), moduleBinder -> moduleBinder.bind(LowMemoryKiller.class).to(clazz).in(Scopes.SINGLETON))); }

Target:
Nit: could name this variable `binder`
Source:
public void initialize() { if (initialized.compareAndSet(false, true)) { taskStateMachine.addStateChangeListener(new StateChangeListener<TaskState>() { @Override public void stateChanged(TaskState newState) { if (newState.isDone()) { executionEndTime.set(DateTime.now()); endNanos.set(System.nanoTime()); } } }); } }

Target:
can this be turned into lambda?
Source:
public void initialize() { if (initialized.compareAndSet(false, true)) { taskStateMachine.addStateChangeListener(newState -> { if (newState.isDone()) { executionEndTime.set(DateTime.now()); endNanos.set(System.nanoTime()); } }); } }

Target:
There is a better way to do this. You make the constructor and the initialize method private, and then add a factory method that call the constructor and the initialize. This makes the state tracking simple.
Source:
void fail(Throwable e) { // The error must be recorded before setting the finish marker to make sure // isFinished will observe failure instead of successful completion. // Only record the first error message. if (setIf(stateReference, State.failed(e), state -> state.getKind() == INITIAL)) { // Stop the split loader before finishing the queue. // Once the queue is finished, it will always return a completed future to avoid blocking any caller. // This could lead to a short period of busy loop in splitLoader (although unlikely in general setup). splitLoader.stop(); queues.finish(); } checkState(stateReference.get().getKind() == FAILED, "Another thread raced to complete this split source before failure info is recorded"); }

Target:
what about timeout, close, or limit
Source:
public Ordering(String field, SortItem.Ordering sortOrder, SortItem.NullOrdering nullOrder) { this.field = field; this.sortOrder = sortOrder; this.nullOrder = nullOrder; }

Target:
private? Since there is a factory method below
Source:
public String toString() { return toStringHelper(this) .omitNullValues() .add("filter", filter) .toString(); }

Target:
there are no null values to omit
Source:
public synchronized ListenableFuture<Supplier<PagesSpatialIndex>> createPagesSpatialIndex() { activeProbeOperators.retain(); if (pagesSpatialIndex != null) { return immediateFuture(pagesSpatialIndex); } SettableFuture<Supplier<PagesSpatialIndex>> future = SettableFuture.create(); pagesSpatialIndexFutures.add(future); return future; }

Target:
as i noted in the operator, this could return `ListenableFuture<PagesSpatialIndex>`
Source:
public long getSizeInBytes() { // channels is a List created with ImmutableList#copyOf. // Each element of the List is an ObjectArrayList<Block>. // Hence, the memory used by channels is estimated as // <header-size-of-ImmutableList> + // <instance-size-of-ObjectArrayList> * <length-of-outer-list> + // <sum-of-all-Blocks> return INSTANCE_SIZE + IMMUTABLE_LIST_HEADER_SIZE + OBJECT_ARRAY_LIST_INSTANCE_SIZE * channels.size() + channels.stream() .flatMap(List::stream) .mapToLong(Block::getRetainedSizeInBytes) .sum(); }

Target:
You can format this as below to categorize different types of overhead. ``` return INSTANCE_SIZE + IMMUTABLE_LIST_HEADER_SIZE + OBJECT_ARRAY_LIST_INSTANCE_SIZE * channels.size() + channels.stream() .flatMap(List::stream) .mapToLong(Block::getRetainedSizeInBytes) .sum(); ```
Source:
public PagesSpatialIndex get() { if (rtree.isEmpty()) { return EMPTY_INDEX; } else { return new PagesRTreeIndex(session, addresses, types, outputChannels, channels, rtree, spatialRelationshipTest, filterFunctionFactory); } }

Target:
`else` not needed.
Source:
private long computeMemorySizeInBytes(AbstractNode root) { if (root.getLevel() == 0) { return ABSTRACT_NODE_INSTANCE_SIZE + ENVELOPE_INSTANCE_SIZE + root.getChildBoundables().stream().mapToLong(child -> computeMemorySizeInBytes((ItemBoundable) child)).sum(); } else { return ABSTRACT_NODE_INSTANCE_SIZE + ENVELOPE_INSTANCE_SIZE + root.getChildBoundables().stream().mapToLong(child -> computeMemorySizeInBytes((AbstractNode) child)).sum(); } }

Target:
`else` not needed.
Source:
public int getDay(Type type, Block block, int position) { if (type.equals(DATE)) { return toIntExact(DATE.getLong(block, position)); } if (type.equals(TIMESTAMP)) { long millis = block.getLong(position, 0); long local = timeZone.convertUTCToLocal(millis); long days = MILLISECONDS.toDays(local); return toIntExact(days); } throw new IllegalArgumentException("Wrong type for temporal column: " + type); }

Target:
This is wrong. You should never read from blocks directly. Always use `Type` to access the block, as types own the data representation within a block.
Source:
public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table) { ElasticsearchTableHandle handle = checkType(table, ElasticsearchTableHandle.class, "table"); checkArgument(handle.getConnectorId().equals(connectorId), "tableHandle is not for this connector"); SchemaTableName tableName = new SchemaTableName(handle.getSchemaName(), handle.getTableName()); return getTableMetadata(session, tableName); }

Target:
fix `checkArgument ` error message.
Source:
private void checkFieldType(int field, Set<Type> expectedTypes) { Type actual = getType(field); checkArgument(expectedTypes.contains(actual), "Field %s expected type inconsistent with %s", field, actual); StringBuilder builder = new StringBuilder(); for (Type type : expectedTypes) { builder.append(", "); builder.append(type.getDisplayName()); } }

Target:
`result` -> `results`
Source:
public long getLong(int field) { checkFieldType(field, ImmutableSet.of(BIGINT, INTEGER)); return Long.valueOf(String.valueOf(getFieldValue(field))); }

Target:
why not `(Long) getFieldValue(field);` as you do in other methods?
Source:
public synchronized void setTableDescriptionSupplier(Supplier<Map<SchemaTableName, ElasticsearchTableDescription>> tableDescriptionSupplier) { this.tableDescriptionSupplier = Optional.of(requireNonNull(tableDescriptionSupplier, "tableDescriptionSupplier is null")); }

Target:
pass this in constructor
Source:
ElasticsearchTableDescriptionSupplier(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { this.codec = requireNonNull(codec, "codec is null"); this.config = requireNonNull(config, "config is null"); }

Target:
nit: move `config` up as it's the first constructor parameter
Source:
private static List<File> listFiles(File dir) { if ((dir != null) && dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { return ImmutableList.copyOf(files); } } return ImmutableList.of(); }

Target:
unnecessary parens around `dir != null`
Source:
public static <T> DataType<T> dataType(String insertType, Type prestoResultType) { return new DataType<>(insertType, prestoResultType, Object::toString, Function.identity()); }

Target:
Since this method is good only under certain assumptions (that is: that `toString()` produces good SQL literal), it should be `private`
Source:
public TestingConnectorSession(List<PropertyMetadata<?>> properties) { this("user", Optional.of("test"), UTC_KEY, ENGLISH, System.currentTimeMillis(), properties, ImmutableMap.of(), true); }

Target:
Shouldn't the default here (`true`) should be taken from F.C.: `new FeatureConfig().isLegacyTimestamp()`?
Source:
public void close() { checkState(initialized.get(), "Driver is not initialized"); // mark the service for destruction if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) { return; } exclusiveLock.interruptCurrentOwner(); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown tryWithLock(() -> TRUE); }

Target:
Close is called in cleanup-after-exceptional-condition situations, so it should just do the job. If it is to complain about anything, this should be the last thing it does.
Source:
public boolean set(@Nullable V value) { return super.set(value); }

Target:
I think this can be private or at least package protected.
Source:
public static Boolean varcharIsJsonScalar(@SqlType("varchar(x)") Slice json) { return isJsonScalar(jsonParse(json)); }

Target:
Don't need to call `jsonParse` here.
Source:
public Object geometryToBingTiles(BenchmarkData data) throws Throwable { return BingTileFunctions.geometryToBingTiles(data.geometry, data.zoomLevel); }

Target:
`throws` can be removed (also for the other benchmark method).
Source:
public void close() { if (client == null) { return; } try { client.close(); } catch (Exception e) { log.warn("Error closing client", e); } }

Target:
Can you change the order of parameters? In airlift it's (e, message).
Source:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { requireNonNull(hostLocationHandle, "hostLocationHandle is null"); requireNonNull(prestoThriftService, "prestoThriftService is null"); this.hostLocationHandle = hostLocationHandle; this.prestoThriftService = prestoThriftService; }

Target:
inline with assignments
Source:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { this.hostLocationHandle = requireNonNull(hostLocationHandle, "hostLocationHandle is null"); this.prestoThriftService = requireNonNull(prestoThriftService, "prestoThriftService is null"); }

Target:
nit: I'd initialize in the order of parameters - first service, then location.
Source:
void shutdown() { try { retryExecutor.shutdownNow(); } catch (Exception ignore) { } }

Target:
if(retryExecutor!=null)
Source:
public int getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += SizeOf.sizeOfObjectArray(addresses.size()); for (HostAddress address : addresses) { result += HOST_ADDRESS_INSTANCE_SIZE + address.getHostText().length() * Character.BYTES; } return result; }

Target:
Add parens
Source:
public void serializeWithType(PlanNode value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { if (rootLevel) { rootLevel = false; JsonSerializer<Object> subTypeSerializer = provider.findTypedValueSerializer(value.getClass(), true, null); subTypeSerializer.serializeWithType(value, gen, serializers, typeSer); rootLevel = true; return; } superTypeSerializer.serializeWithType(value, gen, serializers, typeSer); }

Target:
maybe a finally
Source:
public int hashCode() { return Objects.hash(name); }

Target:
Since you have only one argument you can do `Objects.hashCode(name)` which is more efficient.
Source:
public static Optional<Principal> createPrincipal(Optional<String> principal) { return principal.map(name -> new InternalPrincipal(name)); }

Target:
Put this static method after instance methods.
Source:
public PipelineStatus getPipelineStatus() { return new PipelineStatus(ImmutableList.copyOf(this.drivers)); }

Target:
Make the `PipelineStatus` constructor as dumb as possible. Put logic here instead.
Source:
public static ColumnIO getArrayElementColumn(ColumnIO columnIO) { while ((columnIO instanceof GroupColumnIO) && !columnIO.getType().isRepetition(REPEATED)) { columnIO = ((GroupColumnIO) columnIO).getChild(0); } if (columnIO instanceof GroupColumnIO && columnIO.getType().getOriginalType() == null && ((GroupColumnIO) columnIO).getChildrenCount() == 1) { return ((GroupColumnIO) columnIO).getChild(0); } return columnIO; }

Target:
parentheses around instanceof check is not necessary.
Source:
public void testClientTagsBasedSelection() throws InterruptedException { InternalResourceGroupManager manager = queryRunner.getCoordinator().getResourceGroupManager().get(); DbResourceGroupConfigurationManager dbConfigurationManager = (DbResourceGroupConfigurationManager) manager.getConfigurationManager(); dbConfigurationManager.load(); assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), "global.bi-user"); assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), "global.user-user.adhoc-user"); }

Target:
I don't think `load()` call is needed here. I remember adding `load()` to make reloading of the config deterministic when we update config in the tests.
Source:
public boolean isNull(int field) { return Objects.isNull(value); }

Target:
`return value == null;` I don't see value of `Objects.isNull` over `== null`. And there's only 1 place in Presto code that this is used.
Source:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { ThriftIndexHandle thriftIndexHandle = (ThriftIndexHandle) indexHandle; return new ThriftConnectorIndex(clientProvider, thriftIndexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }

Target:
inline this
Source:
public static Slice toQuadKey(@SqlType(BingTileType.NAME) long input) { return Slices.utf8Slice(BingTile.decode(input).toQuadKey()); }

Target:
static import `utf8Slice`
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.setBytes(0); revocableLocalMemoryContext.setBytes(0); systemLocalMemoryContext.setBytes(0); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }

Target:
Explain why local memory doesn't go in closer, whereas aggregate memory does. In addition, I vaguely remember that you intended to add `close` method to local memory context due to address race issues.
Source:
public SliceInput getDelegate() { if (delegate == null) { delegate = requireNonNull(loader.get(), "loader returned a null stream"); verify(delegate.length() == globalLength, "loader returned stream of length %s, but length %s was expected", delegate.length(), globalLength); delegate.setPosition(initialPosition); } return delegate; }

Target:
This looks like it should be private
Source:
public boolean process() { checkState(!finished); finished = prerequisite.process(); if (!finished) { return false; } finished = true; result = transform.apply(prerequisite.getResult()); return true; }

Target:
This line is no-op
Source:
public List<Type> getTypes() { return (List<Type>) localExchangeFactory.getTypes(); }

Target:
Change the getter so you don't need the cast
Source:
private HashUtil() { throw new UnsupportedOperationException(); }

Target:
No need for this exception. This class cannot be instantiated anyway.
Source:
public GroupedHistogramState( Type keyType, int expectedEntriesCount) { valuesBlockBuilder = keyType.createBlockBuilder(null, computeBucketCount(expectedEntriesCount, GroupedTypedHistogram.MAX_FILL_RATIO)); typedHistogram = new GroupedTypedHistogram(keyType, expectedEntriesCount, valuesBlockBuilder); }

Target:
No need to break across multiple lines
Source:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = getGeometry(OGCGeometry.createFromEsriGeometry(new Point(x, y), null), "ST_Point", POINT); return serialize(geometry); }

Target:
getGeometry call here is redundant, because OGCGeometry.createFromEsriGeometry(new Point(x, y), null) can't return anything other than point. Perhaps, remove it.
Source:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = OGCGeometry.createFromEsriGeometry(new Point(x, y), null); return serialize(geometry); }

Target:
static import `createFromEsriGeometry`
Source:
public void addValue(long value) { nonNullValueCount++; minimum = Math.min(value, minimum); maximum = Math.max(value, maximum); try { sum = addExact(sum, value); } catch (ArithmeticException e) { overflow = true; } }

Target:
I would only execute this try if `overflow` is not already set. Given the way this code is currently written, I'm concerned about repeated throws in a tight loop.
Source:
protected TestMemorySmoke() { super(MemoryQueryRunner::createQueryRunner); }

Target:
This should technically be public since it's a public class for TestNG to execute. (it apparently bypasses privilege checks using reflection
Source:
public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { return views.entrySet().stream() .filter(entry -> prefix.matches(entry.getKey())) .collect(ImmutableMap.toImmutableMap( Map.Entry::getKey, entry -> new ConnectorViewDefinition(entry.getKey(), Optional.empty(), entry.getValue()))); }

Target:
Static import
Source:
static Expression rewrite(Expression expression, Rule.Context context) { return LambdaCaptureDesugaringRewriter.rewrite(expression, context.getSymbolAllocator().getTypes(), context.getSymbolAllocator()); }

Target:
why not private?
Source:
public static Expression rewrite(Expression expression, Map<Symbol, Type> symbolTypes, SymbolAllocator symbolAllocator) { checkState(!(expression instanceof GroupingOperation), "GroupingOperation should have been re-written to a FunctionCall before execution"); if (expression instanceof SymbolReference) { return expression; } return ExpressionTreeRewriter.rewriteWith(new Visitor(symbolTypes, symbolAllocator), expression, new Context()); }

Target:
is this needed? not much will be executed for such expression
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"); checkArgument(!(expression instanceof GroupingOperation), "GroupingOperation should have been re-written to a FunctionCall before execution"); if (expression instanceof SymbolReference) { return expression; } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList()); // parameters already replaced return rewrite(expression, expressionTypes); }

Target:
Why grouping causes issues? I thought that it is irrelevant.
Source:
public InputStream handleException(Request request, Exception exception) throws RuntimeException { throw new RuntimeException("Request to worker failed", exception); }

Target:
These `throws` shouldn't be necessary for an unchecked exception
Source:
public void queryStopped() { runningQueries.decrementAndGet(); queuedQueries.decrementAndGet(); }

Target:
Aren't you decrementing the `queuedQueries` twice? First the query will get queued (`queryQueued` will get called), then the query will start running (`queryStarted ` gets called and decrements), then query will finish (`queryStopped ` will get called and decrements), right?
Source:
private static final Type entryType(Type keyType, Type valueType) { return new ArrayType(new RowType(ImmutableList.of(keyType, valueType), Optional.empty())); }

Target:
I don't think we use `final` for functions in our code base
Source:
private boolean tryBuildPage() { if (pageBuilder.isEmpty()) { return false; } if (finished || pageBuilder.isFull()) { buildPage(); return true; } return false; }

Target:
Not sure why you consult `finished` here? BTW this seems to be always `false` when this method is called. However, if you consulted `finishing` it wouldn't be good either (you would probably produce single-row pages for whole last page of the input).
Source:
public void close() throws IOException { try { writeRowGroup(); output.close(); } finally { Closer closer = Closer.create(); closer.register(keySectionOutput::destroy); for (ColumnEncoder columnEncoder : columnEncoders) { closer.register(columnEncoder::destroy); } closer.close(); } }

Target:
Consider `try (Closer closer = ...)` if you already use `Closer`. Also, this `Closer` instance could also handle the `try` section, eliminating `try-finally`. (Mind the order in which closer closes though).
Source:
public int hashCode() { return Objects.hash(filter, leftBlocksSize, sortChannel); }

Target:
You could reorder hashing so that if follow order in equals. This helps verifying they agree. Best if they followed order of fields, but let's not change this _now_, to be on the safe side.
Source:
private static PagesHashStrategy pagesHashStrategy() { return new SimplePagesHashStrategy( ImmutableList.of(BIGINT), ImmutableList.of(), ImmutableList.of(ImmutableList.of(TEST_PAGE.getBlock(0))), ImmutableList.of(), Optional.empty(), Optional.of(new SortExpressionExtractor.RowSortExpressionContext(0))); }

Target:
should the `SortExpressionExtractor` be renamed as well?
Source:
public String toString() { String predicate = Joiner.on("AND") .join(filterExpectedMappings.entrySet().stream() .map(entry -> entry.getKey() + " = " + entry.getValue()) .collect(toImmutableList())); return toStringHelper(this) .add("predicate", filterExpectedMappings) .toString(); }

Target:
`predicate` is not used.
Source:
void trivialMatchers() { //any assertMatch(any(), 42); assertMatch(any(), "John Doe"); //class based assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); }

Target:
[DONE] public?
Source:
public Optional<PlanNode> apply(PlanNode node, Context context) { FilterNode filterNode = (FilterNode) node; Expression rewritten = rewriter.rewrite(filterNode.getPredicate(), context); if (filterNode.getPredicate().equals(rewritten)) { return Optional.empty(); } else { return Optional.of(new FilterNode(node.getId(), filterNode.getSource(), rewritten)); } }

Target:
not needed `else` block. Here in other rewrites as well.
Source:
public void testFilterExpressionRewrite() { tester().assertThat(zeroRewriter).on(p -> p.filter(new LongLiteral("1"), p.values())) .matches( filter("0", PlanMatchPattern.values())); }

Target:
use static imports for `PlanMatchPattern` things
Source:
protected ExpressionRewriteRuleSet(ExpressionRewriteRule rewrite) { this.rewriter = rewrite; }

Target:
make it public
Source:
private static byte[] reverse(final byte[] a) { final int length = a.length; int i = length / 2; while(i-- != 0) { final byte t = a[length - i - 1]; a[length - i - 1] = a[i]; a[i] = t; } return a; }

Target:
This looks to me like maybe you accidentally included an unrelated change?
Source:
public AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes, Optional<Symbol> mask) { checkArgument(expression instanceof FunctionCall); FunctionCall aggregation = (FunctionCall) expression; Signature signature = metadata.getFunctionRegistry().resolveFunction(aggregation.getName(), TypeSignatureProvider.fromTypes(inputTypes)); return addAggregation(output, new Aggregation(aggregation, signature, mask)); }

Target:
Maybe this method could get rid of `Optional`? As in case of `Optional.empty()` the method you just added can called.
Source:
public SimplifyExpressions(Metadata metadata, SqlParser sqlParser) { super((expression, context) -> rewrite(expression, context, metadata, sqlParser)); }

Target:
I thought there were more rewrites.
Source:
public FailureInfo getLastFailureInfo() { Exception lastFailureException = getLastFailureException(); if (lastFailureException == null) { return null; } else { return Failures.toFailure(lastFailureException).toFailureInfo(); } }

Target:
unnecessary else as previous if returns.
Source:
public ListeningScheduledExecutorService createRetryDriverScheduledExecutor(ThriftConnectorConfig config) { return MoreExecutors.listeningDecorator(newScheduledThreadPool(config.getRetryDriverThreads(), threadsNamed("thrift-retry-driver-%s"))); }

Target:
use static import
Source:
private boolean connectorSupportsTest(TypeElement connector, Class<?> test) { Set<ConnectorFeature> supportedFeatures = supportedFeatures(connector); Set<ConnectorFeature> requiredFeatures = requiredFeatures(test); return supportedFeatures.containsAll(requiredFeatures); }

Target:
This can be `static`
Source:
private <T extends PlanNode> void findAllRecursive(PlanNode node, ImmutableList.Builder<T> nodes) { node = lookup.resolve(node); if (where.test(node)) { nodes.add((T) node); } if (skipOnly.test(node) || where.test(node)) { for (PlanNode source : node.getSources()) { findAllRecursive(source, nodes); } } }

Target:
`skipOnly` is named terribly wrong. However as long as it means "continue search only when", you should _not_ modify this `if`.
Source:
public long getRegionSizeInBytes(int positionOffset, int length) { int positionCount = getPositionCount(); if (positionOffset < 0 || length < 0 || positionOffset + length > positionCount) { throw new IndexOutOfBoundsException("Invalid position " + positionOffset + " in block with " + positionCount + " positions"); } return (long) length * (fixedSize + Byte.BYTES); }

Target:
It is not obvious whether this is correct: `(long) x * y`. I would rewrite it to either `y * (long) x` or `x * (long) y`.
Source:
private String convertDaysToMidnightTimestamp(String columnName) { // A date is stored as an integer of days from 1970-01-01. Multiplying it by milliseconds per day renders the UTC midnight timestamp, which is stored as a bigint. return format("(CAST (%s AS BIGINT) * %s)", columnName, TimeUnit.DAYS.toMillis(1)); }

Target:
use static import for `days`
Source:
private static Iterable<Expression> pullNullableConjunctsThroughOuterJoin(List<Expression> conjuncts, Collection<Symbol> outputSymbols, Predicate<Symbol>... nullSymbolScopes) { // Conjuncts without any symbol dependencies cannot be applied to the effective predicate (e.g. FALSE literal) return conjuncts.stream() .map(expression -> pullExpressionThroughSymbols(expression, outputSymbols)) .map(expression -> SymbolsExtractor.extractAll(expression).anyMatch(alwaysTrue()) ? TRUE_LITERAL : expression) .map(expressionOrNullSymbols(nullSymbolScopes)) .collect(toImmutableList()); }

Target:
This is wrong. `isEmpty()` can be migrated to `count() == 1`
Source:
public TestTpchDistributedStats() throws Exception { runner = createQueryRunnerWithoutCatalogs(emptyMap(), emptyMap(), 4); runner.createCatalog("tpch", "tpch", ImmutableMap.of( "tpch.column-naming", ColumnNaming.STANDARD.name() )); }

Target:
Can you just add another overloaded method that does not take a worker count (similar to what you did already)?
Source:
public Node visitWindowSpecification(SqlBaseParser.WindowSpecificationContext context) { return new WindowSpecification( getLocation(context), Optional.ofNullable(context.identifier()).map(i -> (Identifier) visit(i)), visit(context.partition, Expression.class), visit(context.sortItem(), SortItem.class), visitIfPresent(context.windowFrame(), WindowFrame.class)); }

Target:
ditto, `s/i/identifier/`
Source:
public boolean advanceNextPosition() { if (this.closed) { return false; } try { boolean result = this.resultSet.next(); if (!result) { this.close(); } return result; } catch (SQLException | RuntimeException e) { throw this.handleSqlException(e); } }

Target:
The body of this method looks very much like `com.facebook.presto.plugin.jdbc.JdbcRecordCursor#advanceNextPosition`. Perhaps there is a possibility to retain reuse? Same applies to other methods too. Even if you need to copy something (i hope you don't), clearly separate copying and enhancements into two separate commits, otherwise I don't know what to review.
Source:
public void setUp() { tester = new RuleTester(); }

Target:
Make these methods final so they can't accidentally be overridden
Source:
private boolean isKnownCost(PlanNode node) { return !Objects.equals(UNKNOWN_COST, costs.getOrDefault(node.getId(), UNKNOWN_COST)); }

Target:
Since this is comparing with a constant object, no need to use `Objects.equals` ```java return !UNKNOWN_COST.equals(costs.getOrDefault(node.getId(), UNKNOWN_COST));
Source:
public ResourceGroupStateInfo getQueryStateInfos(@PathParam("resourceGroupId") String resourceGroupIdString) { if (!isNullOrEmpty(resourceGroupIdString)) { try { return resourceGroupManager.getResourceGroupStateInfo(new ResourceGroupId( newArrayList(resourceGroupIdString.split("/")).stream() .map(ResourceGroupStateInfoResource::urlDecode).collect(toImmutableList()))); } catch (NoSuchElementException e) { throw new WebApplicationException(NOT_FOUND); } } throw new WebApplicationException(NOT_FOUND); }

Target:
Arrays.stream() might be easier, and the collect call should be on a newline. Maybe something like: ```java try { return resourceGroupManager.getResourceGroupStateInfo( new ResourceGroupId( Arrays.stream(resourceGroupIdString.split("/")) .map(ResourceGroupStateInfoResource::urlDecode) .collect(toImmutableList()))); } ```
Source:
static void waitForQueryCount(DistributedQueryRunner queryRunner, Set<QueryState> countingStates, int expectedCount) throws InterruptedException { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); while (queryManager.getAllQueryInfo().stream().filter(q -> countingStates.contains(q.getState())).count() != expectedCount) { MILLISECONDS.sleep(500); } }

Target:
Split into multiple lines
Source:
private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getDomains().get().entrySet().stream() .filter(entrySet -> isPathColumnHandle(entrySet.getKey())) .findFirst() .map(entrySet -> entrySet.getValue()); }

Target:
It's an `entry`, not `entrySet`. In addition, you can write `Map.Entry::getValue` here.
Source:
public void tryEvaluateWithAll(String expression, Type expectedType) { executeProjectionWithAll(expression, expectedType, session, compiler); }

Target:
Have this call the other `tryEvaluateWithAll` method
Source:
public boolean needsInput() { boolean stateNeedsInput = state == State.CONSUMING_INPUT || (state == State.SPILLING_INPUT && spillInProgress.isDone()); return stateNeedsInput && !lookupSourceFactoryDestroyed.isDone(); }

Target:
add parentheses