proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
crate_crate
|
crate/server/src/main/java/io/crate/execution/TransportExecutorModule.java
|
TransportExecutorModule
|
configure
|
class TransportExecutorModule extends AbstractModule {
@Override
protected void configure() {<FILL_FUNCTION_BODY>}
}
|
bind(JobSetup.class).asEagerSingleton();
bind(LuceneQueryBuilder.class).asEagerSingleton();
bind(TransportCreateTableAction.class).asEagerSingleton();
bind(TransportRenameTableAction.class).asEagerSingleton();
bind(TransportSwapAndDropIndexNameAction.class).asEagerSingleton();
bind(TransportOpenCloseTableOrPartitionAction.class).asEagerSingleton();
bind(TransportCloseTable.class).asEagerSingleton();
bind(TransportDropTableAction.class).asEagerSingleton();
bind(TransportCreateUserDefinedFunctionAction.class).asEagerSingleton();
bind(TransportDropUserDefinedFunctionAction.class).asEagerSingleton();
bind(TransportCreateViewAction.class).asEagerSingleton();
bind(TransportDropViewAction.class).asEagerSingleton();
bind(TransportSwapRelationsAction.class).asEagerSingleton();
bind(TransportAlterTableAction.class).asEagerSingleton();
bind(TransportDropConstraintAction.class).asEagerSingleton();
bind(TransportAddColumnAction.class).asEagerSingleton();
bind(TransportDropColumnAction.class).asEagerSingleton();
bind(TransportAnalyzeAction.class).asEagerSingleton();
bind(TransportCreatePublicationAction.class).asEagerSingleton();
bind(TransportDropPublicationAction.class).asEagerSingleton();
bind(TransportAlterPublicationAction.class).asEagerSingleton();
bind(TransportCreateSubscriptionAction.class).asEagerSingleton();
| 35
| 398
| 433
|
<methods>public non-sealed void <init>() ,public final synchronized void configure(org.elasticsearch.common.inject.Binder) <variables>org.elasticsearch.common.inject.Binder binder
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/AbstractDDLTransportAction.java
|
AbstractDDLTransportAction
|
masterOperation
|
class AbstractDDLTransportAction<Request extends AcknowledgedRequest<Request>, Response extends AcknowledgedResponse> extends TransportMasterNodeAction<Request, Response> {
private final Writeable.Reader<Response> reader;
private final Function<Boolean, Response> ackedResponseFunction;
private final String source;
public AbstractDDLTransportAction(String actionName,
TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
Writeable.Reader<Request> requestReader,
Writeable.Reader<Response> responseReader,
Function<Boolean, Response> ackedResponseFunction,
String source) {
super(actionName, transportService, clusterService, threadPool, requestReader);
this.reader = responseReader;
this.ackedResponseFunction = ackedResponseFunction;
this.source = source;
}
@Override
protected String executor() {
// no need to use a thread pool, we go async right away
return ThreadPool.Names.SAME;
}
@Override
protected Response read(StreamInput in) throws IOException {
return reader.read(in);
}
@Override
protected void masterOperation(Request request,
ClusterState state,
ActionListener<Response> listener) throws Exception {<FILL_FUNCTION_BODY>}
public abstract ClusterStateTaskExecutor<Request> clusterStateTaskExecutor(Request request);
}
|
clusterService.submitStateUpdateTask(source,
request,
ClusterStateTaskConfig.build(Priority.HIGH, request.masterNodeTimeout()),
clusterStateTaskExecutor(request),
new AckedClusterStateTaskListener() {
@Override
public void onFailure(String source, Exception e) {
listener.onFailure(e);
}
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Exception e) {
listener.onResponse(ackedResponseFunction.apply(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(ackedResponseFunction.apply(false));
}
@Override
public TimeValue ackTimeout() {
return request.ackTimeout();
}
});
| 348
| 221
| 569
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/TransportSwapRelationsAction.java
|
TransportSwapRelationsAction
|
checkBlock
|
class TransportSwapRelationsAction extends TransportMasterNodeAction<SwapRelationsRequest, AcknowledgedResponse> {
private final SwapRelationsOperation swapRelationsOperation;
private final ActiveShardsObserver activeShardsObserver;
@Inject
public TransportSwapRelationsAction(Settings settings,
TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
DDLClusterStateService ddlClusterStateService,
AllocationService allocationService) {
super(
"internal:crate:sql/alter/cluster/indices",
transportService,
clusterService,
threadPool,
SwapRelationsRequest::new
);
this.activeShardsObserver = new ActiveShardsObserver(clusterService);
this.swapRelationsOperation = new SwapRelationsOperation(
allocationService, ddlClusterStateService);
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected AcknowledgedResponse read(StreamInput in) throws IOException {
return new AcknowledgedResponse(in);
}
@Override
protected void masterOperation(SwapRelationsRequest request,
ClusterState state,
ActionListener<AcknowledgedResponse> listener) throws Exception {
AtomicReference<String[]> indexNamesAfterRelationSwap = new AtomicReference<>(null);
ActionListener<AcknowledgedResponse> waitForShardsListener = ActionListeners.waitForShards(
listener,
activeShardsObserver,
request.ackTimeout(),
() -> logger.info("Switched name of relations, but the operation timed out waiting for enough shards to be started"),
indexNamesAfterRelationSwap::get
);
AckedClusterStateUpdateTask<AcknowledgedResponse> updateTask =
new AckedClusterStateUpdateTask<AcknowledgedResponse>(Priority.HIGH, request, waitForShardsListener) {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
if (logger.isInfoEnabled()) {
Iterable<String> swapActions = request.swapActions().stream()
.map(x -> x.source().fqn() + " <-> " + x.target().fqn())
::iterator;
logger.info("Swapping tables [{}]", String.join(", ", swapActions));
}
SwapRelationsOperation.UpdatedState newState = swapRelationsOperation.execute(currentState, request);
indexNamesAfterRelationSwap.set(newState.newIndices.toArray(new String[0]));
return newState.newState;
}
@Override
protected AcknowledgedResponse newResponse(boolean acknowledged) {
return new AcknowledgedResponse(acknowledged);
}
};
clusterService.submitStateUpdateTask("swap-relations", updateTask);
}
@Override
protected ClusterBlockException checkBlock(SwapRelationsRequest request, ClusterState state) {<FILL_FUNCTION_BODY>}
}
|
Set<String> affectedIndices = new HashSet<>();
Metadata metadata = state.metadata();
for (RelationNameSwap swapAction : request.swapActions()) {
affectedIndices.addAll(Arrays.asList(IndexNameExpressionResolver.concreteIndexNames(
metadata, IndicesOptions.LENIENT_EXPAND_OPEN, swapAction.source().indexNameOrAlias())));
affectedIndices.addAll(Arrays.asList(IndexNameExpressionResolver.concreteIndexNames(
metadata, IndicesOptions.LENIENT_EXPAND_OPEN, swapAction.target().indexNameOrAlias())));
}
for (RelationName dropRelation : request.dropRelations()) {
affectedIndices.addAll(Arrays.asList(IndexNameExpressionResolver.concreteIndexNames(
metadata, IndicesOptions.LENIENT_EXPAND_OPEN, dropRelation.indexNameOrAlias())));
}
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, affectedIndices.toArray(new String[0]));
| 761
| 274
| 1,035
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/tables/AddColumnRequest.java
|
AddColumnRequest
|
writeTo
|
class AddColumnRequest extends AcknowledgedRequest<AddColumnRequest> {
private final RelationName relationName;
private final List<Reference> colsToAdd;
private final IntArrayList pKeyIndices;
private final Map<String, String> checkConstraints;
/**
* @param checkConstraints must be accumulated map of all columns' constraints in case of adding multiple columns.
*/
public AddColumnRequest(@NotNull RelationName relationName,
@NotNull List<Reference> colsToAdd,
@NotNull Map<String, String> checkConstraints,
@NotNull IntArrayList pKeyIndices) {
this.relationName = relationName;
this.colsToAdd = colsToAdd;
this.checkConstraints = checkConstraints;
this.pKeyIndices = pKeyIndices;
assert colsToAdd.isEmpty() == false : "Columns to add must not be empty";
}
public AddColumnRequest(StreamInput in) throws IOException {
super(in);
this.relationName = new RelationName(in);
this.checkConstraints = in.readMap(
LinkedHashMap::new, StreamInput::readString, StreamInput::readString);
this.colsToAdd = in.readList(Reference::fromStream);
int numPKIndices = in.readVInt();
this.pKeyIndices = new IntArrayList(numPKIndices);
for (int i = 0; i < numPKIndices; i++) {
pKeyIndices.add(in.readVInt());
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
@NotNull
public RelationName relationName() {
return this.relationName;
}
@NotNull
public Map<String, String> checkConstraints() {
return this.checkConstraints;
}
@NotNull
public List<Reference> references() {
return this.colsToAdd;
}
@NotNull
public IntArrayList pKeyIndices() {
return this.pKeyIndices;
}
}
|
super.writeTo(out);
relationName.writeTo(out);
out.writeMap(checkConstraints, StreamOutput::writeString, StreamOutput::writeString);
out.writeCollection(colsToAdd, Reference::toStream);
out.writeVInt(pKeyIndices.size());
for (int i = 0; i < pKeyIndices.size(); i++) {
out.writeVInt(pKeyIndices.get(i));
}
| 533
| 119
| 652
|
<methods>public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public io.crate.common.unit.TimeValue ackTimeout() ,public final io.crate.execution.ddl.tables.AddColumnRequest timeout(java.lang.String) ,public final io.crate.execution.ddl.tables.AddColumnRequest timeout(io.crate.common.unit.TimeValue) ,public final io.crate.common.unit.TimeValue timeout() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>public static final io.crate.common.unit.TimeValue DEFAULT_ACK_TIMEOUT,protected io.crate.common.unit.TimeValue timeout
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/tables/CreateTableRequest.java
|
CreateTableRequest
|
writeTo
|
class CreateTableRequest extends MasterNodeRequest<CreateTableRequest> implements AckedRequest {
// Fields required to add column(s), aligned with AddColumnRequest
private final RelationName relationName;
private final List<Reference> colsToAdd;
@Nullable
private final String pkConstraintName;
private final IntArrayList pKeyIndices;
private final Map<String, String> checkConstraints;
// Everything what's not covered by AddColumnRequest is added as a separate field.
private final Settings settings;
@Nullable
private final String routingColumn;
private final ColumnPolicy tableColumnPolicy; // The only setting which is set as a "mapping" change (see TableParameter.mappings()), 'strict' by default.
private final List<List<String>> partitionedBy;
@Deprecated
private CreateIndexRequest createIndexRequest;
@Deprecated
private PutIndexTemplateRequest putIndexTemplateRequest;
public CreateTableRequest(RelationName relationName,
@Nullable String pkConstraintName,
List<Reference> colsToAdd,
IntArrayList pKeyIndices,
Map<String, String> checkConstraints,
Settings settings,
@Nullable String routingColumn,
ColumnPolicy tableColumnPolicy,
List<List<String>> partitionedBy) {
this.relationName = relationName;
this.pkConstraintName = pkConstraintName;
this.colsToAdd = colsToAdd;
this.pKeyIndices = pKeyIndices;
this.checkConstraints = checkConstraints;
this.settings = settings;
this.routingColumn = routingColumn;
this.tableColumnPolicy = tableColumnPolicy;
this.partitionedBy = partitionedBy;
this.createIndexRequest = null;
this.putIndexTemplateRequest = null;
}
@Deprecated
public CreateTableRequest(CreateIndexRequest createIndexRequest) {
this(RelationName.fromIndexName(createIndexRequest.index()),
null,
List.of(),
new IntArrayList(),
Map.of(),
Settings.EMPTY,
null,
ColumnPolicy.STRICT,
List.of()
);
this.createIndexRequest = createIndexRequest;
this.putIndexTemplateRequest = null;
}
@Deprecated
public CreateTableRequest(PutIndexTemplateRequest putIndexTemplateRequest) {
this(RelationName.fromIndexName(putIndexTemplateRequest.aliases().iterator().next().name()),
null,
List.of(),
new IntArrayList(),
Map.of(),
Settings.EMPTY,
null,
ColumnPolicy.STRICT,
List.of()
);
this.createIndexRequest = null;
this.putIndexTemplateRequest = putIndexTemplateRequest;
}
@Nullable
public CreateIndexRequest getCreateIndexRequest() {
return createIndexRequest;
}
@Nullable
public PutIndexTemplateRequest getPutIndexTemplateRequest() {
return putIndexTemplateRequest;
}
@NotNull
public RelationName getTableName() {
return relationName;
}
@Nullable
public String pkConstraintName() {
return pkConstraintName;
}
@Override
public TimeValue ackTimeout() {
return DEFAULT_ACK_TIMEOUT;
}
public CreateTableRequest(StreamInput in) throws IOException {
super(in);
if (in.getVersion().onOrAfter(Version.V_5_6_0)) {
this.pkConstraintName = in.readOptionalString();
} else {
this.pkConstraintName = null;
}
if (in.getVersion().onOrAfter(Version.V_5_4_0)) {
this.relationName = new RelationName(in);
this.checkConstraints = in.readMap(
LinkedHashMap::new, StreamInput::readString, StreamInput::readString);
this.colsToAdd = in.readList(Reference::fromStream);
int numPKIndices = in.readVInt();
this.pKeyIndices = new IntArrayList(numPKIndices);
for (int i = 0; i < numPKIndices; i++) {
pKeyIndices.add(in.readVInt());
}
this.settings = readSettingsFromStream(in);
this.routingColumn = in.readOptionalString();
this.tableColumnPolicy = ColumnPolicy.VALUES.get(in.readVInt());
this.partitionedBy = in.readList(StreamInput::readStringList);
createIndexRequest = null;
putIndexTemplateRequest = null;
} else {
if (in.readBoolean()) {
createIndexRequest = new CreateIndexRequest(in);
putIndexTemplateRequest = null;
} else {
putIndexTemplateRequest = new PutIndexTemplateRequest(in);
createIndexRequest = null;
}
this.relationName = null;
this.colsToAdd = null;
this.pKeyIndices = null;
this.checkConstraints = null;
this.settings = null;
this.routingColumn = null;
this.tableColumnPolicy = null;
this.partitionedBy = null;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
@NotNull
public Settings settings() {
return settings;
}
@Nullable
public String routingColumn() {
return routingColumn;
}
@NotNull
public ColumnPolicy tableColumnPolicy() {
return tableColumnPolicy;
}
@NotNull
public List<List<String>> partitionedBy() {
return partitionedBy;
}
@NotNull
public Map<String, String> checkConstraints() {
return this.checkConstraints;
}
@NotNull
public List<Reference> references() {
return this.colsToAdd;
}
@NotNull
public IntArrayList pKeyIndices() {
return this.pKeyIndices;
}
}
|
super.writeTo(out);
if (out.getVersion().onOrAfter(Version.V_5_6_0)) {
out.writeOptionalString(pkConstraintName);
}
if (out.getVersion().onOrAfter(Version.V_5_4_0)) {
relationName.writeTo(out);
out.writeMap(checkConstraints, StreamOutput::writeString, StreamOutput::writeString);
out.writeCollection(colsToAdd, Reference::toStream);
out.writeVInt(pKeyIndices.size());
for (int i = 0; i < pKeyIndices.size(); i++) {
out.writeVInt(pKeyIndices.get(i));
}
writeSettingsToStream(out, settings);
out.writeOptionalString(routingColumn);
out.writeVInt(tableColumnPolicy.ordinal());
out.writeCollection(partitionedBy, StreamOutput::writeStringCollection);
} else {
boolean isIndexRequest = createIndexRequest != null;
out.writeBoolean(isIndexRequest);
var request = isIndexRequest ? createIndexRequest : putIndexTemplateRequest;
request.writeTo(out);
}
| 1,520
| 298
| 1,818
|
<methods>public final io.crate.execution.ddl.tables.CreateTableRequest masterNodeTimeout(io.crate.common.unit.TimeValue) ,public final io.crate.execution.ddl.tables.CreateTableRequest masterNodeTimeout(java.lang.String) ,public final io.crate.common.unit.TimeValue masterNodeTimeout() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>public static final io.crate.common.unit.TimeValue DEFAULT_MASTER_NODE_TIMEOUT,protected io.crate.common.unit.TimeValue masterNodeTimeout
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/tables/TransportCreateTableAction.java
|
TransportCreateTableAction
|
masterOperation
|
class TransportCreateTableAction extends TransportMasterNodeAction<CreateTableRequest, CreateTableResponse> {
public static final String NAME = "internal:crate:sql/tables/admin/create";
private final MetadataCreateIndexService createIndexService;
private final MetadataIndexTemplateService indexTemplateService;
private final NodeContext nodeContext;
private final IndexScopedSettings indexScopedSettings;
@Inject
public TransportCreateTableAction(TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
MetadataCreateIndexService createIndexService,
MetadataIndexTemplateService indexTemplateService,
NodeContext nodeContext,
IndexScopedSettings indexScopedSettings) {
super(
NAME,
transportService,
clusterService, threadPool,
CreateTableRequest::new
);
this.createIndexService = createIndexService;
this.indexTemplateService = indexTemplateService;
this.nodeContext = nodeContext;
this.indexScopedSettings = indexScopedSettings;
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected CreateTableResponse read(StreamInput in) throws IOException {
return new CreateTableResponse(in);
}
@Override
protected ClusterBlockException checkBlock(CreateTableRequest request, ClusterState state) {
var relationName = request.getTableName();
assert relationName != null : "relationName must not be null";
var isPartitioned = request.getPutIndexTemplateRequest() != null || request.partitionedBy().isEmpty() == false;
if (isPartitioned) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
} else {
return state.blocks().indexBlockedException(
ClusterBlockLevel.METADATA_WRITE,
relationName.indexNameOrAlias()
);
}
}
@Override
protected void masterOperation(final CreateTableRequest createTableRequest,
final ClusterState state,
final ActionListener<CreateTableResponse> listener) {<FILL_FUNCTION_BODY>}
/**
* Similar to {@link TransportCreateIndexAction#masterOperation}
* but also can pass on CrateDB specific objects to build mapping only at the latest stage.
*
* @param mapping is NOT NULL if passed mapping without OID-s can be used directly (for Pre 5.4 code)
* or NULL if we have to build it and assign OID out of references.
*/
private void createIndex(CreateTableRequest createTableRequest, ActionListener<CreateTableResponse> listener, @Nullable String mapping) {
ActionListener<CreateIndexResponse> wrappedListener = ActionListener.wrap(
response -> listener.onResponse(new CreateTableResponse(response.isShardsAcknowledged())),
listener::onFailure
);
String cause = "api"; // Before we used CreateIndexRequest with an empty cause which turned into "api".
final String indexName = createTableRequest.getTableName().indexNameOrAlias(); // getTableName call is BWC.
final CreateIndexClusterStateUpdateRequest updateRequest = new CreateIndexClusterStateUpdateRequest(
cause, indexName, indexName)
.ackTimeout(DEFAULT_ACK_TIMEOUT) // Before we used CreateIndexRequest with default ack timeout.
.masterNodeTimeout(createTableRequest.masterNodeTimeout())
.settings(createTableRequest.settings())
.mapping(mapping)
.aliases(new HashSet<>()) // Before we used CreateIndexRequest with an empty set, it's changed only on resizing indices.
.waitForActiveShards(ActiveShardCount.DEFAULT); // Before we used CreateIndexRequest with default active shards count, it's changed only on resizing indices.
createIndexService.createIndex(
nodeContext,
updateRequest,
createTableRequest,
wrappedListener.map(response ->
new CreateIndexResponse(response.isAcknowledged(), response.isShardsAcknowledged(), indexName))
);
}
/**
* Similar to {@link TransportPutIndexTemplateAction#masterOperation}
* but also can pass on CrateDB specific objects to build mapping only at the latest stage.
*
* @param mapping is NOT NULL if passed mapping without OID-s can be used directly (for Pre 5.4 code)
* or NULL if we have to build it and assign OID out of references.
*/
private void createTemplate(CreateTableRequest createTableRequest, ActionListener<CreateTableResponse> listener, @Nullable String mapping) {
ActionListener<AcknowledgedResponse> wrappedListener = ActionListener.wrap(
response -> listener.onResponse(new CreateTableResponse(response.isAcknowledged())),
listener::onFailure
);
RelationName relationName = createTableRequest.getTableName(); // getTableName call is BWC.
final Settings.Builder templateSettingsBuilder = Settings.builder();
templateSettingsBuilder.put(createTableRequest.settings()).normalizePrefix(IndexMetadata.INDEX_SETTING_PREFIX);
indexScopedSettings.validate(templateSettingsBuilder.build(), true); // templates must be consistent with regards to dependencies
String name = PartitionName.templateName(relationName.schema(), relationName.name());
indexTemplateService.putTemplate(new MetadataIndexTemplateService.PutRequest("api", name)
.patterns(Collections.singletonList(PartitionName.templatePrefix(
relationName.schema(),
relationName.name())))
.settings(templateSettingsBuilder.build())
.mapping(mapping)
.aliases(Set.of(new Alias(relationName.indexNameOrAlias()))) // We used PutIndexTemplateRequest which creates a single alias
.create(true) // We used PutIndexTemplateRequest with explicit 'true'
.masterTimeout(createTableRequest.masterNodeTimeout())
.version(null),
// We used PutIndexTemplateRequest with default version value
createTableRequest,
new MetadataIndexTemplateService.PutListener() {
@Override
public void onResponse(MetadataIndexTemplateService.PutResponse response) {
wrappedListener.onResponse(new AcknowledgedResponse(response.acknowledged()));
}
@Override
public void onFailure(Exception e) {
logger.debug(() -> new ParameterizedMessage("failed to put template [{}]", name), e);
wrappedListener.onFailure(e);
}
});
}
private static void validateSettings(Settings settings, ClusterState state) {
var indexSettingsBuilder = Settings.builder();
indexSettingsBuilder.put(settings);
setIndexVersionCreatedSetting(indexSettingsBuilder, state);
validateSoftDeletesSetting(indexSettingsBuilder.build());
}
}
|
final RelationName relationName = createTableRequest.getTableName();
if (state.metadata().contains(relationName)) {
listener.onFailure(new RelationAlreadyExists(relationName));
return;
}
validateSettings(createTableRequest.settings(), state);
if (state.nodes().getMinNodeVersion().onOrAfter(Version.V_5_4_0)) {
if (createTableRequest.partitionedBy().isEmpty()) {
createIndex(createTableRequest, listener, null);
} else {
createTemplate(createTableRequest, listener, null);
}
} else {
// TODO: Remove BWC branch in 5.5
assert createTableRequest.getCreateIndexRequest() != null || createTableRequest.getPutIndexTemplateRequest() != null : "Unknown request type";
if (createTableRequest.getCreateIndexRequest() != null) {
assert createTableRequest.getCreateIndexRequest().mapping() != null : "Pre 5.4 createTableRequest must have not-null mapping.";
createIndex(createTableRequest, listener, createTableRequest.getCreateIndexRequest().mapping());
} else {
assert createTableRequest.getPutIndexTemplateRequest().mapping() != null : "Pre 5.4 createTableRequest must have not-null mapping.";
createTemplate(createTableRequest, listener, createTableRequest.getPutIndexTemplateRequest().mapping());
}
}
| 1,660
| 350
| 2,010
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/tables/TransportDropConstraintAction.java
|
TransportDropConstraintAction
|
clusterStateTaskExecutor
|
class TransportDropConstraintAction extends AbstractDDLTransportAction<DropConstraintRequest, AcknowledgedResponse> {
private static final String ACTION_NAME = "internal:crate:sql/table/drop_constraint";
private final NodeContext nodeContext;
private final IndicesService indicesService;
@Inject
public TransportDropConstraintAction(TransportService transportService,
ClusterService clusterService,
IndicesService indicesService,
ThreadPool threadPool,
NodeContext nodeContext) {
super(ACTION_NAME,
transportService,
clusterService,
threadPool,
DropConstraintRequest::new,
AcknowledgedResponse::new,
AcknowledgedResponse::new,
"drop-constraint");
this.nodeContext = nodeContext;
this.indicesService = indicesService;
}
@Override
public ClusterStateTaskExecutor<DropConstraintRequest> clusterStateTaskExecutor(DropConstraintRequest request) {<FILL_FUNCTION_BODY>}
private boolean updateMapping(ClusterState currentState,
Metadata.Builder metadataBuilder,
DropConstraintRequest request) throws IOException {
Index[] concreteIndices = resolveIndices(currentState, request.relationName().indexNameOrAlias());
boolean updated = false;
for (Index index : concreteIndices) {
final IndexMetadata indexMetadata = currentState.metadata().getIndexSafe(index);
Map<String, Object> currentSource = indexMetadata.mapping().sourceAsMap();
updated |= removeConstraints(currentSource, List.of(request.constraintName()));
MapperService mapperService = indicesService.createIndexMapperService(indexMetadata);
mapperService.merge(currentSource, MapperService.MergeReason.MAPPING_UPDATE);
DocumentMapper mapper = mapperService.documentMapper();
IndexMetadata.Builder imBuilder = IndexMetadata.builder(indexMetadata);
imBuilder.putMapping(new MappingMetadata(mapper.mappingSource())).mappingVersion(1 + imBuilder.mappingVersion());
metadataBuilder.put(imBuilder); // implicitly increments metadata version.
}
return updated;
}
@Override
public ClusterBlockException checkBlock(DropConstraintRequest request, ClusterState state) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
}
}
|
return new DDLClusterStateTaskExecutor<>() {
@Override
protected ClusterState execute(ClusterState currentState, DropConstraintRequest request) throws Exception {
Metadata.Builder metadataBuilder = Metadata.builder(currentState.metadata());
boolean updated = false;
// Update template if table is partitioned
String templateName = PartitionName.templateName(request.relationName().schema(), request.relationName().name());
IndexTemplateMetadata indexTemplateMetadata = currentState.metadata().templates().get(templateName);
if (indexTemplateMetadata != null) {
// Removal happens by key, value in the deepest map is not used.
Map<String, Object> mapToRemove = Map.of("_meta", Map.of("check_constraints", Map.of(request.constraintName(), "")));
IndexTemplateMetadata newIndexTemplateMetadata = DDLClusterStateHelpers.updateTemplate(
indexTemplateMetadata,
Collections.emptyMap(),
mapToRemove,
Settings.EMPTY,
IndexScopedSettings.DEFAULT_SCOPED_SETTINGS // Not used if new settings are empty
);
updated = true;
metadataBuilder.put(newIndexTemplateMetadata);
}
updated |= updateMapping(currentState, metadataBuilder, request);
if (updated) {
// ensure the new table can still be parsed into a DocTableInfo to avoid breaking the table.
new DocTableInfoFactory(nodeContext).create(request.relationName(), currentState.metadata());
return ClusterState.builder(currentState).metadata(metadataBuilder).build();
}
return currentState;
}
};
| 577
| 399
| 976
|
<methods>public void <init>(java.lang.String, org.elasticsearch.transport.TransportService, org.elasticsearch.cluster.service.ClusterService, org.elasticsearch.threadpool.ThreadPool, Reader<io.crate.execution.ddl.tables.DropConstraintRequest>, Reader<org.elasticsearch.action.support.master.AcknowledgedResponse>, Function<java.lang.Boolean,org.elasticsearch.action.support.master.AcknowledgedResponse>, java.lang.String) ,public abstract ClusterStateTaskExecutor<io.crate.execution.ddl.tables.DropConstraintRequest> clusterStateTaskExecutor(io.crate.execution.ddl.tables.DropConstraintRequest) <variables>private final non-sealed Function<java.lang.Boolean,org.elasticsearch.action.support.master.AcknowledgedResponse> ackedResponseFunction,private final non-sealed Reader<org.elasticsearch.action.support.master.AcknowledgedResponse> reader,private final non-sealed java.lang.String source
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/tables/TransportRenameTableAction.java
|
TransportRenameTableAction
|
masterOperation
|
class TransportRenameTableAction extends TransportMasterNodeAction<RenameTableRequest, AcknowledgedResponse> {
private static final String ACTION_NAME = "internal:crate:sql/table/rename";
private static final IndicesOptions STRICT_INDICES_OPTIONS = IndicesOptions.fromOptions(false, false, false, false);
private final RenameTableClusterStateExecutor executor;
private final ActiveShardsObserver activeShardsObserver;
@Inject
public TransportRenameTableAction(TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
AllocationService allocationService,
DDLClusterStateService ddlClusterStateService) {
super(ACTION_NAME,
transportService,
clusterService,
threadPool,
RenameTableRequest::new
);
activeShardsObserver = new ActiveShardsObserver(clusterService);
executor = new RenameTableClusterStateExecutor(
allocationService,
ddlClusterStateService
);
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected AcknowledgedResponse read(StreamInput in) throws IOException {
return new AcknowledgedResponse(in);
}
@Override
protected void masterOperation(RenameTableRequest request,
ClusterState state,
ActionListener<AcknowledgedResponse> listener) throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected ClusterBlockException checkBlock(RenameTableRequest request, ClusterState state) {
ViewsMetadata views = state.metadata().custom(ViewsMetadata.TYPE);
if (views != null && views.contains(request.sourceName())) {
return null;
}
try {
return state.blocks().indicesBlockedException(
ClusterBlockLevel.METADATA_WRITE,
IndexNameExpressionResolver.concreteIndexNames(
state.metadata(),
STRICT_INDICES_OPTIONS,
request.sourceName().indexNameOrAlias()
)
);
} catch (IndexNotFoundException e) {
if (request.isPartitioned() == false) {
throw e;
}
// empty partition, no indices just a template exists.
return null;
}
}
}
|
AtomicReference<String[]> newIndexNames = new AtomicReference<>(null);
ActionListener<AcknowledgedResponse> waitForShardsListener = ActionListeners.waitForShards(
listener,
activeShardsObserver,
request.timeout(),
() -> logger.info("Renamed a relation, but the operation timed out waiting for enough shards to become available"),
newIndexNames::get
);
clusterService.submitStateUpdateTask(
"rename-table",
new AckedClusterStateUpdateTask<AcknowledgedResponse>(Priority.HIGH, request, waitForShardsListener) {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
ClusterState updatedState = executor.execute(currentState, request);
IndicesOptions openIndices = IndicesOptions.fromOptions(
true,
true,
true,
false,
true,
true,
false
);
newIndexNames.set(IndexNameExpressionResolver.concreteIndexNames(
updatedState.metadata(), openIndices, request.targetName().indexNameOrAlias()));
return updatedState;
}
@Override
protected AcknowledgedResponse newResponse(boolean acknowledged) {
return new AcknowledgedResponse(acknowledged);
}
});
| 581
| 331
| 912
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/views/TransportCreateViewAction.java
|
TransportCreateViewAction
|
masterOperation
|
class TransportCreateViewAction extends TransportMasterNodeAction<CreateViewRequest, CreateViewResponse> {
@Inject
public TransportCreateViewAction(TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool) {
super(
"internal:crate:sql/views/create",
transportService,
clusterService,
threadPool,
CreateViewRequest::new
);
}
@Override
protected String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
protected CreateViewResponse read(StreamInput in) throws IOException {
return new CreateViewResponse(in);
}
@Override
protected void masterOperation(CreateViewRequest request,
ClusterState state,
ActionListener<CreateViewResponse> listener) {<FILL_FUNCTION_BODY>}
@Override
protected ClusterBlockException checkBlock(CreateViewRequest request, ClusterState state) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
}
}
|
if (!request.replaceExisting() && state.metadata().contains(request.name())) {
listener.onResponse(new CreateViewResponse(true));
} else {
clusterService.submitStateUpdateTask("views/create [" + request.name() + "]",
new AckedClusterStateUpdateTask<CreateViewResponse>(Priority.HIGH, request, listener) {
boolean alreadyExitsFailure = false;
@Override
public ClusterState execute(ClusterState currentState) {
ViewsMetadata views = currentState.metadata().custom(ViewsMetadata.TYPE);
if (currentState.metadata().contains(request.name())) {
boolean replacesView = request.replaceExisting() && views != null && views.contains(request.name());
if (!replacesView) {
alreadyExitsFailure = true;
return currentState;
}
}
return ClusterState.builder(currentState)
.metadata(
Metadata.builder(currentState.metadata())
.putCustom(
ViewsMetadata.TYPE,
ViewsMetadata.addOrReplace(
views,
request.name(),
request.query(),
request.owner(),
request.searchPath()))
.build()
).build();
}
@Override
protected CreateViewResponse newResponse(boolean acknowledged) {
return new CreateViewResponse(alreadyExitsFailure);
}
});
}
| 266
| 351
| 617
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/ddl/views/TransportDropViewAction.java
|
TransportDropViewAction
|
masterOperation
|
class TransportDropViewAction extends TransportMasterNodeAction<DropViewRequest, DropViewResponse> {
private final DDLClusterStateService ddlClusterStateService;
@Inject
public TransportDropViewAction(TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
DDLClusterStateService ddlClusterStateService) {
super(
"internal:crate:sql/views/drop",
transportService,
clusterService,
threadPool,
DropViewRequest::new
);
this.ddlClusterStateService = ddlClusterStateService;
}
@Override
protected String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
protected DropViewResponse read(StreamInput in) throws IOException {
return new DropViewResponse(in);
}
@Override
protected void masterOperation(DropViewRequest request,
ClusterState state,
ActionListener<DropViewResponse> listener) {<FILL_FUNCTION_BODY>}
@Override
protected ClusterBlockException checkBlock(DropViewRequest request, ClusterState state) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
}
}
|
clusterService.submitStateUpdateTask("views/drop",
new AckedClusterStateUpdateTask<DropViewResponse>(Priority.HIGH, request, listener) {
private List<RelationName> missing;
@Override
public ClusterState execute(ClusterState currentState) {
ViewsMetadata views = currentState.metadata().custom(ViewsMetadata.TYPE);
if (views == null) {
missing = request.names();
return currentState;
}
ViewsMetadata.RemoveResult removeResult = views.remove(request.names());
missing = removeResult.missing();
if (!removeResult.missing().isEmpty() && !request.ifExists()) {
// We missed a view -> This is an error case so we must not update the cluster state
return currentState;
}
currentState = ddlClusterStateService.onDropView(currentState, request.names());
return ClusterState.builder(currentState)
.metadata(
Metadata.builder(currentState.metadata())
.putCustom(ViewsMetadata.TYPE, removeResult.updatedViews())
.build()
)
.build();
}
@Override
protected DropViewResponse newResponse(boolean acknowledged) {
return new DropViewResponse(missing);
}
});
| 311
| 320
| 631
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/BitStringIndexer.java
|
BitStringIndexer
|
indexValue
|
class BitStringIndexer implements ValueIndexer<BitString> {
private final Reference ref;
private final FieldType fieldType;
private final String name;
public BitStringIndexer(Reference ref, FieldType fieldType) {
this.ref = ref;
this.name = ref.storageIdent();
this.fieldType = fieldType == null
? BitStringFieldMapper.Defaults.FIELD_TYPE
: fieldType;
}
@Override
public void indexValue(BitString value,
XContentBuilder xcontentBuilder,
Consumer<? super IndexableField> addField,
Map<ColumnIdent, Synthetic> synthetics,
Map<ColumnIdent, ColumnConstraint> toValidate) throws IOException {<FILL_FUNCTION_BODY>}
}
|
BitSet bitSet = value.bitSet();
byte[] bytes = bitSet.toByteArray();
xcontentBuilder.value(bytes);
BytesRef binaryValue = new BytesRef(bytes);
if (ref.indexType() != IndexType.NONE) {
addField.accept(new Field(name, binaryValue, fieldType));
}
if (ref.hasDocValues()) {
addField.accept(new SortedSetDocValuesField(name, binaryValue));
} else {
addField.accept(new Field(
FieldNamesFieldMapper.NAME,
name,
FieldNamesFieldMapper.Defaults.FIELD_TYPE));
}
| 195
| 170
| 365
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/FloatIndexer.java
|
FloatIndexer
|
indexValue
|
class FloatIndexer implements ValueIndexer<Float> {
private final Reference ref;
private final FieldType fieldType;
private String name;
public FloatIndexer(Reference ref, FieldType fieldType) {
this.ref = ref;
this.name = ref.storageIdent();
this.fieldType = fieldType;
}
@Override
public void indexValue(Float value,
XContentBuilder xcontentBuilder,
Consumer<? super IndexableField> addField,
Map<ColumnIdent, Synthetic> synthetics,
Map<ColumnIdent, ColumnConstraint> toValidate) throws IOException {<FILL_FUNCTION_BODY>}
}
|
xcontentBuilder.value(value);
float floatValue = value.floatValue();
if (ref.hasDocValues() && ref.indexType() != IndexType.NONE) {
addField.accept(new FloatField(name, floatValue, fieldType.stored() ? Field.Store.YES : Field.Store.NO));
} else {
if (ref.indexType() != IndexType.NONE) {
addField.accept(new FloatPoint(name, floatValue));
}
if (ref.hasDocValues()) {
addField.accept(
new SortedNumericDocValuesField(name, NumericUtils.floatToSortableInt(floatValue))
);
} else {
addField.accept(new Field(
FieldNamesFieldMapper.NAME,
name,
FieldNamesFieldMapper.Defaults.FIELD_TYPE));
}
if (fieldType.stored()) {
addField.accept(new StoredField(name, floatValue));
}
}
| 171
| 256
| 427
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/FloatVectorIndexer.java
|
FloatVectorIndexer
|
indexValue
|
class FloatVectorIndexer implements ValueIndexer<float[]> {
final FieldType fieldType;
private final String name;
private final Reference ref;
public FloatVectorIndexer(Reference ref, @Nullable FieldType fieldType) {
if (fieldType == null) {
fieldType = new FieldType(FloatVectorFieldMapper.Defaults.FIELD_TYPE);
fieldType.setVectorAttributes(
ref.valueType().characterMaximumLength(),
VectorEncoding.FLOAT32,
FloatVectorType.SIMILARITY_FUNC
);
}
this.ref = ref;
this.name = ref.storageIdent();
this.fieldType = fieldType;
}
@Override
public void indexValue(float @Nullable [] values,
XContentBuilder xcontentBuilder,
Consumer<? super IndexableField> addField,
Map<ColumnIdent, Synthetic> synthetics,
Map<ColumnIdent, ColumnConstraint> toValidate) throws IOException {<FILL_FUNCTION_BODY>}
public static void createFields(String fqn,
FieldType fieldType,
boolean indexed,
boolean hasDocValues,
float @NotNull [] values,
Consumer<? super IndexableField> addField) {
if (indexed) {
addField.accept(new KnnFloatVectorField(fqn, values, fieldType));
}
if (hasDocValues) {
int capacity = values.length * Float.BYTES;
ByteBuffer buffer = ByteBuffer.allocate(capacity).order(ByteOrder.BIG_ENDIAN);
for (float value : values) {
buffer.putFloat(value);
}
byte[] bytes = new byte[buffer.flip().limit()];
buffer.get(bytes);
var field = new BinaryDocValuesField(fqn, new BytesRef(bytes));
addField.accept(field);
} else {
addField.accept(new Field(
FieldNamesFieldMapper.NAME,
fqn,
FieldNamesFieldMapper.Defaults.FIELD_TYPE));
}
}
}
|
if (values == null) {
return;
}
xcontentBuilder.startArray();
for (float value : values) {
xcontentBuilder.value(value);
}
xcontentBuilder.endArray();
createFields(
name,
fieldType,
ref.indexType() != IndexType.NONE,
ref.hasDocValues(),
values,
addField
);
if (fieldType.stored()) {
throw new UnsupportedOperationException("Cannot store float_vector as stored field");
}
| 534
| 141
| 675
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/FulltextIndexer.java
|
FulltextIndexer
|
indexValue
|
class FulltextIndexer implements ValueIndexer<String> {
private final Reference ref;
private final FieldType fieldType;
public FulltextIndexer(Reference ref, FieldType fieldType) {
this.ref = ref;
this.fieldType = fieldType;
}
@Override
public void indexValue(String value,
XContentBuilder xcontentBuilder,
Consumer<? super IndexableField> addField,
Map<ColumnIdent, Indexer.Synthetic> synthetics,
Map<ColumnIdent, Indexer.ColumnConstraint> toValidate) throws IOException {<FILL_FUNCTION_BODY>}
}
|
xcontentBuilder.value(value);
if (value == null) {
return;
}
String name = ref.storageIdent();
if (fieldType.indexOptions() != IndexOptions.NONE || fieldType.stored()) {
Field field = new Field(name, value, fieldType);
addField.accept(field);
if (fieldType.omitNorms()) {
addField.accept(new Field(
FieldNamesFieldMapper.NAME,
name,
FieldNamesFieldMapper.Defaults.FIELD_TYPE));
}
}
| 160
| 145
| 305
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/ShardRequest.java
|
ShardRequest
|
toString
|
class ShardRequest<T extends ShardRequest<T, I>, I extends ShardRequest.Item>
extends ReplicationRequest<T>
implements Iterable<I>, Accountable {
private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(ShardRequest.class);
private final UUID jobId;
protected List<I> items;
public ShardRequest(ShardId shardId, UUID jobId) {
setShardId(shardId);
this.jobId = jobId;
this.index = shardId.getIndexName();
this.items = new ArrayList<>();
}
public void add(int location, I item) {
item.location(location);
items.add(item);
}
public List<I> items() {
return items;
}
@Override
public Iterator<I> iterator() {
return Collections.unmodifiableCollection(items).iterator();
}
public UUID jobId() {
return jobId;
}
public ShardRequest(StreamInput in) throws IOException {
super(in);
jobId = new UUID(in.readLong(), in.readLong());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeLong(jobId.getMostSignificantBits());
out.writeLong(jobId.getLeastSignificantBits());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ShardRequest<?, ?> that = (ShardRequest<?, ?>) o;
return Objects.equals(jobId, that.jobId) &&
Objects.equals(items, that.items);
}
@Override
public int hashCode() {
return Objects.hash(jobId, items);
}
/**
* The description is used when creating transport, replication and search tasks and it defaults to `toString`.
* Only return the shard id to avoid the overhead of including all the items.
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public long ramBytesUsed() {
long bytes = SHALLOW_SIZE;
for (var item : items) {
bytes += item.ramBytesUsed();
}
return bytes;
}
public abstract static class Item implements Writeable, Accountable {
protected final String id;
protected long version = Versions.MATCH_ANY;
private int location = -1;
protected long seqNo = SequenceNumbers.UNASSIGNED_SEQ_NO;
protected long primaryTerm = SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
public Item(String id) {
this.id = id;
}
protected Item(StreamInput in) throws IOException {
id = in.readString();
version = in.readLong();
location = in.readInt();
seqNo = in.readLong();
primaryTerm = in.readLong();
}
@Override
public long ramBytesUsed() {
return RamUsageEstimator.sizeOf(id)
+ Long.BYTES // version
+ Integer.BYTES // location
+ Long.BYTES // seqNo
+ Long.BYTES; // primaryTerm
}
public String id() {
return id;
}
public long version() {
return version;
}
public void version(long version) {
this.version = version;
}
public void location(int location) {
this.location = location;
}
public int location() {
return location;
}
public long seqNo() {
return seqNo;
}
public void seqNo(long seqNo) {
this.seqNo = seqNo;
}
public long primaryTerm() {
return primaryTerm;
}
public void primaryTerm(long primaryTerm) {
this.primaryTerm = primaryTerm;
}
public void writeTo(StreamOutput out) throws IOException {
out.writeString(id);
out.writeLong(version);
out.writeInt(location);
out.writeLong(seqNo);
out.writeLong(primaryTerm);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return version == item.version &&
location == item.location &&
seqNo == item.seqNo &&
primaryTerm == item.primaryTerm &&
java.util.Objects.equals(id, item.id);
}
@Override
public int hashCode() {
return java.util.Objects.hash(id, version, location, seqNo, primaryTerm);
}
@Override
public String toString() {
return "Item{" +
"id='" + id + '\'' +
", version=" + version +
", location=" + location +
", seqNo=" + seqNo +
", primaryTerm=" + primaryTerm +
'}';
}
}
}
|
return "ShardRequest{" +
", shardId=" + shardId +
", timeout=" + timeout +
'}';
| 1,398
| 39
| 1,437
|
<methods>public void <init>() ,public void <init>(org.elasticsearch.index.shard.ShardId) ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public java.lang.String getDescription() ,public java.lang.String index() ,public final T index(java.lang.String) ,public java.lang.String[] indices() ,public org.elasticsearch.action.support.IndicesOptions indicesOptions() ,public void onRetry() ,public T setShardId(org.elasticsearch.index.shard.ShardId) ,public org.elasticsearch.index.shard.ShardId shardId() ,public final T timeout(io.crate.common.unit.TimeValue) ,public final T timeout(java.lang.String) ,public io.crate.common.unit.TimeValue timeout() ,public abstract java.lang.String toString() ,public org.elasticsearch.action.support.ActiveShardCount waitForActiveShards() ,public final T waitForActiveShards(org.elasticsearch.action.support.ActiveShardCount) ,public final T waitForActiveShards(int) ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>public static final io.crate.common.unit.TimeValue DEFAULT_TIMEOUT,protected java.lang.String index,private long routedBasedOnClusterVersion,protected org.elasticsearch.index.shard.ShardId shardId,protected io.crate.common.unit.TimeValue timeout,protected org.elasticsearch.action.support.ActiveShardCount waitForActiveShards
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dml/delete/ShardDeleteRequest.java
|
ShardDeleteRequest
|
writeTo
|
class ShardDeleteRequest extends ShardRequest<ShardDeleteRequest, ShardDeleteRequest.Item> {
private int skipFromLocation = -1;
public ShardDeleteRequest(ShardId shardId, UUID jobId) {
super(shardId, jobId);
}
void skipFromLocation(int location) {
skipFromLocation = location;
}
int skipFromLocation() {
return skipFromLocation;
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
public ShardDeleteRequest(StreamInput in) throws IOException {
super(in);
int numItems = in.readVInt();
if (numItems > 0) {
items = new ArrayList<>(numItems);
for (int i = 0; i < numItems; i++) {
items.add(new ShardDeleteRequest.Item(in));
}
}
if (in.readBoolean()) {
skipFromLocation = in.readVInt();
}
}
public static class Item extends ShardRequest.Item {
public static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(Item.class);
protected Item(StreamInput in) throws IOException {
super(in);
}
public Item(String id) {
super(id);
}
}
}
|
super.writeTo(out);
out.writeVInt(items.size());
for (Item item : items) {
item.writeTo(out);
}
if (skipFromLocation > -1) {
out.writeBoolean(true);
out.writeVInt(skipFromLocation);
} else {
out.writeBoolean(false);
}
| 356
| 96
| 452
|
<methods>public void <init>(org.elasticsearch.index.shard.ShardId, java.util.UUID) ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public void add(int, io.crate.execution.dml.delete.ShardDeleteRequest.Item) ,public boolean equals(java.lang.Object) ,public int hashCode() ,public List<io.crate.execution.dml.delete.ShardDeleteRequest.Item> items() ,public Iterator<io.crate.execution.dml.delete.ShardDeleteRequest.Item> iterator() ,public java.util.UUID jobId() ,public long ramBytesUsed() ,public java.lang.String toString() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private static final long SHALLOW_SIZE,protected List<io.crate.execution.dml.delete.ShardDeleteRequest.Item> items,private final non-sealed java.util.UUID jobId
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/phases/CountPhase.java
|
CountPhase
|
equals
|
class CountPhase implements UpstreamPhase {
private final int executionPhaseId;
private final Routing routing;
private final Symbol where;
private DistributionInfo distributionInfo;
public CountPhase(int executionPhaseId,
Routing routing,
Symbol where,
DistributionInfo distributionInfo) {
this.executionPhaseId = executionPhaseId;
this.routing = routing;
this.where = where;
this.distributionInfo = distributionInfo;
}
@Override
public Type type() {
return Type.COUNT;
}
@Override
public String name() {
return "count";
}
public Routing routing() {
return routing;
}
public Symbol where() {
return where;
}
@Override
public int phaseId() {
return executionPhaseId;
}
@Override
public Set<String> nodeIds() {
return routing.nodes();
}
@Override
public DistributionInfo distributionInfo() {
return distributionInfo;
}
@Override
public void distributionInfo(DistributionInfo distributionInfo) {
this.distributionInfo = distributionInfo;
}
@Override
public <C, R> R accept(ExecutionPhaseVisitor<C, R> visitor, C context) {
return visitor.visitCountPhase(this, context);
}
public CountPhase(StreamInput in) throws IOException {
executionPhaseId = in.readVInt();
routing = new Routing(in);
where = Symbols.fromStream(in);
distributionInfo = new DistributionInfo(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(executionPhaseId);
routing.writeTo(out);
Symbols.toStream(where, out);
distributionInfo.writeTo(out);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(executionPhaseId, routing, where, distributionInfo);
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CountPhase that = (CountPhase) o;
return executionPhaseId == that.executionPhaseId &&
Objects.equals(routing, that.routing) &&
Objects.equals(where, that.where) &&
Objects.equals(distributionInfo, that.distributionInfo);
| 552
| 121
| 673
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/phases/ExecutionPhases.java
|
ExecutionPhases
|
debugPrint
|
class ExecutionPhases {
/**
* @return true if the executionNodes indicate a execution on the handler node.
*
* size == 0 is also true
* (this currently is the case on MergePhases if there is a direct-response from previous phase to MergePhase)
*/
public static boolean executesOnHandler(String handlerNode, Collection<String> executionNodes) {
switch (executionNodes.size()) {
case 0:
return true;
case 1:
return executionNodes.iterator().next().equals(handlerNode);
default:
return false;
}
}
public static ExecutionPhase fromStream(StreamInput in) throws IOException {
return ExecutionPhase.Type.VALUES.get(in.readVInt()).fromStream(in);
}
public static void toStream(StreamOutput out, ExecutionPhase node) throws IOException {
out.writeVInt(node.type().ordinal());
node.writeTo(out);
}
public static boolean hasDirectResponseDownstream(Collection<String> downstreamNodes) {
for (String nodeId : downstreamNodes) {
if (nodeId.equals(ExecutionPhase.DIRECT_RESPONSE)) {
return true;
}
}
return false;
}
public static String debugPrint(ExecutionPhase phase) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder("phase{id=");
sb.append(phase.phaseId());
sb.append("/");
sb.append(phase.name());
sb.append(", ");
sb.append("nodes=");
sb.append(phase.nodeIds());
if (phase instanceof UpstreamPhase) {
UpstreamPhase uPhase = (UpstreamPhase) phase;
sb.append(", dist=");
sb.append(uPhase.distributionInfo().distributionType());
}
sb.append("}");
return sb.toString();
| 354
| 148
| 502
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/phases/FetchPhase.java
|
FetchPhase
|
equals
|
class FetchPhase implements ExecutionPhase {
private final TreeMap<String, Integer> bases;
private final Map<RelationName, Collection<String>> tableIndices;
private final Collection<Reference> fetchRefs;
private final int executionPhaseId;
private final Set<String> executionNodes;
public FetchPhase(int executionPhaseId,
Set<String> executionNodes,
TreeMap<String, Integer> bases,
Map<RelationName, Collection<String>> tableIndices,
Collection<Reference> fetchRefs) {
this.executionPhaseId = executionPhaseId;
this.executionNodes = executionNodes;
this.bases = bases;
this.tableIndices = tableIndices;
this.fetchRefs = fetchRefs;
}
public Collection<Reference> fetchRefs() {
return fetchRefs;
}
@Override
public Type type() {
return Type.FETCH;
}
@Override
public String name() {
return "fetchPhase";
}
@Override
public int phaseId() {
return executionPhaseId;
}
@Override
public Set<String> nodeIds() {
return executionNodes;
}
@Override
public <C, R> R accept(ExecutionPhaseVisitor<C, R> visitor, C context) {
return visitor.visitFetchPhase(this, context);
}
public FetchPhase(StreamInput in) throws IOException {
executionPhaseId = in.readVInt();
int n = in.readVInt();
executionNodes = new HashSet<>(n);
for (int i = 0; i < n; i++) {
executionNodes.add(in.readString());
}
n = in.readVInt();
bases = new TreeMap<>();
for (int i = 0; i < n; i++) {
bases.put(in.readString(), in.readVInt());
}
n = in.readVInt();
fetchRefs = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
fetchRefs.add(Reference.fromStream(in));
}
n = in.readVInt();
tableIndices = new HashMap<>(n);
for (int i = 0; i < n; i++) {
RelationName ti = new RelationName(in);
int nn = in.readVInt();
for (int j = 0; j < nn; j++) {
Collection<String> collection = tableIndices.computeIfAbsent(ti, ignored -> new ArrayList<>());
collection.add(in.readString());
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(executionPhaseId);
out.writeVInt(executionNodes.size());
for (String executionNode : executionNodes) {
out.writeString(executionNode);
}
out.writeVInt(bases.size());
for (Map.Entry<String, Integer> entry : bases.entrySet()) {
out.writeString(entry.getKey());
out.writeVInt(entry.getValue());
}
out.writeVInt(fetchRefs.size());
for (Reference ref : fetchRefs) {
Reference.toStream(out, ref);
}
out.writeVInt(tableIndices.size());
for (Map.Entry<RelationName, Collection<String>> entry : tableIndices.entrySet()) {
entry.getKey().writeTo(out);
out.writeVInt(entry.getValue().size());
for (String s : entry.getValue()) {
out.writeString(s);
}
}
}
public Map<RelationName, Collection<String>> tableIndices() {
return tableIndices;
}
public TreeMap<String, Integer> bases() {
return bases;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(bases, tableIndices, fetchRefs, executionPhaseId, executionNodes);
}
@Override
public String toString() {
return "FetchPhase{bases=" + bases
+ ", executionNodes=" + executionNodes
+ ", executionPhaseId=" + executionPhaseId
+ ", fetchRefs=" + fetchRefs
+ ", tableIndices=" + tableIndices + "}";
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FetchPhase that = (FetchPhase) o;
return executionPhaseId == that.executionPhaseId &&
Objects.equals(bases, that.bases) &&
Objects.equals(tableIndices, that.tableIndices) &&
Objects.equals(fetchRefs, that.fetchRefs) &&
Objects.equals(executionNodes, that.executionNodes);
| 1,181
| 145
| 1,326
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/phases/NodeOperationTree.java
|
NodeOperationTree
|
toString
|
class NodeOperationTree {
private final Collection<NodeOperation> nodeOperations;
private final ExecutionPhase leaf;
public NodeOperationTree(Collection<NodeOperation> nodeOperations, ExecutionPhase leaf) {
this.nodeOperations = nodeOperations;
this.leaf = leaf;
}
/**
* all NodeOperations (leaf is not included)
*/
public Collection<NodeOperation> nodeOperations() {
return nodeOperations;
}
/**
* the final executionPhase which will provide the final result.
*/
public ExecutionPhase leaf() {
return leaf;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "NodeOperationTree{" +
"nodeOperations=" + nodeOperations +
", leaf=" + leaf +
'}';
| 187
| 39
| 226
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/phases/PKLookupPhase.java
|
PKLookupPhase
|
writeTo
|
class PKLookupPhase extends AbstractProjectionsPhase implements CollectPhase {
private final List<ColumnIdent> partitionedByColumns;
private final List<Symbol> toCollect;
private final Map<String, Map<ShardId, List<PKAndVersion>>> idsByShardByNode;
private DistributionInfo distInfo = DistributionInfo.DEFAULT_BROADCAST;
public PKLookupPhase(UUID jobId,
int phaseId,
List<ColumnIdent> partitionedByColumns,
List<Symbol> toCollect,
Map<String, Map<ShardId, List<PKAndVersion>>> idsByShardByNode) {
super(jobId, phaseId, "pkLookup", Collections.emptyList());
assert toCollect.stream().noneMatch(
st -> SymbolVisitors.any(s -> s instanceof ScopedSymbol || s instanceof SelectSymbol, st))
: "toCollect must not contain any fields or selectSymbols: " + toCollect;
this.partitionedByColumns = partitionedByColumns;
this.toCollect = toCollect;
this.idsByShardByNode = idsByShardByNode;
}
public PKLookupPhase(StreamInput in) throws IOException {
super(in);
distInfo = new DistributionInfo(in);
toCollect = Symbols.listFromStream(in);
int numNodes = in.readVInt();
idsByShardByNode = new HashMap<>(numNodes);
for (int nodeIdx = 0; nodeIdx < numNodes; nodeIdx++) {
String nodeId = in.readString();
int numShards = in.readVInt();
HashMap<ShardId, List<PKAndVersion>> idsByShard = new HashMap<>(numShards);
idsByShardByNode.put(nodeId, idsByShard);
for (int shardIdx = 0; shardIdx < numShards; shardIdx++) {
ShardId shardId = new ShardId(in);
int numPks = in.readVInt();
ArrayList<PKAndVersion> pks = new ArrayList<>(numPks);
for (int pkIdx = 0; pkIdx < numPks; pkIdx++) {
pks.add(new PKAndVersion(in));
}
idsByShard.put(shardId, pks);
}
}
int numPartitionedByCols = in.readVInt();
if (numPartitionedByCols == 0) {
partitionedByColumns = Collections.emptyList();
} else {
partitionedByColumns = new ArrayList<>(numPartitionedByCols);
for (int i = 0; i < numPartitionedByCols; i++) {
partitionedByColumns.add(new ColumnIdent(in));
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<DataType<?>> outputTypes() {
if (projections.isEmpty()) {
return Symbols.typeView(toCollect);
}
return super.outputTypes();
}
@Override
public List<Symbol> toCollect() {
return toCollect;
}
@Override
public DistributionInfo distributionInfo() {
return distInfo;
}
@Override
public void distributionInfo(DistributionInfo distributionInfo) {
this.distInfo = distributionInfo;
}
@Override
public Type type() {
return Type.PKLookup;
}
@Override
public Collection<String> nodeIds() {
return idsByShardByNode.keySet();
}
@Override
public <C, R> R accept(ExecutionPhaseVisitor<C, R> visitor, C context) {
return visitor.visitPKLookup(this, context);
}
public Map<ShardId,List<PKAndVersion>> getIdsByShardId(String nodeId) {
return idsByShardByNode.getOrDefault(nodeId, Collections.emptyMap());
}
public List<ColumnIdent> partitionedByColumns() {
return partitionedByColumns;
}
}
|
super.writeTo(out);
distInfo.writeTo(out);
Symbols.toStream(toCollect, out);
out.writeVInt(idsByShardByNode.size());
for (Map.Entry<String, Map<ShardId, List<PKAndVersion>>> byNodeEntry : idsByShardByNode.entrySet()) {
Map<ShardId, List<PKAndVersion>> idsByShard = byNodeEntry.getValue();
out.writeString(byNodeEntry.getKey());
out.writeVInt(idsByShard.size());
for (Map.Entry<ShardId, List<PKAndVersion>> shardEntry : idsByShard.entrySet()) {
List<PKAndVersion> ids = shardEntry.getValue();
shardEntry.getKey().writeTo(out);
out.writeVInt(ids.size());
for (PKAndVersion id : ids) {
id.writeTo(out);
}
}
}
out.writeVInt(partitionedByColumns.size());
for (ColumnIdent partitionedByColumn : partitionedByColumns) {
partitionedByColumn.writeTo(out);
}
| 1,080
| 301
| 1,381
|
<methods>public void addProjection(io.crate.execution.dsl.projection.Projection) ,public boolean equals(java.lang.Object) ,public Optional<io.crate.execution.dsl.projection.Projection> finalProjection() ,public boolean hasProjections() ,public int hashCode() ,public java.util.UUID jobId() ,public java.lang.String name() ,public List<DataType<?>> outputTypes() ,public int phaseId() ,public List<io.crate.execution.dsl.projection.Projection> projections() ,public java.lang.String toString() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private final non-sealed int executionPhaseId,private final non-sealed java.util.UUID jobId,private final non-sealed java.lang.String name,protected List<DataType<?>> outputTypes,protected final non-sealed List<io.crate.execution.dsl.projection.Projection> projections
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/FetchProjection.java
|
FetchProjection
|
generateStreamersGroupedByReaderAndNode
|
class FetchProjection extends Projection {
private static final int HEAP_IN_MB = (int) (JvmInfo.jvmInfo().getConfiguredMaxHeapSize() / (1024 * 1024));
private static final int MAX_FETCH_SIZE = maxFetchSize(HEAP_IN_MB);
private final int fetchPhaseId;
private final int fetchSize;
private final Map<RelationName, FetchSource> fetchSources;
private final List<Symbol> outputSymbols;
private final Map<String, IntSet> nodeReaders;
private final TreeMap<Integer, String> readerIndices;
private final Map<String, RelationName> indicesToIdents;
private final List<DataType<?>> inputTypes;
public FetchProjection(int fetchPhaseId,
int suppliedFetchSize,
Map<RelationName, FetchSource> fetchSources,
List<Symbol> outputSymbols,
List<DataType<?>> inputTypes,
Map<String, IntSet> nodeReaders,
TreeMap<Integer, String> readerIndices,
Map<String, RelationName> indicesToIdents) {
assert outputSymbols.stream().noneMatch(s ->
SymbolVisitors.any(x -> x instanceof ScopedSymbol || x instanceof SelectSymbol, s))
: "Cannot operate on Field or SelectSymbol symbols: " + outputSymbols;
this.fetchPhaseId = fetchPhaseId;
this.fetchSources = fetchSources;
this.outputSymbols = outputSymbols;
this.inputTypes = inputTypes;
this.nodeReaders = nodeReaders;
this.readerIndices = readerIndices;
this.indicesToIdents = indicesToIdents;
this.fetchSize = boundedFetchSize(suppliedFetchSize, MAX_FETCH_SIZE);
}
@VisibleForTesting
static int maxFetchSize(int maxHeapInMb) {
/* These values were chosen after some manuel testing with a single node started with
* different heap configurations: 56mb, 256mb and 2048mb
*
* This should result in fetchSizes that err on the safe-side to prevent out of memory issues.
* And yet they get large quickly enough that on a decently sized cluster it's on the maximum
* (4gb heap already has a fetchSize of 500000)
*
* The returned maxFetchSize may still be too large in case of very large result payloads,
* but there's still a circuit-breaker which should prevent OOM errors.
*/
int x0 = 56;
int y0 = 2000;
int x1 = 256;
int y1 = 30000;
// linear interpolation formula.
return Math.min(y0 + (maxHeapInMb - x0) * ((y1 - y0) / (x1 - x0)), Paging.PAGE_SIZE);
}
@VisibleForTesting
static int boundedFetchSize(int suppliedFetchSize, int maxSize) {
if (suppliedFetchSize == 0) {
return maxSize;
}
return Math.min(suppliedFetchSize, maxSize);
}
public int fetchPhaseId() {
return fetchPhaseId;
}
public int getFetchSize() {
return fetchSize;
}
public Map<RelationName, FetchSource> fetchSources() {
return fetchSources;
}
public List<Symbol> outputSymbols() {
return outputSymbols;
}
public List<DataType<?>> inputTypes() {
return inputTypes;
}
public Map<String, IntSet> nodeReaders() {
return nodeReaders;
}
@Override
public ProjectionType projectionType() {
return ProjectionType.FETCH;
}
@Override
public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
return visitor.visitFetchProjection(this, context);
}
@Override
public List<? extends Symbol> outputs() {
return outputSymbols;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FetchProjection that = (FetchProjection) o;
return fetchPhaseId == that.fetchPhaseId;
}
@Override
public int hashCode() {
return fetchPhaseId;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new UnsupportedOperationException("writeTo is not supported for " +
FetchProjection.class.getSimpleName());
}
@Override
public Map<String, Object> mapRepresentation() {
return MapBuilder.<String, Object>newMapBuilder()
.put("type", "Fetch")
.put("outputs", Lists.joinOn(", ", outputSymbols, Symbol::toString))
.put("fetchSize", fetchSize)
.map();
}
public Map<String, ? extends IntObjectMap<Streamer<?>[]>> generateStreamersGroupedByReaderAndNode() {<FILL_FUNCTION_BODY>}
public FetchSource getFetchSourceByReader(int readerId) {
String index = readerIndices.floorEntry(readerId).getValue();
RelationName relationName = indicesToIdents.get(index);
assert relationName != null : "Must have a relationName for readerId=" + readerId;
FetchSource fetchSource = fetchSources.get(relationName);
assert fetchSource != null : "Must have a fetchSource for relationName=" + relationName;
return fetchSource;
}
}
|
HashMap<String, IntObjectHashMap<Streamer<?>[]>> streamersByReaderByNode = new HashMap<>();
for (Map.Entry<String, IntSet> entry : nodeReaders.entrySet()) {
IntObjectHashMap<Streamer<?>[]> streamersByReaderId = new IntObjectHashMap<>();
String nodeId = entry.getKey();
streamersByReaderByNode.put(nodeId, streamersByReaderId);
for (IntCursor readerIdCursor : entry.getValue()) {
int readerId = readerIdCursor.value;
String index = readerIndices.floorEntry(readerId).getValue();
RelationName relationName = indicesToIdents.get(index);
FetchSource fetchSource = fetchSources.get(relationName);
if (fetchSource == null) {
continue;
}
streamersByReaderId.put(readerIdCursor.value, Symbols.streamerArray(fetchSource.references()));
}
}
return streamersByReaderByNode;
| 1,493
| 255
| 1,748
|
<methods>public non-sealed void <init>() ,public abstract R accept(ProjectionVisitor<C,R>, C) ,public abstract boolean equals(java.lang.Object) ,public static io.crate.execution.dsl.projection.Projection fromStream(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public int hashCode() ,public Map<java.lang.String,java.lang.Object> mapRepresentation() ,public abstract List<? extends io.crate.expression.symbol.Symbol> outputs() ,public abstract io.crate.execution.dsl.projection.ProjectionType projectionType() ,public io.crate.metadata.RowGranularity requiredGranularity() ,public static void toStream(io.crate.execution.dsl.projection.Projection, org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException,public abstract void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>static final Predicate<io.crate.execution.dsl.projection.Projection> IS_NODE_PROJECTION,static final Predicate<io.crate.execution.dsl.projection.Projection> IS_SHARD_PROJECTION
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/GroupProjection.java
|
GroupProjection
|
equals
|
class GroupProjection extends Projection {
private final List<Symbol> keys;
private final List<Aggregation> values;
private List<Symbol> outputs;
private final AggregateMode mode;
private final RowGranularity requiredGranularity;
public GroupProjection(List<Symbol> keys,
List<Aggregation> values,
AggregateMode mode,
RowGranularity requiredGranularity) {
assert keys.stream().noneMatch(s ->
SymbolVisitors.any(Symbols.IS_COLUMN.or(x -> x instanceof SelectSymbol), s))
: "Cannot operate on Reference, Field or SelectSymbol symbols: " + keys;
assert values.stream().noneMatch(s ->
SymbolVisitors.any(Symbols.IS_COLUMN.or(x -> x instanceof SelectSymbol), s))
: "Cannot operate on Reference, Field or SelectSymbol symbols: " + values;
this.keys = keys;
this.values = values;
this.mode = mode;
this.requiredGranularity = requiredGranularity;
}
public GroupProjection(StreamInput in) throws IOException {
mode = AggregateMode.readFrom(in);
keys = Symbols.listFromStream(in);
int size = in.readVInt();
values = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
values.add((Aggregation) Symbols.fromStream(in));
}
requiredGranularity = RowGranularity.fromStream(in);
}
public List<Symbol> keys() {
return keys;
}
public List<Aggregation> values() {
return values;
}
@Override
public ProjectionType projectionType() {
return ProjectionType.GROUP;
}
@Override
public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
return visitor.visitGroupProjection(this, context);
}
/**
* returns a list of outputs, with the group by keys going first,
* and the aggregations coming last
*/
@Override
public List<? extends Symbol> outputs() {
if (outputs == null) {
outputs = new ArrayList<>(keys.size() + values.size());
outputs.addAll(keys);
outputs.addAll(values);
}
return outputs;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
AggregateMode.writeTo(mode, out);
Symbols.toStream(keys, out);
Symbols.toStream(values, out);
RowGranularity.toStream(requiredGranularity, out);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), keys, values, outputs, mode, requiredGranularity);
}
@Override
public RowGranularity requiredGranularity() {
return requiredGranularity;
}
public AggregateMode mode() {
return mode;
}
@Override
public Map<String, Object> mapRepresentation() {
return MapBuilder.<String, Object>newMapBuilder()
.put("type", "HashAggregation")
.put("keys", Lists.joinOn(", ", keys, Symbol::toString))
.put("aggregations", Lists.joinOn(", ", values, Symbol::toString))
.map();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GroupProjection that = (GroupProjection) o;
return Objects.equals(keys, that.keys) &&
Objects.equals(values, that.values) &&
Objects.equals(outputs, that.outputs) &&
mode == that.mode &&
requiredGranularity == that.requiredGranularity;
| 919
| 130
| 1,049
|
<methods>public non-sealed void <init>() ,public abstract R accept(ProjectionVisitor<C,R>, C) ,public abstract boolean equals(java.lang.Object) ,public static io.crate.execution.dsl.projection.Projection fromStream(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public int hashCode() ,public Map<java.lang.String,java.lang.Object> mapRepresentation() ,public abstract List<? extends io.crate.expression.symbol.Symbol> outputs() ,public abstract io.crate.execution.dsl.projection.ProjectionType projectionType() ,public io.crate.metadata.RowGranularity requiredGranularity() ,public static void toStream(io.crate.execution.dsl.projection.Projection, org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException,public abstract void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>static final Predicate<io.crate.execution.dsl.projection.Projection> IS_NODE_PROJECTION,static final Predicate<io.crate.execution.dsl.projection.Projection> IS_SHARD_PROJECTION
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/LimitAndOffsetProjection.java
|
LimitAndOffsetProjection
|
equals
|
class LimitAndOffsetProjection extends Projection {
private final int limit;
private final int offset;
private final List<Symbol> outputs;
public LimitAndOffsetProjection(int limit, int offset, List<DataType<?>> outputTypes) {
this.limit = limit;
this.offset = offset;
this.outputs = InputColumn.mapToInputColumns(outputTypes);
}
public LimitAndOffsetProjection(StreamInput in) throws IOException {
offset = in.readVInt();
limit = in.readVInt();
outputs = Symbols.listFromStream(in);
}
@Override
public List<Symbol> outputs() {
return outputs;
}
public int limit() {
return limit;
}
public int offset() {
return offset;
}
@Override
public ProjectionType projectionType() {
return ProjectionType.LIMITANDOFFSET;
}
@Override
public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
return visitor.visitLimitAndOffsetProjection(this, context);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(offset);
out.writeVInt(limit);
Symbols.toStream(outputs, out);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = limit;
result = 31 * result + offset;
result = 31 * result + outputs.hashCode();
return result;
}
@Override
public Map<String, Object> mapRepresentation() {
return MapBuilder.<String, Object>newMapBuilder()
.put("type", "LimitAndOffset")
.put("limit", limit)
.put("offset", offset)
.put("outputs", Lists.joinOn(", ", outputs, Symbol::toString))
.map();
}
@Override
public String toString() {
return "LimitAndOffsetProjection{" +
"outputs=" + outputs +
", limit=" + limit +
", offset=" + offset +
'}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LimitAndOffsetProjection that = (LimitAndOffsetProjection) o;
if (limit != that.limit) return false;
if (offset != that.offset) return false;
if (!outputs.equals(that.outputs)) return false;
return true;
| 586
| 106
| 692
|
<methods>public non-sealed void <init>() ,public abstract R accept(ProjectionVisitor<C,R>, C) ,public abstract boolean equals(java.lang.Object) ,public static io.crate.execution.dsl.projection.Projection fromStream(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public int hashCode() ,public Map<java.lang.String,java.lang.Object> mapRepresentation() ,public abstract List<? extends io.crate.expression.symbol.Symbol> outputs() ,public abstract io.crate.execution.dsl.projection.ProjectionType projectionType() ,public io.crate.metadata.RowGranularity requiredGranularity() ,public static void toStream(io.crate.execution.dsl.projection.Projection, org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException,public abstract void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>static final Predicate<io.crate.execution.dsl.projection.Projection> IS_NODE_PROJECTION,static final Predicate<io.crate.execution.dsl.projection.Projection> IS_SHARD_PROJECTION
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/SysUpdateProjection.java
|
SysUpdateProjection
|
writeTo
|
class SysUpdateProjection extends Projection {
private final Symbol uidSymbol;
private Map<Reference, Symbol> assignments;
private Symbol[] outputs;
@Nullable
private Symbol[] returnValues;
public SysUpdateProjection(Symbol uidSymbol,
Map<Reference, Symbol> assignments,
Symbol[] outputs,
@Nullable Symbol[] returnValues
) {
this.uidSymbol = uidSymbol;
this.assignments = assignments;
this.returnValues = returnValues;
assert Arrays.stream(outputs).noneMatch(s -> SymbolVisitors.any(Symbols.IS_COLUMN.or(x -> x instanceof SelectSymbol), s))
: "Cannot operate on Reference, Field or SelectSymbol symbols: " + outputs;
this.outputs = outputs;
}
public SysUpdateProjection(StreamInput in) throws IOException {
uidSymbol = Symbols.fromStream(in);
int numAssignments = in.readVInt();
assignments = new HashMap<>(numAssignments, 1.0f);
for (int i = 0; i < numAssignments; i++) {
assignments.put(Reference.fromStream(in), Symbols.fromStream(in));
}
if (in.getVersion().onOrAfter(Version.V_4_2_0)) {
int outputSize = in.readVInt();
outputs = new Symbol[outputSize];
for (int i = 0; i < outputSize; i++) {
outputs[i] = Symbols.fromStream(in);
}
int returnValuesSize = in.readVInt();
if (returnValuesSize > 0) {
returnValues = new Symbol[returnValuesSize];
for (int i = 0; i < returnValuesSize; i++) {
returnValues[i] = Symbols.fromStream(in);
}
}
} else {
//Outputs should never be null and for BwC reasons
//the default value in pre 4.1 was a long for a count
outputs = new Symbol[]{new InputColumn(0, DataTypes.LONG)};
}
}
@Override
public ProjectionType projectionType() {
return ProjectionType.SYS_UPDATE;
}
@Nullable
public Symbol[] returnValues() {
return returnValues;
}
@Override
public List<? extends Symbol> outputs() {
return List.of(outputs);
}
@Override
public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
return visitor.visitSysUpdateProjection(this, context);
}
public Map<Reference, Symbol> assignments() {
return assignments;
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SysUpdateProjection that = (SysUpdateProjection) o;
return Objects.equals(uidSymbol, that.uidSymbol) &&
Objects.equals(assignments, that.assignments) &&
Arrays.equals(outputs, that.outputs) &&
Arrays.equals(returnValues, that.returnValues);
}
@Override
public int hashCode() {
int result = Objects.hash(super.hashCode(), uidSymbol, assignments);
result = 31 * result + Arrays.hashCode(outputs);
result = 31 * result + Arrays.hashCode(returnValues);
return result;
}
@Override
public RowGranularity requiredGranularity() {
return RowGranularity.NODE;
}
}
|
Symbols.toStream(uidSymbol, out);
out.writeVInt(assignments.size());
for (Map.Entry<Reference, Symbol> e : assignments.entrySet()) {
Reference.toStream(out, e.getKey());
Symbols.toStream(e.getValue(), out);
}
if (out.getVersion().onOrAfter(Version.V_4_2_0)) {
out.writeVInt(outputs.length);
for (int i = 0; i < outputs.length; i++) {
Symbols.toStream(outputs[i], out);
}
if (returnValues != null) {
out.writeVInt(returnValues.length);
for (int i = 0; i < returnValues.length; i++) {
Symbols.toStream(returnValues[i], out);
}
} else {
out.writeVInt(0);
}
}
| 978
| 238
| 1,216
|
<methods>public non-sealed void <init>() ,public abstract R accept(ProjectionVisitor<C,R>, C) ,public abstract boolean equals(java.lang.Object) ,public static io.crate.execution.dsl.projection.Projection fromStream(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public int hashCode() ,public Map<java.lang.String,java.lang.Object> mapRepresentation() ,public abstract List<? extends io.crate.expression.symbol.Symbol> outputs() ,public abstract io.crate.execution.dsl.projection.ProjectionType projectionType() ,public io.crate.metadata.RowGranularity requiredGranularity() ,public static void toStream(io.crate.execution.dsl.projection.Projection, org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException,public abstract void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>static final Predicate<io.crate.execution.dsl.projection.Projection> IS_NODE_PROJECTION,static final Predicate<io.crate.execution.dsl.projection.Projection> IS_SHARD_PROJECTION
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/UpdateProjection.java
|
UpdateProjection
|
equals
|
class UpdateProjection extends Projection {
final Symbol uidSymbol;
private Symbol[] assignments;
// All values of this list are expected to be a FQN columnIdent.
private String[] assignmentsColumns;
private Symbol[] outputs;
@Nullable
private Symbol[] returnValues;
@Nullable
private Long requiredVersion;
public UpdateProjection(Symbol uidSymbol,
String[] assignmentsColumns,
Symbol[] assignments,
Symbol[] outputs,
@Nullable Symbol[] returnValues,
@Nullable Long requiredVersion) {
this.uidSymbol = uidSymbol;
this.assignmentsColumns = assignmentsColumns;
this.assignments = assignments;
this.returnValues = returnValues;
assert Arrays.stream(outputs).noneMatch(s -> SymbolVisitors.any(Symbols.IS_COLUMN.or(x -> x instanceof SelectSymbol), s))
: "Cannot operate on Reference, Field or SelectSymbol symbols: " + outputs;
this.outputs = outputs;
this.requiredVersion = requiredVersion;
}
public UpdateProjection(StreamInput in) throws IOException {
uidSymbol = Symbols.fromStream(in);
int assignmentColumnsSize = in.readVInt();
assignmentsColumns = new String[assignmentColumnsSize];
for (int i = 0; i < assignmentColumnsSize; i++) {
assignmentsColumns[i] = in.readString();
}
int assignmentsSize = in.readVInt();
assignments = new Symbol[assignmentsSize];
for (int i = 0; i < assignmentsSize; i++) {
assignments[i] = Symbols.fromStream(in);
}
requiredVersion = in.readVLong();
if (requiredVersion == 0) {
requiredVersion = null;
}
if (in.getVersion().onOrAfter(Version.V_4_2_0)) {
int outputSize = in.readVInt();
outputs = new Symbol[outputSize];
for (int i = 0; i < outputSize; i++) {
outputs[i] = Symbols.fromStream(in);
}
int returnValuesSize = in.readVInt();
if (returnValuesSize > 0) {
returnValues = new Symbol[returnValuesSize];
for (int i = 0; i < returnValuesSize; i++) {
returnValues[i] = Symbols.fromStream(in);
}
}
} else {
//Outputs should never be null and for BwC reasons
//the default value in pre 4.1 was a long for a count
outputs = new Symbol[]{new InputColumn(0, DataTypes.LONG)};
}
}
public Symbol uidSymbol() {
return uidSymbol;
}
@Nullable
public Symbol[] returnValues() {
return returnValues;
}
public String[] assignmentsColumns() {
return assignmentsColumns;
}
public Symbol[] assignments() {
return assignments;
}
@Nullable
public Long requiredVersion() {
return requiredVersion;
}
@Override
public ProjectionType projectionType() {
return ProjectionType.UPDATE;
}
@Override
public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
return visitor.visitUpdateProjection(this, context);
}
@Override
public List<? extends Symbol> outputs() {
return List.of(outputs);
}
@Override
public RowGranularity requiredGranularity() {
return RowGranularity.SHARD;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + Arrays.hashCode(assignments);
result = 31 * result + Arrays.hashCode(assignmentsColumns);
result = 31 * result + (requiredVersion != null ? requiredVersion.hashCode() : 0);
result = 31 * result + uidSymbol.hashCode();
result = 31 * result + Arrays.hashCode(returnValues);
result = 31 * result + Arrays.hashCode(outputs);
return result;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
Symbols.toStream(uidSymbol, out);
out.writeVInt(assignmentsColumns.length);
for (int i = 0; i < assignmentsColumns.length; i++) {
out.writeString(assignmentsColumns[i]);
}
out.writeVInt(assignments.length);
for (int i = 0; i < assignments.length; i++) {
Symbols.toStream(assignments[i], out);
}
if (requiredVersion == null) {
out.writeVLong(0);
} else {
out.writeVLong(requiredVersion);
}
if (out.getVersion().onOrAfter(Version.V_4_2_0)) {
out.writeVInt(outputs.length);
for (int i = 0; i < outputs.length; i++) {
Symbols.toStream(outputs[i], out);
}
if (returnValues != null) {
out.writeVInt(returnValues.length);
for (int i = 0; i < returnValues.length; i++) {
Symbols.toStream(returnValues[i], out);
}
} else {
out.writeVInt(0);
}
}
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UpdateProjection that = (UpdateProjection) o;
if (!Arrays.equals(assignments, that.assignments)) return false;
if (!Arrays.equals(assignmentsColumns, that.assignmentsColumns)) return false;
if (requiredVersion != null ? !requiredVersion.equals(that.requiredVersion) : that.requiredVersion != null)
return false;
if (!uidSymbol.equals(that.uidSymbol)) return false;
if (!Arrays.equals(returnValues, that.returnValues)) return false;
if (!Arrays.equals(outputs, that.outputs)) return false;
return true;
| 1,414
| 191
| 1,605
|
<methods>public non-sealed void <init>() ,public abstract R accept(ProjectionVisitor<C,R>, C) ,public abstract boolean equals(java.lang.Object) ,public static io.crate.execution.dsl.projection.Projection fromStream(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public int hashCode() ,public Map<java.lang.String,java.lang.Object> mapRepresentation() ,public abstract List<? extends io.crate.expression.symbol.Symbol> outputs() ,public abstract io.crate.execution.dsl.projection.ProjectionType projectionType() ,public io.crate.metadata.RowGranularity requiredGranularity() ,public static void toStream(io.crate.execution.dsl.projection.Projection, org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException,public abstract void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>static final Predicate<io.crate.execution.dsl.projection.Projection> IS_NODE_PROJECTION,static final Predicate<io.crate.execution.dsl.projection.Projection> IS_SHARD_PROJECTION
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/dsl/projection/builder/SplitPointsBuilder.java
|
Context
|
create
|
class Context {
private final ArrayList<Function> aggregates = new ArrayList<>();
private final ArrayList<Function> tableFunctions = new ArrayList<>();
private final ArrayList<Symbol> standalone = new ArrayList<>();
private final ArrayList<WindowFunction> windowFunctions = new ArrayList<>();
private final ArrayList<SelectSymbol> correlatedQueries = new ArrayList<>();
/**
* OuterColumns found within a relation
* For example in
*
* <pre>
* SELECT (SELECT t.mountain) FROM sys.summits t
* </pre>
*
* This would contain `t.mountain` when processing the <b>inner</b> relation.
*/
private final ArrayList<OuterColumn> outerColumns = new ArrayList<>();
private boolean insideAggregate = false;
private int tableFunctionLevel = 0;
boolean foundAggregateOrTableFunction = false;
Context() {
}
void allocateTableFunction(Function tableFunction) {
if (tableFunctions.contains(tableFunction) == false) {
tableFunctions.add(tableFunction);
}
}
void allocateAggregate(Function aggregate) {
if (aggregates.contains(aggregate) == false) {
aggregates.add(aggregate);
}
}
void allocateWindowFunction(WindowFunction windowFunction) {
if (windowFunctions.contains(windowFunction) == false) {
windowFunctions.add(windowFunction);
}
}
}
private void process(Collection<Symbol> symbols, Context context) {
for (Symbol symbol : symbols) {
process(symbol, context);
}
}
private void process(Symbol symbol, Context context) {
context.foundAggregateOrTableFunction = false;
symbol.accept(this, context);
if (context.foundAggregateOrTableFunction == false) {
context.standalone.add(symbol);
}
}
public static SplitPoints create(QueriedSelectRelation relation) {<FILL_FUNCTION_BODY>
|
Context context = new Context();
INSTANCE.process(relation.outputs(), context);
OrderBy orderBy = relation.orderBy();
if (orderBy != null) {
INSTANCE.process(orderBy.orderBySymbols(), context);
}
Symbol having = relation.having();
if (having != null) {
having.accept(INSTANCE, context);
}
for (var joinPair : relation.joinPairs()) {
Symbol condition = joinPair.condition();
if (condition != null) {
INSTANCE.process(condition, context);
}
}
Symbol where = relation.where();
where.accept(INSTANCE, context);
LinkedHashSet<Symbol> toCollect = new LinkedHashSet<>();
for (Function tableFunction : context.tableFunctions) {
toCollect.addAll(extractColumns(tableFunction.arguments()));
}
for (Function aggregate : context.aggregates) {
toCollect.addAll(aggregate.arguments());
if (aggregate.filter() != null) {
toCollect.add(aggregate.filter());
}
}
for (WindowFunction windowFunction : context.windowFunctions) {
toCollect.addAll(extractColumns(windowFunction.arguments()));
if (windowFunction.filter() != null) {
toCollect.add(windowFunction.filter());
}
INSTANCE.process(windowFunction.windowDefinition().partitions(), context);
OrderBy windowOrderBy = windowFunction.windowDefinition().orderBy();
if (windowOrderBy != null) {
INSTANCE.process(windowOrderBy.orderBySymbols(), context);
}
}
// group-by symbols must be processed on a dedicated context to be able extract table functions which must
// be processed *below* a grouping operator
var groupByContext = new Context();
if (relation.groupBy().isEmpty() == false) {
INSTANCE.process(relation.groupBy(), groupByContext);
for (Function tableFunction : groupByContext.tableFunctions) {
toCollect.addAll(extractColumns(tableFunction.arguments()));
}
toCollect.addAll(groupByContext.standalone);
context.tableFunctions.removeAll(groupByContext.tableFunctions);
} else if (context.aggregates.isEmpty() && relation.groupBy().isEmpty()) {
toCollect.addAll(context.standalone);
}
var collectOuterColumns = new DefaultTraversalSymbolVisitor<Void, Void>() {
public Void visitOuterColumn(OuterColumn outerColumn, Void ignored) {
toCollect.add(outerColumn.symbol());
return null;
}
};
for (var selectSymbol : context.correlatedQueries) {
selectSymbol.relation().visitSymbols(symbol -> symbol.accept(collectOuterColumns, null));
}
RefVisitor.visitRefs(where, toCollect::add);
FieldsVisitor.visitFields(where, toCollect::add);
ArrayList<Symbol> outputs = new ArrayList<>();
for (var output : toCollect) {
if (Symbols.containsCorrelatedSubQuery(output)) {
outputs.addAll(extractColumns(output));
} else {
outputs.add(output);
}
}
return new SplitPoints(
outputs,
context.outerColumns,
context.aggregates,
context.tableFunctions,
groupByContext.tableFunctions,
context.windowFunctions
);
| 518
| 890
| 1,408
|
<methods>public non-sealed void <init>() ,public java.lang.Void visitAlias(io.crate.expression.symbol.AliasSymbol, io.crate.execution.dsl.projection.builder.SplitPointsBuilder.Context) ,public java.lang.Void visitFetchReference(io.crate.expression.symbol.FetchReference, io.crate.execution.dsl.projection.builder.SplitPointsBuilder.Context) ,public java.lang.Void visitFunction(io.crate.expression.symbol.Function, io.crate.execution.dsl.projection.builder.SplitPointsBuilder.Context) ,public java.lang.Void visitMatchPredicate(io.crate.expression.symbol.MatchPredicate, io.crate.execution.dsl.projection.builder.SplitPointsBuilder.Context) ,public java.lang.Void visitWindowFunction(io.crate.expression.symbol.WindowFunction, io.crate.execution.dsl.projection.builder.SplitPointsBuilder.Context) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/PagingUnsupportedResultListener.java
|
PagingUnsupportedResultListener
|
needMore
|
class PagingUnsupportedResultListener implements PageResultListener {
static final PagingUnsupportedResultListener INSTANCE = new PagingUnsupportedResultListener();
private PagingUnsupportedResultListener() {
}
@Override
public void needMore(boolean needMore) {<FILL_FUNCTION_BODY>}
}
|
if (needMore) {
throw new IllegalStateException(
"A downstream requested more data from an upstream, but that is not supported in direct-response mode");
}
| 82
| 47
| 129
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/Aggregations.java
|
Aggregations
|
addFunctions
|
class Aggregations implements FunctionsProvider {
@Override
public void addFunctions(Settings settings,
SessionSettingRegistry sessionSettingRegistry,
Builder builder) {<FILL_FUNCTION_BODY>}
}
|
AverageAggregation.register(builder);
NumericAverageAggregation.register(builder);
IntervalAverageAggregation.register(builder);
MinimumAggregation.register(builder);
MaximumAggregation.register(builder);
ArbitraryAggregation.register(builder);
CmpByAggregation.register(builder);
IntervalSumAggregation.register(builder);
SumAggregation.register(builder);
NumericSumAggregation.register(builder);
CountAggregation.register(builder);
CollectSetAggregation.register(builder);
PercentileAggregation.register(builder);
StringAgg.register(builder);
ArrayAgg.register(builder);
VarianceAggregation.register(builder);
GeometricMeanAggregation.register(builder);
StandardDeviationAggregation.register(builder);
| 55
| 214
| 269
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/MaximumAggregation.java
|
FixedMaximumAggregation
|
reduce
|
class FixedMaximumAggregation extends MaximumAggregation {
private final int size;
public FixedMaximumAggregation(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
size = ((FixedWidthType) partialType()).fixedSize();
}
@Nullable
@Override
public DocValueAggregator<?> getDocValueAggregator(LuceneReferenceResolver referenceResolver,
List<Reference> aggregationReferences,
DocTableInfo table,
List<Literal<?>> optionalParams) {
Reference reference = aggregationReferences.get(0);
if (!reference.hasDocValues()) {
return null;
}
DataType<?> arg = reference.valueType();
switch (arg.id()) {
case ByteType.ID:
case ShortType.ID:
case IntegerType.ID:
case LongType.ID:
case TimestampType.ID_WITH_TZ:
case TimestampType.ID_WITHOUT_TZ:
return new LongMax(reference.storageIdent(), arg);
case FloatType.ID:
return new FloatMax(reference.storageIdent());
case DoubleType.ID:
return new DoubleMax(reference.storageIdent());
default:
return null;
}
}
@Nullable
@Override
public Object newState(RamAccounting ramAccounting,
Version indexVersionCreated,
Version minNodeInCluster,
MemoryManager memoryManager) {
ramAccounting.addBytes(size);
return null;
}
@Override
public Object reduce(RamAccounting ramAccounting, Object state1, Object state2) {<FILL_FUNCTION_BODY>}
}
|
if (state1 == null) {
return state2;
}
if (state2 == null) {
return state1;
}
int cmp = type.compare(state1, state2);
if (cmp < 0) {
return state2;
}
return state1;
| 432
| 82
| 514
|
<methods>public non-sealed void <init>() ,public DocValueAggregator<?> getDocValueAggregator(io.crate.expression.reference.doc.lucene.LuceneReferenceResolver, List<io.crate.metadata.Reference>, io.crate.metadata.doc.DocTableInfo, List<Literal<?>>) ,public boolean isRemovableCumulative() ,public transient abstract java.lang.Object iterate(io.crate.data.breaker.RamAccounting, io.crate.memory.MemoryManager, java.lang.Object, Input<?>[]) throws org.elasticsearch.common.breaker.CircuitBreakingException,public abstract java.lang.Object newState(io.crate.data.breaker.RamAccounting, org.elasticsearch.Version, org.elasticsearch.Version, io.crate.memory.MemoryManager) ,public AggregationFunction<?,java.lang.Object> optimizeForExecutionAsWindowFunction() ,public abstract DataType<?> partialType() ,public abstract java.lang.Object reduce(io.crate.data.breaker.RamAccounting, java.lang.Object, java.lang.Object) ,public java.lang.Object removeFromAggregatedState(io.crate.data.breaker.RamAccounting, java.lang.Object, Input<?>[]) ,public abstract java.lang.Object terminatePartial(io.crate.data.breaker.RamAccounting, java.lang.Object) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/StandardDeviationAggregation.java
|
StdDevStateType
|
iterate
|
class StdDevStateType extends DataType<StandardDeviation> implements Streamer<StandardDeviation>, FixedWidthType {
public static final StdDevStateType INSTANCE = new StdDevStateType();
public static final int ID = 8192;
@Override
public int id() {
return ID;
}
@Override
public Precedence precedence() {
return Precedence.CUSTOM;
}
@Override
public String getName() {
return "stddev_state";
}
@Override
public Streamer<StandardDeviation> streamer() {
return this;
}
@Override
public StandardDeviation sanitizeValue(Object value) {
return (StandardDeviation) value;
}
@Override
public int compare(StandardDeviation val1, StandardDeviation val2) {
return val1.compareTo(val2);
}
@Override
public int fixedSize() {
return 56;
}
@Override
public StandardDeviation readValueFrom(StreamInput in) throws IOException {
return new StandardDeviation(in);
}
@Override
public void writeValueTo(StreamOutput out, StandardDeviation v) throws IOException {
v.writeTo(out);
}
@Override
public long valueBytes(StandardDeviation value) {
return fixedSize();
}
}
private final Signature signature;
private final BoundSignature boundSignature;
public StandardDeviationAggregation(Signature signature, BoundSignature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
}
@Override
public Signature signature() {
return signature;
}
@Override
public BoundSignature boundSignature() {
return boundSignature;
}
@Nullable
@Override
public StandardDeviation newState(RamAccounting ramAccounting,
Version indexVersionCreated,
Version minNodeInCluster,
MemoryManager memoryManager) {
ramAccounting.addBytes(StdDevStateType.INSTANCE.fixedSize());
return new StandardDeviation();
}
@Override
public StandardDeviation iterate(RamAccounting ramAccounting,
MemoryManager memoryManager,
StandardDeviation state,
Input<?>... args) throws CircuitBreakingException {<FILL_FUNCTION_BODY>
|
if (state != null) {
Number value = (Number) args[0].value();
if (value != null) {
state.increment(value.doubleValue());
}
}
return state;
| 609
| 60
| 669
|
<methods>public non-sealed void <init>() ,public DocValueAggregator<?> getDocValueAggregator(io.crate.expression.reference.doc.lucene.LuceneReferenceResolver, List<io.crate.metadata.Reference>, io.crate.metadata.doc.DocTableInfo, List<Literal<?>>) ,public boolean isRemovableCumulative() ,public transient abstract io.crate.execution.engine.aggregation.statistics.StandardDeviation iterate(io.crate.data.breaker.RamAccounting, io.crate.memory.MemoryManager, io.crate.execution.engine.aggregation.statistics.StandardDeviation, Input<?>[]) throws org.elasticsearch.common.breaker.CircuitBreakingException,public abstract io.crate.execution.engine.aggregation.statistics.StandardDeviation newState(io.crate.data.breaker.RamAccounting, org.elasticsearch.Version, org.elasticsearch.Version, io.crate.memory.MemoryManager) ,public AggregationFunction<?,java.lang.Double> optimizeForExecutionAsWindowFunction() ,public abstract DataType<?> partialType() ,public abstract io.crate.execution.engine.aggregation.statistics.StandardDeviation reduce(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.statistics.StandardDeviation, io.crate.execution.engine.aggregation.statistics.StandardDeviation) ,public io.crate.execution.engine.aggregation.statistics.StandardDeviation removeFromAggregatedState(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.statistics.StandardDeviation, Input<?>[]) ,public abstract java.lang.Double terminatePartial(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.statistics.StandardDeviation) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/StringAgg.java
|
StringAggStateType
|
removeFromAggregatedState
|
class StringAggStateType extends DataType<StringAggState> implements Streamer<StringAggState> {
static final StringAggStateType INSTANCE = new StringAggStateType();
@Override
public int id() {
return 1025;
}
@Override
public Precedence precedence() {
return Precedence.CUSTOM;
}
@Override
public String getName() {
return "string_list";
}
@Override
public Streamer<StringAggState> streamer() {
return this;
}
@Override
public StringAggState sanitizeValue(Object value) {
return (StringAggState) value;
}
@Override
public int compare(StringAggState val1, StringAggState val2) {
return 0;
}
@Override
public StringAggState readValueFrom(StreamInput in) throws IOException {
return new StringAggState(in);
}
@Override
public void writeValueTo(StreamOutput out, StringAggState val) throws IOException {
val.writeTo(out);
}
@Override
public long valueBytes(StringAggState value) {
throw new UnsupportedOperationException("valueSize is not implemented for StringAggStateType");
}
}
private final Signature signature;
private final BoundSignature boundSignature;
public StringAgg(Signature signature, BoundSignature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
}
@Override
public StringAggState newState(RamAccounting ramAccounting,
Version indexVersionCreated,
Version minNodeInCluster,
MemoryManager memoryManager) {
return new StringAggState();
}
@Override
public StringAggState iterate(RamAccounting ramAccounting,
MemoryManager memoryManager,
StringAggState state,
Input<?>... args) throws CircuitBreakingException {
String expression = (String) args[0].value();
if (expression == null) {
return state;
}
ramAccounting.addBytes(LIST_ENTRY_OVERHEAD + RamUsageEstimator.sizeOf(expression));
String delimiter = (String) args[1].value();
if (delimiter != null) {
if (state.firstDelimiter == null && state.values.isEmpty()) {
state.firstDelimiter = delimiter;
} else {
ramAccounting.addBytes(LIST_ENTRY_OVERHEAD + RamUsageEstimator.sizeOf(delimiter));
state.values.add(delimiter);
}
}
state.values.add(expression);
return state;
}
@Override
public boolean isRemovableCumulative() {
return true;
}
@Override
public StringAggState removeFromAggregatedState(RamAccounting ramAccounting,
StringAggState previousAggState,
Input<?>[]stateToRemove) {<FILL_FUNCTION_BODY>
|
String expression = (String) stateToRemove[0].value();
if (expression == null) {
return previousAggState;
}
String delimiter = (String) stateToRemove[1].value();
int indexOfExpression = previousAggState.values.indexOf(expression);
if (indexOfExpression > -1) {
ramAccounting.addBytes(-LIST_ENTRY_OVERHEAD + RamUsageEstimator.sizeOf(expression));
if (delimiter != null) {
String elementNextToExpression = previousAggState.values.get(indexOfExpression + 1);
if (elementNextToExpression.equalsIgnoreCase(delimiter)) {
previousAggState.values.remove(indexOfExpression + 1);
}
}
previousAggState.values.remove(indexOfExpression);
}
return previousAggState;
| 793
| 215
| 1,008
|
<methods>public non-sealed void <init>() ,public DocValueAggregator<?> getDocValueAggregator(io.crate.expression.reference.doc.lucene.LuceneReferenceResolver, List<io.crate.metadata.Reference>, io.crate.metadata.doc.DocTableInfo, List<Literal<?>>) ,public boolean isRemovableCumulative() ,public transient abstract io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState iterate(io.crate.data.breaker.RamAccounting, io.crate.memory.MemoryManager, io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState, Input<?>[]) throws org.elasticsearch.common.breaker.CircuitBreakingException,public abstract io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState newState(io.crate.data.breaker.RamAccounting, org.elasticsearch.Version, org.elasticsearch.Version, io.crate.memory.MemoryManager) ,public AggregationFunction<?,java.lang.String> optimizeForExecutionAsWindowFunction() ,public abstract DataType<?> partialType() ,public abstract io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState reduce(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState, io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState) ,public io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState removeFromAggregatedState(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState, Input<?>[]) ,public abstract java.lang.String terminatePartial(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.StringAgg.StringAggState) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/TDigestState.java
|
TDigestState
|
read
|
class TDigestState extends AVLTreeDigest {
public static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(TDigestState.class);
private static final int DEFAULT_COMPRESSION = 100;
private final double compression;
private double[] fractions;
TDigestState(double compression, double[] fractions) {
super(compression);
this.compression = compression;
this.fractions = fractions;
}
static TDigestState createEmptyState() {
return new TDigestState(DEFAULT_COMPRESSION, new double[]{});
}
boolean isEmpty() {
return fractions.length == 0;
}
@Override
public double compression() {
return compression;
}
double[] fractions() {
return fractions;
}
void fractions(double[] fractions) {
this.fractions = fractions;
}
public static void write(TDigestState state, StreamOutput out) throws IOException {
out.writeDouble(state.compression);
out.writeDoubleArray(state.fractions);
out.writeVInt(state.centroidCount());
for (Centroid centroid : state.centroids()) {
out.writeDouble(centroid.mean());
out.writeVLong(centroid.count());
}
}
public static TDigestState read(StreamInput in) throws IOException {<FILL_FUNCTION_BODY>}
}
|
double compression = in.readDouble();
double[] fractions = in.readDoubleArray();
TDigestState state = new TDigestState(compression, fractions);
int n = in.readVInt();
for (int i = 0; i < n; i++) {
state.add(in.readDouble(), in.readVInt());
}
return state;
| 382
| 99
| 481
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/average/AverageAggregation.java
|
AverageState
|
compareTo
|
class AverageState implements Comparable<AverageState> {
private double sum = 0;
private long count = 0;
private final KahanSummationForDouble kahanSummationForDouble = new KahanSummationForDouble();
public Double value() {
if (count > 0) {
return sum / count;
} else {
return null;
}
}
public void addNumber(double number, boolean isIntegral) {
this.sum = isIntegral ? this.sum + number : kahanSummationForDouble.sum(this.sum, number);
this.count++;
}
public void removeNumber(double number, boolean isIntegral) {
this.sum = isIntegral ? this.sum - number : kahanSummationForDouble.sum(this.sum, -number);
this.count--;
}
public void reduce(@NotNull AverageState other, boolean isIntegral) {
this.count += other.count;
this.sum = isIntegral ? this.sum + other.sum : kahanSummationForDouble.sum(this.sum, other.sum);
}
@Override
public int compareTo(AverageState o) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "sum: " + sum + " count: " + count;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AverageState that = (AverageState) o;
return Objects.equals(that.value(), value());
}
@Override
public int hashCode() {
return Objects.hash(value());
}
}
|
if (o == null) {
return 1;
} else {
int compare = Double.compare(sum, o.sum);
if (compare == 0) {
return Long.compare(count, o.count);
}
return compare;
}
| 469
| 71
| 540
|
<methods>public non-sealed void <init>() ,public DocValueAggregator<?> getDocValueAggregator(io.crate.expression.reference.doc.lucene.LuceneReferenceResolver, List<io.crate.metadata.Reference>, io.crate.metadata.doc.DocTableInfo, List<Literal<?>>) ,public boolean isRemovableCumulative() ,public transient abstract io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState iterate(io.crate.data.breaker.RamAccounting, io.crate.memory.MemoryManager, io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState, Input<?>[]) throws org.elasticsearch.common.breaker.CircuitBreakingException,public abstract io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState newState(io.crate.data.breaker.RamAccounting, org.elasticsearch.Version, org.elasticsearch.Version, io.crate.memory.MemoryManager) ,public AggregationFunction<?,java.lang.Double> optimizeForExecutionAsWindowFunction() ,public abstract DataType<?> partialType() ,public abstract io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState reduce(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState, io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState) ,public io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState removeFromAggregatedState(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState, Input<?>[]) ,public abstract java.lang.Double terminatePartial(io.crate.data.breaker.RamAccounting, io.crate.execution.engine.aggregation.impl.average.AverageAggregation.AverageState) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/average/numeric/NumericAverageStateType.java
|
NumericAverageStateType
|
writeValueTo
|
class NumericAverageStateType extends DataType<NumericAverageState> implements Streamer<NumericAverageState> {
public static final int ID = 1026;
public static final long INIT_SIZE = NumericType.size(BigDecimal.ZERO) + 8; // Nominator and primitive long denominator.
public static final NumericAverageStateType INSTANCE = new NumericAverageStateType();
@Override
public int id() {
return ID;
}
@Override
public Precedence precedence() {
return Precedence.CUSTOM;
}
@Override
public String getName() {
return "numeric_average_state";
}
@Override
public Streamer<NumericAverageState> streamer() {
return this;
}
@Override
public NumericAverageState sanitizeValue(Object value) {
return (NumericAverageState) value;
}
@Override
public int compare(NumericAverageState val1, NumericAverageState val2) {
if (val1 == null) return -1;
return val1.compareTo(val2);
}
@Override
public NumericAverageState readValueFrom(StreamInput in) throws IOException {
// Cannot use NumericType.INSTANCE as it has default precision and scale values
// which might not be equal to written BigDecimal's precision and scale.
return new NumericAverageState<>(
new BigDecimalValueWrapper(NumericType.of(in.readInt(), in.readInt()).readValueFrom(in)),
in.readVLong()
);
}
@Override
public void writeValueTo(StreamOutput out, NumericAverageState v) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public long valueBytes(NumericAverageState value) {
throw new UnsupportedOperationException("valueSize is not implemented on NumericAverageStateType");
}
}
|
// We want to preserve the scale and precision
// from the numeric argument type for the return type.
out.writeInt(v.sum.value().precision());
out.writeInt(v.sum.value().scale());
NumericType.INSTANCE.writeValueTo(out, v.sum.value()); // NumericType.INSTANCE writes unscaled value
out.writeVLong(v.count);
| 518
| 106
| 624
|
<methods>public non-sealed void <init>() ,public void addMappingOptions(Map<java.lang.String,java.lang.Object>) ,public java.lang.Integer characterMaximumLength() ,public ColumnStatsSupport<NumericAverageState#RAW> columnStatsSupport() ,public int compareTo(DataType<?>) ,public boolean equals(java.lang.Object) ,public NumericAverageState#RAW explicitCast(java.lang.Object, io.crate.metadata.settings.SessionSettings) throws java.lang.IllegalArgumentException, java.lang.ClassCastException,public abstract java.lang.String getName() ,public List<DataType<?>> getTypeParameters() ,public io.crate.types.TypeSignature getTypeSignature() ,public int hashCode() ,public abstract int id() ,public NumericAverageState#RAW implicitCast(java.lang.Object) throws java.lang.IllegalArgumentException, java.lang.ClassCastException,public boolean isConvertableTo(DataType<?>, boolean) ,public java.lang.Integer numericPrecision() ,public abstract io.crate.types.DataType.Precedence precedence() ,public boolean precedes(DataType<?>) ,public long ramBytesUsed() ,public abstract NumericAverageState#RAW sanitizeValue(java.lang.Object) ,public StorageSupport<? super NumericAverageState#RAW> storageSupport() ,public final StorageSupport<? super NumericAverageState#RAW> storageSupportSafe() ,public abstract Streamer<NumericAverageState#RAW> streamer() ,public ColumnType<io.crate.sql.tree.Expression> toColumnType(io.crate.sql.tree.ColumnPolicy, Supplier<List<ColumnDefinition<io.crate.sql.tree.Expression>>>) ,public java.lang.String toString() ,public abstract long valueBytes(NumericAverageState#RAW) ,public NumericAverageState#RAW valueForInsert(NumericAverageState#RAW) ,public final ValueIndexer<? super NumericAverageState#RAW> valueIndexer(io.crate.metadata.RelationName, io.crate.metadata.Reference, Function<java.lang.String,FieldType>, Function<io.crate.metadata.ColumnIdent,io.crate.metadata.Reference>) ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/impl/templates/SortedNumericDocValueAggregator.java
|
SortedNumericDocValueAggregator
|
apply
|
class SortedNumericDocValueAggregator<T> implements DocValueAggregator<T> {
private final String columnName;
private final TriFunction<RamAccounting, MemoryManager, Version, T> stateInitializer;
private final CheckedBiConsumer<SortedNumericDocValues, T, IOException> docValuesConsumer;
private SortedNumericDocValues values;
public SortedNumericDocValueAggregator(String columnName,
TriFunction<RamAccounting, MemoryManager,Version, T> stateInitializer,
CheckedBiConsumer<SortedNumericDocValues, T, IOException> docValuesConsumer) {
this.columnName = columnName;
this.stateInitializer = stateInitializer;
this.docValuesConsumer = docValuesConsumer;
}
@Override
public T initialState(RamAccounting ramAccounting, MemoryManager memoryManager, Version version) {
return stateInitializer.apply(ramAccounting, memoryManager, version);
}
@Override
public void loadDocValues(LeafReaderContext reader) throws IOException {
values = DocValues.getSortedNumeric(reader.reader(), columnName);
}
@Override
public void apply(RamAccounting ramAccounting, int doc, T state) throws IOException {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public Object partialResult(RamAccounting ramAccounting, T state) {
return state;
}
}
|
if (values.advanceExact(doc) && values.docValueCount() == 1) {
docValuesConsumer.accept(values, state);
}
| 363
| 42
| 405
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/aggregation/statistics/Variance.java
|
Variance
|
merge
|
class Variance implements Writeable, Comparable<Variance> {
private double sumOfSqrs;
private double sum;
private long count;
public Variance() {
sumOfSqrs = 0.0;
sum = 0.0;
count = 0;
}
public Variance(StreamInput in) throws IOException {
sumOfSqrs = in.readDouble();
sum = in.readDouble();
count = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(sumOfSqrs);
out.writeDouble(sum);
out.writeVLong(count);
}
public void increment(double value) {
sumOfSqrs += (value * value);
sum += value;
count++;
}
public void decrement(double value) {
sumOfSqrs -= (value * value);
sum -= value;
count--;
}
public double result() {
if (count == 0) {
return Double.NaN;
}
return (sumOfSqrs - ((sum * sum) / count)) / count;
}
public void merge(Variance other) {<FILL_FUNCTION_BODY>}
@Override
public int compareTo(Variance o) {
return Double.compare(result(), o.result());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Variance variance = (Variance) o;
return Objects.equals(variance.result(), result());
}
@Override
public int hashCode() {
return Objects.hash(result());
}
}
|
sumOfSqrs += other.sumOfSqrs;
sum += other.sum;
count += other.count;
| 484
| 35
| 519
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/BlobShardCollectorProvider.java
|
BlobShardCollectorProvider
|
getOrderedCollector
|
class BlobShardCollectorProvider extends ShardCollectorProvider {
private final BlobShard blobShard;
private final InputFactory inputFactory;
public BlobShardCollectorProvider(BlobShard blobShard,
ClusterService clusterService,
Schemas schemas,
NodeLimits nodeJobsCounter,
CircuitBreakerService circuitBreakerService,
NodeContext nodeCtx,
ThreadPool threadPool,
Settings settings,
ElasticsearchClient elasticsearchClient,
Map<String, FileOutputFactory> fileOutputFactoryMap) {
super(
clusterService,
circuitBreakerService,
schemas,
nodeJobsCounter,
nodeCtx,
threadPool,
settings,
elasticsearchClient,
blobShard.indexShard(),
new ShardRowContext(blobShard, clusterService),
fileOutputFactoryMap
);
inputFactory = new InputFactory(nodeCtx);
this.blobShard = blobShard;
}
@Nullable
@Override
protected BatchIterator<Row> getProjectionFusedIterator(RoutedCollectPhase normalizedPhase, CollectTask collectTask) {
return null;
}
@Override
protected BatchIterator<Row> getUnorderedIterator(RoutedCollectPhase collectPhase,
boolean requiresScroll,
CollectTask collectTask) {
return InMemoryBatchIterator.of(getBlobRows(collectTask.txnCtx(), collectPhase, requiresScroll), SentinelRow.SENTINEL,
true);
}
private Iterable<Row> getBlobRows(TransactionContext txnCtx, RoutedCollectPhase collectPhase, boolean requiresRepeat) {
Iterable<File> files = blobShard.blobContainer().getFiles();
Iterable<Row> rows = RowsTransformer.toRowsIterable(txnCtx, inputFactory, BlobReferenceResolver.INSTANCE, collectPhase, files);
if (requiresRepeat) {
return Lists.of(rows);
}
return rows;
}
public OrderedDocCollector getOrderedCollector(RoutedCollectPhase collectPhase,
SharedShardContext sharedShardContext,
CollectTask collectTask,
boolean requiresRepeat) {<FILL_FUNCTION_BODY>}
}
|
RoutedCollectPhase normalizedCollectPhase = collectPhase.normalize(shardNormalizer, collectTask.txnCtx());
return new BlobOrderedDocCollector(
blobShard.indexShard().shardId(),
getBlobRows(collectTask.txnCtx(), normalizedCollectPhase, requiresRepeat));
| 594
| 87
| 681
|
<methods>public CompletableFuture<io.crate.execution.engine.collect.ShardCollectorProvider.BatchIteratorFactory> awaitShardSearchActive() ,public io.crate.execution.engine.pipeline.ProjectorFactory getProjectorFactory() ,public io.crate.expression.reference.sys.shard.ShardRowContext shardRowContext() <variables>private final non-sealed io.crate.execution.engine.collect.ShardCollectorProvider.BatchIteratorFactory batchIteratorFactory,protected final non-sealed org.elasticsearch.index.shard.IndexShard indexShard,private final non-sealed io.crate.execution.engine.pipeline.ProjectorFactory projectorFactory,protected final non-sealed io.crate.metadata.Schemas schemas,final non-sealed io.crate.expression.eval.EvaluatingNormalizer shardNormalizer,private final non-sealed io.crate.expression.reference.sys.shard.ShardRowContext shardRowContext
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/PKLookupOperation.java
|
PKLookupOperation
|
lookup
|
class PKLookupOperation {
private final IndicesService indicesService;
private final ShardCollectSource shardCollectSource;
public PKLookupOperation(IndicesService indicesService, ShardCollectSource shardCollectSource) {
this.indicesService = indicesService;
this.shardCollectSource = shardCollectSource;
}
@Nullable
public static Doc lookupDoc(IndexShard shard,
String id,
long version,
VersionType versionType,
long seqNo,
long primaryTerm,
@Nullable SourceParser sourceParser) {
Term uidTerm = new Term(IdFieldMapper.NAME, Uid.encodeId(id));
Engine.Get get = new Engine.Get(id, uidTerm)
.version(version)
.versionType(versionType)
.setIfSeqNo(seqNo)
.setIfPrimaryTerm(primaryTerm);
try (Engine.GetResult getResult = shard.get(get)) {
var docIdAndVersion = getResult.docIdAndVersion();
if (docIdAndVersion == null) {
return null;
}
SourceFieldVisitor visitor = new SourceFieldVisitor();
try {
StoredFields storedFields = docIdAndVersion.reader.storedFields();
storedFields.document(docIdAndVersion.docId, visitor);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Map<String, Object> sourceMap;
if (sourceParser == null) {
sourceMap = Map.of();
} else {
sourceMap = sourceParser.parse(visitor.source());
}
return new Doc(
docIdAndVersion.docId,
shard.shardId().getIndexName(),
id,
docIdAndVersion.version,
docIdAndVersion.seqNo,
docIdAndVersion.primaryTerm,
sourceMap,
() -> visitor.source().utf8ToString()
);
}
}
public BatchIterator<Row> lookup(UUID jobId,
TransactionContext txnCtx,
Supplier<RamAccounting> ramAccountingSupplier,
Supplier<MemoryManager> memoryManagerSupplier,
boolean ignoreMissing,
Map<ShardId, List<PKAndVersion>> idsByShard,
Collection<? extends Projection> projections,
boolean requiresScroll,
Function<Doc, Row> resultToRow,
SourceParser sourceParser) {<FILL_FUNCTION_BODY>}
}
|
ArrayList<BatchIterator<Row>> iterators = new ArrayList<>(idsByShard.size());
for (Map.Entry<ShardId, List<PKAndVersion>> idsByShardEntry : idsByShard.entrySet()) {
ShardId shardId = idsByShardEntry.getKey();
IndexService indexService = indicesService.indexService(shardId.getIndex());
if (indexService == null) {
if (ignoreMissing) {
continue;
}
throw new IndexNotFoundException(shardId.getIndex());
}
IndexShard shard = indexService.getShardOrNull(shardId.id());
if (shard == null) {
if (ignoreMissing) {
continue;
}
throw new ShardNotFoundException(shardId);
}
Stream<Row> rowStream = idsByShardEntry.getValue().stream()
.map(pkAndVersion -> lookupDoc(
shard,
pkAndVersion.id(),
pkAndVersion.version(),
VersionType.EXTERNAL,
pkAndVersion.seqNo(),
pkAndVersion.primaryTerm(),
sourceParser
))
.filter(Objects::nonNull)
.map(resultToRow);
if (projections.isEmpty()) {
final Iterable<Row> rowIterable = requiresScroll
? rowStream.map(row -> new RowN(row.materialize())).collect(Collectors.toList())
: rowStream::iterator;
iterators.add(InMemoryBatchIterator.of(rowIterable, SentinelRow.SENTINEL, true));
} else {
ProjectorFactory projectorFactory;
try {
projectorFactory = shardCollectSource.getProjectorFactory(shardId);
} catch (ShardNotFoundException e) {
if (ignoreMissing) {
continue;
}
throw e;
}
Projectors projectors = new Projectors(
projections,
jobId,
txnCtx,
ramAccountingSupplier.get(),
memoryManagerSupplier.get(),
projectorFactory);
final Iterable<Row> rowIterable = requiresScroll && !projectors.providesIndependentScroll()
? rowStream.map(row -> new RowN(row.materialize())).collect(Collectors.toList())
: rowStream::iterator;
iterators.add(projectors.wrap(InMemoryBatchIterator.of(rowIterable, SentinelRow.SENTINEL, true)));
}
}
return CompositeBatchIterator.seqComposite(iterators);
| 632
| 655
| 1,287
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/RemoteCollectorFactory.java
|
RemoteCollectorFactory
|
createCollector
|
class RemoteCollectorFactory {
private static final Logger LOGGER = LogManager.getLogger(RemoteCollectorFactory.class);
private static final int SENDER_PHASE_ID = 0;
private final ClusterService clusterService;
private final TasksService tasksService;
private final ElasticsearchClient elasticsearchClient;
private final IndicesService indicesService;
private final Executor searchTp;
@Inject
public RemoteCollectorFactory(ClusterService clusterService,
TasksService tasksService,
Node node,
IndicesService indicesService,
ThreadPool threadPool) {
this.clusterService = clusterService;
this.tasksService = tasksService;
this.elasticsearchClient = node.client();
this.indicesService = indicesService;
searchTp = threadPool.executor(ThreadPool.Names.SEARCH);
}
/**
* create a RemoteCollector
* The RemoteCollector will collect data from another node using a wormhole as if it was collecting on this node.
* <p>
* This should only be used if a shard is not available on the current node due to a relocation
*/
public CompletableFuture<BatchIterator<Row>> createCollector(ShardId shardId,
RoutedCollectPhase collectPhase,
CollectTask collectTask,
ShardCollectorProviderFactory shardCollectorProviderFactory,
boolean requiresScroll) {<FILL_FUNCTION_BODY>}
private CompletableFuture<BatchIterator<Row>> localOrRemoteCollect(
ShardRouting primaryRouting,
RoutedCollectPhase collectPhase,
CollectTask collectTask,
ShardCollectorProviderFactory collectorFactory,
boolean requiresScroll) {
String nodeId = primaryRouting.currentNodeId();
String localNodeId = clusterService.localNode().getId();
if (localNodeId.equalsIgnoreCase(nodeId)) {
var indexShard = indicesService.indexServiceSafe(primaryRouting.index())
.getShard(primaryRouting.shardId().id());
var collectorProvider = collectorFactory.create(indexShard);
try {
return collectorProvider.awaitShardSearchActive().thenApply(
biFactory -> biFactory.getIterator(collectPhase, requiresScroll, collectTask));
} catch (Exception e) {
throw Exceptions.toRuntimeException(e);
}
} else {
return remoteBatchIterator(primaryRouting, collectPhase, collectTask, requiresScroll);
}
}
private CompletableFuture<BatchIterator<Row>> remoteBatchIterator(ShardRouting primaryRouting,
RoutedCollectPhase collectPhase,
CollectTask collectTask,
boolean requiresScroll) {
CapturingRowConsumer consumer = new CapturingRowConsumer(requiresScroll, collectTask.completionFuture());
String remoteNodeId = primaryRouting.currentNodeId();
String localNodeId = clusterService.localNode().getId();
UUID childJobId = UUIDs.dirtyUUID();
LOGGER.trace(
"Creating child remote collect with id={} for parent job={}",
childJobId,
collectPhase.jobId()
);
RemoteCollector remoteCollector = new RemoteCollector(
childJobId,
collectTask.txnCtx().sessionSettings(),
localNodeId,
remoteNodeId,
req -> elasticsearchClient.execute(JobAction.INSTANCE, req),
req -> elasticsearchClient.execute(KillJobsNodeAction.INSTANCE, req),
searchTp,
tasksService,
collectTask.getRamAccounting(),
consumer,
createRemoteCollectPhase(childJobId, collectPhase, primaryRouting.shardId(), remoteNodeId)
);
collectTask.completionFuture().exceptionally(err -> {
remoteCollector.kill(err);
consumer.capturedBatchIterator().whenComplete((bi, ignored) -> {
if (bi != null) {
bi.kill(err);
}
});
return null;
});
remoteCollector.doCollect();
return consumer.capturedBatchIterator();
}
private static RoutedCollectPhase createRemoteCollectPhase(UUID childJobId,
RoutedCollectPhase collectPhase,
ShardId shardId,
String nodeId) {
Routing routing = new Routing(
Map.of(
nodeId, Map.of(shardId.getIndexName(), IntArrayList.from(shardId.id()))
)
);
return new RoutedCollectPhase(
childJobId,
SENDER_PHASE_ID,
collectPhase.name(),
routing,
collectPhase.maxRowGranularity(),
collectPhase.toCollect(),
Projections.shardProjections(collectPhase.projections()),
collectPhase.where(),
DistributionInfo.DEFAULT_BROADCAST
);
}
}
|
ShardStateObserver shardStateObserver = new ShardStateObserver(clusterService);
return shardStateObserver.waitForActiveShard(shardId).thenCompose(primaryRouting -> localOrRemoteCollect(
primaryRouting,
collectPhase,
collectTask,
shardCollectorProviderFactory,
requiresScroll
));
| 1,247
| 89
| 1,336
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/RowCollectExpression.java
|
RowCollectExpression
|
setNextRow
|
class RowCollectExpression implements CollectExpression<Row, Object> {
private final int index;
private Object value;
public RowCollectExpression(int index) {
this.index = index;
}
@Override
public void setNextRow(Row row) {<FILL_FUNCTION_BODY>}
@Override
public Object value() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RowCollectExpression that = (RowCollectExpression) o;
if (index != that.index) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
return true;
}
@Override
public int hashCode() {
int result = index;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "RowCollectExpression{idx=" + index + '}';
}
}
|
assert row.numColumns() > index
: "Wanted to retrieve value for column at position=" + index + " from row=" + row + " but row has only " + row.numColumns() + " columns";
value = row.get(index);
| 302
| 65
| 367
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/RowShardResolver.java
|
RowShardResolver
|
setNextRow
|
class RowShardResolver {
private final Function<List<String>, String> idFunction;
private final List<Input<?>> primaryKeyInputs;
private final Input<?> routingInput;
private final Iterable<CollectExpression<Row, ?>> expressions;
private String id;
private String routing;
private List<String> pkValues;
private long autoGeneratedTimestamp = Translog.UNSET_AUTO_GENERATED_TIMESTAMP;
private boolean setAutoGeneratedTimestamp;
public RowShardResolver(TransactionContext txnCtx,
NodeContext nodeCtx,
List<ColumnIdent> pkColumns,
List<? extends Symbol> primaryKeySymbols,
@Nullable ColumnIdent clusteredByColumn,
@Nullable Symbol routingSymbol) {
InputFactory inputFactory = new InputFactory(nodeCtx);
InputFactory.Context<CollectExpression<Row, ?>> context = inputFactory.ctxForInputColumns(txnCtx);
idFunction = Id.compileWithNullValidation(pkColumns, clusteredByColumn);
setAutoGeneratedTimestamp = pkColumns.size() == 1 && pkColumns.get(0).equals(DocSysColumns.ID);
if (routingSymbol == null) {
routingInput = null;
} else {
routingInput = context.add(routingSymbol);
}
primaryKeyInputs = new ArrayList<>(primaryKeySymbols.size());
for (Symbol primaryKeySymbol : primaryKeySymbols) {
primaryKeyInputs.add(context.add(primaryKeySymbol));
}
expressions = context.expressions();
}
public void setNextRow(Row row) {<FILL_FUNCTION_BODY>}
private static List<String> pkValues(List<Input<?>> primaryKeyInputs) {
return Lists.map(primaryKeyInputs, input -> nullOrString(input.value()));
}
public long autoGeneratedTimestamp() {
return autoGeneratedTimestamp;
}
public List<String> pkValues() {
return pkValues;
}
/**
* Returns the through collected inputs generated id
*/
public String id() {
return id;
}
/**
* Returns the collected routing value (if available)
*/
@Nullable
public String routing() {
return routing;
}
}
|
for (CollectExpression<Row, ?> expression : expressions) {
expression.setNextRow(row);
}
if (setAutoGeneratedTimestamp) {
autoGeneratedTimestamp = Math.max(0, System.currentTimeMillis());
}
pkValues = pkValues(primaryKeyInputs);
id = idFunction.apply(pkValues);
if (routingInput == null) {
routing = null;
} else {
// If clustered by column is specified it cannot be null.
var clusteredBy = routingInput.value();
if (clusteredBy == null) {
throw new IllegalArgumentException("Clustered by value must not be NULL");
}
routing = clusteredBy.toString();
}
| 587
| 185
| 772
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/RowsTransformer.java
|
RowsTransformer
|
toRowsIterable
|
class RowsTransformer {
public static Iterable<Row> toRowsIterable(TransactionContext txnCtx,
InputFactory inputFactory,
ReferenceResolver<?> referenceResolver,
RoutedCollectPhase collectPhase,
Iterable<?> iterable) {
return toRowsIterable(txnCtx, inputFactory, referenceResolver, collectPhase, iterable, true);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static Iterable<Row> toRowsIterable(TransactionContext txnCtx,
InputFactory inputFactory,
ReferenceResolver<?> referenceResolver,
RoutedCollectPhase collectPhase,
Iterable<?> iterable,
boolean sort) {<FILL_FUNCTION_BODY>}
public static Iterable<Row> sortRows(Iterable<Object[]> rows, RoutedCollectPhase collectPhase) {
List<Object[]> objects = Lists.of(rows);
Comparator<Object[]> ordering = OrderingByPosition.arrayOrdering(collectPhase);
objects.sort(ordering);
return Lists.mapLazy(objects, Buckets.arrayToSharedRow());
}
}
|
if (!WhereClause.canMatch(collectPhase.where())) {
return Collections.emptyList();
}
InputFactory.Context ctx = inputFactory.ctxForRefs(txnCtx, referenceResolver);
ctx.add(collectPhase.toCollect());
OrderBy orderBy = collectPhase.orderBy();
if (orderBy != null) {
for (Symbol symbol : orderBy.orderBySymbols()) {
ctx.add(symbol);
}
}
ValueAndInputRow<Object> inputRow = new ValueAndInputRow<>(ctx.topLevelInputs(), ctx.expressions());
assert DataTypes.BOOLEAN.equals(collectPhase.where().valueType()) :
"whereClause.query() must be of type " + DataTypes.BOOLEAN;
Predicate<Row> predicate = InputCondition.asPredicate(ctx.add(collectPhase.where()));
if (sort == false || orderBy == null) {
return () -> StreamSupport.stream((Spliterator<Object>) iterable.spliterator(), false)
.map(inputRow)
.filter(predicate)
.iterator();
}
ArrayList<Object[]> items = new ArrayList<>();
for (var item : iterable) {
var row = inputRow.apply(item);
if (predicate.test(row)) {
items.add(row.materialize());
}
}
items.sort(OrderingByPosition.arrayOrdering(collectPhase));
return Lists.mapLazy(items, Buckets.arrayToSharedRow());
| 312
| 399
| 711
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/ValueAndInputRow.java
|
ValueAndInputRow
|
apply
|
class ValueAndInputRow<TValue> extends InputRow implements Function<TValue, Row>, Supplier<TValue> {
private final Iterable<? extends CollectExpression<TValue, ?>> expressions;
private TValue value;
public ValueAndInputRow(List<? extends Input<?>> inputs, Iterable<? extends CollectExpression<TValue, ?>> expressions) {
super(inputs);
this.expressions = expressions;
}
@Override
public TValue get() {
return value;
}
@Nullable
@Override
public Row apply(@Nullable TValue input) {<FILL_FUNCTION_BODY>}
}
|
value = input;
for (CollectExpression<TValue, ?> expression : expressions) {
expression.setNextRow(input);
}
return this;
| 166
| 44
| 210
|
<methods>public void <init>(List<? extends Input<?>>) ,public java.lang.Object get(int) ,public int numColumns() ,public java.lang.String toString() <variables>private final non-sealed List<? extends Input<?>> inputs
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/LuceneBatchIterator.java
|
LuceneBatchIterator
|
moveNext
|
class LuceneBatchIterator implements BatchIterator<Row> {
private final IndexSearcher indexSearcher;
private final Query query;
private final CollectorContext collectorContext;
private final boolean doScores;
private final LuceneCollectorExpression[] expressions;
private final List<LeafReaderContext> leaves;
private final InputRow row;
private Weight weight;
private final Float minScore;
private Iterator<LeafReaderContext> leavesIt;
private LeafReaderContext currentLeaf;
private Scorer currentScorer;
private DocIdSetIterator currentDocIdSetIt;
private volatile Throwable killed;
public LuceneBatchIterator(IndexSearcher indexSearcher,
Query query,
@Nullable Float minScore,
boolean doScores,
CollectorContext collectorContext,
List<? extends Input<?>> inputs,
Collection<? extends LuceneCollectorExpression<?>> expressions) {
this.indexSearcher = indexSearcher;
this.query = query;
this.doScores = doScores || minScore != null;
this.minScore = minScore;
this.collectorContext = collectorContext;
this.row = new InputRow(inputs);
this.expressions = expressions.toArray(new LuceneCollectorExpression[0]);
leaves = indexSearcher.getTopReaderContext().leaves();
leavesIt = leaves.iterator();
}
@Override
public Row currentElement() {
return row;
}
@Override
public void moveToStart() {
raiseIfKilled();
leavesIt = leaves.iterator();
}
@Override
public boolean moveNext() {<FILL_FUNCTION_BODY>}
private boolean innerMoveNext() throws IOException {
while (tryAdvanceDocIdSetIterator()) {
LeafReader reader = currentLeaf.reader();
Bits liveDocs = reader.getLiveDocs();
int doc;
while ((doc = currentDocIdSetIt.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
if (docDeleted(liveDocs, doc) || belowMinScore(currentScorer)) {
continue;
}
onDoc(doc);
return true;
}
currentDocIdSetIt = null;
}
clearState();
return false;
}
private boolean belowMinScore(Scorer currentScorer) throws IOException {
return minScore != null && currentScorer.score() < minScore;
}
private boolean tryAdvanceDocIdSetIterator() throws IOException {
if (currentDocIdSetIt != null) {
return true;
}
while (leavesIt.hasNext()) {
LeafReaderContext leaf = leavesIt.next();
Scorer scorer = weight.scorer(leaf);
if (scorer == null) {
continue;
}
currentScorer = scorer;
currentLeaf = leaf;
currentDocIdSetIt = scorer.iterator();
var readerContext = new ReaderContext(currentLeaf);
for (LuceneCollectorExpression<?> expression : expressions) {
expression.setScorer(currentScorer);
expression.setNextReader(readerContext);
}
return true;
}
return false;
}
private void clearState() {
currentDocIdSetIt = null;
currentScorer = null;
currentLeaf = null;
}
@Override
public void close() {
clearState();
killed = BatchIterator.CLOSED;
}
@Override
public CompletionStage<?> loadNextBatch() throws Exception {
throw new IllegalStateException("BatchIterator already fully loaded");
}
private Weight createWeight() throws IOException {
for (LuceneCollectorExpression<?> expression : expressions) {
expression.startCollect(collectorContext);
}
ScoreMode scoreMode = doScores ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES;
return indexSearcher.createWeight(indexSearcher.rewrite(query), scoreMode, 1f);
}
@Override
public boolean allLoaded() {
return true;
}
@Override
public boolean hasLazyResultSet() {
return true;
}
private static boolean docDeleted(@Nullable Bits liveDocs, int doc) {
if (liveDocs == null) {
return false;
}
return liveDocs.get(doc) == false;
}
private void onDoc(int doc) throws IOException {
for (LuceneCollectorExpression<?> expression : expressions) {
expression.setNextDocId(doc);
}
}
private void raiseIfKilled() {
if (killed != null) {
Exceptions.rethrowUnchecked(killed);
}
}
@Override
public void kill(@NotNull Throwable throwable) {
killed = throwable;
}
}
|
raiseIfKilled();
if (weight == null) {
try {
weight = createWeight();
} catch (IOException e) {
Exceptions.rethrowUnchecked(e);
}
}
try {
return innerMoveNext();
} catch (IOException e) {
throw new RuntimeException(e);
}
| 1,279
| 91
| 1,370
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/OrderedDocCollector.java
|
OrderedDocCollector
|
empty
|
class OrderedDocCollector implements Supplier<KeyIterable<ShardId, Row>>, AutoCloseable, Killable {
private final ShardId shardId;
protected final KeyIterable<ShardId, Row> empty;
boolean exhausted = false;
public static OrderedDocCollector empty(ShardId shardId) {<FILL_FUNCTION_BODY>}
OrderedDocCollector(ShardId shardId) {
this.shardId = shardId;
empty = new KeyIterable<>(shardId, Collections.<Row>emptyList());
}
public ShardId shardId() {
return shardId;
}
@Override
public void close() {
}
@Override
public void kill(@NotNull Throwable t) {
}
/**
* Returns an iterable for a batch of rows. In order to consume all rows of this collector,
* {@code #get()} needs to be called while {@linkplain #exhausted()} is {@code false}.
* After {@linkplain #exhausted()} is {@code true}, all subsequent calls to {@code #get()}
* will return an empty iterable.
*
* @return an iterable for the next batch of rows.
*/
@Override
public KeyIterable<ShardId, Row> get() {
return collect();
}
protected abstract KeyIterable<ShardId, Row> collect();
/**
* Returns {@code true} if this collector has no rows to deliver anymore.
*/
public boolean exhausted() {
return exhausted;
}
public KeyIterable<ShardId, Row> empty() {
return empty;
}
}
|
return new OrderedDocCollector(shardId) {
@Override
protected KeyIterable<ShardId, Row> collect() {
return empty;
}
@Override
public boolean exhausted() {
return true;
}
};
| 437
| 70
| 507
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/OrderedLuceneBatchIteratorFactory.java
|
Factory
|
toMapByShardId
|
class Factory {
private final List<OrderedDocCollector> orderedDocCollectors;
private final Executor executor;
private final IntSupplier availableThreads;
private final PagingIterator<ShardId, Row> pagingIterator;
private final Map<ShardId, OrderedDocCollector> collectorsByShardId;
Factory(List<OrderedDocCollector> orderedDocCollectors,
Comparator<Row> rowComparator,
RowAccounting<Row> rowAccounting,
Executor executor,
IntSupplier availableThreads,
boolean requiresScroll) {
this.orderedDocCollectors = orderedDocCollectors;
this.executor = executor;
this.availableThreads = availableThreads;
if (orderedDocCollectors.size() == 1) {
pagingIterator = requiresScroll ?
new RamAccountingPageIterator<>(PassThroughPagingIterator.repeatable(), rowAccounting)
: PassThroughPagingIterator.oneShot();
collectorsByShardId = null;
} else {
collectorsByShardId = toMapByShardId(orderedDocCollectors);
pagingIterator = new RamAccountingPageIterator<>(
PagingIterator.createSorted(rowComparator, requiresScroll),
rowAccounting
);
}
}
BatchIterator<Row> create() {
return new BatchPagingIterator<>(
pagingIterator,
this::tryFetchMore,
this::allExhausted,
throwable -> close()
);
}
private KillableCompletionStage<List<KeyIterable<ShardId, Row>>> tryFetchMore(ShardId shardId) {
if (allExhausted()) {
return KillableCompletionStage.whenKilled(
CompletableFuture.failedFuture(new IllegalStateException("Cannot fetch more if source is exhausted")),
t -> { });
}
CompletionStage<List<KeyIterable<ShardId, Row>>> stage;
if (shardId == null) {
// when running inside threads, the threads must be cancelled/interrupted to stop further processing
stage = ThreadPools.runWithAvailableThreads(
executor,
availableThreads,
Lists.map(orderedDocCollectors, Function.identity()));
} else {
stage = loadFrom(collectorsByShardId.get(shardId));
}
return KillableCompletionStage.whenKilled(stage, this::kill);
}
private static CompletionStage<List<KeyIterable<ShardId, Row>>> loadFrom(OrderedDocCollector collector) {
try {
return CompletableFuture.completedFuture(singletonList(collector.get()));
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
}
private void close() {
for (OrderedDocCollector collector : orderedDocCollectors) {
collector.close();
}
}
private boolean allExhausted() {
for (OrderedDocCollector collector : orderedDocCollectors) {
if (!collector.exhausted) {
return false;
}
}
return true;
}
private void kill(Throwable t) {
for (OrderedDocCollector collector : orderedDocCollectors) {
collector.kill(t);
}
}
}
private static Map<ShardId, OrderedDocCollector> toMapByShardId(List<OrderedDocCollector> collectors) {<FILL_FUNCTION_BODY>
|
Map<ShardId, OrderedDocCollector> collectorsByShardId = new HashMap<>(collectors.size());
for (OrderedDocCollector collector : collectors) {
collectorsByShardId.put(collector.shardId(), collector);
}
return collectorsByShardId;
| 904
| 82
| 986
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/RemoteCollector.java
|
RemoteCollector
|
createLocalContext
|
class RemoteCollector {
private static final Logger LOGGER = LogManager.getLogger(RemoteCollector.class);
private static final int RECEIVER_PHASE_ID = 1;
private final UUID jobId;
private final SessionSettings sessionSettings;
private final String localNode;
private final String remoteNode;
private final Executor executor;
private final ActionExecutor<NodeRequest<JobRequest>, JobResponse> jobAction;
private final ActionExecutor<KillJobsNodeRequest, KillResponse> killNodeAction;
private final TasksService tasksService;
private final RamAccounting ramAccounting;
private final RowConsumer consumer;
private final RoutedCollectPhase collectPhase;
private final Object killLock = new Object();
private final boolean scrollRequired;
private final boolean enableProfiling;
private RootTask context = null;
private boolean collectorKilled = false;
public RemoteCollector(UUID jobId,
SessionSettings sessionSettings,
String localNode,
String remoteNode,
ActionExecutor<NodeRequest<JobRequest>, JobResponse> jobAction,
ActionExecutor<KillJobsNodeRequest, KillResponse> killNodeAction,
Executor executor,
TasksService tasksService,
RamAccounting ramAccounting,
RowConsumer consumer,
RoutedCollectPhase collectPhase) {
this.jobId = jobId;
this.sessionSettings = sessionSettings;
this.localNode = localNode;
this.remoteNode = remoteNode;
this.executor = executor;
/*
* We don't wanna profile the timings of the remote execution context, because the remoteCollect is already
* part of the subcontext duration of the original Task profiling.
*/
this.enableProfiling = false;
this.scrollRequired = consumer.requiresScroll();
this.jobAction = jobAction;
this.killNodeAction = killNodeAction;
this.tasksService = tasksService;
this.ramAccounting = ramAccounting;
this.consumer = consumer;
this.collectPhase = collectPhase;
}
public void doCollect() {
if (!createLocalContext()) return;
createRemoteContext();
}
@VisibleForTesting
boolean createLocalContext() {<FILL_FUNCTION_BODY>}
@VisibleForTesting
void createRemoteContext() {
NodeOperation nodeOperation = new NodeOperation(
collectPhase, Collections.singletonList(localNode), RECEIVER_PHASE_ID, (byte) 0);
synchronized (killLock) {
if (collectorKilled) {
context.kill(null);
return;
}
jobAction
.execute(
JobRequest.of(
remoteNode,
jobId,
sessionSettings,
localNode,
Collections.singletonList(nodeOperation),
enableProfiling))
.whenComplete(
(resp, t) -> {
if (t == null) {
LOGGER.trace("RemoteCollector jobId={} jobAction=onResponse collectorKilled={}", jobId, collectorKilled);
if (collectorKilled) {
killRemoteContext();
}
} else {
LOGGER.error("RemoteCollector jobId={} jobAction=onFailure collectorKilled={} error={}", jobId, collectorKilled, t);
context.kill(t.getMessage());
}
}
);
}
}
private RootTask.Builder createPageDownstreamContext() {
RootTask.Builder builder = tasksService.newBuilder(
jobId,
sessionSettings.userName(),
localNode,
Collections.emptySet()
);
PassThroughPagingIterator<Integer, Row> pagingIterator;
if (scrollRequired) {
pagingIterator = PassThroughPagingIterator.repeatable();
} else {
pagingIterator = PassThroughPagingIterator.oneShot();
}
PageBucketReceiver pageBucketReceiver = new CumulativePageBucketReceiver(
localNode,
RECEIVER_PHASE_ID,
executor,
DataTypes.getStreamers(collectPhase.outputTypes()),
consumer,
pagingIterator,
1);
builder.addTask(new DistResultRXTask(
RECEIVER_PHASE_ID,
"RemoteCollectPhase",
pageBucketReceiver,
ramAccounting,
1
));
return builder;
}
private void killRemoteContext() {
KillJobsNodeRequest killRequest = new KillJobsNodeRequest(
List.of(),
List.of(jobId),
sessionSettings.userName(),
null
);
killNodeAction
.execute(killRequest)
.whenComplete(
(resp, t) -> {
if (t == null) {
context.kill(null);
} else {
context.kill(t.getMessage());
}
}
);
}
public void kill(@Nullable Throwable throwable) {
synchronized (killLock) {
collectorKilled = true;
/**
* due to the lock there are 3 kill windows:
*
* 1. localContext not even created - doCollect aborts
* 2. localContext created, no requests sent - doCollect aborts
* 3. localContext created, requests sent - clean-up happens once response from remote is received
*/
}
}
}
|
RootTask.Builder builder = createPageDownstreamContext();
try {
synchronized (killLock) {
if (collectorKilled) {
consumer.accept(null, new InterruptedException());
return false;
}
context = tasksService.createTask(builder);
context.start();
return true;
}
} catch (Throwable t) {
if (context == null) {
consumer.accept(null, t);
} else {
context.kill(t.getMessage());
}
return false;
}
| 1,388
| 142
| 1,530
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/ScoreDocRowFunction.java
|
ScoreDocRowFunction
|
apply
|
class ScoreDocRowFunction implements Function<ScoreDoc, Row> {
private final List<OrderByCollectorExpression> orderByCollectorExpressions = new ArrayList<>();
private final IndexReader indexReader;
private final LuceneCollectorExpression[] expressions;
private final DummyScorer scorer;
private final InputRow inputRow;
private final Runnable onScoreDoc;
private final ReaderContext[] readerContexts;
ScoreDocRowFunction(IndexReader indexReader,
List<? extends Input<?>> inputs,
Collection<? extends LuceneCollectorExpression<?>> expressions,
DummyScorer scorer,
Runnable onScoreDoc) {
this.indexReader = indexReader;
this.expressions = expressions.toArray(new LuceneCollectorExpression[0]);
this.scorer = scorer;
this.inputRow = new InputRow(inputs);
this.onScoreDoc = onScoreDoc;
for (LuceneCollectorExpression<?> expression : this.expressions) {
if (expression instanceof OrderByCollectorExpression orderByExpr) {
orderByCollectorExpressions.add(orderByExpr);
}
}
List<LeafReaderContext> leaves = indexReader.leaves();
readerContexts = new ReaderContext[leaves.size()];
try {
for (int i = 0; i < readerContexts.length; i++) {
readerContexts[i] = new ReaderContext(leaves.get(i));
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Nullable
@Override
public Row apply(@Nullable ScoreDoc input) {<FILL_FUNCTION_BODY>}
}
|
onScoreDoc.run();
if (input == null) {
return null;
}
FieldDoc fieldDoc = (FieldDoc) input;
scorer.score(fieldDoc.score);
for (int i = 0; i < orderByCollectorExpressions.size(); i++) {
orderByCollectorExpressions.get(i).setNextFieldDoc(fieldDoc);
}
List<LeafReaderContext> leaves = indexReader.leaves();
int readerIndex = ReaderUtil.subIndex(fieldDoc.doc, leaves);
LeafReaderContext subReaderContext = leaves.get(readerIndex);
var readerContext = readerContexts[readerIndex];
int subDoc = fieldDoc.doc - subReaderContext.docBase;
try {
for (LuceneCollectorExpression<?> expression : expressions) {
expression.setNextReader(readerContext);
expression.setNextDocId(subDoc);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return inputRow;
| 433
| 263
| 696
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/collectors/ShardStateObserver.java
|
ShardStateObserver
|
shardStartedOrIndexDeleted
|
class ShardStateObserver {
private static final TimeValue MAX_WAIT_TIME_FOR_NEW_STATE = TimeValue.timeValueSeconds(30);
private static final Logger LOGGER = LogManager.getLogger(ShardStateObserver.class);
private final ClusterService clusterService;
public ShardStateObserver(ClusterService clusterService) {
this.clusterService = clusterService;
}
public CompletableFuture<ShardRouting> waitForActiveShard(ShardId shardId) {
ClusterState state = clusterService.state();
try {
var routingTable = state.routingTable().shardRoutingTable(shardId);
var primaryShardRouting = routingTable.primaryShard();
if (primaryShardRouting.started()) {
return CompletableFuture.completedFuture(primaryShardRouting);
}
} catch (IndexNotFoundException e) {
return CompletableFuture.failedFuture(e);
} catch (ShardNotFoundException ignored) {
// Fall-through to use observer and wait for state update
}
var stateObserver = new ClusterStateObserver(
state, clusterService, MAX_WAIT_TIME_FOR_NEW_STATE, LOGGER);
var listener = new RetryIsShardActive(shardId);
stateObserver.waitForNextChange(listener, newState -> shardStartedOrIndexDeleted(newState, shardId));
return listener.result();
}
private static boolean shardStartedOrIndexDeleted(ClusterState state, ShardId shardId) {<FILL_FUNCTION_BODY>}
private static class RetryIsShardActive implements ClusterStateObserver.Listener {
private final ShardId shardId;
private final CompletableFuture<ShardRouting> result = new CompletableFuture<>();
RetryIsShardActive(ShardId shardId) {
this.shardId = shardId;
}
@Override
public void onNewClusterState(ClusterState state) {
try {
var routingTable = state.routingTable().shardRoutingTable(shardId);
var primaryShardRouting = routingTable.primaryShard();
if (primaryShardRouting.started()) {
result.complete(primaryShardRouting);
}
} catch (Throwable e) {
result.completeExceptionally(e);
}
}
@Override
public void onClusterServiceClose() {
result.completeExceptionally(new IllegalStateException(
"ClusterService was closed while waiting for shard=" + shardId + " to become active"));
}
@Override
public void onTimeout(TimeValue timeout) {
result.completeExceptionally(
new TimeoutException("Timeout waiting for shard=" + shardId + " to become active"));
}
public CompletableFuture<ShardRouting> result() {
return result;
}
}
}
|
try {
return state.routingTable().shardRoutingTable(shardId).primaryShard().started();
} catch (ShardNotFoundException e) {
return false;
} catch (IndexNotFoundException e) {
return true;
}
| 742
| 69
| 811
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/files/CopyModule.java
|
CopyModule
|
configure
|
class CopyModule extends AbstractModule {
List<CopyPlugin> copyPlugins;
public CopyModule(List<CopyPlugin> copyPlugins) {
this.copyPlugins = copyPlugins;
}
@Override
protected void configure() {<FILL_FUNCTION_BODY>}
}
|
MapBinder<String, FileInputFactory> fileInputFactoryMapBinder = MapBinder.newMapBinder(binder(), String.class, FileInputFactory.class);
MapBinder<String, FileOutputFactory> fileOutputFactoryMapBinder = MapBinder.newMapBinder(binder(), String.class, FileOutputFactory.class);
fileInputFactoryMapBinder.addBinding(LocalFsFileInputFactory.NAME).to(LocalFsFileInputFactory.class).asEagerSingleton();
fileOutputFactoryMapBinder.addBinding(LocalFsFileOutputFactory.NAME).to(LocalFsFileOutputFactory.class).asEagerSingleton();
for (var copyPlugin : copyPlugins) {
for (var e : copyPlugin.getFileInputFactories().entrySet()) {
fileInputFactoryMapBinder.addBinding(e.getKey()).toInstance(e.getValue());
}
for (var e : copyPlugin.getFileOutputFactories().entrySet()) {
fileOutputFactoryMapBinder.addBinding(e.getKey()).toInstance(e.getValue());
}
}
| 82
| 274
| 356
|
<methods>public non-sealed void <init>() ,public final synchronized void configure(org.elasticsearch.common.inject.Binder) <variables>org.elasticsearch.common.inject.Binder binder
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/files/FileReadingIterator.java
|
LineCursor
|
equals
|
class LineCursor {
private URI uri;
private long lineNumber;
private String line;
private IOException failure;
public LineCursor() {
}
public LineCursor(URI uri, long lineNumber, @Nullable String line, @Nullable IOException failure) {
this.uri = uri;
this.lineNumber = lineNumber;
this.line = line;
this.failure = failure;
}
public URI uri() {
return uri;
}
public long lineNumber() {
return lineNumber;
}
@Nullable
public String line() {
return line;
}
@Nullable
public IOException failure() {
return failure;
}
@VisibleForTesting
public LineCursor copy() {
return new LineCursor(uri, lineNumber, line, failure);
}
@Override
public String toString() {
return "LineCursor{" + uri + ":" + lineNumber + ":line=" + line + ", failure=" + failure + "}";
}
@Override
public int hashCode() {
return Objects.hash(uri, lineNumber, line, failure);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LineCursor other = (LineCursor) obj;
return Objects.equals(uri, other.uri)
&& lineNumber == other.lineNumber
&& Objects.equals(line, other.line)
&& Objects.equals(failure, other.failure);
| 326
| 126
| 452
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/files/SummitsIterable.java
|
SummitsIterable
|
fetchSummits
|
class SummitsIterable implements Iterable<SummitsContext> {
private final Supplier<List<SummitsContext>> summitsSupplierCache = Suppliers.memoizeWithExpiration(
this::fetchSummits, 4, TimeUnit.MINUTES
);
private List<SummitsContext> fetchSummits() {<FILL_FUNCTION_BODY>}
private static Integer tryParse(String string) {
Long result = null;
try {
result = Long.parseLong(string, 10);
} catch (NumberFormatException e) {
return null;
}
if (result != result.intValue()) {
return null;
} else {
return result.intValue();
}
}
@Nullable
private static Point safeParseCoordinates(String value) {
return value.isEmpty() ? null : DataTypes.GEO_POINT.implicitCast(value);
}
@Override
public Iterator<SummitsContext> iterator() {
return summitsSupplierCache.get().iterator();
}
}
|
List<SummitsContext> summits = new ArrayList<>();
try (InputStream input = SummitsIterable.class.getResourceAsStream("/config/names.txt")) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
List<String> parts = StringUtils.splitToList('\t', line);
summits.add(new SummitsContext(
parts.get(0),
tryParse(parts.get(1)),
tryParse(parts.get(2)),
safeParseCoordinates(parts.get(3)),
parts.get(4),
parts.get(5),
parts.get(6),
parts.get(7),
tryParse(parts.get(8)))
);
}
}
} catch (IOException e) {
throw new RuntimeException("Cannot populate the sys.summits table", e);
}
return summits;
| 272
| 259
| 531
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/files/URLFileInput.java
|
URLFileInput
|
expandUri
|
class URLFileInput implements FileInput {
private final URI fileUri;
public URLFileInput(URI fileUri) {
// If the full fileUri contains a wildcard the fileUri passed as argument here is the fileUri up to the wildcard
this.fileUri = fileUri;
}
@Override
public boolean isGlobbed() {
return false;
}
@Override
public URI uri() {
return fileUri;
}
@Override
public List<URI> expandUri() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public InputStream getStream(URI uri) throws IOException {
URL url = uri.toURL();
return url.openStream();
}
@Override
public boolean sharedStorageDefault() {
return true;
}
}
|
// for URLs listing directory contents is not supported so always return the full fileUri for now
return Collections.singletonList(this.fileUri);
| 210
| 39
| 249
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/sources/FileCollectSource.java
|
FileCollectSource
|
targetUriToStringList
|
class FileCollectSource implements CollectSource {
private final ClusterService clusterService;
private final Map<String, FileInputFactory> fileInputFactoryMap;
private final InputFactory inputFactory;
private final NodeContext nodeCtx;
private final ThreadPool threadPool;
private final Roles roles;
@Inject
public FileCollectSource(NodeContext nodeCtx,
ClusterService clusterService,
Map<String, FileInputFactory> fileInputFactoryMap,
ThreadPool threadPool,
Roles roles) {
this.fileInputFactoryMap = fileInputFactoryMap;
this.nodeCtx = nodeCtx;
this.inputFactory = new InputFactory(nodeCtx);
this.clusterService = clusterService;
this.threadPool = threadPool;
this.roles = roles;
}
@Override
public CompletableFuture<BatchIterator<Row>> getIterator(TransactionContext txnCtx,
CollectPhase collectPhase,
CollectTask collectTask,
boolean supportMoveToStart) {
FileUriCollectPhase fileUriCollectPhase = (FileUriCollectPhase) collectPhase;
InputFactory.Context<LineCollectorExpression<?>> ctx =
inputFactory.ctxForRefs(txnCtx, FileLineReferenceResolver::getImplementation);
ctx.add(collectPhase.toCollect());
Role user = requireNonNull(roles.findUser(txnCtx.sessionSettings().userName()), "User who invoked a statement must exist");
List<URI> fileUris = targetUriToStringList(txnCtx, nodeCtx, fileUriCollectPhase.targetUri()).stream()
.map(s -> {
var uri = FileReadingIterator.toURI(s);
if (uri.getScheme().equals("file") && user.isSuperUser() == false) {
throw new UnauthorizedException("Only a superuser can read from the local file system");
}
return uri;
})
.toList();
FileReadingIterator fileReadingIterator = new FileReadingIterator(
fileUris,
fileUriCollectPhase.compression(),
fileInputFactoryMap,
fileUriCollectPhase.sharedStorage(),
fileUriCollectPhase.nodeIds().size(),
getReaderNumber(fileUriCollectPhase.nodeIds(), clusterService.state().nodes().getLocalNodeId()),
fileUriCollectPhase.withClauseOptions(),
threadPool.scheduler()
);
CopyFromParserProperties parserProperties = fileUriCollectPhase.parserProperties();
LineProcessor lineProcessor = new LineProcessor(
parserProperties.skipNumLines() > 0
? new SkippingBatchIterator<>(fileReadingIterator, (int) parserProperties.skipNumLines())
: fileReadingIterator,
ctx.topLevelInputs(),
ctx.expressions(),
fileUriCollectPhase.inputFormat(),
parserProperties,
fileUriCollectPhase.targetColumns()
);
return CompletableFuture.completedFuture(lineProcessor);
}
@VisibleForTesting
public static int getReaderNumber(Collection<String> nodeIds, String localNodeId) {
String[] readers = nodeIds.toArray(new String[0]);
Arrays.sort(readers);
return Arrays.binarySearch(readers, localNodeId);
}
private static List<String> targetUriToStringList(TransactionContext txnCtx,
NodeContext nodeCtx,
Symbol targetUri) {<FILL_FUNCTION_BODY>}
}
|
Object value = SymbolEvaluator.evaluate(txnCtx, nodeCtx, targetUri, Row.EMPTY, SubQueryResults.EMPTY);
if (targetUri.valueType().id() == DataTypes.STRING.id()) {
String uri = (String) value;
return Collections.singletonList(uri);
} else if (DataTypes.STRING_ARRAY.equals(targetUri.valueType())) {
return DataTypes.STRING_ARRAY.implicitCast(value);
}
// this case actually never happens because the check is already done in the analyzer
throw AnalyzedCopyFrom.raiseInvalidType(targetUri.valueType());
| 870
| 165
| 1,035
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/sources/TableFunctionCollectSource.java
|
TableFunctionCollectSource
|
getIterator
|
class TableFunctionCollectSource implements CollectSource {
private final NodeContext nodeCtx;
private final InputFactory inputFactory;
@Inject
public TableFunctionCollectSource(NodeContext nodeCtx) {
this.nodeCtx = nodeCtx;
inputFactory = new InputFactory(nodeCtx);
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<BatchIterator<Row>> getIterator(TransactionContext txnCtx,
CollectPhase collectPhase,
CollectTask collectTask,
boolean supportMoveToStart) {<FILL_FUNCTION_BODY>}
}
|
TableFunctionCollectPhase phase = (TableFunctionCollectPhase) collectPhase;
TableFunctionImplementation<?> functionImplementation = phase.functionImplementation();
RowType rowType = functionImplementation.returnType();
//noinspection unchecked Only literals can be passed to table functions. Anything else is invalid SQL
List<Input<?>> inputs = (List<Input<?>>) (List<?>) phase.functionArguments();
List<Input<?>> topLevelInputs = new ArrayList<>(phase.toCollect().size());
List<String> columns = rowType.fieldNames();
InputFactory.Context<RowCollectExpression> ctx = inputFactory.ctxForRefs(
txnCtx,
ref -> {
for (int i = 0; i < columns.size(); i++) {
String column = columns.get(i);
if (ref.column().isRoot() && ref.column().name().equals(column)) {
return new RowCollectExpression(i);
}
}
throw new IllegalStateException(
"Column `" + ref + "` not found in " + functionImplementation.signature().getName().displayName());
});
for (Symbol symbol : phase.toCollect()) {
topLevelInputs.add(ctx.add(symbol));
}
var inputRow = new ValueAndInputRow<>(topLevelInputs, ctx.expressions());
Input<Boolean> condition = (Input<Boolean>) ctx.add(phase.where());
Iterable<Row> rows = () -> StreamSupport
.stream(functionImplementation.evaluate(txnCtx, nodeCtx, inputs.toArray(new Input[0])).spliterator(), false)
.map(inputRow)
.filter(InputCondition.asPredicate(condition))
.iterator();
return CompletableFuture.completedFuture(
InMemoryBatchIterator.of(rows, SentinelRow.SENTINEL, functionImplementation.hasLazyResultSet())
);
| 160
| 491
| 651
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/collect/stats/NodeStatsRequest.java
|
StatsRequest
|
writeTo
|
class StatsRequest extends TransportRequest {
private final Set<ColumnIdent> columns;
private StatsRequest(Set<ColumnIdent> columns) {
this.columns = columns;
}
public Set<ColumnIdent> columnIdents() {
return columns;
}
StatsRequest(StreamInput in) throws IOException {
super(in);
columns = new HashSet<>();
int columnIdentsSize = in.readVInt();
for (int i = 0; i < columnIdentsSize; i++) {
columns.add(new ColumnIdent(in));
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
}
|
super.writeTo(out);
out.writeVInt(columns.size());
for (ColumnIdent columnIdent : columns) {
columnIdent.writeTo(out);
}
| 185
| 49
| 234
|
<methods>public void <init>(java.lang.String, io.crate.execution.engine.collect.stats.NodeStatsRequest.StatsRequest) ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public io.crate.execution.engine.collect.stats.NodeStatsRequest.StatsRequest innerRequest() ,public java.lang.String nodeId() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private final non-sealed io.crate.execution.engine.collect.stats.NodeStatsRequest.StatsRequest innerRequest,private final non-sealed java.lang.String nodeId
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/BroadcastingBucketBuilder.java
|
BroadcastingBucketBuilder
|
build
|
class BroadcastingBucketBuilder implements MultiBucketBuilder {
private final int numBuckets;
private final StreamBucket.Builder bucketBuilder;
public BroadcastingBucketBuilder(Streamer<?>[] streamers, int numBuckets, RamAccounting ramAccounting) {
this.numBuckets = numBuckets;
this.bucketBuilder = new StreamBucket.Builder(streamers, ramAccounting);
}
@Override
public void add(Row row) {
bucketBuilder.add(row);
}
@Override
public int size() {
return bucketBuilder.size();
}
@Override
public long ramBytesUsed() {
return bucketBuilder.ramBytesUsed();
}
@Override
public void build(StreamBucket[] buckets) {<FILL_FUNCTION_BODY>}
}
|
assert buckets.length == numBuckets : "length of the provided array must match numBuckets";
StreamBucket bucket = bucketBuilder.build();
bucketBuilder.reset();
for (int i = 0; i < numBuckets; i++) {
buckets[i] = bucket;
}
| 220
| 81
| 301
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/DistributedResultRequest.java
|
Builder
|
of
|
class Builder {
public final DistributedResultRequest innerRequest;
public Builder(UUID jobId, int executionPhaseId, byte inputId, int bucketIdx, Throwable throwable, boolean isKilled) {
this.innerRequest = new DistributedResultRequest(jobId, executionPhaseId, inputId, bucketIdx, throwable, isKilled);
}
public NodeRequest<DistributedResultRequest> build(String nodeId) {
return new NodeRequest<>(nodeId, innerRequest);
}
}
public static NodeRequest<DistributedResultRequest> of(String nodeId,
UUID jobId,
int executionPhaseId,
byte inputId,
int bucketIdx,
StreamBucket rows,
boolean isLast) {<FILL_FUNCTION_BODY>
|
return new NodeRequest<>(
nodeId,
new DistributedResultRequest(jobId, executionPhaseId, inputId, bucketIdx, rows, isLast)
);
| 207
| 47
| 254
|
<methods>public void <init>() ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public org.elasticsearch.tasks.TaskId getParentTask() ,public void setParentTask(org.elasticsearch.tasks.TaskId) ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private org.elasticsearch.tasks.TaskId parentTaskId
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/ModuloBucketBuilder.java
|
ModuloBucketBuilder
|
hashCode
|
class ModuloBucketBuilder implements MultiBucketBuilder {
private final int numBuckets;
private final List<StreamBucket.Builder> bucketBuilders;
private final int distributedByColumnIdx;
private int size = 0;
public ModuloBucketBuilder(Streamer<?>[] streamers, int numBuckets, int distributedByColumnIdx, RamAccounting ramAccounting) {
this.numBuckets = numBuckets;
this.distributedByColumnIdx = distributedByColumnIdx;
this.bucketBuilders = new ArrayList<>(numBuckets);
for (int i = 0; i < numBuckets; i++) {
bucketBuilders.add(new StreamBucket.Builder(streamers, ramAccounting));
}
}
@Override
public void add(Row row) {
StreamBucket.Builder builder = bucketBuilders.get(getBucket(row));
builder.add(row);
size++;
}
@Override
public int size() {
return size;
}
@Override
public void build(StreamBucket[] buckets) {
assert buckets.length == numBuckets : "length of the provided array must match numBuckets";
for (int i = 0; i < numBuckets; i++) {
StreamBucket.Builder builder = bucketBuilders.get(i);
buckets[i] = builder.build();
builder.reset();
}
size = 0;
}
/**
* get bucket number by doing modulo hashcode of the defined row-element
*/
private int getBucket(Row row) {
int hash = hashCode(row.get(distributedByColumnIdx));
if (hash == Integer.MIN_VALUE) {
hash = 0; // Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
}
return Math.abs(hash) % numBuckets;
}
private static int hashCode(@Nullable Object value) {<FILL_FUNCTION_BODY>}
@Override
public long ramBytesUsed() {
long sum = 0;
for (int i = 0; i < bucketBuilders.size(); i++) {
sum += bucketBuilders.get(i).ramBytesUsed();
}
return sum;
}
}
|
if (value == null) {
return 0;
}
return value.hashCode();
| 590
| 29
| 619
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/SingleBucketBuilder.java
|
SingleBucketBuilder
|
accept
|
class SingleBucketBuilder implements RowConsumer, CompletionListenable<StreamBucket> {
private final Streamer<?>[] streamers;
private RamAccounting ramAccounting;
private final CompletableFuture<StreamBucket> bucketFuture = new CompletableFuture<>();
public SingleBucketBuilder(Streamer<?>[] streamers, RamAccounting ramAccounting) {
this.streamers = streamers;
this.ramAccounting = ramAccounting;
}
@Override
public CompletableFuture<StreamBucket> completionFuture() {
return bucketFuture;
}
@Override
public void accept(BatchIterator<Row> iterator, @Nullable Throwable failure) {<FILL_FUNCTION_BODY>}
}
|
if (failure == null) {
StreamBucketCollector streamBucketCollector = new StreamBucketCollector(streamers, ramAccounting);
BatchIterators.collect(iterator, streamBucketCollector.supplier().get(), streamBucketCollector, bucketFuture);
} else {
if (iterator != null) {
iterator.close();
}
bucketFuture.completeExceptionally(failure);
}
| 186
| 111
| 297
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/merge/BatchPagingIterator.java
|
BatchPagingIterator
|
close
|
class BatchPagingIterator<Key> implements BatchIterator<Row> {
private final PagingIterator<Key, Row> pagingIterator;
private final Function<Key, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>>> fetchMore;
private final BooleanSupplier isUpstreamExhausted;
private final Consumer<? super Throwable> closeCallback;
private Throwable killed;
private KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> currentlyLoading;
private Iterator<Row> it;
private boolean closed = false;
private Row current;
public BatchPagingIterator(PagingIterator<Key, Row> pagingIterator,
Function<Key, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>>> fetchMore,
BooleanSupplier isUpstreamExhausted,
Consumer<? super Throwable> closeCallback) {
this.pagingIterator = pagingIterator;
this.it = pagingIterator;
this.fetchMore = fetchMore;
this.isUpstreamExhausted = isUpstreamExhausted;
this.closeCallback = closeCallback;
}
@Override
public Row currentElement() {
return current;
}
@Override
public void moveToStart() {
raiseIfClosedOrKilled();
this.it = pagingIterator.repeat().iterator();
current = null;
}
@Override
public boolean moveNext() {
raiseIfClosedOrKilled();
if (it.hasNext()) {
current = it.next();
return true;
}
current = null;
return false;
}
@Override
public void close() {<FILL_FUNCTION_BODY>}
@Override
public CompletionStage<?> loadNextBatch() throws Exception {
if (closed) {
throw new IllegalStateException("BatchIterator already closed");
}
if (allLoaded()) {
throw new IllegalStateException("All data already loaded");
}
Throwable err;
KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> future;
synchronized (this) {
err = this.killed;
if (err == null) {
currentlyLoading = future = fetchMore.apply(pagingIterator.exhaustedIterable());
} else {
future = KillableCompletionStage.failed(err);
}
}
if (err == null) {
return future.whenComplete(this::onNextPage);
}
return future;
}
private void onNextPage(Iterable<? extends KeyIterable<Key, Row>> rows, Throwable ex) {
if (ex == null) {
pagingIterator.merge(rows);
if (isUpstreamExhausted.getAsBoolean()) {
pagingIterator.finish();
}
} else {
killed = ex;
throw Exceptions.toRuntimeException(ex);
}
}
@Override
public boolean allLoaded() {
return isUpstreamExhausted.getAsBoolean();
}
@Override
public boolean hasLazyResultSet() {
return true;
}
private void raiseIfClosedOrKilled() {
Throwable err;
synchronized (this) {
err = killed;
}
if (err != null) {
Exceptions.rethrowUnchecked(err);
}
if (closed) {
throw new IllegalStateException("Iterator is closed");
}
}
@Override
public void kill(@NotNull Throwable throwable) {
KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>> loading;
synchronized (this) {
killed = throwable;
loading = this.currentlyLoading;
}
close();
if (loading != null) {
loading.kill(throwable);
}
}
}
|
if (!closed) {
closed = true;
pagingIterator.finish(); // release resource, specially possible ram accounted bytes
closeCallback.accept(killed);
}
| 1,031
| 48
| 1,079
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/distribution/merge/RamAccountingPageIterator.java
|
RamAccountingPageIterator
|
merge
|
class RamAccountingPageIterator<TKey> implements PagingIterator<TKey, Row> {
@VisibleForTesting
final PagingIterator<TKey, Row> delegatePagingIterator;
private final RowAccounting<Row> rowAccounting;
public RamAccountingPageIterator(PagingIterator<TKey, Row> delegatePagingIterator, RowAccounting<Row> rowAccounting) {
this.delegatePagingIterator = delegatePagingIterator;
this.rowAccounting = rowAccounting;
}
@Override
public void merge(Iterable<? extends KeyIterable<TKey, Row>> keyIterables) {<FILL_FUNCTION_BODY>}
@Override
public void finish() {
delegatePagingIterator.finish();
}
@Override
public TKey exhaustedIterable() {
return delegatePagingIterator.exhaustedIterable();
}
@Override
public Iterable<Row> repeat() {
return delegatePagingIterator.repeat();
}
@Override
public boolean hasNext() {
return delegatePagingIterator.hasNext();
}
@Override
public Row next() {
return delegatePagingIterator.next();
}
}
|
for (KeyIterable<TKey, Row> iterable : keyIterables) {
for (Row row : iterable) {
rowAccounting.accountForAndMaybeBreak(row);
}
}
delegatePagingIterator.merge(keyIterables);
| 309
| 68
| 377
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/export/LocalFsFileOutput.java
|
LocalFsFileOutput
|
acquireOutputStream
|
class LocalFsFileOutput implements FileOutput {
@Override
public OutputStream acquireOutputStream(Executor executor, URI uri, WriterProjection.CompressionType compressionType) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (uri.getHost() != null) {
throw new IllegalArgumentException("the URI host must be defined");
}
String path = uri.getPath();
File outFile = new File(path);
if (outFile.exists()) {
if (outFile.isDirectory()) {
throw new IOException("Output path is a directory: " + path);
}
}
OutputStream os = new FileOutputStream(outFile);
if (compressionType != null) {
os = new GZIPOutputStream(os);
}
return new BufferedOutputStream(os);
| 59
| 148
| 207
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/FetchCollector.java
|
FetchCollector
|
collect
|
class FetchCollector {
private final LuceneCollectorExpression[] collectorExpressions;
private final InputRow row;
private final Streamer<?>[] streamers;
private final RamAccounting ramAccounting;
private final int readerId;
private final FetchTask fetchTask;
FetchCollector(List<LuceneCollectorExpression<?>> collectorExpressions,
Streamer<?>[] streamers,
FetchTask fetchTask,
RamAccounting ramAccounting,
int readerId) {
this.fetchTask = fetchTask;
// use toArray to avoid iterator allocations in docIds loop
this.collectorExpressions = collectorExpressions.toArray(new LuceneCollectorExpression[0]);
this.streamers = streamers;
this.ramAccounting = ramAccounting;
this.readerId = readerId;
var table = fetchTask.table(readerId);
CollectorContext collectorContext = new CollectorContext(readerId, table.droppedColumns(), table.lookupNameBySourceKey());
for (LuceneCollectorExpression<?> collectorExpression : this.collectorExpressions) {
collectorExpression.startCollect(collectorContext);
}
this.row = new InputRow(collectorExpressions);
}
private void setNextDocId(ReaderContext readerContext, int doc) throws IOException {
for (LuceneCollectorExpression<?> e : collectorExpressions) {
e.setNextReader(readerContext);
e.setNextDocId(doc);
}
}
public StreamBucket collect(IntArrayList docIds) {<FILL_FUNCTION_BODY>}
private int readerIndex(int docId, List<LeafReaderContext> leaves) {
int readerIndex = ReaderUtil.subIndex(docId, leaves);
if (readerIndex == -1) {
throw new IllegalStateException("jobId=" + fetchTask.jobId() + " docId " + docId + " doesn't fit to leaves of searcher " + readerId + " fetchTask=" + fetchTask);
}
return readerIndex;
}
static boolean isSequential(IntArrayList docIds) {
if (docIds.size() < 2) {
return false;
}
// checks if doc ids are in sequential order using the following conditions:
// (last element - first element) = (number of elements in between first and last)
// [3,4,5,6,7] -> 7 - 3 == 4
int last = docIds.get(docIds.size() - 1);
int first = docIds.get(0);
return last - first == docIds.size() - 1;
}
}
|
boolean collectSequential = isSequential(docIds);
StreamBucket.Builder builder = new StreamBucket.Builder(streamers, ramAccounting);
try (var borrowed = fetchTask.searcher(readerId)) {
var searcher = borrowed.item();
List<LeafReaderContext> leaves = searcher.getTopReaderContext().leaves();
var readerContexts = new IntObjectHashMap<ReaderContext>(leaves.size());
for (var cursor : docIds) {
int docId = cursor.value;
int readerIndex = readerIndex(docId, leaves);
LeafReaderContext subReaderContext = leaves.get(readerIndex);
try {
var readerContext = readerContexts.get(readerIndex);
if (readerContext == null) {
// If the document access is sequential, the field reader from the merge instance can be used
// to provide a significant speed up. However, accessing the merge CompressingStoredFieldsReader is expensive
// because the underlying inputData is cloned.
if (collectSequential && subReaderContext.reader() instanceof SequentialStoredFieldsLeafReader storedFieldsLeafReader) {
StoredFieldsReader sequentialStoredFieldsReader = storedFieldsLeafReader.getSequentialStoredFieldsReader();
readerContext = new ReaderContext(subReaderContext, sequentialStoredFieldsReader::document);
} else {
readerContext = new ReaderContext(subReaderContext);
}
readerContexts.put(readerIndex, readerContext);
}
setNextDocId(readerContext, docId - subReaderContext.docBase);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
builder.add(row);
}
}
return builder.build();
| 679
| 437
| 1,116
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/FetchProjector.java
|
FetchProjector
|
create
|
class FetchProjector {
private static final long MIN_BYTES_PER_BUCKETS = ByteSizeUnit.KB.toBytes(64);
// We only know the memory of the incoming rows up-front, so the percentage is low
// to leave space for the cells being fetched.
private static final double BREAKER_LIMIT_PERCENTAGE = 0.20d;
public static long computeReaderBucketsByteThreshold(CircuitBreaker circuitBreaker) {
return Math.max(
(long) (circuitBreaker.getFree() * BREAKER_LIMIT_PERCENTAGE),
MIN_BYTES_PER_BUCKETS
);
}
public static Projector create(FetchProjection projection,
RamAccounting ramAccounting,
LongSupplier getBucketsBytesThreshold,
TransactionContext txnCtx,
NodeContext nodeCtx,
FetchOperation fetchOperation) {<FILL_FUNCTION_BODY>}
}
|
final FetchRows fetchRows = FetchRows.create(
txnCtx,
nodeCtx,
projection.fetchSources(),
projection.outputSymbols()
);
CellsSizeEstimator estimateRowSize = CellsSizeEstimator.forColumns(projection.inputTypes());
return (BatchIterator<Row> source) -> {
final long maxBucketsSizeInBytes = getBucketsBytesThreshold.getAsLong();
BatchIterator<ReaderBuckets> buckets = BatchIterators.chunks(
source,
projection.getFetchSize(),
() -> new ReaderBuckets(fetchRows, projection::getFetchSourceByReader, estimateRowSize, ramAccounting),
ReaderBuckets::add,
readerBuckets -> readerBuckets.ramBytesUsed() > maxBucketsSizeInBytes
);
return new AsyncFlatMapBatchIterator<>(
buckets,
new FetchMapper(fetchOperation, projection.nodeReaders())
);
};
| 256
| 259
| 515
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/FetchRows.java
|
FetchRows
|
updatedOutputRow
|
class FetchRows {
public static FetchRows create(TransactionContext txnCtx,
NodeContext nodeCtx,
Map<RelationName, FetchSource> fetchSourceByTable,
List<Symbol> outputSymbols) {
IntArrayList fetchIdPositions = new IntArrayList();
ArrayList<Object[]> nullRows = new ArrayList<>();
IntObjectHashMap<UnsafeArrayRow> fetchedRows = new IntObjectHashMap<>();
for (var fetchSource : fetchSourceByTable.values()) {
Object[] nullRow = new Object[fetchSource.references().size()];
for (InputColumn ic : fetchSource.fetchIdCols()) {
fetchIdPositions.add(ic.index());
nullRows.add(nullRow);
fetchedRows.put(ic.index(), new UnsafeArrayRow());
}
}
final UnsafeArrayRow inputRow = new UnsafeArrayRow();
var visitor = new BaseImplementationSymbolVisitor<Void>(txnCtx, nodeCtx) {
@Override
public Input<?> visitInputColumn(final InputColumn inputColumn, final Void context) {
final int idx = inputColumn.index();
return () -> inputRow.get(idx);
}
@Override
public Input<?> visitFetchReference(final FetchReference fetchReference, final Void context) {
var ref = fetchReference.ref();
UnsafeArrayRow row = fetchedRows.get(fetchReference.fetchId().index());
int posInFetchedRow = fetchSourceByTable.get(ref.ident().tableIdent()).references().indexOf(ref);
return () -> row.get(posInFetchedRow);
}
};
List<Input<?>> outputExpressions = Lists.map(outputSymbols, x -> x.accept(visitor, null));
return new FetchRows(fetchIdPositions, outputExpressions, inputRow, fetchedRows, nullRows);
}
/**
* The indices in the incoming cells where there is a _fetchId value
*/
private final int[] fetchIdPositions;
/**
* Row that is always mutated to contain the values of the current incoming row
**/
private final UnsafeArrayRow inputRow;
/**
* Outgoing row. Encapsulates the value retrieval from incoming row and readerBuckets.
**/
private final Row output;
private final IntObjectHashMap<UnsafeArrayRow> fetchedRows;
/**
* Contains an entry per fetchIdPosition.
* Each entry contains only null values; the length matches `fetchSource.references().size`.
*
* This is used as substitute fetchedRow if the _fetchId in the incoming row is null.
*/
private final ArrayList<Object[]> nullRows;
public FetchRows(IntArrayList fetchIdPositions,
List<Input<?>> outputExpressions,
UnsafeArrayRow inputRow,
IntObjectHashMap<UnsafeArrayRow> fetchedRows,
ArrayList<Object[]> nullRows) {
this.fetchedRows = fetchedRows;
this.nullRows = nullRows;
this.fetchIdPositions = fetchIdPositions.toArray();
this.output = new InputRow(outputExpressions);
this.inputRow = inputRow;
}
public Row updatedOutputRow(Object[] incomingCells, IntFunction<ReaderBucket> getReaderBucket) {<FILL_FUNCTION_BODY>}
public int[] fetchIdPositions() {
return fetchIdPositions;
}
}
|
for (int i = 0; i < fetchIdPositions.length; i++) {
int fetchIdPos = fetchIdPositions[i];
Long fetchId = (Long) incomingCells[fetchIdPos];
UnsafeArrayRow fetchedRow = fetchedRows.get(fetchIdPos);
if (fetchId == null) {
fetchedRow.cells(nullRows.get(i));
} else {
int readerId = FetchId.decodeReaderId(fetchId);
int docId = FetchId.decodeDocId(fetchId);
ReaderBucket readerBucket = getReaderBucket.apply(readerId);
Object[] cells = readerBucket.get(docId);
assert cells != null : "Must have cells in readerBucket docId=" + docId + ", readerId=" + readerId;
fetchedRow.cells(cells);
}
}
inputRow.cells(incomingCells);
return output;
| 895
| 244
| 1,139
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/NodeFetchOperation.java
|
TableFetchInfo
|
fetch
|
class TableFetchInfo {
private final Streamer<?>[] streamers;
private final Collection<Reference> refs;
private final FetchTask fetchTask;
TableFetchInfo(Collection<Reference> refs, FetchTask fetchTask) {
this.refs = refs;
this.fetchTask = fetchTask;
this.streamers = Symbols.streamerArray(refs);
}
FetchCollector createCollector(int readerId, RamAccounting ramAccounting) {
IndexService indexService = fetchTask.indexService(readerId);
var mapperService = indexService.mapperService();
LuceneReferenceResolver resolver = new LuceneReferenceResolver(
indexService.index().getName(),
mapperService::fieldType,
fetchTask.table(readerId).partitionedByColumns()
);
ArrayList<LuceneCollectorExpression<?>> exprs = new ArrayList<>(refs.size());
for (Reference reference : refs) {
exprs.add(resolver.getImplementation(reference));
}
return new FetchCollector(
exprs,
streamers,
fetchTask,
ramAccounting,
readerId
);
}
}
public NodeFetchOperation(ThreadPoolExecutor executor,
int numProcessors,
JobsLogs jobsLogs,
TasksService tasksService,
CircuitBreaker circuitBreaker) {
this.executor = executor;
this.numProcessors = numProcessors;
this.jobsLogs = jobsLogs;
this.tasksService = tasksService;
this.circuitBreaker = circuitBreaker;
}
public CompletableFuture<? extends IntObjectMap<StreamBucket>> fetch(UUID jobId,
int phaseId,
@Nullable IntObjectMap<IntArrayList> docIdsToFetch,
boolean closeTaskOnFinish) {<FILL_FUNCTION_BODY>
|
if (docIdsToFetch == null) {
if (closeTaskOnFinish) {
tryCloseTask(jobId, phaseId);
}
jobsLogs.operationStarted(phaseId, jobId, "fetch", () -> -1);
jobsLogs.operationFinished(phaseId, jobId, null);
return CompletableFuture.completedFuture(new IntObjectHashMap<>(0));
}
RootTask context = tasksService.getTask(jobId);
FetchTask fetchTask = context.getTask(phaseId);
jobsLogs.operationStarted(phaseId, jobId, "fetch", () -> -1);
BiConsumer<? super IntObjectMap<StreamBucket>, ? super Throwable> whenComplete = (res, err) -> {
if (closeTaskOnFinish) {
if (err == null) {
fetchTask.close();
} else {
fetchTask.kill(err);
}
}
if (err == null) {
jobsLogs.operationFinished(phaseId, jobId, null);
} else {
jobsLogs.operationFinished(phaseId, jobId, SQLExceptions.messageOf(err));
}
};
try {
return doFetch(fetchTask, docIdsToFetch).whenComplete(whenComplete);
} catch (Throwable t) {
whenComplete.accept(null, t);
return CompletableFuture.failedFuture(t);
}
| 490
| 370
| 860
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/NodeFetchRequest.java
|
FetchRequest
|
writeTo
|
class FetchRequest extends TransportRequest {
private final UUID jobId;
private final int fetchPhaseId;
private final boolean closeContext;
@Nullable
private final IntObjectMap<IntArrayList> toFetch;
private FetchRequest(UUID jobId,
int fetchPhaseId,
boolean closeContext,
IntObjectMap<IntArrayList> toFetch) {
this.jobId = jobId;
this.fetchPhaseId = fetchPhaseId;
this.closeContext = closeContext;
if (toFetch.isEmpty()) {
this.toFetch = null;
} else {
this.toFetch = toFetch;
}
}
public UUID jobId() {
return jobId;
}
public int fetchPhaseId() {
return fetchPhaseId;
}
public boolean isCloseContext() {
return closeContext;
}
@Nullable
public IntObjectMap<IntArrayList> toFetch() {
return toFetch;
}
public FetchRequest(StreamInput in) throws IOException {
super(in);
jobId = new UUID(in.readLong(), in.readLong());
fetchPhaseId = in.readVInt();
closeContext = in.readBoolean();
int numReaders = in.readVInt();
if (numReaders > 0) {
IntObjectHashMap<IntArrayList> toFetch = new IntObjectHashMap<>(numReaders);
for (int i = 0; i < numReaders; i++) {
int readerId = in.readVInt();
int numDocs = in.readVInt();
IntArrayList docs = new IntArrayList(numDocs);
toFetch.put(readerId, docs);
for (int j = 0; j < numDocs; j++) {
docs.add(in.readInt());
}
}
this.toFetch = toFetch;
} else {
this.toFetch = null;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
}
|
super.writeTo(out);
out.writeLong(jobId.getMostSignificantBits());
out.writeLong(jobId.getLeastSignificantBits());
out.writeVInt(fetchPhaseId);
out.writeBoolean(closeContext);
if (toFetch == null) {
out.writeVInt(0);
} else {
out.writeVInt(toFetch.size());
for (IntObjectCursor<? extends IntContainer> toFetchCursor : toFetch) {
out.writeVInt(toFetchCursor.key);
out.writeVInt(toFetchCursor.value.size());
for (IntCursor docCursor : toFetchCursor.value) {
out.writeInt(docCursor.value);
}
}
}
| 551
| 203
| 754
|
<methods>public void <init>(java.lang.String, io.crate.execution.engine.fetch.NodeFetchRequest.FetchRequest) ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public io.crate.execution.engine.fetch.NodeFetchRequest.FetchRequest innerRequest() ,public java.lang.String nodeId() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private final non-sealed io.crate.execution.engine.fetch.NodeFetchRequest.FetchRequest innerRequest,private final non-sealed java.lang.String nodeId
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/TransportFetchNodeAction.java
|
TransportFetchNodeAction
|
nodeOperation
|
class TransportFetchNodeAction extends TransportAction<NodeFetchRequest, NodeFetchResponse> {
private final Transports transports;
private final NodeFetchOperation nodeFetchOperation;
@Inject
public TransportFetchNodeAction(Settings settings,
TransportService transportService,
Transports transports,
ThreadPool threadPool,
JobsLogs jobsLogs,
TasksService tasksService,
CircuitBreakerService circuitBreakerService) {
super(FetchNodeAction.NAME);
this.transports = transports;
this.nodeFetchOperation = new NodeFetchOperation(
(ThreadPoolExecutor) threadPool.executor(ThreadPool.Names.SEARCH),
EsExecutors.numberOfProcessors(settings),
jobsLogs,
tasksService,
circuitBreakerService.getBreaker(HierarchyCircuitBreakerService.QUERY)
);
transportService.registerRequestHandler(
FetchNodeAction.NAME,
ThreadPool.Names.SEARCH,
// force execution because this handler might receive empty close requests which
// need to be processed to not leak the FetchTask.
// This shouldn't cause too much of an issue because fetch requests always happen after a query phase.
// If the threadPool is overloaded the query phase would fail first.
true,
false,
NodeFetchRequest.FetchRequest::new,
new NodeActionRequestHandler<>(this::nodeOperation)
);
}
@Override
public void doExecute(NodeFetchRequest nodeFetchRequest, ActionListener<NodeFetchResponse> listener) {
transports.sendRequest(
FetchNodeAction.NAME,
nodeFetchRequest.nodeId(),
nodeFetchRequest.innerRequest(),
listener,
new ActionListenerResponseHandler<>(listener, nodeFetchRequest.createResponseReader())
);
}
private CompletableFuture<NodeFetchResponse> nodeOperation(final NodeFetchRequest.FetchRequest request) {<FILL_FUNCTION_BODY>}
}
|
CompletableFuture<? extends IntObjectMap<StreamBucket>> resultFuture = nodeFetchOperation.fetch(
request.jobId(),
request.fetchPhaseId(),
request.toFetch(),
request.isCloseContext()
);
return resultFuture.thenApply(NodeFetchResponse::new);
| 501
| 80
| 581
|
<methods>public final CompletableFuture<io.crate.execution.engine.fetch.NodeFetchResponse> execute(io.crate.execution.engine.fetch.NodeFetchRequest) ,public final CompletableFuture<T> execute(io.crate.execution.engine.fetch.NodeFetchRequest, Function<? super io.crate.execution.engine.fetch.NodeFetchResponse,? extends T>) <variables>protected final non-sealed java.lang.String actionName
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/fetch/TransportFetchOperation.java
|
TransportFetchOperation
|
ramAccountingForIncomingResponse
|
class TransportFetchOperation implements FetchOperation {
private static final Function<NodeFetchResponse, IntObjectMap<? extends Bucket>> GET_FETCHED = NodeFetchResponse::fetched;
private final ActionExecutor<NodeFetchRequest, NodeFetchResponse> fetchNodeAction;
private final Map<String, ? extends IntObjectMap<Streamer<?>[]>> nodeIdToReaderIdToStreamers;
private final UUID jobId;
private final int fetchPhaseId;
private final RamAccounting ramAccounting;
public TransportFetchOperation(ActionExecutor<NodeFetchRequest, NodeFetchResponse> fetchNodeAction,
Map<String, ? extends IntObjectMap<Streamer<?>[]>> nodeIdToReaderIdToStreamers,
UUID jobId,
int fetchPhaseId,
RamAccounting ramAccounting) {
this.fetchNodeAction = fetchNodeAction;
this.nodeIdToReaderIdToStreamers = nodeIdToReaderIdToStreamers;
this.jobId = jobId;
this.fetchPhaseId = fetchPhaseId;
this.ramAccounting = ramAccounting;
}
@Override
public CompletableFuture<IntObjectMap<? extends Bucket>> fetch(String nodeId,
IntObjectMap<IntArrayList> toFetch,
boolean closeContext) {
FutureActionListener<NodeFetchResponse> listener = new FutureActionListener<>();
return fetchNodeAction
.execute(
new NodeFetchRequest(nodeId,
jobId,
fetchPhaseId,
closeContext,
toFetch,
nodeIdToReaderIdToStreamers.get(nodeId),
ramAccountingForIncomingResponse(ramAccounting, toFetch, closeContext)))
.whenComplete(listener)
.thenApply(GET_FETCHED);
}
@VisibleForTesting
static RamAccounting ramAccountingForIncomingResponse(RamAccounting ramAccounting,
IntObjectMap<? extends IntContainer> toFetch,
boolean closeContext) {<FILL_FUNCTION_BODY>}
}
|
if (toFetch.isEmpty() && closeContext) {
// No data will arrive, so no ram accounting needed.
// Indeed, with valid ram accounting, incoming accounted bytes may never be released because the release
// logic may already happened (BatchAccumulator.close() calls do not block/wait for asynchronous responses)
return RamAccounting.NO_ACCOUNTING;
}
// Each response may run in a different thread and thus should use its own ram accounting instance
return new BlockBasedRamAccounting(
usedBytes -> {
// Projectors usually operate single-threaded and can receive a RamAccounting instance that is not thread-safe
// So we must ensure thread-safety here.
synchronized (ramAccounting) {
ramAccounting.addBytes(usedBytes);
}
},
MAX_BLOCK_SIZE_IN_BYTES
);
| 521
| 217
| 738
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/BulkShardCreationLimiter.java
|
BulkShardCreationLimiter
|
test
|
class BulkShardCreationLimiter implements Predicate<ShardedRequests<?, ?>> {
/**
* Defines the maximum number of new shards per node which can be safely created before running into the
* <p>wait_for_active_shards</p> timeout of 30sec. Value was wisely chosen after some brave testing.
*/
static final int MAX_NEW_SHARDS_PER_NODE = 10;
private static final Logger LOGGER = LogManager.getLogger(BulkShardCreationLimiter.class);
private final int numDataNodes;
private final int numberOfAllShards;
BulkShardCreationLimiter(int numberOfShards, int numberOfReplicas, int numDataNodes) {
this.numDataNodes = numDataNodes;
this.numberOfAllShards = (numberOfShards + (numberOfShards * numberOfReplicas));
}
@Override
public boolean test(ShardedRequests<?, ?> requests) {<FILL_FUNCTION_BODY>}
}
|
if (requests.itemsByMissingIndex.isEmpty() == false) {
int numberOfShardForAllIndices = numberOfAllShards * requests.itemsByMissingIndex.size();
int numberOfShardsPerNode = numberOfShardForAllIndices / numDataNodes;
if (numberOfShardsPerNode >= MAX_NEW_SHARDS_PER_NODE) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Number of NEW shards per node {} reached maximum limit of {}",
numberOfShardsPerNode, MAX_NEW_SHARDS_PER_NODE);
}
return true;
}
}
return false;
| 269
| 168
| 437
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/IndexNameResolver.java
|
IndexNameResolver
|
forPartition
|
class IndexNameResolver {
private IndexNameResolver() {
}
public static Supplier<String> create(RelationName relationName,
@Nullable String partitionIdent,
@Nullable List<Input<?>> partitionedByInputs) {
if (partitionIdent == null && (partitionedByInputs == null || partitionedByInputs.isEmpty())) {
return forTable(relationName);
}
if (partitionIdent == null) {
return forPartition(relationName, partitionedByInputs);
}
return forPartition(relationName, partitionIdent);
}
public static Supplier<String> forTable(final RelationName relationName) {
return relationName::indexNameOrAlias;
}
private static Supplier<String> forPartition(RelationName relationName, String partitionIdent) {
return () -> IndexParts.toIndexName(relationName, partitionIdent);
}
private static Supplier<String> forPartition(final RelationName relationName, final List<Input<?>> partitionedByInputs) {<FILL_FUNCTION_BODY>}
}
|
assert partitionedByInputs.size() > 0 : "must have at least 1 partitionedByInput";
final LoadingCache<List<String>, String> cache = Caffeine.newBuilder()
.executor(Runnable::run)
.initialCapacity(10)
.maximumSize(20)
.build(new CacheLoader<List<String>, String>() {
@Override
public String load(@NotNull List<String> key) {
return IndexParts.toIndexName(relationName, PartitionName.encodeIdent(key));
}
});
return () -> {
// copy because the values of the inputs are mutable
List<String> partitions = Lists.map(partitionedByInputs, input -> nullOrString(input.value()));
return cache.get(partitions);
};
| 274
| 212
| 486
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/IndexWriterProjector.java
|
MapInput
|
value
|
class MapInput implements Input<String> {
private final Input<Map<String, Object>> sourceInput;
private final String[] excludes;
private static final Logger LOGGER = LogManager.getLogger(MapInput.class);
private int lastSourceSize;
private MapInput(Input<Map<String, Object>> sourceInput, String[] excludes) {
this.sourceInput = sourceInput;
this.excludes = excludes;
this.lastSourceSize = PageCacheRecycler.BYTE_PAGE_SIZE;
}
@Override
public String value() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> value = sourceInput.value();
if (value == null) {
return null;
}
assert value instanceof LinkedHashMap<String, Object> : "the raw source order should be preserved";
if (excludes != null) {
for (String exclude : excludes) {
String[] path = exclude.split("\\.");
Maps.removeByPath(value, Arrays.asList(path));
}
}
try (XContentBuilder xContentBuilder = new XContentBuilder(XContentType.JSON.xContent(), new BytesStreamOutput(lastSourceSize))) {
BytesReference bytes = BytesReference.bytes(xContentBuilder.map(value));
lastSourceSize = bytes.length();
return bytes.utf8ToString();
} catch (IOException ex) {
LOGGER.error("could not parse xContent", ex);
}
return null;
| 160
| 225
| 385
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/ShardLocation.java
|
ShardLocation
|
hashCode
|
class ShardLocation {
final ShardId shardId;
final String nodeId;
public ShardLocation(ShardId shardId, String nodeId) {
this.shardId = shardId;
this.nodeId = nodeId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShardLocation that = (ShardLocation) o;
if (!shardId.equals(that.shardId)) return false;
return nodeId != null ? nodeId.equals(that.nodeId) : that.nodeId == null;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int result = shardId.hashCode();
result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0);
return result;
| 208
| 46
| 254
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/ShardedRequests.java
|
ReadFailureAndLineNumber
|
toString
|
class ReadFailureAndLineNumber {
final String readFailure;
final long lineNumber;
ReadFailureAndLineNumber(String readFailure, long lineNumber) {
this.readFailure = readFailure;
this.lineNumber = lineNumber;
}
}
@Override
public void close() {
ramAccounting.addBytes(-usedMemoryEstimate);
usedMemoryEstimate = 0L;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>
|
return "ShardedRequests{"
+ "numShards=" + itemsByShard.size()
+ ", bytesUsed=" + usedMemoryEstimate
+ ", sizePerShard=" + usedMemoryEstimate / Math.max(1, itemsByShard.size())
+ "}";
| 129
| 77
| 206
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/indexing/UpsertResultCollectors.java
|
SummaryCollector
|
processShardResponse
|
class SummaryCollector implements UpsertResultCollector {
private final Map<String, String> nodeInfo;
private final Object lock = new Object();
SummaryCollector(Map<String, String> nodeInfo) {
this.nodeInfo = nodeInfo;
}
@Override
public Supplier<UpsertResults> supplier() {
return () -> new UpsertResults(nodeInfo);
}
@Override
public Accumulator accumulator() {
return this::processShardResponse;
}
@Override
public BinaryOperator<UpsertResults> combiner() {
return (i, o) -> {
synchronized (lock) {
i.merge(o);
}
return i;
};
}
@Override
public Function<UpsertResults, Iterable<Row>> finisher() {
return UpsertResults::rowsIterable;
}
void processShardResponse(UpsertResults upsertResults,
ShardResponse shardResponse,
List<RowSourceInfo> rowSourceInfos) {<FILL_FUNCTION_BODY>}
}
|
synchronized (lock) {
List<ShardResponse.Failure> failures = shardResponse.failures();
IntArrayList locations = shardResponse.itemIndices();
for (int i = 0; i < failures.size(); i++) {
ShardResponse.Failure failure = failures.get(i);
int location = locations.get(i);
RowSourceInfo rowSourceInfo = rowSourceInfos.get(location);
String msg = failure == null ? null : failure.message();
upsertResults.addResult(rowSourceInfo.sourceUri, msg, rowSourceInfo.lineNumber);
}
}
| 291
| 154
| 445
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/join/NestedLoopOperation.java
|
NestedLoopOperation
|
buildCrossJoinBatchIterator
|
class NestedLoopOperation implements CompletionListenable {
private final CapturingRowConsumer leftConsumer;
private final CapturingRowConsumer rightConsumer;
private final RowConsumer resultConsumer;
public NestedLoopOperation(int numLeftCols,
int numRightCols,
RowConsumer nlResultConsumer,
Predicate<Row> joinPredicate,
JoinType joinType,
CircuitBreaker circuitBreaker,
RamAccounting ramAccounting,
List<DataType<?>> leftSideColumnTypes,
long estimatedRowsSizeLeft,
long estimatedNumberOfRowsLeft,
boolean blockNestedLoop) {
this.resultConsumer = nlResultConsumer;
this.leftConsumer = new CapturingRowConsumer(nlResultConsumer.requiresScroll(), nlResultConsumer.completionFuture());
this.rightConsumer = new CapturingRowConsumer(true, nlResultConsumer.completionFuture());
CompletableFuture.allOf(leftConsumer.capturedBatchIterator(), rightConsumer.capturedBatchIterator())
.whenComplete((result, failure) -> {
if (failure == null) {
BatchIterator<Row> nlIterator = createNestedLoopIterator(
leftConsumer.capturedBatchIterator().join(),
numLeftCols,
rightConsumer.capturedBatchIterator().join(),
numRightCols,
joinType,
joinPredicate,
circuitBreaker,
ramAccounting,
leftSideColumnTypes,
estimatedRowsSizeLeft,
estimatedNumberOfRowsLeft,
blockNestedLoop
);
nlResultConsumer.accept(nlIterator, null);
} else {
nlResultConsumer.accept(null, failure);
}
});
}
@Override
public CompletableFuture<?> completionFuture() {
return resultConsumer.completionFuture();
}
public RowConsumer leftConsumer() {
return leftConsumer;
}
public RowConsumer rightConsumer() {
return rightConsumer;
}
@VisibleForTesting
static BatchIterator<Row> createNestedLoopIterator(BatchIterator<Row> left,
int leftNumCols,
BatchIterator<Row> right,
int rightNumCols,
JoinType joinType,
Predicate<Row> joinCondition,
CircuitBreaker circuitBreaker,
RamAccounting ramAccounting,
List<DataType<?>> leftSideColumnTypes,
long estimatedRowsSizeLeft,
long estimatedNumberOfRowsLeft,
boolean blockNestedLoop) {
final CombinedRow combiner = new CombinedRow(leftNumCols, rightNumCols);
switch (joinType) {
case CROSS:
return buildCrossJoinBatchIterator(
left,
right,
combiner,
circuitBreaker,
ramAccounting,
leftSideColumnTypes,
estimatedRowsSizeLeft,
blockNestedLoop
);
case INNER:
return new FilteringBatchIterator<>(
buildCrossJoinBatchIterator(
left,
right,
combiner,
circuitBreaker,
ramAccounting,
leftSideColumnTypes,
estimatedRowsSizeLeft,
blockNestedLoop),
joinCondition);
case LEFT:
return new LeftJoinNLBatchIterator<>(left, right, combiner, joinCondition);
case RIGHT:
return new RightJoinNLBatchIterator<>(left, right, combiner, joinCondition);
case FULL:
return new FullOuterJoinNLBatchIterator<>(left, right, combiner, joinCondition);
case SEMI:
return new SemiJoinNLBatchIterator<>(left, right, combiner, joinCondition);
case ANTI:
return new AntiJoinNLBatchIterator<>(left, right, combiner, joinCondition);
default:
throw new AssertionError("Invalid joinType: " + joinType);
}
}
private static BatchIterator<Row> buildCrossJoinBatchIterator(BatchIterator<Row> left,
BatchIterator<Row> right,
CombinedRow combiner,
CircuitBreaker circuitBreaker,
RamAccounting ramAccounting,
List<DataType<?>> leftSideColumnTypes,
long estimatedRowsSizeLeft,
boolean blockNestedLoop) {<FILL_FUNCTION_BODY>}
}
|
if (blockNestedLoop) {
var blockSizeCalculator = new RamBlockSizeCalculator(
Paging.PAGE_SIZE,
circuitBreaker,
estimatedRowsSizeLeft
);
var rowAccounting = new TypedCellsAccounting(leftSideColumnTypes, ramAccounting, 0);
return new CrossJoinBlockNLBatchIterator(left, right, combiner, blockSizeCalculator, rowAccounting);
} else {
return new CrossJoinNLBatchIterator<>(left, right, combiner);
}
| 1,087
| 133
| 1,220
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/sort/InputFieldComparator.java
|
InputFieldComparator
|
copy
|
class InputFieldComparator extends FieldComparator<Object> implements LeafFieldComparator {
private final Object[] values;
private final Input<?> input;
private final List<? extends LuceneCollectorExpression<?>> collectorExpressions;
private final Comparator<Object> comparator;
private final @Nullable Object missingValue;
private Object bottom;
private Object top;
InputFieldComparator(int numHits,
List<? extends LuceneCollectorExpression<?>> collectorExpressions,
Input<?> input,
Comparator<Object> comparator,
@Nullable Object missingValue) {
this.collectorExpressions = collectorExpressions;
this.comparator = comparator;
this.missingValue = missingValue;
this.values = new Object[numHits];
this.input = input;
}
@Override
public LeafFieldComparator getLeafComparator(LeafReaderContext context) throws IOException {
for (int i = 0; i < collectorExpressions.size(); i++) {
collectorExpressions.get(i).setNextReader(new ReaderContext(context));
}
return this;
}
@Override
public int compare(int slot1, int slot2) {
return comparator.compare(values[slot1], values[slot2]);
}
@Override
public void setBottom(int slot) {
bottom = values[slot];
}
@Override
public void setTopValue(Object value) {
top = value;
}
@Override
public int compareBottom(int doc) throws IOException {
for (int i = 0; i < collectorExpressions.size(); i++) {
collectorExpressions.get(i).setNextDocId(doc);
}
return comparator.compare(bottom, getFirstNonNullOrNull(input.value(), missingValue));
}
@Nullable
private static Object getFirstNonNullOrNull(Object first, Object second) {
if (first != null) {
return first;
} else {
return second;
}
}
@Override
public int compareTop(int doc) throws IOException {
for (int i = 0; i < collectorExpressions.size(); i++) {
collectorExpressions.get(i).setNextDocId(doc);
}
return comparator.compare(top, getFirstNonNullOrNull(input.value(), missingValue));
}
@Override
public void copy(int slot, int doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void setScorer(Scorable scorer) {
}
@Override
public Object value(int slot) {
return values[slot];
}
}
|
for (int i = 0; i < collectorExpressions.size(); i++) {
collectorExpressions.get(i).setNextDocId(doc);
}
Object value = input.value();
if (value == null) {
values[slot] = missingValue;
} else {
values[slot] = value;
}
| 714
| 93
| 807
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/sort/OrderingByPosition.java
|
OrderingByPosition
|
rowOrdering
|
class OrderingByPosition {
public static Comparator<Object[]> arrayOrdering(RoutedCollectPhase collectPhase) {
OrderBy orderBy = collectPhase.orderBy();
assert orderBy != null : "collectPhase must have an orderBy clause to generate an ordering";
int[] positions = OrderByPositionVisitor.orderByPositions(orderBy.orderBySymbols(), collectPhase.toCollect());
return arrayOrdering(
Symbols.typeView(collectPhase.toCollect()),
positions,
orderBy.reverseFlags(),
orderBy.nullsFirst()
);
}
public static Comparator<Row> rowOrdering(List<? extends DataType<?>> rowTypes, PositionalOrderBy orderBy) {
return rowOrdering(rowTypes, orderBy.indices(), orderBy.reverseFlags(), orderBy.nullsFirst());
}
public static Comparator<Row> rowOrdering(OrderBy orderBy, List<Symbol> toCollect) {<FILL_FUNCTION_BODY>}
public static Comparator<Row> rowOrdering(List<? extends DataType<?>> rowTypes,
int[] positions,
boolean[] reverseFlags,
boolean[] nullsFirst) {
List<Comparator<Row>> comparators = new ArrayList<>(positions.length);
for (int i = 0; i < positions.length; i++) {
int position = positions[i];
Comparator<Row> rowOrdering = rowOrdering(rowTypes.get(position), position, reverseFlags[i], nullsFirst[i]);
comparators.add(rowOrdering);
}
return Ordering.compound(comparators);
}
@SuppressWarnings("unchecked")
public static <T> Comparator<Row> rowOrdering(DataType<T> type, int position, boolean reverse, boolean nullsFirst) {
return new NullAwareComparator<>(row -> (T) row.get(position), type, reverse, nullsFirst);
}
public static Comparator<Object[]> arrayOrdering(List<? extends DataType<?>> rowTypes,
int[] positions,
boolean[] reverse,
boolean[] nullsFirst) {
assert rowTypes.size() >= positions.length : "Must have a type for each order by position";
if (positions.length == 1) {
int position = positions[0];
return arrayOrdering(rowTypes.get(position), position, reverse[0], nullsFirst[0]);
}
List<Comparator<Object[]>> comparators = new ArrayList<>(positions.length);
for (int i = 0, positionLength = positions.length; i < positionLength; i++) {
int position = positions[i];
comparators.add(arrayOrdering(rowTypes.get(position), position, reverse[i], nullsFirst[i]));
}
return Ordering.compound(comparators);
}
@SuppressWarnings("unchecked")
public static <T> Comparator<Object[]> arrayOrdering(DataType<T> type, int position, boolean reverse, boolean nullsFirst) {
return new NullAwareComparator<>(cells -> (T) cells[position], type, reverse, nullsFirst);
}
}
|
int[] positions = OrderByPositionVisitor.orderByPositions(orderBy.orderBySymbols(), toCollect);
return rowOrdering(Symbols.typeView(toCollect), positions, orderBy.reverseFlags(), orderBy.nullsFirst());
| 831
| 63
| 894
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/sort/UnboundedSortingLimitAndOffsetCollector.java
|
UnboundedSortingLimitAndOffsetCollector
|
pqToIterable
|
class UnboundedSortingLimitAndOffsetCollector implements Collector<Row, PriorityQueue<Object[]>, Bucket> {
private final Collection<? extends Input<?>> inputs;
private final Iterable<? extends CollectExpression<Row, ?>> expressions;
private final int numOutputs;
private final Comparator<Object[]> comparator;
private final int initialCapacity;
private final int offset;
private final int maxNumberOfRowsInQueue;
private final RowAccounting<Object[]> rowAccounting;
/**
* @param rowAccounting sorting is a pipeline breaker so account for the used memory
* @param inputs contains output {@link Input}s and orderBy {@link Input}s
* @param expressions expressions linked to the inputs
* @param numOutputs number of output columns
* @param comparator used to sort the rows
* @param initialCapacity the initial capacity of the backing queue
* @param limit the max number of rows the result should contain
* @param offset the number of rows to skip (after sort)
*/
public UnboundedSortingLimitAndOffsetCollector(RowAccounting<Object[]> rowAccounting,
Collection<? extends Input<?>> inputs,
Iterable<? extends CollectExpression<Row, ?>> expressions,
int numOutputs,
Comparator<Object[]> comparator,
int initialCapacity,
int limit,
int offset) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException("Invalid initial capacity: value must be > 0; got: " + initialCapacity);
}
if (limit <= 0) {
throw new IllegalArgumentException("Invalid LIMIT: value must be > 0; got: " + limit);
}
if (offset < 0) {
throw new IllegalArgumentException("Invalid OFFSET: value must be >= 0; got: " + offset);
}
this.rowAccounting = rowAccounting;
this.inputs = inputs;
this.expressions = expressions;
this.numOutputs = numOutputs;
this.comparator = comparator;
this.initialCapacity = initialCapacity;
this.offset = offset;
this.maxNumberOfRowsInQueue = limit + offset;
if (maxNumberOfRowsInQueue >= ArrayUtil.MAX_ARRAY_LENGTH || maxNumberOfRowsInQueue < 0) {
// Throw exception to prevent confusing OOME in PriorityQueue
// 1) if offset + limit exceeds maximum array length
// 2) if offset + limit exceeds Integer.MAX_VALUE (then maxSize is negative!)
throw new IllegalArgumentException(
"Invalid LIMIT + OFFSET: value must be <= " + (ArrayUtil.MAX_ARRAY_LENGTH - 1) + "; got: " + maxNumberOfRowsInQueue);
}
}
@Override
public Supplier<PriorityQueue<Object[]>> supplier() {
return () -> new PriorityQueue<>(initialCapacity, comparator.reversed());
}
@Override
public BiConsumer<PriorityQueue<Object[]>, Row> accumulator() {
return this::onNextRow;
}
@Override
public BinaryOperator<PriorityQueue<Object[]>> combiner() {
return (pq1, pq2) -> {
throw new UnsupportedOperationException("combine not supported");
};
}
@Override
public Function<PriorityQueue<Object[]>, Bucket> finisher() {
return this::pqToIterable;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
private void onNextRow(PriorityQueue<Object[]> pq, Row row) {
for (CollectExpression<Row, ?> expression : expressions) {
expression.setNextRow(row);
}
Object[] rowCells = new Object[inputs.size()];
int i = 0;
for (Input<?> input : inputs) {
rowCells[i] = input.value();
i++;
}
rowAccounting.accountForAndMaybeBreak(rowCells);
if (pq.size() == maxNumberOfRowsInQueue) {
Object[] highestElementInOrder = pq.peek();
if (highestElementInOrder == null || comparator.compare(rowCells, highestElementInOrder) < 0) {
pq.poll();
pq.add(rowCells);
}
} else {
pq.add(rowCells);
}
}
private Bucket pqToIterable(PriorityQueue<Object[]> pq) {<FILL_FUNCTION_BODY>}
}
|
if (offset > pq.size()) {
return new ArrayBucket(new Object[0][0], numOutputs);
}
int resultSize = Math.max(Math.min(maxNumberOfRowsInQueue - offset, pq.size() - offset), 0);
Object[][] rows = new Object[resultSize][];
for (int i = resultSize - 1; i >= 0; i--) {
rows[i] = pq.poll();
}
return new ArrayBucket(rows, numOutputs);
| 1,172
| 137
| 1,309
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/window/ArithmeticOperatorsFactory.java
|
ArithmeticOperatorsFactory
|
getSubtractFunction
|
class ArithmeticOperatorsFactory {
private static final BinaryOperator<Double> ADD_DOUBLE_FUNCTION = Double::sum;
private static final BinaryOperator<Integer> ADD_INTEGER_FUNCTION = Integer::sum;
private static final BinaryOperator<Long> ADD_LONG_FUNCTION = Long::sum;
private static final BinaryOperator<Float> ADD_FLOAT_FUNCTION = Float::sum;
private static final BinaryOperator<Double> SUB_DOUBLE_FUNCTION = (arg0, arg1) -> arg0 - arg1;
private static final BinaryOperator<Integer> SUB_INTEGER_FUNCTION = (arg0, arg1) -> arg0 - arg1;
private static final BinaryOperator<Long> SUB_LONG_FUNCTION = (arg0, arg1) -> arg0 - arg1;
private static final BinaryOperator<Float> SUB_FLOAT_FUNCTION = (arg0, arg1) -> arg0 - arg1;
static BiFunction getAddFunction(DataType<?> fstArgDataType, DataType<?> sndArgDataType) {
switch (fstArgDataType.id()) {
case LongType.ID:
case TimestampType.ID_WITH_TZ:
case TimestampType.ID_WITHOUT_TZ:
if (IntervalType.ID == sndArgDataType.id()) {
var signature = IntervalTimestampArithmeticScalar.signatureFor(
fstArgDataType,
ArithmeticFunctions.Names.ADD
);
return new IntervalTimestampArithmeticScalar(
"+",
signature,
BoundSignature.sameAsUnbound(signature)
);
}
return ADD_LONG_FUNCTION;
case DoubleType.ID:
return ADD_DOUBLE_FUNCTION;
case FloatType.ID:
return ADD_FLOAT_FUNCTION;
case ByteType.ID:
case ShortType.ID:
case IntegerType.ID:
return ADD_INTEGER_FUNCTION;
default:
throw new UnsupportedOperationException(
"Cannot create add function for data type " + fstArgDataType.getName());
}
}
static BiFunction getSubtractFunction(DataType<?> fstArgDataType, DataType<?> sndArgDataType) {<FILL_FUNCTION_BODY>}
}
|
switch (fstArgDataType.id()) {
case LongType.ID:
case TimestampType.ID_WITH_TZ:
case TimestampType.ID_WITHOUT_TZ:
if (IntervalType.ID == sndArgDataType.id()) {
var signature = IntervalTimestampArithmeticScalar.signatureFor(
fstArgDataType,
ArithmeticFunctions.Names.SUBTRACT
);
return new IntervalTimestampArithmeticScalar(
"-",
signature,
BoundSignature.sameAsUnbound(signature)
);
}
return SUB_LONG_FUNCTION;
case DoubleType.ID:
return SUB_DOUBLE_FUNCTION;
case FloatType.ID:
return SUB_FLOAT_FUNCTION;
case ByteType.ID:
case ShortType.ID:
case IntegerType.ID:
return SUB_INTEGER_FUNCTION;
default:
throw new UnsupportedOperationException(
"Cannot create subtract function for data type " + fstArgDataType.getName());
}
| 600
| 277
| 877
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/window/RowNumberWindowFunction.java
|
RowNumberWindowFunction
|
execute
|
class RowNumberWindowFunction implements WindowFunction {
private static final String NAME = "row_number";
public static void register(Functions.Builder builder) {
builder.add(
Signature.window(
NAME,
DataTypes.INTEGER.getTypeSignature()
),
RowNumberWindowFunction::new
);
}
private final Signature signature;
private final BoundSignature boundSignature;
private RowNumberWindowFunction(Signature signature, BoundSignature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
}
@Override
public Object execute(int idxInPartition,
WindowFrameState currentFrame,
List<? extends CollectExpression<Row, ?>> expressions,
@Nullable Boolean ignoreNulls,
Input<?> ... args) {<FILL_FUNCTION_BODY>}
@Override
public Signature signature() {
return signature;
}
@Override
public BoundSignature boundSignature() {
return boundSignature;
}
}
|
if (ignoreNulls != null) {
throw new IllegalArgumentException("row_number cannot accept RESPECT or IGNORE NULLS flag.");
}
return idxInPartition + 1;
| 262
| 50
| 312
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/engine/window/WindowFunctionBatchIterator.java
|
WindowFunctionBatchIterator
|
next
|
class WindowFunctionBatchIterator {
private static final Logger LOGGER = LogManager.getLogger(WindowFunctionBatchIterator.class);
public static BatchIterator<Row> of(BatchIterator<Row> source,
RowAccounting<Row> rowAccounting,
ComputeFrameBoundary<Object[]> computeFrameStart,
ComputeFrameBoundary<Object[]> computeFrameEnd,
Comparator<Object[]> cmpPartitionBy,
Comparator<Object[]> cmpOrderBy,
int numCellsInSourceRow,
IntSupplier numAvailableThreads,
Executor executor,
List<WindowFunction> windowFunctions,
List<? extends CollectExpression<Row, ?>> argsExpressions,
Boolean[] ignoreNulls,
Input<?>[] ... args) {
assert windowFunctions.size() == args.length : "arguments must be defined for each window function";
assert args.length == ignoreNulls.length : "ignore-nulls option must be defined for each window function";
// As optimization we use 1 list that acts both as inputs(source) and as outputs.
// The window function results are injected during the computation into spare cells that are eagerly created
Function<Row, Object[]> materialize = row -> {
rowAccounting.accountForAndMaybeBreak(row);
return materializeWithSpare(row, windowFunctions.size());
};
return CollectingBatchIterator.newInstance(
source,
src -> src.map(materialize).toList()
.thenCompose(rows -> sortAndComputeWindowFunctions(
rows,
computeFrameStart,
computeFrameEnd,
cmpPartitionBy,
cmpOrderBy,
numCellsInSourceRow,
numAvailableThreads,
executor,
windowFunctions,
argsExpressions,
ignoreNulls,
args
))
.thenApply(rows -> Iterables.transform(rows, Buckets.arrayToSharedRow()::apply)),
source.hasLazyResultSet()
);
}
private static Object[] materializeWithSpare(Row row, int numWindowFunctions) {
Object[] cells = new Object[row.numColumns() + numWindowFunctions];
for (int i = 0; i < row.numColumns(); i++) {
cells[i] = row.get(i);
}
return cells;
}
static CompletableFuture<Iterable<Object[]>> sortAndComputeWindowFunctions(
List<Object[]> rows,
ComputeFrameBoundary<Object[]> computeFrameStart,
ComputeFrameBoundary<Object[]> computeFrameEnd,
@Nullable Comparator<Object[]> cmpPartitionBy,
@Nullable Comparator<Object[]> cmpOrderBy,
int numCellsInSourceRow,
IntSupplier numAvailableThreads,
Executor executor,
List<WindowFunction> windowFunctions,
List<? extends CollectExpression<Row, ?>> argsExpressions,
Boolean[] ignoreNulls,
Input<?>[]... args) {
Function<List<Object[]>, Iterable<Object[]>> computeWindowsFn = sortedRows -> computeWindowFunctions(
sortedRows,
computeFrameStart,
computeFrameEnd,
cmpPartitionBy,
numCellsInSourceRow,
windowFunctions,
argsExpressions,
ignoreNulls,
args);
Comparator<Object[]> cmpPartitionThenOrderBy = joinCmp(cmpPartitionBy, cmpOrderBy);
if (cmpPartitionThenOrderBy == null) {
return CompletableFuture.completedFuture(computeWindowsFn.apply(rows));
} else {
int minItemsPerThread = 1 << 13; // Same as Arrays.MIN_ARRAY_SORT_GRAN
return Sort
.parallelSort(rows, cmpPartitionThenOrderBy, minItemsPerThread, numAvailableThreads.getAsInt(), executor)
.thenApply(computeWindowsFn);
}
}
private static Iterable<Object[]> computeWindowFunctions(List<Object[]> sortedRows,
ComputeFrameBoundary<Object[]> computeFrameStart,
ComputeFrameBoundary<Object[]> computeFrameEnd,
@Nullable Comparator<Object[]> cmpPartitionBy,
int numCellsInSourceRow,
List<WindowFunction> windowFunctions,
List<? extends CollectExpression<Row, ?>> argsExpressions,
Boolean[] ignoreNulls,
Input<?>[]... args) {
return () -> new Iterator<>() {
private boolean isTraceEnabled = LOGGER.isTraceEnabled();
private final int start = 0;
private final int end = sortedRows.size();
private final WindowFrameState frame = new WindowFrameState(start, end, sortedRows);
private int pStart = start;
private int pEnd = findFirstNonPeer(sortedRows, pStart, end, cmpPartitionBy);
private int i = 0;
private int idxInPartition = 0;
@Override
public boolean hasNext() {
return i < end;
}
@Override
public Object[] next() {<FILL_FUNCTION_BODY>}
};
}
@Nullable
private static Comparator<Object[]> joinCmp(@Nullable Comparator<Object[]> cmpPartitionBy,
@Nullable Comparator<Object[]> cmpOrderBy) {
if (cmpPartitionBy == null) {
return cmpOrderBy;
}
if (cmpOrderBy == null) {
return cmpPartitionBy;
}
return cmpPartitionBy.thenComparing(cmpOrderBy);
}
private static Object[] computeAndInjectResults(List<Object[]> rows,
int numCellsInSourceRow,
List<WindowFunction> windowFunctions,
WindowFrameState frame,
int idx,
int idxInPartition,
List<? extends CollectExpression<Row, ?>> argsExpressions,
Boolean[] ignoreNulls,
Input<?>[]... args) {
Object[] row = rows.get(idx);
for (int c = 0; c < windowFunctions.size(); c++) {
WindowFunction windowFunction = windowFunctions.get(c);
Object result = windowFunction.execute(idxInPartition, frame, argsExpressions, ignoreNulls[c], args[c]);
row[numCellsInSourceRow + c] = result;
}
return row;
}
}
|
if (!hasNext()) {
throw new NoSuchElementException();
}
if (i == pEnd) {
pStart = i;
idxInPartition = 0;
pEnd = findFirstNonPeer(sortedRows, pStart, end, cmpPartitionBy);
}
int wBegin = computeFrameStart.apply(pStart, pEnd, i, sortedRows);
int wEnd = computeFrameEnd.apply(pStart, pEnd, i, sortedRows);
frame.updateBounds(pStart, pEnd, wBegin, wEnd);
final Object[] row = computeAndInjectResults(
sortedRows, numCellsInSourceRow, windowFunctions, frame, i, idxInPartition, argsExpressions, ignoreNulls, args);
if (isTraceEnabled) {
LOGGER.trace(
"idx={} idxInPartition={} pStart={} pEnd={} wBegin={} wEnd={} row={}",
i, idxInPartition, pStart, pEnd, wBegin, wEnd, Arrays.toString(sortedRows.get(i)));
}
i++;
idxInPartition++;
return row;
| 1,642
| 290
| 1,932
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/jobs/CountTask.java
|
CountTask
|
innerKill
|
class CountTask extends AbstractTask {
private final CountPhase countPhase;
private final TransactionContext txnCtx;
private final CountOperation countOperation;
private final RowConsumer consumer;
private final Map<String, IntIndexedContainer> indexShardMap;
private CompletableFuture<Long> countFuture;
private volatile Throwable killReason;
CountTask(CountPhase countPhase,
TransactionContext txnCtx,
CountOperation countOperation,
RowConsumer consumer,
Map<String, IntIndexedContainer> indexShardMap) {
super(countPhase.phaseId());
this.countPhase = countPhase;
this.txnCtx = txnCtx;
this.countOperation = countOperation;
this.consumer = consumer;
this.indexShardMap = indexShardMap;
}
@Override
public synchronized CompletableFuture<Void> innerStart() {
try {
countFuture = countOperation.count(txnCtx, indexShardMap, countPhase.where());
} catch (Throwable t) {
consumer.accept(null, t);
return null;
}
countFuture.whenComplete((rowCount, failure) -> {
Throwable killed = killReason; // 1 volatile read
failure = killed == null ? failure : killed;
if (failure == null) {
consumer.accept(InMemoryBatchIterator.of(new Row1(rowCount), SENTINEL), null);
close();
} else {
consumer.accept(null, failure);
kill(failure);
}
});
return null;
}
@Override
public synchronized void innerKill(@NotNull Throwable throwable) {<FILL_FUNCTION_BODY>}
@Override
public String name() {
return countPhase.name();
}
@Override
public long bytesUsed() {
return -1;
}
}
|
if (countFuture == null) {
consumer.accept(null, throwable);
} else {
killReason = throwable;
countFuture.cancel(true);
}
| 498
| 49
| 547
|
<methods>public CompletableFuture<java.lang.Void> completionFuture() ,public int id() ,public final void kill(java.lang.Throwable) ,public final CompletableFuture<java.lang.Void> start() <variables>private final java.util.concurrent.atomic.AtomicBoolean firstClose,private final CompletableFuture<java.lang.Void> future,protected final non-sealed int id
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/jobs/kill/TransportKillNodeAction.java
|
TransportKillNodeAction
|
broadcast
|
class TransportKillNodeAction {
private TransportKillNodeAction() {
}
static <T extends TransportRequest> void broadcast(ClusterService clusterService,
TransportService transportService,
T request,
String actionName,
ActionListener<KillResponse> listener,
Collection<String> excludedNodeIds) {<FILL_FUNCTION_BODY>}
}
|
Stream<DiscoveryNode> nodes = StreamSupport.stream(clusterService.state().nodes().spliterator(), false);
Collection<DiscoveryNode> filteredNodes = nodes.filter(node -> !excludedNodeIds.contains(node.getId())).collect(
Collectors.toList());
MultiActionListener<KillResponse, Long, KillResponse> multiListener =
new MultiActionListener<>(filteredNodes.size(),
() -> 0L,
(state, response) -> state += response.numKilled(),
KillResponse::new,
listener);
TransportResponseHandler<KillResponse> responseHandler =
new ActionListenerResponseHandler<>(multiListener, KillResponse::new);
for (DiscoveryNode node : filteredNodes) {
transportService.sendRequest(node, actionName, request, responseHandler);
}
| 99
| 208
| 307
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/jobs/transport/NodeDisconnectJobMonitorService.java
|
NodeDisconnectJobMonitorService
|
broadcastKillToParticipatingNodes
|
class NodeDisconnectJobMonitorService extends AbstractLifecycleComponent implements TransportConnectionListener {
private final TasksService tasksService;
private final NodeLimits nodeLimits;
private final TransportService transportService;
private final ActionExecutor<KillJobsNodeRequest, KillResponse> killNodeAction;
private static final Logger LOGGER = LogManager.getLogger(NodeDisconnectJobMonitorService.class);
@Inject
public NodeDisconnectJobMonitorService(TasksService tasksService,
NodeLimits nodeLimits,
TransportService transportService,
Node node) {
this(tasksService, nodeLimits, transportService, req -> node.client().execute(KillJobsNodeAction.INSTANCE, req));
}
@VisibleForTesting
NodeDisconnectJobMonitorService(TasksService tasksService,
NodeLimits nodeLimits,
TransportService transportService,
ActionExecutor<KillJobsNodeRequest, KillResponse> killNodeAction) {
this.tasksService = tasksService;
this.nodeLimits = nodeLimits;
this.transportService = transportService;
this.killNodeAction = killNodeAction;
}
@Override
protected void doStart() {
transportService.addConnectionListener(this);
}
@Override
protected void doStop() {
transportService.removeConnectionListener(this);
}
@Override
protected void doClose() {
}
@Override
public void onNodeConnected(DiscoveryNode node, Transport.Connection connection) {
}
@Override
public void onNodeDisconnected(DiscoveryNode node, Transport.Connection connection) {
nodeLimits.nodeDisconnected(node.getId());
killJobsCoordinatedBy(node);
broadcastKillToParticipatingNodes(node);
}
/**
* Broadcast the kill if *this* node is the coordinator and a participating node died
* The information which nodes are participating is only available on the coordinator, so other nodes
* can not kill the jobs on their own.
*
* <pre>
* n1 n2 n3
* | | |
* startJob 1 (n1,n2,n3) | |
* | | |
* | *dies* |
* | |
* onNodeDisc(n2) onNodeDisc(n2)
* broadcast kill job1 does not know which jobs involve n2
* |
* kill job1 <-+----------------------------------> kill job1
*
* </pre>
*/
private void broadcastKillToParticipatingNodes(DiscoveryNode deadNode) {<FILL_FUNCTION_BODY>}
/**
* Immediately kills all jobs that were initiated by the disconnected node.
* It is not possible to send results to the disconnected node.
* <pre>
*
* n1 n2 n3
* | | |
* startJob 1 (n1,n2,n3) | |
* | | |
* *dies* | |
* onNodeDisc(n1) onNodeDisc(n1)
* killJob 1 killJob1
* </pre>
*/
private void killJobsCoordinatedBy(DiscoveryNode deadNode) {
List<UUID> jobsStartedByDeadNode = tasksService
.getJobIdsByCoordinatorNode(deadNode.getId()).collect(Collectors.toList());
if (jobsStartedByDeadNode.isEmpty()) {
return;
}
tasksService.killJobs(
jobsStartedByDeadNode,
Role.CRATE_USER.name(),
"Participating node=" + deadNode.getName() + " disconnected."
);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Killed {} jobs started by disconnected node={}", jobsStartedByDeadNode.size(), deadNode.getId());
}
}
}
|
List<UUID> affectedJobs = tasksService
.getJobIdsByParticipatingNodes(deadNode.getId()).collect(Collectors.toList());
if (affectedJobs.isEmpty()) {
return;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Broadcasting kill for {} jobs because they involved disconnected node={}",
affectedJobs.size(),
deadNode.getId());
}
List<String> excludedNodeIds = Collections.singletonList(deadNode.getId());
KillJobsNodeRequest killRequest = new KillJobsNodeRequest(
excludedNodeIds,
affectedJobs,
Role.CRATE_USER.name(),
"Participating node=" + deadNode.getName() + " disconnected."
);
killNodeAction
.execute(killRequest)
.whenComplete(
(resp, t) -> {
if (t != null) {
LOGGER.warn("failed to send kill request to nodes");
}
}
);
| 1,030
| 263
| 1,293
|
<methods>public void addLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void close() ,public org.elasticsearch.common.component.Lifecycle.State lifecycleState() ,public void removeLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void start() ,public void stop() <variables>protected final org.elasticsearch.common.component.Lifecycle lifecycle,private final List<org.elasticsearch.common.component.LifecycleListener> listeners
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/jobs/transport/TransportCancelAction.java
|
TransportCancelAction
|
doExecute
|
class TransportCancelAction extends TransportAction<CancelRequest, AcknowledgedResponse> {
public static final String NAME = "internal:crate:pg/cancel";
public static final ActionType<AcknowledgedResponse> ACTION = new ActionType<>(NAME);
private final Sessions sessions;
private final ClusterService clusterService;
private final TransportService transportService;
@Inject
public TransportCancelAction(Sessions sessions,
ClusterService clusterService,
TransportService transportService) {
super(NAME);
this.sessions = sessions;
this.clusterService = clusterService;
this.transportService = transportService;
NodeAction<CancelRequest, TransportResponse> nodeAction = this::nodeOperation;
transportService.registerRequestHandler(
NAME,
ThreadPool.Names.SAME, // operation is cheap
true,
false,
CancelRequest::new,
new NodeActionRequestHandler<>(nodeAction)
);
}
protected void doExecute(CancelRequest request, ActionListener<AcknowledgedResponse> finalListener) {<FILL_FUNCTION_BODY>}
CompletableFuture<TransportResponse> nodeOperation(CancelRequest request) {
sessions.cancelLocally(request.keyData());
return CompletableFuture.completedFuture(TransportResponse.Empty.INSTANCE);
}
}
|
DiscoveryNodes nodes = clusterService.state().nodes();
var multiActionListener = new MultiActionListener<>(
nodes.getSize() - 1, // localNode is excluded
() -> null,
(x, y) -> {},
state -> new AcknowledgedResponse(true),
finalListener
);
for (var node : nodes) {
if (node.equals(clusterService.localNode())) {
continue;
}
transportService.sendRequest(
node,
NAME,
request,
new ActionListenerResponseHandler<>(multiActionListener, AcknowledgedResponse::new)
);
}
| 329
| 163
| 492
|
<methods>public final CompletableFuture<org.elasticsearch.action.support.master.AcknowledgedResponse> execute(io.crate.execution.jobs.transport.CancelRequest) ,public final CompletableFuture<T> execute(io.crate.execution.jobs.transport.CancelRequest, Function<? super org.elasticsearch.action.support.master.AcknowledgedResponse,? extends T>) <variables>protected final non-sealed java.lang.String actionName
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/jobs/transport/TransportJobAction.java
|
TransportJobAction
|
maybeInstrumentProfiler
|
class TransportJobAction extends TransportAction<NodeRequest<JobRequest>, JobResponse> {
private final IndicesService indicesService;
private final Transports transports;
private final TasksService tasksService;
private final JobSetup jobSetup;
@Inject
public TransportJobAction(TransportService transportService,
IndicesService indicesService,
Transports transports,
TasksService tasksService,
JobSetup jobSetup) {
super(JobAction.NAME);
this.indicesService = indicesService;
this.transports = transports;
this.tasksService = tasksService;
this.jobSetup = jobSetup;
transportService.registerRequestHandler(
JobAction.NAME,
ThreadPool.Names.SEARCH,
JobRequest::new,
new NodeActionRequestHandler<>(this::nodeOperation));
}
@Override
public void doExecute(NodeRequest<JobRequest> request, ActionListener<JobResponse> listener) {
transports.sendRequest(
JobAction.NAME,
request.nodeId(),
request.innerRequest(),
listener,
new ActionListenerResponseHandler<>(listener, JobResponse::new)
);
}
private CompletableFuture<JobResponse> nodeOperation(final JobRequest request) {
RootTask.Builder contextBuilder = tasksService.newBuilder(
request.jobId(),
request.sessionSettings().userName(),
request.coordinatorNodeId(),
Collections.emptySet()
);
SharedShardContexts sharedShardContexts = maybeInstrumentProfiler(request.enableProfiling(), contextBuilder);
List<CompletableFuture<StreamBucket>> directResponseFutures = jobSetup.prepareOnRemote(
request.sessionSettings(),
request.nodeOperations(),
contextBuilder,
sharedShardContexts
);
try {
RootTask context = tasksService.createTask(contextBuilder);
context.start();
} catch (Throwable t) {
return CompletableFuture.failedFuture(t);
}
if (directResponseFutures.size() == 0) {
return CompletableFuture.completedFuture(new JobResponse(List.of()));
} else {
return CompletableFutures.allAsList(directResponseFutures).thenApply(JobResponse::new);
}
}
private SharedShardContexts maybeInstrumentProfiler(boolean enableProfiling, RootTask.Builder contextBuilder) {<FILL_FUNCTION_BODY>}
}
|
if (enableProfiling) {
var profilers = new ArrayList<QueryProfiler>();
ProfilingContext profilingContext = new ProfilingContext(profilers);
contextBuilder.profilingContext(profilingContext);
return new SharedShardContexts(
indicesService,
indexSearcher -> {
var queryProfiler = new QueryProfiler();
profilers.add(queryProfiler);
return new InstrumentedIndexSearcher(indexSearcher, queryProfiler);
}
);
} else {
return new SharedShardContexts(indicesService, UnaryOperator.identity());
}
| 621
| 174
| 795
|
<methods>public final CompletableFuture<io.crate.execution.jobs.transport.JobResponse> execute(NodeRequest<io.crate.execution.jobs.transport.JobRequest>) ,public final CompletableFuture<T> execute(NodeRequest<io.crate.execution.jobs.transport.JobRequest>, Function<? super io.crate.execution.jobs.transport.JobResponse,? extends T>) <variables>protected final non-sealed java.lang.String actionName
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/support/ActionListeners.java
|
ActionListeners
|
waitForShards
|
class ActionListeners {
private ActionListeners() {
}
public static <T extends AcknowledgedResponse> ActionListener<T> waitForShards(ActionListener<T> delegate,
ActiveShardsObserver observer,
TimeValue timeout,
Runnable onShardsNotAcknowledged,
Supplier<String[]> indices) {<FILL_FUNCTION_BODY>}
}
|
return ActionListener.wrap(
resp -> {
if (resp.isAcknowledged()) {
observer.waitForActiveShards(
indices.get(),
ActiveShardCount.DEFAULT,
timeout,
shardsAcknowledged -> {
if (!shardsAcknowledged) {
onShardsNotAcknowledged.run();
}
delegate.onResponse(resp);
},
delegate::onFailure
);
} else {
delegate.onResponse(resp);
}
},
delegate::onFailure
);
| 106
| 149
| 255
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/support/OneRowActionListener.java
|
OneRowActionListener
|
accept
|
class OneRowActionListener<Response> implements ActionListener<Response>, BiConsumer<Response, Throwable> {
private final RowConsumer consumer;
private final Function<? super Response, ? extends Row> toRowFunction;
public static OneRowActionListener<? super AcknowledgedResponse> oneIfAcknowledged(RowConsumer consumer) {
return new OneRowActionListener<>(consumer, resp -> resp.isAcknowledged() ? new Row1(1L) : new Row1(0L));
}
public OneRowActionListener(RowConsumer consumer, Function<? super Response, ? extends Row> toRowFunction) {
this.consumer = consumer;
this.toRowFunction = toRowFunction;
}
@Override
public void onResponse(Response response) {
final Row row;
try {
row = toRowFunction.apply(response);
} catch (Throwable t) {
consumer.accept(null, t);
return;
}
consumer.accept(InMemoryBatchIterator.of(row, SENTINEL), null);
}
@Override
public void onFailure(@NotNull Exception e) {
consumer.accept(null, e);
}
@Override
public void accept(Response response, Throwable t) {<FILL_FUNCTION_BODY>}
}
|
if (t == null) {
onResponse(response);
} else {
consumer.accept(null, t);
}
| 332
| 37
| 369
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/support/RetryRunnable.java
|
RetryRunnable
|
run
|
class RetryRunnable implements Runnable, Scheduler.Cancellable {
private static final Logger LOGGER = LogManager.getLogger(RetryRunnable.class);
private final ThreadPool threadPool;
private final String executorName;
private final Executor executor;
private final Iterator<TimeValue> delay;
private final Runnable retryCommand;
private volatile Scheduler.Cancellable cancellable;
public RetryRunnable(ThreadPool threadPool,
String executorName,
Runnable command,
Iterable<TimeValue> backOffPolicy) {
this.threadPool = threadPool;
this.executorName = executorName;
this.executor = threadPool.executor(executorName);
this.delay = backOffPolicy.iterator();
this.retryCommand = command;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public boolean cancel() {
if (cancellable != null) {
return cancellable.cancel();
}
return false;
}
@Override
public boolean isCancelled() {
if (cancellable != null) {
return cancellable.isCancelled();
}
return false;
}
}
|
try {
executor.execute(retryCommand);
} catch (EsRejectedExecutionException e) {
if (delay.hasNext()) {
long currentDelay = delay.next().millis();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Received RejectedExecutionException, will retry again in {}ms", currentDelay);
}
cancellable = threadPool.scheduleUnlessShuttingDown(
new TimeValue(currentDelay, TimeUnit.MILLISECONDS),
executorName,
retryCommand
);
} else {
LOGGER.warn("Received RejectedExecutionException after max retries, giving up");
}
} catch (Exception e) {
LOGGER.error("Received unhandled exception", e);
}
| 334
| 200
| 534
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/execution/support/Transports.java
|
Transports
|
sendRequest
|
class Transports {
private final ClusterService clusterService;
private final TransportService transportService;
@Inject
public Transports(ClusterService clusterService, TransportService transportService) {
this.clusterService = clusterService;
this.transportService = transportService;
}
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest(
String action,
String node,
TRequest request,
ActionListener<TResponse> listener,
TransportResponseHandler<TResponse> handler,
TransportRequestOptions options) {<FILL_FUNCTION_BODY>}
public <TRequest extends TransportRequest, TResponse extends TransportResponse> void sendRequest(
String action,
String node,
TRequest request,
ActionListener<TResponse> listener,
TransportResponseHandler<TResponse> handler) {
sendRequest(action, node, request, listener, handler, TransportRequestOptions.EMPTY);
}
}
|
DiscoveryNode discoveryNode = clusterService.state().nodes().get(node);
if (discoveryNode == null) {
listener.onFailure(new NodeNotConnectedException(null,
String.format(Locale.ENGLISH, "node \"%s\" not found in cluster state!", node)));
return;
}
try {
transportService.sendRequest(discoveryNode, action, request, options, handler);
} catch (Throwable t) {
listener.onFailure(Exceptions.toException(t));
}
| 236
| 137
| 373
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/RowFilter.java
|
RowFilter
|
create
|
class RowFilter implements Predicate<Row> {
private final Input<Boolean> filterCondition;
private final List<CollectExpression<Row, ?>> expressions;
public static Predicate<Row> create(TransactionContext txnCtx, InputFactory inputFactory, @Nullable Symbol filterSymbol) {<FILL_FUNCTION_BODY>}
private RowFilter(TransactionContext txnCtx, InputFactory inputFactory, Symbol filterSymbol) {
InputFactory.Context<CollectExpression<Row, ?>> ctx = inputFactory.ctxForInputColumns(txnCtx);
//noinspection unchecked
filterCondition = (Input) ctx.add(filterSymbol);
expressions = ctx.expressions();
}
@Override
public boolean test(@Nullable Row row) {
//noinspection ForLoopReplaceableByForEach // avoids iterator allocation - rowFilter test is invoked per row
for (int i = 0, expressionsSize = expressions.size(); i < expressionsSize; i++) {
CollectExpression<Row, ?> expression = expressions.get(i);
expression.setNextRow(row);
}
return InputCondition.matches(filterCondition);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RowFilter rowFilter = (RowFilter) o;
if (!filterCondition.equals(rowFilter.filterCondition)) return false;
return expressions.equals(rowFilter.expressions);
}
@Override
public int hashCode() {
int result = filterCondition.hashCode();
result = 31 * result + expressions.hashCode();
return result;
}
}
|
if (filterSymbol == null) {
return i -> true;
}
return new RowFilter(txnCtx, inputFactory, filterSymbol);
| 427
| 42
| 469
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/eval/NullEliminator.java
|
Visitor
|
visitFunction
|
class Visitor extends FunctionCopyVisitor<Context> {
@Override
public Symbol visitFunction(Function func, Context context) {<FILL_FUNCTION_BODY>}
@Override
public Symbol visitLiteral(Literal<?> symbol, Context context) {
if (context.insideLogicalOperator && symbol.value() == null) {
return Literal.of(context.nullReplacement);
}
return symbol;
}
}
|
String functionName = func.name();
// only operate inside logical operators
if (Operators.LOGICAL_OPERATORS.contains(functionName)) {
final boolean currentNullReplacement = context.nullReplacement;
final boolean currentInsideLogicalOperator = context.insideLogicalOperator;
context.insideLogicalOperator = true;
if (NotPredicate.NAME.equals(functionName)) {
// not(null) -> not(false) would evaluate to true, so replacement boolean must be flipped
context.nullReplacement = !currentNullReplacement;
}
Symbol newFunc = super.visitFunction(func, context);
if (newFunc != func) {
newFunc = context.postProcessor.apply(newFunc);
}
// reset context
context.insideLogicalOperator = currentInsideLogicalOperator;
context.nullReplacement = currentNullReplacement;
return newFunc;
}
return func;
| 114
| 246
| 360
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/AndOperator.java
|
AndOperator
|
of
|
class AndOperator extends Operator<Boolean> {
public static final String NAME = "op_and";
public static final Signature SIGNATURE = Signature.scalar(
NAME,
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
);
public static void register(Functions.Builder builder) {
builder.add(SIGNATURE, AndOperator::new);
}
public AndOperator(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function function, TransactionContext txnCtx, NodeContext nodeCtx) {
assert function != null : "function must not be null";
assert function.arguments().size() == 2 : "number of args must be 2";
Symbol left = function.arguments().get(0);
Symbol right = function.arguments().get(1);
if (left instanceof Input && right instanceof Input) {
return Literal.of(evaluate(txnCtx, nodeCtx, (Input) left, (Input) right));
}
/**
* true and x -> x
* false and x -> false
* null and x -> false or null -> function as is
*/
if (left instanceof Input leftInput) {
Object value = leftInput.value();
if (value == null) {
return function;
}
if ((Boolean) value) {
return right;
} else {
return Literal.of(false);
}
}
if (right instanceof Input<?> rightInput) {
Object value = rightInput.value();
if (value == null) {
return function;
}
if ((Boolean) value) {
return left;
} else {
return Literal.of(false);
}
}
return function;
}
@Override
@SafeVarargs
public final Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Boolean>... args) {
assert args != null : "args must not be null";
assert args.length == 2 : "number of args must be 2";
assert args[0] != null && args[1] != null : "1st and 2nd arguments must not be null";
// implement three valued logic.
// don't touch anything unless you have a good reason for it! :)
// http://en.wikipedia.org/wiki/Three-valued_logic
Boolean left = args[0].value();
Boolean right = args[1].value();
if (left == null && right == null) {
return null;
}
if (left == null) {
return (!right) ? false : null;
}
if (right == null) {
return (!left) ? false : null;
}
return left && right;
}
@Override
public Query toQuery(Function function, Context context) {
BooleanQuery.Builder query = new BooleanQuery.Builder();
for (Symbol symbol : function.arguments()) {
query.add(symbol.accept(context.visitor(), context), BooleanClause.Occur.MUST);
}
return query.build();
}
public static Function of(Symbol first, Symbol second) {<FILL_FUNCTION_BODY>}
public static Symbol join(Iterable<? extends Symbol> symbols) {
return join(symbols.iterator());
}
public static Symbol join(Iterator<? extends Symbol> symbols) {
return join(symbols, Literal.BOOLEAN_TRUE);
}
public static Symbol join(Iterable<? extends Symbol> symbols, Symbol defaultSymbol) {
return join(symbols.iterator(), defaultSymbol);
}
public static Symbol join(Iterator<? extends Symbol> symbols, Symbol defaultSymbol) {
if (!symbols.hasNext()) {
return defaultSymbol;
}
Symbol first = symbols.next();
while (symbols.hasNext()) {
var next = symbols.next();
if (!Filter.isMatchAll(next)) {
first = new Function(SIGNATURE, List.of(first, next), Operator.RETURN_TYPE);
}
}
return first;
}
/**
* Split a symbol by AND functions.
* <pre>
* x = 1 AND y = 2 -> [(x = 1), y = 2)]
* x = 1 -> [(x = 1)]
* </pre>
*
* @return The parts of a predicate
*/
public static List<Symbol> split(Symbol predicate) {
ArrayList<Symbol> conjunctions = new ArrayList<>();
predicate.accept(SplitVisitor.INSTANCE, conjunctions);
if (conjunctions.isEmpty()) {
conjunctions.add(predicate);
}
return conjunctions;
}
static class SplitVisitor extends SymbolVisitor<List<Symbol>, Symbol> {
private static final SplitVisitor INSTANCE = new SplitVisitor();
@Override
protected Symbol visitSymbol(Symbol symbol, List<Symbol> context) {
return symbol;
}
@Override
public Symbol visitFunction(Function func, List<Symbol> conjunctions) {
var signature = func.signature();
assert signature != null : "Expecting functions signature not to be null";
if (signature.equals(SIGNATURE)) {
for (Symbol argument : func.arguments()) {
Symbol result = argument.accept(this, conjunctions);
if (result != null) {
conjunctions.add(result);
}
}
return null;
} else {
return func;
}
}
}
}
|
assert first.valueType().equals(DataTypes.BOOLEAN) || first.valueType().equals(DataTypes.UNDEFINED) :
"first symbol must have BOOLEAN return type to create AND function";
assert second.valueType().equals(DataTypes.BOOLEAN) || second.valueType().equals(DataTypes.UNDEFINED) :
"second symbol must have BOOLEAN return type to create AND function";
return new Function(SIGNATURE, List.of(first, second), Operator.RETURN_TYPE);
| 1,470
| 136
| 1,606
|
<methods>public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>public static final java.lang.String PREFIX,public static final io.crate.types.BooleanType RETURN_TYPE
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/CmpOperator.java
|
CmpOperator
|
evaluate
|
class CmpOperator extends Operator<Object> {
private final IntPredicate isMatch;
private final DataType<Object> type;
@SuppressWarnings("unchecked")
public CmpOperator(Signature signature, BoundSignature boundSignature, IntPredicate cmpResultIsMatch) {
super(signature, boundSignature);
this.type = (DataType<Object>) boundSignature.argTypes().get(0);
this.isMatch = cmpResultIsMatch;
}
@Override
@SafeVarargs
public final Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {<FILL_FUNCTION_BODY>}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Query toQuery(String functionName, Reference ref, Object value) {
StorageSupport<?> storageSupport = ref.valueType().storageSupport();
if (storageSupport == null) {
return null;
}
EqQuery eqQuery = storageSupport.eqQuery();
if (eqQuery == null) {
return new MatchNoDocsQuery("For types that do not support EqQuery, a `x [>, >=, <, <=] <value>` is always considered a no-match");
}
String field = ref.storageIdent();
return switch (functionName) {
case GtOperator.NAME -> eqQuery.rangeQuery(
field,
value,
null,
false,
false,
ref.hasDocValues(),
ref.indexType() != IndexType.NONE);
case GteOperator.NAME -> eqQuery.rangeQuery(
field,
value,
null,
true,
false,
ref.hasDocValues(),
ref.indexType() != IndexType.NONE);
case LtOperator.NAME -> eqQuery.rangeQuery(
field,
null,
value,
false,
false,
ref.hasDocValues(),
ref.indexType() != IndexType.NONE);
case LteOperator.NAME -> eqQuery.rangeQuery(
field,
null,
value,
false,
true,
ref.hasDocValues(),
ref.indexType() != IndexType.NONE);
default -> throw new IllegalArgumentException(functionName + " is not a supported comparison operator");
};
}
@Override
public Query toQuery(Reference ref, Literal<?> literal) {
return CmpOperator.toQuery(signature.getName().name(), ref, literal.value());
}
}
|
assert args != null : "args must not be null";
assert args.length == 2 : "number of args must be 2";
assert args[0] != null && args[1] != null : "1st and 2nd argument must not be null";
Object left = args[0].value();
Object right = args[1].value();
if (left == null || right == null) {
return null;
}
assert (left.getClass().equals(right.getClass())) : "left and right must have the same type for comparison";
return isMatch.test(type.compare(left, right));
| 646
| 159
| 805
|
<methods>public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>public static final java.lang.String PREFIX,public static final io.crate.types.BooleanType RETURN_TYPE
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/LikeOperator.java
|
LikeOperator
|
compile
|
class LikeOperator extends Operator<String> {
private final FourPredicate<String, String, Character, CaseSensitivity> matcher;
private final CaseSensitivity caseSensitivity;
private final java.util.function.Function<Input<String>[], Character> escapeFromInputs;
private final java.util.function.Function<List<Symbol>, Character> escapeFromSymbols;
private final int evaluateArgsCount;
public LikeOperator(Signature signature,
BoundSignature boundSignature,
FourPredicate<String, String, Character, CaseSensitivity> matcher,
CaseSensitivity caseSensitivity) {
super(signature, boundSignature);
this.matcher = matcher;
this.caseSensitivity = caseSensitivity;
this.evaluateArgsCount = signature.getArgumentDataTypes().size();
if (signature.getArgumentDataTypes().size() == 3) {
escapeFromInputs = inputs -> validateAndGetEscape(inputs[2]);
escapeFromSymbols = symbols -> {
Symbol escape = symbols.get(2);
assert escape instanceof Literal<?> : "Escape character must be a literal";
return validateAndGetEscape((Literal<?>) escape);
};
} else {
// BWC branch for pre-5.6 signature without ESCAPE.
escapeFromInputs = (ignored) -> LikeOperators.DEFAULT_ESCAPE;
escapeFromSymbols = (ignored) -> LikeOperators.DEFAULT_ESCAPE;
}
}
/**
* @return escape character.
* NULL indicates disabled escaping.
*/
@Nullable
private static Character validateAndGetEscape(Input<?> escapeInput) {
String value = (String) escapeInput.value();
if (value.length() > 1) {
throw new IllegalArgumentException("ESCAPE must be a single character");
}
if (value.isEmpty()) {
return null;
}
return value.charAt(0);
}
@Override
public Scalar<Boolean, String> compile(List<Symbol> arguments, String userName, Roles roles) {<FILL_FUNCTION_BODY>}
@Override
public Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<String>... args) {
assert args != null : "args must not be null";
assert args.length == evaluateArgsCount : "number of args must be " + evaluateArgsCount;
String expression = args[0].value();
String pattern = args[1].value();
if (expression == null || pattern == null) {
return null;
}
Character escapeChar = escapeFromInputs.apply(args);
return matcher.test(expression, pattern, escapeChar, caseSensitivity);
}
@Override
@Nullable
public Query toQuery(Function function, LuceneQueryBuilder.Context context) {
List<Symbol> args = function.arguments();
if (args.get(0) instanceof Reference ref
&& args.get(1) instanceof Literal<?> patternLiteral
) {
Object value = patternLiteral.value();
assert value instanceof String
: "LikeOperator is registered for string types. Value must be a string";
if (((String) value).isEmpty()) {
return new TermQuery(new Term(ref.storageIdent(), ""));
}
Character escapeChar = escapeFromSymbols.apply(args);
return caseSensitivity.likeQuery(ref.storageIdent(),
(String) value,
escapeChar,
ref.indexType() != IndexType.NONE
);
}
return null;
}
private static class CompiledLike extends Scalar<Boolean, String> {
private final Pattern pattern;
CompiledLike(Signature signature,
BoundSignature boundSignature,
String pattern,
Character escapeChar,
CaseSensitivity caseSensitivity) {
super(signature, boundSignature);
this.pattern = LikeOperators.makePattern(pattern, caseSensitivity, escapeChar);
}
@SafeVarargs
@Override
public final Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<String>... args) {
String value = args[0].value();
if (value == null) {
return null;
}
return pattern.matcher(value).matches();
}
}
}
|
Symbol pattern = arguments.get(1);
if (pattern instanceof Input) {
Object value = ((Input<?>) pattern).value();
if (value == null) {
return this;
}
Character escapeChar = escapeFromSymbols.apply(arguments);
return new CompiledLike(signature, boundSignature, (String) value, escapeChar, caseSensitivity);
}
return super.compile(arguments, userName, roles);
| 1,103
| 113
| 1,216
|
<methods>public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>public static final java.lang.String PREFIX,public static final io.crate.types.BooleanType RETURN_TYPE
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/LtOperator.java
|
LtOperator
|
register
|
class LtOperator {
public static final String NAME = "op_<";
public static void register(Functions.Builder builder) {<FILL_FUNCTION_BODY>}
}
|
for (var supportedType : DataTypes.PRIMITIVE_TYPES) {
builder.add(
Signature.scalar(
NAME,
supportedType.getTypeSignature(),
supportedType.getTypeSignature(),
Operator.RETURN_TYPE.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new CmpOperator(signature, boundSignature, cmpResult -> cmpResult < 0)
);
}
| 49
| 126
| 175
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/Operator.java
|
Operator
|
normalizeSymbol
|
class Operator<I> extends Scalar<Boolean, I> {
public static final BooleanType RETURN_TYPE = DataTypes.BOOLEAN;
public static final String PREFIX = "op_";
protected Operator(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function function, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
}
|
// all operators evaluates to NULL if one argument is NULL
// let's handle this here to prevent unnecessary collect operations
for (Symbol symbol : function.arguments()) {
if (symbol instanceof Input && ((Input<?>) symbol).value() == null) {
return Literal.of(RETURN_TYPE, null);
}
}
return super.normalizeSymbol(function, txnCtx, nodeCtx);
| 126
| 106
| 232
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Boolean,I> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<I>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.