Search in sources :

Example 26 with RelationName

use of io.crate.metadata.RelationName in project crate by crate.

the class FetchTask method start.

@Override
public void start() {
    synchronized (jobId) {
        if (killed != null) {
            result.completeExceptionally(killed);
            return;
        }
        HashMap<String, RelationName> index2TableIdent = new HashMap<>();
        for (Map.Entry<RelationName, Collection<String>> entry : phase.tableIndices().entrySet()) {
            for (String indexName : entry.getValue()) {
                index2TableIdent.put(indexName, entry.getKey());
            }
        }
        Set<RelationName> tablesWithFetchRefs = new HashSet<>();
        for (Reference reference : phase.fetchRefs()) {
            tablesWithFetchRefs.add(reference.ident().tableIdent());
        }
        String source = "fetch-task: " + jobId.toString() + '-' + phase.phaseId() + '-' + phase.name();
        for (Routing routing : routingIterable) {
            Map<String, Map<String, IntIndexedContainer>> locations = routing.locations();
            Map<String, IntIndexedContainer> indexShards = locations.get(localNodeId);
            for (Map.Entry<String, IntIndexedContainer> indexShardsEntry : indexShards.entrySet()) {
                String indexName = indexShardsEntry.getKey();
                Integer base = phase.bases().get(indexName);
                if (base == null) {
                    continue;
                }
                IndexMetadata indexMetadata = metadata.index(indexName);
                if (indexMetadata == null) {
                    if (IndexParts.isPartitioned(indexName)) {
                        continue;
                    }
                    throw new IndexNotFoundException(indexName);
                }
                Index index = indexMetadata.getIndex();
                RelationName ident = index2TableIdent.get(indexName);
                assert ident != null : "no relationName found for index " + indexName;
                tableIdents.put(base, ident);
                toFetch.put(ident, new ArrayList<>());
                for (IntCursor shard : indexShardsEntry.getValue()) {
                    ShardId shardId = new ShardId(index, shard.value);
                    int readerId = base + shardId.id();
                    SharedShardContext shardContext = shardContexts.get(readerId);
                    if (shardContext == null) {
                        try {
                            shardContext = sharedShardContexts.createContext(shardId, readerId);
                            shardContexts.put(readerId, shardContext);
                            if (tablesWithFetchRefs.contains(ident)) {
                                searchers.put(readerId, shardContext.acquireSearcher(source));
                            }
                        } catch (IndexNotFoundException e) {
                            if (!IndexParts.isPartitioned(indexName)) {
                                throw e;
                            }
                        }
                    }
                }
            }
        }
        for (Reference reference : phase.fetchRefs()) {
            Collection<Reference> references = toFetch.get(reference.ident().tableIdent());
            if (references != null) {
                references.add(reference);
            }
        }
    }
    if (searchers.isEmpty() || phase.fetchRefs().isEmpty()) {
        // no fetch references means there will be no fetch requests
        // this context is only here to allow the collectors to generate docids with the right bases
        // the bases are fetched in the prepare phase therefore this context can be closed
        close();
    }
}
Also used : HashMap(java.util.HashMap) IntObjectHashMap(com.carrotsearch.hppc.IntObjectHashMap) Index(org.elasticsearch.index.Index) ShardId(org.elasticsearch.index.shard.ShardId) IntCursor(com.carrotsearch.hppc.cursors.IntCursor) RelationName(io.crate.metadata.RelationName) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) HashSet(java.util.HashSet) Reference(io.crate.metadata.Reference) Routing(io.crate.metadata.Routing) IntIndexedContainer(com.carrotsearch.hppc.IntIndexedContainer) Collection(java.util.Collection) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) IntObjectHashMap(com.carrotsearch.hppc.IntObjectHashMap) SharedShardContext(io.crate.execution.jobs.SharedShardContext)

Example 27 with RelationName

use of io.crate.metadata.RelationName in project crate by crate.

the class ViewAnalyzer method analyze.

public AnalyzedDropView analyze(DropView dropView, CoordinatorTxnCtx txnCtx) {
    // No exists check to avoid stale clusterState race conditions
    ArrayList<RelationName> views = new ArrayList<>(dropView.names().size());
    ArrayList<RelationName> missing = new ArrayList<>();
    for (QualifiedName qualifiedName : dropView.names()) {
        try {
            views.add(schemas.resolveView(qualifiedName, txnCtx.sessionContext().searchPath()).v2());
        } catch (RelationUnknown e) {
            if (!dropView.ifExists()) {
                missing.add(RelationName.of(qualifiedName, txnCtx.sessionContext().searchPath().currentSchema()));
            }
        }
    }
    if (!missing.isEmpty()) {
        throw new RelationsUnknown(missing);
    }
    return new AnalyzedDropView(views, dropView.ifExists());
}
Also used : RelationsUnknown(io.crate.exceptions.RelationsUnknown) RelationUnknown(io.crate.exceptions.RelationUnknown) QualifiedName(io.crate.sql.tree.QualifiedName) ArrayList(java.util.ArrayList) RelationName(io.crate.metadata.RelationName)

Example 28 with RelationName

use of io.crate.metadata.RelationName in project crate by crate.

the class ViewAnalyzer method analyze.

public CreateViewStmt analyze(CreateView createView, CoordinatorTxnCtx txnCtx) {
    RelationName name = RelationName.of(createView.name(), txnCtx.sessionContext().searchPath().currentSchema());
    name.ensureValidForRelationCreation();
    if (BlobSchemaInfo.NAME.equals(name.schema())) {
        throw new UnsupportedOperationException("Creating a view in the \"blob\" schema is not supported");
    }
    AnalyzedRelation query;
    String formattedQuery;
    try {
        formattedQuery = SqlFormatter.formatSql(createView.query());
    } catch (Exception e) {
        throw new UnsupportedOperationException("Invalid query used in CREATE VIEW. Query: " + createView.query());
    }
    try {
        // Analyze the formatted Query to make sure the formatting didn't mess it up in any way.
        query = relationAnalyzer.analyze((Query) SqlParser.createStatement(formattedQuery), txnCtx, ParamTypeHints.EMPTY);
    } catch (Exception e) {
        throw new UnsupportedOperationException("Invalid query used in CREATE VIEW. " + e.getMessage() + ". Query: " + formattedQuery);
    }
    if (query.outputs().stream().map(f -> Symbols.pathFromSymbol(f).sqlFqn()).distinct().count() != query.outputs().size()) {
        throw new IllegalArgumentException("Query in CREATE VIEW must not have duplicate column names");
    }
    return new CreateViewStmt(name, query, createView.query(), createView.replaceExisting(), txnCtx.sessionContext().sessionUser());
}
Also used : RelationName(io.crate.metadata.RelationName) SqlFormatter(io.crate.sql.SqlFormatter) DropView(io.crate.sql.tree.DropView) BlobSchemaInfo(io.crate.metadata.blob.BlobSchemaInfo) ArrayList(java.util.ArrayList) CreateView(io.crate.sql.tree.CreateView) RelationsUnknown(io.crate.exceptions.RelationsUnknown) Symbols(io.crate.expression.symbol.Symbols) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) RelationAnalyzer(io.crate.analyze.relations.RelationAnalyzer) SqlParser(io.crate.sql.parser.SqlParser) Schemas(io.crate.metadata.Schemas) Query(io.crate.sql.tree.Query) RelationUnknown(io.crate.exceptions.RelationUnknown) QualifiedName(io.crate.sql.tree.QualifiedName) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Query(io.crate.sql.tree.Query) RelationName(io.crate.metadata.RelationName) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation)

Example 29 with RelationName

use of io.crate.metadata.RelationName in project crate by crate.

the class TransportAnalyzeAction method publishTableStats.

private CompletableFuture<AcknowledgedResponse> publishTableStats(Map<RelationName, Stats> newTableStats) {
    List<DiscoveryNode> nodesOn41OrAfter = StreamSupport.stream(clusterService.state().nodes().spliterator(), false).filter(x -> x.getVersion().onOrAfter(Version.V_4_1_0)).collect(Collectors.toList());
    var listener = new FutureActionListener<AcknowledgedResponse, AcknowledgedResponse>(x -> x);
    var multiListener = new MultiActionListener<>(nodesOn41OrAfter.size(), Collectors.reducing(new AcknowledgedResponse(true), (resp1, resp2) -> new AcknowledgedResponse(resp1.isAcknowledged() && resp2.isAcknowledged())), listener);
    var responseHandler = new ActionListenerResponseHandler<>(multiListener, AcknowledgedResponse::new, ThreadPool.Names.SAME);
    PublishTableStatsRequest request = new PublishTableStatsRequest(newTableStats);
    for (DiscoveryNode node : nodesOn41OrAfter) {
        transportService.sendRequest(node, RECEIVE_TABLE_STATS, request, responseHandler);
    }
    return listener;
}
Also used : Arrays(java.util.Arrays) RelationName(io.crate.metadata.RelationName) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) Symbols(io.crate.expression.symbol.Symbols) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) StreamSupport(java.util.stream.StreamSupport) TransportService(org.elasticsearch.transport.TransportService) FutureActionListener(io.crate.action.FutureActionListener) SchemaInfo(io.crate.metadata.table.SchemaInfo) TableInfo(io.crate.metadata.table.TableInfo) Streamer(io.crate.Streamer) NodeActionRequestHandler(io.crate.execution.support.NodeActionRequestHandler) ColumnIdent(io.crate.metadata.ColumnIdent) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) CompletableFutures(io.crate.concurrent.CompletableFutures) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Collectors(java.util.stream.Collectors) MultiActionListener(io.crate.execution.support.MultiActionListener) List(java.util.List) Version(org.elasticsearch.Version) Row(io.crate.data.Row) AnalyzeRequest(io.crate.execution.ddl.AnalyzeRequest) DocSchemaInfo(io.crate.metadata.doc.DocSchemaInfo) DataTypes(io.crate.types.DataTypes) Singleton(org.elasticsearch.common.inject.Singleton) Schemas(io.crate.metadata.Schemas) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MultiActionListener(io.crate.execution.support.MultiActionListener) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) FutureActionListener(io.crate.action.FutureActionListener)

Example 30 with RelationName

use of io.crate.metadata.RelationName in project crate by crate.

the class TransportAnalyzeAction method fetchSamples.

private CompletableFuture<Samples> fetchSamples(RelationName relationName, List<Reference> columns) {
    FutureActionListener<FetchSampleResponse, Samples> listener = new FutureActionListener<>(FetchSampleResponse::samples);
    List<DiscoveryNode> nodesOn41OrAfter = StreamSupport.stream(clusterService.state().nodes().spliterator(), false).filter(x -> x.getVersion().onOrAfter(Version.V_4_1_0)).collect(Collectors.toList());
    MultiActionListener<FetchSampleResponse, ?, FetchSampleResponse> multiListener = new MultiActionListener<>(nodesOn41OrAfter.size(), Collectors.reducing(new FetchSampleResponse(Samples.EMPTY), (FetchSampleResponse s1, FetchSampleResponse s2) -> FetchSampleResponse.merge(TransportAnalyzeAction.NUM_SAMPLES, s1, s2)), listener);
    List<Streamer> streamers = Arrays.asList(Symbols.streamerArray(columns));
    ActionListenerResponseHandler<FetchSampleResponse> responseHandler = new ActionListenerResponseHandler<>(multiListener, in -> new FetchSampleResponse(streamers, in), ThreadPool.Names.SAME);
    for (DiscoveryNode node : nodesOn41OrAfter) {
        transportService.sendRequest(node, FETCH_SAMPLES, new FetchSampleRequest(relationName, columns, TransportAnalyzeAction.NUM_SAMPLES), responseHandler);
    }
    return listener;
}
Also used : Arrays(java.util.Arrays) RelationName(io.crate.metadata.RelationName) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) Symbols(io.crate.expression.symbol.Symbols) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) StreamSupport(java.util.stream.StreamSupport) TransportService(org.elasticsearch.transport.TransportService) FutureActionListener(io.crate.action.FutureActionListener) SchemaInfo(io.crate.metadata.table.SchemaInfo) TableInfo(io.crate.metadata.table.TableInfo) Streamer(io.crate.Streamer) NodeActionRequestHandler(io.crate.execution.support.NodeActionRequestHandler) ColumnIdent(io.crate.metadata.ColumnIdent) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) CompletableFutures(io.crate.concurrent.CompletableFutures) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Collectors(java.util.stream.Collectors) MultiActionListener(io.crate.execution.support.MultiActionListener) List(java.util.List) Version(org.elasticsearch.Version) Row(io.crate.data.Row) AnalyzeRequest(io.crate.execution.ddl.AnalyzeRequest) DocSchemaInfo(io.crate.metadata.doc.DocSchemaInfo) DataTypes(io.crate.types.DataTypes) Singleton(org.elasticsearch.common.inject.Singleton) Schemas(io.crate.metadata.Schemas) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MultiActionListener(io.crate.execution.support.MultiActionListener) FutureActionListener(io.crate.action.FutureActionListener) Streamer(io.crate.Streamer) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler)

Aggregations

RelationName (io.crate.metadata.RelationName)180 Test (org.junit.Test)100 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)55 PartitionName (io.crate.metadata.PartitionName)47 Symbol (io.crate.expression.symbol.Symbol)42 Reference (io.crate.metadata.Reference)37 ColumnIdent (io.crate.metadata.ColumnIdent)31 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)21 ReferenceIdent (io.crate.metadata.ReferenceIdent)21 DocTableInfo (io.crate.metadata.doc.DocTableInfo)21 Map (java.util.Map)20 HashMap (java.util.HashMap)19 SqlExpressions (io.crate.testing.SqlExpressions)18 ArrayList (java.util.ArrayList)18 List (java.util.List)17 Before (org.junit.Before)17 DocTableRelation (io.crate.analyze.relations.DocTableRelation)13 SQLExecutor (io.crate.testing.SQLExecutor)11 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)10 IndexTemplateMetadata (org.elasticsearch.cluster.metadata.IndexTemplateMetadata)10