Search in sources :

Example 96 with Language

use of org.intellij.lang.annotations.Language in project presto by prestodb.

the class LocalQueryRunner method executeInternal.

private MaterializedResultWithPlan executeInternal(Session session, @Language("SQL") String sql, WarningCollector warningCollector) {
    lock.readLock().lock();
    try (Closer closer = Closer.create()) {
        AtomicReference<MaterializedResult.Builder> builder = new AtomicReference<>();
        PageConsumerOutputFactory outputFactory = new PageConsumerOutputFactory(types -> {
            builder.compareAndSet(null, MaterializedResult.resultBuilder(session, types));
            return builder.get()::page;
        });
        Plan plan = createPlan(session, sql, warningCollector);
        TaskContext taskContext = TestingTaskContext.builder(notificationExecutor, yieldExecutor, session).setMaxSpillSize(nodeSpillConfig.getMaxSpillPerNode()).setQueryMaxSpillSize(nodeSpillConfig.getQueryMaxSpillPerNode()).setQueryMaxTotalMemory(getQueryMaxTotalMemoryPerNode(session)).setTaskPlan(plan.getRoot()).build();
        taskContext.getQueryContext().setVerboseExceededMemoryLimitErrorsEnabled(isVerboseExceededMemoryLimitErrorsEnabled(session));
        taskContext.getQueryContext().setHeapDumpOnExceededMemoryLimitEnabled(isHeapDumpOnExceededMemoryLimitEnabled(session));
        String heapDumpFilePath = Paths.get(getHeapDumpFileDirectory(session), format("%s_%s.hprof", session.getQueryId().getId(), taskContext.getTaskId().getStageExecutionId().getStageId().getId())).toString();
        taskContext.getQueryContext().setHeapDumpFilePath(heapDumpFilePath);
        List<Driver> drivers = createDrivers(session, plan, outputFactory, taskContext);
        drivers.forEach(closer::register);
        boolean done = false;
        while (!done) {
            boolean processed = false;
            for (Driver driver : drivers) {
                if (alwaysRevokeMemory) {
                    driver.getDriverContext().getOperatorContexts().stream().filter(operatorContext -> operatorContext.getOperatorStats().getRevocableMemoryReservation().getValue() > 0).forEach(OperatorContext::requestMemoryRevoking);
                }
                if (!driver.isFinished()) {
                    driver.process();
                    processed = true;
                }
            }
            done = !processed;
        }
        verify(builder.get() != null, "Output operator was not created");
        return new MaterializedResultWithPlan(builder.get().build(), plan);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        lock.readLock().unlock();
    }
}
Also used : Closer(com.google.common.io.Closer) WarningCollector(com.facebook.presto.spi.WarningCollector) PrepareTask(com.facebook.presto.execution.PrepareTask) RowExpressionDomainTranslator(com.facebook.presto.sql.relational.RowExpressionDomainTranslator) PluginManagerConfig(com.facebook.presto.server.PluginManagerConfig) QueryExplainer(com.facebook.presto.sql.analyzer.QueryExplainer) ResetSession(com.facebook.presto.sql.tree.ResetSession) NodeSelectionStats(com.facebook.presto.execution.scheduler.nodeSelection.NodeSelectionStats) ConnectorPlanOptimizerManager(com.facebook.presto.sql.planner.ConnectorPlanOptimizerManager) RenameColumnTask(com.facebook.presto.execution.RenameColumnTask) MoreFutures.getFutureValue(com.facebook.airlift.concurrent.MoreFutures.getFutureValue) ColumnPropertyManager(com.facebook.presto.metadata.ColumnPropertyManager) NOT_PARTITIONED(com.facebook.presto.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED) StageExecutionDescriptor(com.facebook.presto.operator.StageExecutionDescriptor) ThrowingNodeTtlFetcherManager(com.facebook.presto.ttl.nodettlfetchermanagers.ThrowingNodeTtlFetcherManager) Map(java.util.Map) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName) PageFunctionCompiler(com.facebook.presto.sql.gen.PageFunctionCompiler) CreateTable(com.facebook.presto.sql.tree.CreateTable) TaskCountEstimator(com.facebook.presto.cost.TaskCountEstimator) SessionPropertyDefaults(com.facebook.presto.server.SessionPropertyDefaults) PageSinkManager(com.facebook.presto.split.PageSinkManager) SortOrder(com.facebook.presto.common.block.SortOrder) Prepare(com.facebook.presto.sql.tree.Prepare) StandaloneSpillerFactory(com.facebook.presto.spiller.StandaloneSpillerFactory) Plugin(com.facebook.presto.spi.Plugin) CreateMaterializedView(com.facebook.presto.sql.tree.CreateMaterializedView) DropViewTask(com.facebook.presto.execution.DropViewTask) QueryPreparer(com.facebook.presto.execution.QueryPreparer) PasswordAuthenticatorManager(com.facebook.presto.server.security.PasswordAuthenticatorManager) DropTable(com.facebook.presto.sql.tree.DropTable) RowExpressionPredicateCompiler(com.facebook.presto.sql.gen.RowExpressionPredicateCompiler) RemoteSourceFactory(com.facebook.presto.sql.planner.RemoteSourceFactory) SystemSessionProperties(com.facebook.presto.SystemSessionProperties) RollbackTask(com.facebook.presto.execution.RollbackTask) StreamingPlanSection(com.facebook.presto.execution.scheduler.StreamingPlanSection) PlanOptimizer(com.facebook.presto.sql.planner.optimizations.PlanOptimizer) ViewDefinition(com.facebook.presto.metadata.ViewDefinition) AnalyzePropertiesSystemTable(com.facebook.presto.connector.system.AnalyzePropertiesSystemTable) LookupJoinOperators(com.facebook.presto.operator.LookupJoinOperators) GenericSpillerFactory(com.facebook.presto.spiller.GenericSpillerFactory) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AnalyzePropertyManager(com.facebook.presto.metadata.AnalyzePropertyManager) IndexJoinLookupStats(com.facebook.presto.operator.index.IndexJoinLookupStats) TransactionManager(com.facebook.presto.transaction.TransactionManager) PreparedQuery(com.facebook.presto.execution.QueryPreparer.PreparedQuery) TableCommitContext(com.facebook.presto.operator.TableCommitContext) StreamingPlanSection.extractStreamingSections(com.facebook.presto.execution.scheduler.StreamingPlanSection.extractStreamingSections) Session(com.facebook.presto.Session) IOException(java.io.IOException) SplitSchedulingStrategy(com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy) Split(com.facebook.presto.metadata.Split) ThrowingClusterTtlProviderManager(com.facebook.presto.ttl.clusterttlprovidermanagers.ThrowingClusterTtlProviderManager) SpillerFactory(com.facebook.presto.spiller.SpillerFactory) OperatorContext(com.facebook.presto.operator.OperatorContext) Metadata(com.facebook.presto.metadata.Metadata) LocalExecutionPlanner(com.facebook.presto.sql.planner.LocalExecutionPlanner) TablePropertyManager(com.facebook.presto.metadata.TablePropertyManager) DropMaterializedViewTask(com.facebook.presto.execution.DropMaterializedViewTask) TaskManagerConfig(com.facebook.presto.execution.TaskManagerConfig) SystemSessionProperties.getHeapDumpFileDirectory(com.facebook.presto.SystemSessionProperties.getHeapDumpFileDirectory) Duration(io.airlift.units.Duration) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) WarningCollectorConfig(com.facebook.presto.execution.warnings.WarningCollectorConfig) ConnectorManager(com.facebook.presto.connector.ConnectorManager) GlobalSystemConnector(com.facebook.presto.connector.system.GlobalSystemConnector) UNGROUPED_SCHEDULING(com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING) TransactionBuilder.transaction(com.facebook.presto.transaction.TransactionBuilder.transaction) DropView(com.facebook.presto.sql.tree.DropView) TreeAssertions.assertFormattedSql(com.facebook.presto.sql.testing.TreeAssertions.assertFormattedSql) StatsNormalizer(com.facebook.presto.cost.StatsNormalizer) ImmutableSet(com.google.common.collect.ImmutableSet) QualifiedTablePrefix(com.facebook.presto.metadata.QualifiedTablePrefix) TableWriteInfo.createTableWriteInfo(com.facebook.presto.execution.scheduler.TableWriteInfo.createTableWriteInfo) CostCalculatorUsingExchanges(com.facebook.presto.cost.CostCalculatorUsingExchanges) SourceOperatorFactory(com.facebook.presto.operator.SourceOperatorFactory) CostCalculator(com.facebook.presto.cost.CostCalculator) NodeSpillConfig(com.facebook.presto.spiller.NodeSpillConfig) SplitManager(com.facebook.presto.split.SplitManager) GlobalSystemConnectorFactory(com.facebook.presto.connector.system.GlobalSystemConnectorFactory) TransactionManagerConfig(com.facebook.presto.transaction.TransactionManagerConfig) DefaultWarningCollector(com.facebook.presto.execution.warnings.DefaultWarningCollector) SetSession(com.facebook.presto.sql.tree.SetSession) CreateFunctionTask(com.facebook.presto.execution.CreateFunctionTask) CreateView(com.facebook.presto.sql.tree.CreateView) ExpressionCompiler(com.facebook.presto.sql.gen.ExpressionCompiler) Commit(com.facebook.presto.sql.tree.Commit) DataDefinitionTask(com.facebook.presto.execution.DataDefinitionTask) QueryPrerequisitesManager(com.facebook.presto.dispatcher.QueryPrerequisitesManager) SimpleTtlNodeSelectorConfig(com.facebook.presto.execution.scheduler.nodeSelection.SimpleTtlNodeSelectorConfig) RowExpressionDeterminismEvaluator(com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator) Function(java.util.function.Function) PlanOptimizers(com.facebook.presto.sql.planner.PlanOptimizers) LegacyNetworkTopology(com.facebook.presto.execution.scheduler.LegacyNetworkTopology) DriverFactory(com.facebook.presto.operator.DriverFactory) ImmutableList(com.google.common.collect.ImmutableList) PageSourceManager(com.facebook.presto.split.PageSourceManager) PlanPrinter(com.facebook.presto.sql.planner.planPrinter.PlanPrinter) PlanChecker(com.facebook.presto.sql.planner.sanity.PlanChecker) StatsCalculatorModule.createNewStatsCalculator(com.facebook.presto.cost.StatsCalculatorModule.createNewStatsCalculator) IndexManager(com.facebook.presto.index.IndexManager) DropTableTask(com.facebook.presto.execution.DropTableTask) ScheduledSplit(com.facebook.presto.execution.ScheduledSplit) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) EventListener(com.facebook.presto.spi.eventlistener.EventListener) Plan(com.facebook.presto.sql.planner.Plan) Type(com.facebook.presto.common.type.Type) InMemoryNodeManager(com.facebook.presto.metadata.InMemoryNodeManager) ExecutorService(java.util.concurrent.ExecutorService) SubPlan(com.facebook.presto.sql.planner.SubPlan) CreateViewTask(com.facebook.presto.execution.CreateViewTask) OutputFactory(com.facebook.presto.operator.OutputFactory) JoinFilterFunctionCompiler(com.facebook.presto.sql.gen.JoinFilterFunctionCompiler) CatalogManager(com.facebook.presto.metadata.CatalogManager) PlanNode(com.facebook.presto.spi.plan.PlanNode) Statement(com.facebook.presto.sql.tree.Statement) StartTransaction(com.facebook.presto.sql.tree.StartTransaction) StreamingSubPlan(com.facebook.presto.execution.scheduler.StreamingSubPlan) CreateTypeTask(com.facebook.presto.execution.CreateTypeTask) CreateMaterializedViewTask(com.facebook.presto.execution.CreateMaterializedViewTask) EventListenerManager(com.facebook.presto.eventlistener.EventListenerManager) CatalogSystemTable(com.facebook.presto.connector.system.CatalogSystemTable) NoOpFragmentResultCacheManager(com.facebook.presto.operator.NoOpFragmentResultCacheManager) FinalizerService(com.facebook.presto.util.FinalizerService) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) QueryManagerConfig(com.facebook.presto.execution.QueryManagerConfig) ScalarStatsCalculator(com.facebook.presto.cost.ScalarStatsCalculator) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Rollback(com.facebook.presto.sql.tree.Rollback) PageConsumerOutputFactory(com.facebook.presto.testing.PageConsumerOperator.PageConsumerOutputFactory) GenericPartitioningSpillerFactory(com.facebook.presto.spiller.GenericPartitioningSpillerFactory) Explain(com.facebook.presto.sql.tree.Explain) Set(java.util.Set) CreateType(com.facebook.presto.sql.tree.CreateType) JsonCodec.jsonCodec(com.facebook.airlift.json.JsonCodec.jsonCodec) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) UncheckedIOException(java.io.UncheckedIOException) LocalExecutionPlan(com.facebook.presto.sql.planner.LocalExecutionPlanner.LocalExecutionPlan) TESTING_CATALOG(com.facebook.presto.testing.TestingSession.TESTING_CATALOG) DropMaterializedView(com.facebook.presto.sql.tree.DropMaterializedView) Analyzer(com.facebook.presto.sql.analyzer.Analyzer) NodeInfo(com.facebook.airlift.node.NodeInfo) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) CreateFunction(com.facebook.presto.sql.tree.CreateFunction) ArrayList(java.util.ArrayList) Closer(com.google.common.io.Closer) BlockEncodingManager(com.facebook.presto.common.block.BlockEncodingManager) RenameTable(com.facebook.presto.sql.tree.RenameTable) PageSorter(com.facebook.presto.spi.PageSorter) CommitTask(com.facebook.presto.execution.CommitTask) TaskContext(com.facebook.presto.operator.TaskContext) PlanNodeIdAllocator(com.facebook.presto.spi.plan.PlanNodeIdAllocator) Language(org.intellij.lang.annotations.Language) Driver(com.facebook.presto.operator.Driver) ConnectorFactory(com.facebook.presto.spi.connector.ConnectorFactory) Lock(java.util.concurrent.locks.Lock) AlterFunctionTask(com.facebook.presto.execution.AlterFunctionTask) TracingConfig(com.facebook.presto.tracing.TracingConfig) TestingSession.createBogusTestingCatalog(com.facebook.presto.testing.TestingSession.createBogusTestingCatalog) Paths(java.nio.file.Paths) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) ResetSessionTask(com.facebook.presto.execution.ResetSessionTask) InMemoryTransactionManager(com.facebook.presto.transaction.InMemoryTransactionManager) DriverContext(com.facebook.presto.operator.DriverContext) PartitioningProviderManager(com.facebook.presto.sql.planner.PartitioningProviderManager) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) PartitioningSpillerFactory(com.facebook.presto.spiller.PartitioningSpillerFactory) CostCalculatorWithEstimatedExchanges(com.facebook.presto.cost.CostCalculatorWithEstimatedExchanges) TransactionsSystemTable(com.facebook.presto.connector.system.TransactionsSystemTable) NodeTaskMap(com.facebook.presto.execution.NodeTaskMap) MetadataManager(com.facebook.presto.metadata.MetadataManager) TestingMBeanServer(org.weakref.jmx.testing.TestingMBeanServer) REWINDABLE_GROUPED_SCHEDULING(com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.REWINDABLE_GROUPED_SCHEDULING) NodeScheduler(com.facebook.presto.execution.scheduler.NodeScheduler) FileSingleStreamSpillerFactory(com.facebook.presto.spiller.FileSingleStreamSpillerFactory) NoOpResourceGroupManager(com.facebook.presto.execution.resourceGroups.NoOpResourceGroupManager) PagesIndex(com.facebook.presto.operator.PagesIndex) TempStorageStandaloneSpillerFactory(com.facebook.presto.spiller.TempStorageStandaloneSpillerFactory) StatsCalculator(com.facebook.presto.cost.StatsCalculator) PageIndexerFactory(com.facebook.presto.spi.PageIndexerFactory) ColumnPropertiesSystemTable(com.facebook.presto.connector.system.ColumnPropertiesSystemTable) ConnectorMetadataUpdaterManager(com.facebook.presto.metadata.ConnectorMetadataUpdaterManager) DropFunctionTask(com.facebook.presto.execution.DropFunctionTask) FilterStatsCalculator(com.facebook.presto.cost.FilterStatsCalculator) SplitSource(com.facebook.presto.split.SplitSource) GROUPED_SCHEDULING(com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.GROUPED_SCHEDULING) Lifespan(com.facebook.presto.execution.Lifespan) NodeMemoryConfig(com.facebook.presto.memory.NodeMemoryConfig) NodeSystemTable(com.facebook.presto.connector.system.NodeSystemTable) ImmutableMap(com.google.common.collect.ImmutableMap) SchemaPropertyManager(com.facebook.presto.metadata.SchemaPropertyManager) String.format(java.lang.String.format) SqlParser(com.facebook.presto.sql.parser.SqlParser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) StartTransactionTask(com.facebook.presto.execution.StartTransactionTask) List(java.util.List) RenameColumn(com.facebook.presto.sql.tree.RenameColumn) SystemSessionProperties.isHeapDumpOnExceededMemoryLimitEnabled(com.facebook.presto.SystemSessionProperties.isHeapDumpOnExceededMemoryLimitEnabled) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) PluginManager(com.facebook.presto.server.PluginManager) ConnectorId(com.facebook.presto.spi.ConnectorId) LogicalPlanner(com.facebook.presto.sql.planner.LogicalPlanner) CreateTableTask(com.facebook.presto.execution.CreateTableTask) NodeSchedulerConfig(com.facebook.presto.execution.scheduler.NodeSchedulerConfig) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) SpillerStats(com.facebook.presto.spiller.SpillerStats) ParsingUtil.createParsingOptions(com.facebook.presto.sql.ParsingUtil.createParsingOptions) HashMap(java.util.HashMap) SchemaPropertiesSystemTable(com.facebook.presto.connector.system.SchemaPropertiesSystemTable) AtomicReference(java.util.concurrent.atomic.AtomicReference) NoOpQueryManager(com.facebook.presto.dispatcher.NoOpQueryManager) OrderingCompiler(com.facebook.presto.sql.gen.OrderingCompiler) Verify.verify(com.google.common.base.Verify.verify) Deallocate(com.facebook.presto.sql.tree.Deallocate) Objects.requireNonNull(java.util.Objects.requireNonNull) SystemSessionProperties.getQueryMaxTotalMemoryPerNode(com.facebook.presto.SystemSessionProperties.getQueryMaxTotalMemoryPerNode) SetSessionTask(com.facebook.presto.execution.SetSessionTask) MemoryManagerConfig(com.facebook.presto.memory.MemoryManagerConfig) RenameTableTask(com.facebook.presto.execution.RenameTableTask) PlanFragmenter(com.facebook.presto.sql.planner.PlanFragmenter) PlanNodeSearcher.searchFrom(com.facebook.presto.sql.planner.optimizations.PlanNodeSearcher.searchFrom) PagesIndexPageSorter(com.facebook.presto.PagesIndexPageSorter) DropFunction(com.facebook.presto.sql.tree.DropFunction) NodePartitioningManager(com.facebook.presto.sql.planner.NodePartitioningManager) TaskSource(com.facebook.presto.execution.TaskSource) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DeallocateTask(com.facebook.presto.execution.DeallocateTask) TablePropertiesSystemTable(com.facebook.presto.connector.system.TablePropertiesSystemTable) MetadataUtil(com.facebook.presto.metadata.MetadataUtil) SystemSessionProperties.isVerboseExceededMemoryLimitErrorsEnabled(com.facebook.presto.SystemSessionProperties.isVerboseExceededMemoryLimitErrorsEnabled) TimeUnit(java.util.concurrent.TimeUnit) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) AlterFunction(com.facebook.presto.sql.tree.AlterFunction) CostComparator(com.facebook.presto.cost.CostComparator) GroupByHashPageIndexerFactory(com.facebook.presto.GroupByHashPageIndexerFactory) MBeanExporter(org.weakref.jmx.MBeanExporter) HandleResolver(com.facebook.presto.metadata.HandleResolver) JoinCompiler(com.facebook.presto.sql.gen.JoinCompiler) TaskContext(com.facebook.presto.operator.TaskContext) PageConsumerOutputFactory(com.facebook.presto.testing.PageConsumerOperator.PageConsumerOutputFactory) Driver(com.facebook.presto.operator.Driver) AtomicReference(java.util.concurrent.atomic.AtomicReference) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Plan(com.facebook.presto.sql.planner.Plan) SubPlan(com.facebook.presto.sql.planner.SubPlan) StreamingSubPlan(com.facebook.presto.execution.scheduler.StreamingSubPlan) LocalExecutionPlan(com.facebook.presto.sql.planner.LocalExecutionPlanner.LocalExecutionPlan) OperatorContext(com.facebook.presto.operator.OperatorContext)

Example 97 with Language

use of org.intellij.lang.annotations.Language in project presto by prestodb.

the class AccumuloQueryRunner method copyTable.

private static void copyTable(QueryRunner queryRunner, String catalog, Session session, String schema, TpchTable<?> table) {
    QualifiedObjectName source = new QualifiedObjectName(catalog, schema, table.getTableName());
    String target = table.getTableName();
    @Language("SQL") String sql;
    switch(target) {
        case "customer":
            sql = format("CREATE TABLE %s WITH (index_columns = 'mktsegment') AS SELECT * FROM %s", target, source);
            break;
        case "lineitem":
            sql = format("CREATE TABLE %s WITH (index_columns = 'quantity,discount,returnflag,shipdate,receiptdate,shipinstruct,shipmode') AS SELECT cast(uuid() AS varchar) AS uuid, * FROM %s", target, source);
            break;
        case "orders":
            sql = format("CREATE TABLE %s WITH (index_columns = 'orderdate') AS SELECT * FROM %s", target, source);
            break;
        case "part":
            sql = format("CREATE TABLE %s WITH (index_columns = 'brand,type,size,container') AS SELECT * FROM %s", target, source);
            break;
        case "partsupp":
            sql = format("CREATE TABLE %s WITH (index_columns = 'partkey') AS SELECT cast(uuid() AS varchar) AS uuid, * FROM %s", target, source);
            break;
        case "supplier":
            sql = format("CREATE TABLE %s WITH (index_columns = 'name') AS SELECT * FROM %s", target, source);
            break;
        default:
            sql = format("CREATE TABLE %s AS SELECT * FROM %s", target, source);
            break;
    }
    LOG.info("Running import for %s", target, sql);
    LOG.info("%s", sql);
    long start = System.nanoTime();
    long rows = queryRunner.execute(session, sql).getUpdateCount().getAsLong();
    LOG.info("Imported %s rows for %s in %s", rows, target, nanosSince(start));
}
Also used : Language(org.intellij.lang.annotations.Language) QualifiedObjectName(com.facebook.presto.common.QualifiedObjectName)

Example 98 with Language

use of org.intellij.lang.annotations.Language in project presto by prestodb.

the class TestHiveIntegrationSmokeTest method testMismatchedBucketing.

public void testMismatchedBucketing(Session session) {
    try {
        assertUpdate(session, "CREATE TABLE test_mismatch_bucketing16\n" + "WITH (bucket_count = 16, bucketed_by = ARRAY['key16']) AS\n" + "SELECT orderkey key16, comment value16 FROM orders", 15000);
        assertUpdate(session, "CREATE TABLE test_mismatch_bucketing32\n" + "WITH (bucket_count = 32, bucketed_by = ARRAY['key32']) AS\n" + "SELECT orderkey key32, comment value32 FROM orders", 15000);
        assertUpdate(session, "CREATE TABLE test_mismatch_bucketingN AS\n" + "SELECT orderkey keyN, comment valueN FROM orders", 15000);
        Session withMismatchOptimization = Session.builder(session).setSystemProperty(COLOCATED_JOIN, "true").setCatalogSessionProperty(catalog, "optimize_mismatched_bucket_count", "true").build();
        Session withoutMismatchOptimization = Session.builder(session).setSystemProperty(COLOCATED_JOIN, "true").setCatalogSessionProperty(catalog, "optimize_mismatched_bucket_count", "false").build();
        @Language("SQL") String writeToTableWithMoreBuckets = "CREATE TABLE test_mismatch_bucketing_out32\n" + "WITH (bucket_count = 32, bucketed_by = ARRAY['key16'])\n" + "AS\n" + "SELECT key16, value16, key32, value32, keyN, valueN\n" + "FROM\n" + "  test_mismatch_bucketing16\n" + "JOIN\n" + "  test_mismatch_bucketing32\n" + "ON key16=key32\n" + "JOIN\n" + "  test_mismatch_bucketingN\n" + "ON key16=keyN";
        @Language("SQL") String writeToTableWithFewerBuckets = "CREATE TABLE test_mismatch_bucketing_out8\n" + "WITH (bucket_count = 8, bucketed_by = ARRAY['key16'])\n" + "AS\n" + "SELECT key16, value16, key32, value32, keyN, valueN\n" + "FROM\n" + "  test_mismatch_bucketing16\n" + "JOIN\n" + "  test_mismatch_bucketing32\n" + "ON key16=key32\n" + "JOIN\n" + "  test_mismatch_bucketingN\n" + "ON key16=keyN";
        assertUpdate(withoutMismatchOptimization, writeToTableWithMoreBuckets, 15000, assertRemoteExchangesCount(3));
        assertQuery(withoutMismatchOptimization, "SELECT * FROM test_mismatch_bucketing_out32", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate(withoutMismatchOptimization, "DROP TABLE IF EXISTS test_mismatch_bucketing_out32");
        assertUpdate(withMismatchOptimization, writeToTableWithMoreBuckets, 15000, assertRemoteExchangesCount(2));
        assertQuery(withMismatchOptimization, "SELECT * FROM test_mismatch_bucketing_out32", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate(withMismatchOptimization, writeToTableWithFewerBuckets, 15000, assertRemoteExchangesCount(2));
        assertQuery(withMismatchOptimization, "SELECT * FROM test_mismatch_bucketing_out8", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
    } finally {
        assertUpdate(session, "DROP TABLE IF EXISTS test_mismatch_bucketing16");
        assertUpdate(session, "DROP TABLE IF EXISTS test_mismatch_bucketing32");
        assertUpdate(session, "DROP TABLE IF EXISTS test_mismatch_bucketingN");
        assertUpdate(session, "DROP TABLE IF EXISTS test_mismatch_bucketing_out32");
        assertUpdate(session, "DROP TABLE IF EXISTS test_mismatch_bucketing_out8");
    }
}
Also used : Language(org.intellij.lang.annotations.Language) ConnectorSession(com.facebook.presto.spi.ConnectorSession) HiveQueryRunner.createBucketedSession(com.facebook.presto.hive.HiveQueryRunner.createBucketedSession) Session(com.facebook.presto.Session) HiveQueryRunner.createMaterializeExchangesSession(com.facebook.presto.hive.HiveQueryRunner.createMaterializeExchangesSession)

Example 99 with Language

use of org.intellij.lang.annotations.Language in project presto by prestodb.

the class TestHiveIntegrationSmokeTest method testPartialMergePushdown.

public void testPartialMergePushdown(Session session) {
    try {
        assertUpdate("CREATE TABLE test_partial_merge_pushdown_16buckets\n" + "WITH (bucket_count = 16, bucketed_by = ARRAY['key16']) AS\n" + "SELECT orderkey key16, comment value16 FROM orders", 15000);
        assertUpdate("CREATE TABLE test_partial_merge_pushdown_32buckets\n" + "WITH (bucket_count = 32, bucketed_by = ARRAY['key32']) AS\n" + "SELECT orderkey key32, comment value32 FROM orders", 15000);
        assertUpdate("CREATE TABLE test_partial_merge_pushdown_nobucket AS\n" + "SELECT orderkey key_nobucket, comment value_nobucket FROM orders", 15000);
        Session withPartialMergePushdownOptimization = Session.builder(session).setSystemProperty(COLOCATED_JOIN, "true").setSystemProperty(PARTIAL_MERGE_PUSHDOWN_STRATEGY, PUSH_THROUGH_LOW_MEMORY_OPERATORS.name()).build();
        Session withoutPartialMergePushdownOptimization = Session.builder(session).setSystemProperty(COLOCATED_JOIN, "true").setSystemProperty(PARTIAL_MERGE_PUSHDOWN_STRATEGY, PartialMergePushdownStrategy.NONE.name()).build();
        // 
        // join and write to bucketed table
        // ================================
        @Language("SQL") String joinAndWriteToTableWithSameBuckets = "CREATE TABLE test_partial_merge_pushdown_out16\n" + "WITH (bucket_count = 16, bucketed_by = ARRAY['key16'])\n" + "AS\n" + "SELECT key16, value16, key32, value32, key_nobucket, value_nobucket\n" + "FROM\n" + "  test_partial_merge_pushdown_16buckets\n" + "JOIN\n" + "  test_partial_merge_pushdown_32buckets\n" + "ON key16=key32\n" + "JOIN\n" + "  test_partial_merge_pushdown_nobucket\n" + "ON key16=key_nobucket";
        @Language("SQL") String joinAndWriteToTableWithFewerBuckets = "CREATE TABLE test_partial_merge_pushdown_out8\n" + "WITH (bucket_count = 8, bucketed_by = ARRAY['key16'])\n" + "AS\n" + "SELECT key16, value16, key32, value32, key_nobucket, value_nobucket\n" + "FROM\n" + "  test_partial_merge_pushdown_16buckets\n" + "JOIN\n" + "  test_partial_merge_pushdown_32buckets\n" + "ON key16=key32\n" + "JOIN\n" + "  test_partial_merge_pushdown_nobucket\n" + "ON key16=key_nobucket";
        assertUpdate(withoutPartialMergePushdownOptimization, joinAndWriteToTableWithSameBuckets, 15000, assertRemoteExchangesCount(3));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out16", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out16");
        assertUpdate(withPartialMergePushdownOptimization, joinAndWriteToTableWithSameBuckets, 15000, assertRemoteExchangesCount(2));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out16", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out16");
        assertUpdate(withoutPartialMergePushdownOptimization, joinAndWriteToTableWithFewerBuckets, 15000, assertRemoteExchangesCount(4));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out8", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out8");
        // cannot pushdown the partial merge for TableWrite
        assertUpdate(withPartialMergePushdownOptimization, joinAndWriteToTableWithFewerBuckets, 15000, assertRemoteExchangesCount(3));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out8", "SELECT orderkey, comment, orderkey, comment, orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out8");
        // 
        // read and write to bucketed table
        // =====================================
        @Language("SQL") String readAndWriteToTableWithFewerBuckets = "CREATE TABLE test_partial_merge_pushdown_out8\n" + "WITH (bucket_count = 8, bucketed_by = ARRAY['key16'])\n" + "AS\n" + "SELECT key16, value16\n" + "FROM\n" + "  test_partial_merge_pushdown_16buckets";
        assertUpdate(withoutPartialMergePushdownOptimization, readAndWriteToTableWithFewerBuckets, 15000, assertRemoteExchangesCount(2));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out8", "SELECT orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out8");
        assertUpdate(withPartialMergePushdownOptimization, readAndWriteToTableWithFewerBuckets, 15000, assertRemoteExchangesCount(1));
        assertQuery("SELECT * FROM test_partial_merge_pushdown_out8", "SELECT orderkey, comment from orders");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out8");
    } finally {
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_16buckets");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_32buckets");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_nobucket");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out16");
        assertUpdate("DROP TABLE IF EXISTS test_partial_merge_pushdown_out8");
    }
}
Also used : Language(org.intellij.lang.annotations.Language) ConnectorSession(com.facebook.presto.spi.ConnectorSession) HiveQueryRunner.createBucketedSession(com.facebook.presto.hive.HiveQueryRunner.createBucketedSession) Session(com.facebook.presto.Session) HiveQueryRunner.createMaterializeExchangesSession(com.facebook.presto.hive.HiveQueryRunner.createMaterializeExchangesSession)

Example 100 with Language

use of org.intellij.lang.annotations.Language in project presto by prestodb.

the class TestHiveIntegrationSmokeTest method testInsertPartitionedTable.

private void testInsertPartitionedTable(Session session, HiveStorageFormat storageFormat) {
    @Language("SQL") String createTable = "" + "CREATE TABLE test_insert_partitioned_table " + "(" + "  ORDER_KEY BIGINT," + "  SHIP_PRIORITY INTEGER," + "  ORDER_STATUS VARCHAR" + ") " + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'SHIP_PRIORITY', 'ORDER_STATUS' ]" + ") ";
    assertUpdate(session, createTable);
    TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, "test_insert_partitioned_table");
    assertEquals(tableMetadata.getMetadata().getProperties().get(STORAGE_FORMAT_PROPERTY), storageFormat);
    assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("ship_priority", "order_status"));
    String partitionsTable = "\"test_insert_partitioned_table$partitions\"";
    assertQuery(session, "SELECT * FROM " + partitionsTable, "SELECT shippriority, orderstatus FROM orders LIMIT 0");
    // Hive will reorder the partition keys, so we must insert into the table assuming the partition keys have been moved to the end
    assertUpdate(session, "" + "INSERT INTO test_insert_partitioned_table " + "SELECT orderkey, shippriority, orderstatus " + "FROM tpch.tiny.orders", "SELECT count(*) from orders");
    // verify the partitions
    List<?> partitions = getPartitions("test_insert_partitioned_table");
    assertEquals(partitions.size(), 3);
    assertQuery(session, "SELECT * from test_insert_partitioned_table", "SELECT orderkey, shippriority, orderstatus FROM orders");
    assertQuery(session, "SELECT * FROM " + partitionsTable, "SELECT DISTINCT shippriority, orderstatus FROM orders");
    assertQuery(session, "SELECT * FROM " + partitionsTable + " ORDER BY order_status LIMIT 2", "SELECT DISTINCT shippriority, orderstatus FROM orders ORDER BY orderstatus LIMIT 2");
    assertQuery(session, "SELECT * FROM " + partitionsTable + " WHERE order_status = 'O'", "SELECT DISTINCT shippriority, orderstatus FROM orders WHERE orderstatus = 'O'");
    assertQueryFails(session, "SELECT * FROM " + partitionsTable + " WHERE no_such_column = 1", "line \\S*: Column 'no_such_column' cannot be resolved");
    assertQueryFails(session, "SELECT * FROM " + partitionsTable + " WHERE orderkey = 1", "line \\S*: Column 'orderkey' cannot be resolved");
    assertUpdate(session, "DROP TABLE test_insert_partitioned_table");
    assertFalse(getQueryRunner().tableExists(session, "test_insert_partitioned_table"));
}
Also used : TableMetadata(com.facebook.presto.metadata.TableMetadata) Language(org.intellij.lang.annotations.Language)

Aggregations

Language (org.intellij.lang.annotations.Language)111 TableMetadata (com.facebook.presto.metadata.TableMetadata)25 Test (org.testng.annotations.Test)24 MaterializedResult (com.facebook.presto.testing.MaterializedResult)19 PsiFile (com.intellij.psi.PsiFile)18 MaterializedRow (com.facebook.presto.testing.MaterializedRow)11 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 ImmutableList (com.google.common.collect.ImmutableList)10 Session (com.facebook.presto.Session)9 Constraint (com.facebook.presto.spi.Constraint)9 AbstractTestIntegrationSmokeTest (com.facebook.presto.tests.AbstractTestIntegrationSmokeTest)9 BasePlanTest (com.facebook.presto.sql.planner.assertions.BasePlanTest)8 ColumnConstraint (com.facebook.presto.sql.planner.planPrinter.IOPlanPrinter.ColumnConstraint)8 ImmutableMap (com.google.common.collect.ImmutableMap)8 ColumnMetadata (com.facebook.presto.spi.ColumnMetadata)7 ExpectedValueProvider (com.facebook.presto.sql.planner.assertions.ExpectedValueProvider)7 PlanMatchPattern (com.facebook.presto.sql.planner.assertions.PlanMatchPattern)7 SortOrder (com.facebook.presto.common.block.SortOrder)6