Search in sources :

Example 1 with BIGINT

use of com.facebook.presto.common.type.BigintType.BIGINT in project presto by prestodb.

the class TestDatabaseShardManager method testReplaceShardUuidsFunction.

@Test
public void testReplaceShardUuidsFunction() throws SQLException {
    // node1 shard1 shard4
    // node2 shard2
    // node3 shard3
    // goal: replace shard1 and shard4 with newUuid5
    // Initial data
    long tableId = createTable("test");
    List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT));
    UUID uuid1 = UUID.randomUUID();
    UUID uuid2 = UUID.randomUUID();
    UUID uuid3 = UUID.randomUUID();
    UUID uuid4 = UUID.randomUUID();
    ShardInfo shardInfo1 = new ShardInfo(uuid1, OptionalInt.empty(), ImmutableSet.of("node1"), ImmutableList.of(), 1, 1, 1, 1);
    ShardInfo shardInfo2 = new ShardInfo(uuid2, OptionalInt.empty(), ImmutableSet.of("node2"), ImmutableList.of(), 2, 2, 2, 2);
    ShardInfo shardInfo3 = new ShardInfo(uuid3, OptionalInt.empty(), ImmutableSet.of("node3"), ImmutableList.of(), 3, 3, 3, 3);
    ShardInfo shardInfo4 = new ShardInfo(uuid4, OptionalInt.empty(), ImmutableSet.of("node1"), ImmutableList.of(), 4, 4, 4, 4);
    shardManager.createTable(tableId, columns, false, OptionalLong.empty(), true);
    long transactionId = shardManager.beginTransaction();
    shardManager.commitShards(transactionId, tableId, columns, ImmutableList.of(shardInfo1, shardInfo2, shardInfo3, shardInfo4), Optional.empty(), 0);
    // New data
    UUID newUuid5 = UUID.randomUUID();
    ShardInfo newShardInfo4 = new ShardInfo(newUuid5, OptionalInt.empty(), ImmutableSet.of("node1"), ImmutableList.of(), 5, 5, 5, 5);
    // toReplace
    Set<ShardMetadata> shardMetadata = shardManager.getNodeShardsAndDeltas("node1");
    Set<UUID> replacedUuids = shardMetadata.stream().map(ShardMetadata::getShardUuid).collect(toSet());
    Map<UUID, Optional<UUID>> replaceUuidMap = replacedUuids.stream().collect(Collectors.toMap(uuid -> uuid, uuid -> Optional.empty()));
    transactionId = shardManager.beginTransaction();
    shardManager.replaceShardUuids(transactionId, tableId, columns, replaceUuidMap, ImmutableList.of(newShardInfo4), OptionalLong.of(0), true);
    // check shards on this node1 are correct
    shardMetadata = shardManager.getNodeShardsAndDeltas("node1");
    assertEquals(shardMetadata.size(), 1);
    for (ShardMetadata actual : shardMetadata) {
        assertEquals(actual.getShardUuid(), newUuid5);
        assertEquals(actual.getDeltaUuid(), Optional.empty());
        assertEquals(actual.getRowCount(), 5);
        assertEquals(actual.getCompressedSize(), 5);
        assertEquals(actual.getUncompressedSize(), 5);
    }
    // check that shards are replaced in index table as well
    Set<BucketShards> shardNodes = ImmutableSet.copyOf(shardManager.getShardNodes(tableId, TupleDomain.all(), true));
    Set<UUID> actualAllUuids = shardNodes.stream().map(BucketShards::getShards).flatMap(Collection::stream).map(ShardNodes::getShardUuid).collect(toSet());
    Set<UUID> expectedAllUuids = ImmutableSet.of(uuid2, uuid3, newUuid5);
    assertEquals(actualAllUuids, expectedAllUuids);
    // Verify statistics
    Statement statement = dummyHandle.getConnection().createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT * FROM tables where table_id = " + tableId);
    resultSet.next();
    assertEquals(resultSet.getLong("shard_count"), 3);
    assertEquals(resultSet.getLong("delta_count"), 0);
    assertEquals(resultSet.getLong("row_count"), 10);
    assertEquals(resultSet.getLong("compressed_size"), 10);
    assertEquals(resultSet.getLong("uncompressed_size"), 10);
    resultSet.close();
    statement.close();
}
Also used : TestingTicker(com.facebook.airlift.testing.TestingTicker) IDBI(org.skife.jdbi.v2.IDBI) MoreFiles.deleteRecursively(com.google.common.io.MoreFiles.deleteRecursively) ZonedDateTime(java.time.ZonedDateTime) Test(org.testng.annotations.Test) NodeVersion(com.facebook.presto.client.NodeVersion) AfterMethod(org.testng.annotations.AfterMethod) Duration(io.airlift.units.Duration) Ticker.systemTicker(com.google.common.base.Ticker.systemTicker) HashMultimap(com.google.common.collect.HashMultimap) Node(com.facebook.presto.spi.Node) Strings.repeat(com.google.common.base.Strings.repeat) ResultSet(java.sql.ResultSet) Map(java.util.Map) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) URI(java.net.URI) DaoSupplier(com.facebook.presto.raptor.util.DaoSupplier) Assert.assertFalse(org.testng.Assert.assertFalse) Collectors.toSet(java.util.stream.Collectors.toSet) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) ImmutableSet(com.google.common.collect.ImmutableSet) Range.range(com.facebook.presto.common.predicate.Range.range) ImmutableMap(com.google.common.collect.ImmutableMap) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) Collection(java.util.Collection) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) UUID(java.util.UUID) Ticker(com.google.common.base.Ticker) Collectors(java.util.stream.Collectors) Iterators.transform(com.google.common.collect.Iterators.transform) String.format(java.lang.String.format) Range(com.facebook.presto.common.predicate.Range) SchemaDaoUtil.createTablesWithRetry(com.facebook.presto.raptor.metadata.SchemaDaoUtil.createTablesWithRetry) List(java.util.List) Range.greaterThan(com.facebook.presto.common.predicate.Range.greaterThan) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) LocalDate(java.time.LocalDate) UTC(java.time.ZoneOffset.UTC) Optional(java.util.Optional) Range.greaterThanOrEqual(com.facebook.presto.common.predicate.Range.greaterThanOrEqual) ResultSetMetaData(java.sql.ResultSetMetaData) Slice(io.airlift.slice.Slice) NodeSupplier(com.facebook.presto.raptor.NodeSupplier) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) PrestoException(com.facebook.presto.spi.PrestoException) Multimap(com.google.common.collect.Multimap) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) VarcharType.createVarcharType(com.facebook.presto.common.type.VarcharType.createVarcharType) DATE(com.facebook.presto.common.type.DateType.DATE) HashSet(java.util.HashSet) OptionalLong(java.util.OptionalLong) SQLException(java.sql.SQLException) ALLOW_INSECURE(com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE) ImmutableList(com.google.common.collect.ImmutableList) Files(com.google.common.io.Files) DBI(org.skife.jdbi.v2.DBI) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) DAYS(java.util.concurrent.TimeUnit.DAYS) ResultIterator(org.skife.jdbi.v2.ResultIterator) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) RaptorColumnHandle(com.facebook.presto.raptor.RaptorColumnHandle) Type(com.facebook.presto.common.type.Type) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Range.lessThan(com.facebook.presto.common.predicate.Range.lessThan) DatabaseShardManager.shardIndexTable(com.facebook.presto.raptor.metadata.DatabaseShardManager.shardIndexTable) Assert.fail(org.testng.Assert.fail) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) SERVER_STARTING_UP(com.facebook.presto.spi.StandardErrorCode.SERVER_STARTING_UP) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) TRANSACTION_CONFLICT(com.facebook.presto.spi.StandardErrorCode.TRANSACTION_CONFLICT) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) File(java.io.File) InternalNode(com.facebook.presto.metadata.InternalNode) Handle(org.skife.jdbi.v2.Handle) RAPTOR_EXTERNAL_BATCH_ALREADY_EXISTS(com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_EXTERNAL_BATCH_ALREADY_EXISTS) Statement(java.sql.Statement) Iterators.concat(com.google.common.collect.Iterators.concat) ValueSet(com.facebook.presto.common.predicate.ValueSet) MAX_BINARY_INDEX_SIZE(com.facebook.presto.raptor.storage.ShardStats.MAX_BINARY_INDEX_SIZE) Optional(java.util.Optional) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) Collection(java.util.Collection) UUID(java.util.UUID) Test(org.testng.annotations.Test)

Example 2 with BIGINT

use of com.facebook.presto.common.type.BigintType.BIGINT in project presto by prestodb.

the class TestHashJoinOperator method testYield.

@Test
public void testYield() {
    // create a filter function that yields for every probe match
    // verify we will yield #match times totally
    TaskContext taskContext = createTaskContext();
    DriverContext driverContext = taskContext.addPipelineContext(0, true, true, false).addDriverContext();
    // force a yield for every match
    AtomicInteger filterFunctionCalls = new AtomicInteger();
    InternalJoinFilterFunction filterFunction = new TestInternalJoinFilterFunction(((leftPosition, leftPage, rightPosition, rightPage) -> {
        filterFunctionCalls.incrementAndGet();
        driverContext.getYieldSignal().forceYieldForTesting();
        return true;
    }));
    // build with 40 entries
    int entries = 40;
    RowPagesBuilder buildPages = rowPagesBuilder(true, Ints.asList(0), ImmutableList.of(BIGINT)).addSequencePage(entries, 42);
    BuildSideSetup buildSideSetup = setupBuildSide(true, taskContext, Ints.asList(0), buildPages, Optional.of(filterFunction), false, SINGLE_STREAM_SPILLER_FACTORY);
    JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactory = buildSideSetup.getLookupSourceFactoryManager();
    // probe matching the above 40 entries
    RowPagesBuilder probePages = rowPagesBuilder(false, Ints.asList(0), ImmutableList.of(BIGINT));
    List<Page> probeInput = probePages.addSequencePage(100, 0).build();
    OperatorFactory joinOperatorFactory = LOOKUP_JOIN_OPERATORS.innerJoin(0, new PlanNodeId("test"), lookupSourceFactory, probePages.getTypes(), Ints.asList(0), getHashChannelAsInt(probePages), Optional.empty(), OptionalInt.of(1), PARTITIONING_SPILLER_FACTORY);
    instantiateBuildDrivers(buildSideSetup, taskContext);
    buildLookupSource(buildSideSetup);
    Operator operator = joinOperatorFactory.createOperator(driverContext);
    assertTrue(operator.needsInput());
    operator.addInput(probeInput.get(0));
    operator.finish();
    // we will yield 40 times due to filterFunction
    for (int i = 0; i < entries; i++) {
        driverContext.getYieldSignal().setWithDelay(5 * SECONDS.toNanos(1), driverContext.getYieldExecutor());
        filterFunctionCalls.set(0);
        assertNull(operator.getOutput());
        assertEquals(filterFunctionCalls.get(), 1, "Expected join to stop processing (yield) after calling filter function once");
        driverContext.getYieldSignal().reset();
    }
    // delayed yield is not going to prevent operator from producing a page now (yield won't be forced because filter function won't be called anymore)
    driverContext.getYieldSignal().setWithDelay(5 * SECONDS.toNanos(1), driverContext.getYieldExecutor());
    // expect output page to be produced within few calls to getOutput(), e.g. to facilitate spill
    Page output = null;
    for (int i = 0; output == null && i < 5; i++) {
        output = operator.getOutput();
    }
    assertNotNull(output);
    driverContext.getYieldSignal().reset();
    // make sure we have all 4 entries
    assertEquals(output.getPositionCount(), entries);
}
Also used : PartitioningSpillerFactory(com.facebook.presto.spiller.PartitioningSpillerFactory) Page(com.facebook.presto.common.Page) Arrays(java.util.Arrays) GENERIC_INTERNAL_ERROR(com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) MoreFutures.getFutureValue(com.facebook.airlift.concurrent.MoreFutures.getFutureValue) Collections.singletonList(java.util.Collections.singletonList) Future(java.util.concurrent.Future) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PageBuffer(com.facebook.presto.operator.index.PageBuffer) SingleStreamSpiller(com.facebook.presto.spiller.SingleStreamSpiller) RowPagesBuilder(com.facebook.presto.RowPagesBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) Arrays.asList(java.util.Arrays.asList) HashBuilderOperatorFactory(com.facebook.presto.operator.HashBuilderOperator.HashBuilderOperatorFactory) Lifespan(com.facebook.presto.execution.Lifespan) ImmutableSet(com.google.common.collect.ImmutableSet) GenericPartitioningSpillerFactory(com.facebook.presto.spiller.GenericPartitioningSpillerFactory) ImmutableMap(com.google.common.collect.ImmutableMap) SynchronousQueue(java.util.concurrent.SynchronousQueue) Collections.nCopies(java.util.Collections.nCopies) LocalExchangeSinkOperatorFactory(com.facebook.presto.operator.exchange.LocalExchangeSinkOperator.LocalExchangeSinkOperatorFactory) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) BeforeMethod(org.testng.annotations.BeforeMethod) OperatorAssertion.assertOperatorEquals(com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals) LocalMemoryContext(com.facebook.presto.memory.context.LocalMemoryContext) Assert.assertNotNull(org.testng.Assert.assertNotNull) Iterators.unmodifiableIterator(com.google.common.collect.Iterators.unmodifiableIterator) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) DataSize(io.airlift.units.DataSize) List(java.util.List) Optional(java.util.Optional) LocalExchangeSourceOperatorFactory(com.facebook.presto.operator.exchange.LocalExchangeSourceOperator.LocalExchangeSourceOperatorFactory) FIXED_HASH_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION) TaskStateMachine(com.facebook.presto.execution.TaskStateMachine) RowPagesBuilder.rowPagesBuilder(com.facebook.presto.RowPagesBuilder.rowPagesBuilder) ExceededMemoryLimitException(com.facebook.presto.ExceededMemoryLimitException) JoinFilterFunctionFactory(com.facebook.presto.sql.gen.JoinFilterFunctionCompiler.JoinFilterFunctionFactory) IntStream(java.util.stream.IntStream) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) Iterables(com.google.common.collect.Iterables) PageBufferOperatorFactory(com.facebook.presto.operator.index.PageBufferOperator.PageBufferOperatorFactory) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) DataProvider(org.testng.annotations.DataProvider) Assert.assertNull(org.testng.Assert.assertNull) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Assert.assertEquals(com.facebook.presto.testing.assertions.Assert.assertEquals) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PrestoException(com.facebook.presto.spi.PrestoException) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) ValuesOperatorFactory(com.facebook.presto.operator.ValuesOperator.ValuesOperatorFactory) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) TEST_SESSION(com.facebook.presto.SessionTestUtils.TEST_SESSION) UNGROUPED_EXECUTION(com.facebook.presto.operator.PipelineExecutionStrategy.UNGROUPED_EXECUTION) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SingleStreamSpillerFactory(com.facebook.presto.spiller.SingleStreamSpillerFactory) TestingTaskContext(com.facebook.presto.testing.TestingTaskContext) Type(com.facebook.presto.common.type.Type) ExecutorService(java.util.concurrent.ExecutorService) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) Iterator(java.util.Iterator) Assertions.assertEqualsIgnoreOrder(com.facebook.airlift.testing.Assertions.assertEqualsIgnoreOrder) Session(com.facebook.presto.Session) LocalExchangeSinkFactoryId(com.facebook.presto.operator.exchange.LocalExchange.LocalExchangeSinkFactoryId) Assert.fail(org.testng.Assert.fail) OperatorAssertion.dropChannel(com.facebook.presto.operator.OperatorAssertion.dropChannel) OperatorAssertion.without(com.facebook.presto.operator.OperatorAssertion.without) TestingSession.testSessionBuilder(com.facebook.presto.testing.TestingSession.testSessionBuilder) Ints(com.google.common.primitives.Ints) LocalExchangeFactory(com.facebook.presto.operator.exchange.LocalExchange.LocalExchangeFactory) TimeUnit(java.util.concurrent.TimeUnit) MaterializedResult(com.facebook.presto.testing.MaterializedResult) Collectors.toList(java.util.stream.Collectors.toList) TaskId(com.facebook.presto.execution.TaskId) Futures.immediateFailedFuture(com.google.common.util.concurrent.Futures.immediateFailedFuture) Assert.assertTrue(org.testng.Assert.assertTrue) BYTE(io.airlift.units.DataSize.Unit.BYTE) SECONDS(java.util.concurrent.TimeUnit.SECONDS) PartitioningProviderManager(com.facebook.presto.sql.planner.PartitioningProviderManager) TestingTaskContext(com.facebook.presto.testing.TestingTaskContext) RowPagesBuilder(com.facebook.presto.RowPagesBuilder) Page(com.facebook.presto.common.Page) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashBuilderOperatorFactory(com.facebook.presto.operator.HashBuilderOperator.HashBuilderOperatorFactory) LocalExchangeSinkOperatorFactory(com.facebook.presto.operator.exchange.LocalExchangeSinkOperator.LocalExchangeSinkOperatorFactory) LocalExchangeSourceOperatorFactory(com.facebook.presto.operator.exchange.LocalExchangeSourceOperator.LocalExchangeSourceOperatorFactory) PageBufferOperatorFactory(com.facebook.presto.operator.index.PageBufferOperator.PageBufferOperatorFactory) ValuesOperatorFactory(com.facebook.presto.operator.ValuesOperator.ValuesOperatorFactory) Test(org.testng.annotations.Test)

Example 3 with BIGINT

use of com.facebook.presto.common.type.BigintType.BIGINT in project presto by prestodb.

the class TestSignatureBinder method testFunction.

@Test
public void testFunction() {
    Signature simple = functionSignature().returnType(parseTypeSignature("boolean")).argumentTypes(parseTypeSignature("function(integer,integer)")).build();
    assertThat(simple).boundTo("integer").fails();
    assertThat(simple).boundTo("function(integer,integer)").succeeds();
    // TODO: Support coercion of return type of lambda
    assertThat(simple).boundTo("function(integer,smallint)").withCoercion().fails();
    assertThat(simple).boundTo("function(integer,bigint)").withCoercion().fails();
    Signature applyTwice = functionSignature().returnType(parseTypeSignature("V")).argumentTypes(parseTypeSignature("T"), parseTypeSignature("function(T,U)"), parseTypeSignature("function(U,V)")).typeVariableConstraints(typeVariable("T"), typeVariable("U"), typeVariable("V")).build();
    assertThat(applyTwice).boundTo("integer", "integer", "integer").fails();
    assertThat(applyTwice).boundTo("integer", "function(integer,varchar)", "function(varchar,double)").produces(BoundVariables.builder().setTypeVariable("T", INTEGER).setTypeVariable("U", VARCHAR).setTypeVariable("V", DOUBLE).build());
    assertThat(applyTwice).boundTo("integer", new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(integer,varchar)")), new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(varchar,double)"))).produces(BoundVariables.builder().setTypeVariable("T", INTEGER).setTypeVariable("U", VARCHAR).setTypeVariable("V", DOUBLE).build());
    assertThat(applyTwice).boundTo(// pass function argument to non-function position of a function
    new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(integer,varchar)")), new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(integer,varchar)")), new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(varchar,double)"))).fails();
    assertThat(applyTwice).boundTo(new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(integer,varchar)")), // pass non-function argument to function position of a function
    "integer", new TypeSignatureProvider(functionArgumentTypes -> TypeSignature.parseTypeSignature("function(varchar,double)"))).fails();
    Signature flatMap = functionSignature().returnType(parseTypeSignature("array(T)")).argumentTypes(parseTypeSignature("array(T)"), parseTypeSignature("function(T, array(T))")).typeVariableConstraints(typeVariable("T")).build();
    assertThat(flatMap).boundTo("array(integer)", "function(integer, array(integer))").produces(BoundVariables.builder().setTypeVariable("T", INTEGER).build());
    Signature varargApply = functionSignature().returnType(parseTypeSignature("T")).argumentTypes(parseTypeSignature("T"), parseTypeSignature("function(T, T)")).typeVariableConstraints(typeVariable("T")).setVariableArity(true).build();
    assertThat(varargApply).boundTo("integer", "function(integer, integer)", "function(integer, integer)", "function(integer, integer)").produces(BoundVariables.builder().setTypeVariable("T", INTEGER).build());
    assertThat(varargApply).boundTo("integer", "function(integer, integer)", "function(integer, double)", "function(double, double)").fails();
    Signature loop = functionSignature().returnType(parseTypeSignature("T")).argumentTypes(parseTypeSignature("T"), parseTypeSignature("function(T, T)")).typeVariableConstraints(typeVariable("T")).build();
    assertThat(loop).boundTo("integer", new TypeSignatureProvider(paramTypes -> new FunctionType(paramTypes, BIGINT).getTypeSignature())).fails();
    assertThat(loop).boundTo("integer", new TypeSignatureProvider(paramTypes -> new FunctionType(paramTypes, BIGINT).getTypeSignature())).withCoercion().produces(BoundVariables.builder().setTypeVariable("T", BIGINT).build());
    // TODO: Support coercion of return type of lambda
    assertThat(loop).withCoercion().boundTo("integer", new TypeSignatureProvider(paramTypes -> new FunctionType(paramTypes, SMALLINT).getTypeSignature())).fails();
    // TODO: Support coercion of return type of lambda
    // Without coercion support for return type of lambda, the return type of lambda must be `varchar(x)` to avoid need for coercions.
    Signature varcharApply = functionSignature().returnType(parseTypeSignature("varchar")).argumentTypes(parseTypeSignature("varchar"), parseTypeSignature("function(varchar, varchar(x))", ImmutableSet.of("x"))).build();
    assertThat(varcharApply).withCoercion().boundTo("varchar(10)", new TypeSignatureProvider(paramTypes -> new FunctionType(paramTypes, createVarcharType(1)).getTypeSignature())).succeeds();
    Signature sortByKey = functionSignature().returnType(parseTypeSignature("array(T)")).argumentTypes(parseTypeSignature("array(T)"), parseTypeSignature("function(T,E)")).typeVariableConstraints(typeVariable("T"), orderableTypeParameter("E")).build();
    assertThat(sortByKey).boundTo("array(integer)", new TypeSignatureProvider(paramTypes -> new FunctionType(paramTypes, VARCHAR).getTypeSignature())).produces(BoundVariables.builder().setTypeVariable("T", INTEGER).setTypeVariable("E", VARCHAR).build());
}
Also used : TypeSignatureProvider(com.facebook.presto.sql.analyzer.TypeSignatureProvider) StandardTypes(com.facebook.presto.common.type.StandardTypes) DecimalType(com.facebook.presto.common.type.DecimalType) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) VarcharType.createVarcharType(com.facebook.presto.common.type.VarcharType.createVarcharType) FunctionAndTypeManager.createTestFunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager) TypeSignatureProvider.fromTypes(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes) TypeSignature(com.facebook.presto.common.type.TypeSignature) Signature.typeVariable(com.facebook.presto.spi.function.Signature.typeVariable) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) Signature.orderableTypeParameter(com.facebook.presto.spi.function.Signature.orderableTypeParameter) Assert.assertFalse(org.testng.Assert.assertFalse) Type(com.facebook.presto.common.type.Type) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Signature.comparableTypeParameter(com.facebook.presto.spi.function.Signature.comparableTypeParameter) ImmutableSet(com.google.common.collect.ImmutableSet) TypeVariableConstraint(com.facebook.presto.spi.function.TypeVariableConstraint) ImmutableMap(com.google.common.collect.ImmutableMap) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) Assert.fail(org.testng.Assert.fail) Set(java.util.Set) Assert.assertNotNull(org.testng.Assert.assertNotNull) FunctionType(com.facebook.presto.common.type.FunctionType) SCALAR(com.facebook.presto.spi.function.FunctionKind.SCALAR) String.format(java.lang.String.format) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) TypeSignature.parseTypeSignature(com.facebook.presto.common.type.TypeSignature.parseTypeSignature) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) Signature(com.facebook.presto.spi.function.Signature) TypeSignatureProvider(com.facebook.presto.sql.analyzer.TypeSignatureProvider) Optional(java.util.Optional) Assert.assertTrue(org.testng.Assert.assertTrue) Signature.withVariadicBound(com.facebook.presto.spi.function.Signature.withVariadicBound) TypeSignature(com.facebook.presto.common.type.TypeSignature) TypeSignature.parseTypeSignature(com.facebook.presto.common.type.TypeSignature.parseTypeSignature) Signature(com.facebook.presto.spi.function.Signature) FunctionType(com.facebook.presto.common.type.FunctionType) Test(org.testng.annotations.Test)

Example 4 with BIGINT

use of com.facebook.presto.common.type.BigintType.BIGINT in project presto by prestodb.

the class AbstractTestOrcReader method testCaching.

@Test
public void testCaching() throws Exception {
    Cache<OrcDataSourceId, OrcFileTail> orcFileTailCache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, tail) -> ((OrcFileTail) tail).getFooterSize() + ((OrcFileTail) tail).getMetadataSize()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    OrcFileTailSource orcFileTailSource = new CachingOrcFileTailSource(new StorageOrcFileTailSource(), orcFileTailCache);
    Cache<StripeId, Slice> stripeFootercache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, footer) -> ((Slice) footer).length()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    Cache<StripeStreamId, Slice> stripeStreamCache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, stream) -> ((Slice) stream).length()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    Optional<Cache<StripeStreamId, List<RowGroupIndex>>> rowGroupIndexCache = Optional.of(CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, rowGroupIndices) -> toIntExact(((List<RowGroupIndex>) rowGroupIndices).stream().mapToLong(RowGroupIndex::getRetainedSizeInBytes).sum())).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build());
    StripeMetadataSource stripeMetadataSource = new CachingStripeMetadataSource(new StorageStripeMetadataSource(), stripeFootercache, stripeStreamCache, rowGroupIndexCache);
    try (TempFile tempFile = createTempFile(10001)) {
        OrcBatchRecordReader storageReader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, ImmutableList.of(BIGINT), INITIAL_BATCH_SIZE, orcFileTailSource, stripeMetadataSource, true, ImmutableMap.of(), false);
        assertEquals(orcFileTailCache.stats().missCount(), 1);
        assertEquals(orcFileTailCache.stats().hitCount(), 0);
        OrcBatchRecordReader cacheReader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, ImmutableList.of(BIGINT), INITIAL_BATCH_SIZE, orcFileTailSource, stripeMetadataSource, true, ImmutableMap.of(), false);
        assertEquals(orcFileTailCache.stats().missCount(), 1);
        assertEquals(orcFileTailCache.stats().hitCount(), 1);
        assertEquals(storageReader.getRetainedSizeInBytes(), cacheReader.getRetainedSizeInBytes());
        assertEquals(storageReader.getFileRowCount(), cacheReader.getFileRowCount());
        assertEquals(storageReader.getSplitLength(), cacheReader.getSplitLength());
        storageReader.nextBatch();
        assertEquals(stripeFootercache.stats().missCount(), 1);
        assertEquals(stripeFootercache.stats().hitCount(), 0);
        assertEquals(stripeStreamCache.stats().missCount(), 2);
        assertEquals(stripeStreamCache.stats().hitCount(), 0);
        assertEquals(rowGroupIndexCache.get().stats().missCount(), 1);
        assertEquals(rowGroupIndexCache.get().stats().hitCount(), 0);
        cacheReader.nextBatch();
        assertEquals(stripeFootercache.stats().missCount(), 1);
        assertEquals(stripeFootercache.stats().hitCount(), 1);
        assertEquals(stripeStreamCache.stats().missCount(), 2);
        assertEquals(stripeStreamCache.stats().hitCount(), 2);
        assertEquals(rowGroupIndexCache.get().stats().missCount(), 1);
        assertEquals(rowGroupIndexCache.get().stats().hitCount(), 1);
        assertEquals(storageReader.readBlock(0).getInt(0), cacheReader.readBlock(0).getInt(0));
    }
}
Also used : RecordWriter(org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter) CharType.createCharType(com.facebook.presto.common.type.CharType.createCharType) DateTimeZone(org.joda.time.DateTimeZone) StripeId(com.facebook.presto.orc.StripeReader.StripeId) Writable(org.apache.hadoop.io.Writable) Test(org.testng.annotations.Test) Random(java.util.Random) ORC_12(com.facebook.presto.orc.OrcTester.Format.ORC_12) OrcSerde(org.apache.hadoop.hive.ql.io.orc.OrcSerde) Duration(io.airlift.units.Duration) SESSION(com.facebook.presto.testing.TestingConnectorSession.SESSION) Iterables.concat(com.google.common.collect.Iterables.concat) Iterables.cycle(com.google.common.collect.Iterables.cycle) RowGroupIndex(com.facebook.presto.orc.metadata.RowGroupIndex) HIVE_STORAGE_TIME_ZONE(com.facebook.presto.orc.OrcTester.HIVE_STORAGE_TIME_ZONE) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) OrcTester.createOrcRecordWriter(com.facebook.presto.orc.OrcTester.createOrcRecordWriter) BigInteger(java.math.BigInteger) SqlDecimal(com.facebook.presto.common.type.SqlDecimal) ImmutableMap(com.google.common.collect.ImmutableMap) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) Collections.nCopies(java.util.Collections.nCopies) BeforeClass(org.testng.annotations.BeforeClass) INITIAL_BATCH_SIZE(com.facebook.presto.orc.OrcReader.INITIAL_BATCH_SIZE) Range(com.google.common.collect.Range) StripeStreamId(com.facebook.presto.orc.StripeReader.StripeStreamId) Iterables.limit(com.google.common.collect.Iterables.limit) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) ORC(com.facebook.presto.orc.OrcEncoding.ORC) DataSize(io.airlift.units.DataSize) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) OrcTester.createCustomOrcRecordReader(com.facebook.presto.orc.OrcTester.createCustomOrcRecordReader) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) CompressionKind(com.facebook.presto.orc.metadata.CompressionKind) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) Builder(com.google.common.collect.ImmutableList.Builder) StructField(org.apache.hadoop.hive.serde2.objectinspector.StructField) DecimalType(com.facebook.presto.common.type.DecimalType) ContiguousSet(com.google.common.collect.ContiguousSet) Slice(io.airlift.slice.Slice) TINYINT(com.facebook.presto.common.type.TinyintType.TINYINT) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) DateTimeTestingUtils.sqlTimestampOf(com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) Assert.assertEquals(org.testng.Assert.assertEquals) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) MINUTES(java.util.concurrent.TimeUnit.MINUTES) DATE(com.facebook.presto.common.type.DateType.DATE) REAL(com.facebook.presto.common.type.RealType.REAL) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) SqlDate(com.facebook.presto.common.type.SqlDate) ImmutableList(com.google.common.collect.ImmutableList) OrcFileTail(com.facebook.presto.orc.metadata.OrcFileTail) SqlVarbinary(com.facebook.presto.common.type.SqlVarbinary) DiscreteDomain(com.google.common.collect.DiscreteDomain) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) CharType(com.facebook.presto.common.type.CharType) Math.toIntExact(java.lang.Math.toIntExact) OrcFileTailSource(com.facebook.presto.orc.cache.OrcFileTailSource) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AbstractIterator(com.google.common.collect.AbstractIterator) IOException(java.io.IOException) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) SettableStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) Collectors.toList(java.util.stream.Collectors.toList) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) Serializer(org.apache.hadoop.hive.serde2.Serializer) Cache(com.google.common.cache.Cache) SerDeException(org.apache.hadoop.hive.serde2.SerDeException) OrcTester.createSettableStructObjectInspector(com.facebook.presto.orc.OrcTester.createSettableStructObjectInspector) Collections(java.util.Collections) StripeStreamId(com.facebook.presto.orc.StripeReader.StripeStreamId) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) OrcFileTailSource(com.facebook.presto.orc.cache.OrcFileTailSource) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) Duration(io.airlift.units.Duration) OrcFileTail(com.facebook.presto.orc.metadata.OrcFileTail) StripeId(com.facebook.presto.orc.StripeReader.StripeId) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) RowGroupIndex(com.facebook.presto.orc.metadata.RowGroupIndex) Slice(io.airlift.slice.Slice) DataSize(io.airlift.units.DataSize) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) Cache(com.google.common.cache.Cache) Test(org.testng.annotations.Test)

Example 5 with BIGINT

use of com.facebook.presto.common.type.BigintType.BIGINT in project presto by prestodb.

the class TestCassandraIntegrationSmokeTest method assertSelect.

private void assertSelect(String tableName, boolean createdByPresto) {
    Type uuidType = createdByPresto ? createUnboundedVarcharType() : createVarcharType(36);
    Type inetType = createdByPresto ? createUnboundedVarcharType() : createVarcharType(45);
    String sql = "SELECT " + " key, " + " typeuuid, " + " typeinteger, " + " typelong, " + " typebytes, " + " typetimestamp, " + " typeansi, " + " typeboolean, " + " typedecimal, " + " typedouble, " + " typefloat, " + " typeinet, " + " typevarchar, " + " typevarint, " + " typetimeuuid, " + " typelist, " + " typemap, " + " typeset " + " FROM " + tableName;
    MaterializedResult result = execute(sql);
    int rowCount = result.getRowCount();
    assertEquals(rowCount, 9);
    assertEquals(result.getTypes(), ImmutableList.of(createUnboundedVarcharType(), uuidType, INTEGER, BIGINT, VARBINARY, TIMESTAMP, createUnboundedVarcharType(), BOOLEAN, DOUBLE, DOUBLE, REAL, inetType, createUnboundedVarcharType(), createUnboundedVarcharType(), uuidType, createUnboundedVarcharType(), createUnboundedVarcharType(), createUnboundedVarcharType()));
    List<MaterializedRow> sortedRows = result.getMaterializedRows().stream().sorted((o1, o2) -> o1.getField(1).toString().compareTo(o2.getField(1).toString())).collect(toList());
    for (int rowNumber = 1; rowNumber <= rowCount; rowNumber++) {
        assertEquals(sortedRows.get(rowNumber - 1), new MaterializedRow(DEFAULT_PRECISION, "key " + rowNumber, String.format("00000000-0000-0000-0000-%012d", rowNumber), rowNumber, rowNumber + 1000L, ByteBuffer.wrap(toByteArray(rowNumber)), TIMESTAMP_LOCAL, "ansi " + rowNumber, rowNumber % 2 == 0, Math.pow(2, rowNumber), Math.pow(4, rowNumber), (float) Math.pow(8, rowNumber), "127.0.0.1", "varchar " + rowNumber, BigInteger.TEN.pow(rowNumber).toString(), String.format("d2177dd0-eaa2-11de-a572-001b779c76e%d", rowNumber), String.format("[\"list-value-1%1$d\",\"list-value-2%1$d\"]", rowNumber), String.format("{%d:%d,%d:%d}", rowNumber, rowNumber + 1L, rowNumber + 2, rowNumber + 3L), "[false,true]"));
    }
}
Also used : TABLE_CLUSTERING_KEYS_INEQUALITY(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_CLUSTERING_KEYS_INEQUALITY) VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) LocalDateTime(java.time.LocalDateTime) TABLE_ALL_TYPES(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_ALL_TYPES) MaterializedResult.resultBuilder(com.facebook.presto.testing.MaterializedResult.resultBuilder) Assert.assertEquals(org.testng.Assert.assertEquals) QueryRunner(com.facebook.presto.testing.QueryRunner) Test(org.testng.annotations.Test) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) MINUTES(java.util.concurrent.TimeUnit.MINUTES) VarcharType.createVarcharType(com.facebook.presto.common.type.VarcharType.createVarcharType) ByteBuffer(java.nio.ByteBuffer) REAL(com.facebook.presto.common.type.RealType.REAL) Duration(io.airlift.units.Duration) Bytes.toRawHexString(com.datastax.driver.core.utils.Bytes.toRawHexString) DEFAULT_PRECISION(com.facebook.presto.testing.MaterializedResult.DEFAULT_PRECISION) ImmutableList(com.google.common.collect.ImmutableList) QueryAssertions.assertContains(com.facebook.presto.tests.QueryAssertions.assertContains) TABLE_ALL_TYPES_PARTITION_KEY(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_ALL_TYPES_PARTITION_KEY) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) BigInteger(java.math.BigInteger) Ints.toByteArray(com.google.common.primitives.Ints.toByteArray) Type(com.facebook.presto.common.type.Type) CassandraQueryRunner.createCassandraQueryRunner(com.facebook.presto.cassandra.CassandraQueryRunner.createCassandraQueryRunner) TABLE_ALL_TYPES_INSERT(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_ALL_TYPES_INSERT) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) TABLE_CLUSTERING_KEYS_LARGE(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_CLUSTERING_KEYS_LARGE) Session(com.facebook.presto.Session) BeforeClass(org.testng.annotations.BeforeClass) Timestamp(java.sql.Timestamp) TABLE_CLUSTERING_KEYS(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_CLUSTERING_KEYS) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) CassandraQueryRunner.createCassandraSession(com.facebook.presto.cassandra.CassandraQueryRunner.createCassandraSession) CassandraTestingUtils.createTestTables(com.facebook.presto.cassandra.CassandraTestingUtils.createTestTables) MaterializedResult(com.facebook.presto.testing.MaterializedResult) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) MaterializedRow(com.facebook.presto.testing.MaterializedRow) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) TABLE_MULTI_PARTITION_CLUSTERING_KEYS(com.facebook.presto.cassandra.CassandraTestingUtils.TABLE_MULTI_PARTITION_CLUSTERING_KEYS) AbstractTestIntegrationSmokeTest(com.facebook.presto.tests.AbstractTestIntegrationSmokeTest) QueryAssertions.assertContainsEventually(com.facebook.presto.tests.QueryAssertions.assertContainsEventually) VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) VarcharType.createVarcharType(com.facebook.presto.common.type.VarcharType.createVarcharType) Type(com.facebook.presto.common.type.Type) Bytes.toRawHexString(com.datastax.driver.core.utils.Bytes.toRawHexString) MaterializedResult(com.facebook.presto.testing.MaterializedResult) MaterializedRow(com.facebook.presto.testing.MaterializedRow)

Aggregations

BIGINT (com.facebook.presto.common.type.BigintType.BIGINT)68 Test (org.testng.annotations.Test)62 ImmutableList (com.google.common.collect.ImmutableList)61 Optional (java.util.Optional)59 ImmutableMap (com.google.common.collect.ImmutableMap)46 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)40 List (java.util.List)31 PlanMatchPattern.values (com.facebook.presto.sql.planner.assertions.PlanMatchPattern.values)26 PlanNodeId (com.facebook.presto.spi.plan.PlanNodeId)25 BeforeClass (org.testng.annotations.BeforeClass)25 VARCHAR (com.facebook.presto.common.type.VarcharType.VARCHAR)23 JOIN_DISTRIBUTION_TYPE (com.facebook.presto.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE)21 BOOLEAN (com.facebook.presto.common.type.BooleanType.BOOLEAN)21 AfterClass (org.testng.annotations.AfterClass)21 Type (com.facebook.presto.common.type.Type)20 JoinDistributionType (com.facebook.presto.sql.analyzer.FeaturesConfig.JoinDistributionType)20 RuleTester (com.facebook.presto.sql.planner.iterative.rule.test.RuleTester)20 PlanNodeStatsEstimate (com.facebook.presto.cost.PlanNodeStatsEstimate)19 VariableStatsEstimate (com.facebook.presto.cost.VariableStatsEstimate)19 PlanBuilder.constantExpressions (com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder.constantExpressions)19