Search in sources :

Example 6 with DOUBLE

use of io.trino.spi.type.DoubleType.DOUBLE in project trino by trinodb.

the class BenchmarkFileFormatsUtils method createTpchDataSet.

public static <E extends TpchEntity> TestData createTpchDataSet(FileFormat format, TpchTable<E> tpchTable, List<TpchColumn<E>> columns) {
    List<String> columnNames = columns.stream().map(TpchColumn::getColumnName).collect(toList());
    List<Type> columnTypes = columns.stream().map(BenchmarkFileFormatsUtils::getColumnType).map(type -> format.supportsDate() || !DATE.equals(type) ? type : createUnboundedVarcharType()).collect(toList());
    PageBuilder pageBuilder = new PageBuilder(columnTypes);
    ImmutableList.Builder<Page> pages = ImmutableList.builder();
    long dataSize = 0;
    for (E row : tpchTable.createGenerator(10, 1, 1)) {
        pageBuilder.declarePosition();
        for (int i = 0; i < columns.size(); i++) {
            TpchColumn<E> column = columns.get(i);
            BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i);
            switch(column.getType().getBase()) {
                case IDENTIFIER:
                    BIGINT.writeLong(blockBuilder, column.getIdentifier(row));
                    break;
                case INTEGER:
                    INTEGER.writeLong(blockBuilder, column.getInteger(row));
                    break;
                case DATE:
                    if (format.supportsDate()) {
                        DATE.writeLong(blockBuilder, column.getDate(row));
                    } else {
                        createUnboundedVarcharType().writeString(blockBuilder, column.getString(row));
                    }
                    break;
                case DOUBLE:
                    DOUBLE.writeDouble(blockBuilder, column.getDouble(row));
                    break;
                case VARCHAR:
                    createUnboundedVarcharType().writeSlice(blockBuilder, Slices.utf8Slice(column.getString(row)));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported type " + column.getType());
            }
        }
        if (pageBuilder.isFull()) {
            Page page = pageBuilder.build();
            pages.add(page);
            pageBuilder.reset();
            dataSize += page.getSizeInBytes();
            if (dataSize >= MIN_DATA_SIZE) {
                break;
            }
        }
    }
    if (!pageBuilder.isEmpty()) {
        pages.add(pageBuilder.build());
    }
    return new TestData(columnNames, columnTypes, pages.build());
}
Also used : PageBuilder(io.trino.spi.PageBuilder) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) Type(io.trino.spi.type.Type) RunResult(org.openjdk.jmh.results.RunResult) Page(io.trino.spi.Page) VarcharType.createUnboundedVarcharType(io.trino.spi.type.VarcharType.createUnboundedVarcharType) Random(java.util.Random) Statistics(org.openjdk.jmh.util.Statistics) ImmutableList(com.google.common.collect.ImmutableList) Files.createTempDirectory(java.nio.file.Files.createTempDirectory) Slices(io.airlift.slice.Slices) INTEGER(io.trino.spi.type.IntegerType.INTEGER) TpchEntity(io.trino.tpch.TpchEntity) TpchTable(io.trino.tpch.TpchTable) Collection(java.util.Collection) IOException(java.io.IOException) File(java.io.File) String.format(java.lang.String.format) UncheckedIOException(java.io.UncheckedIOException) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) DataSize(io.airlift.units.DataSize) TpchColumn(io.trino.tpch.TpchColumn) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) BIGINT(io.trino.spi.type.BigintType.BIGINT) BlockBuilder(io.trino.spi.block.BlockBuilder) DATE(io.trino.spi.type.DateType.DATE) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) DATE(io.trino.spi.type.DateType.DATE) ImmutableList(com.google.common.collect.ImmutableList) Page(io.trino.spi.Page) PageBuilder(io.trino.spi.PageBuilder) Type(io.trino.spi.type.Type) VarcharType.createUnboundedVarcharType(io.trino.spi.type.VarcharType.createUnboundedVarcharType) BlockBuilder(io.trino.spi.block.BlockBuilder)

Example 7 with DOUBLE

use of io.trino.spi.type.DoubleType.DOUBLE in project trino by trinodb.

the class TestSwapAdjacentWindowsBySpecifications method subsetComesFirst.

@Test
public void subsetComesFirst() {
    String columnAAlias = "ALIAS_A";
    String columnBAlias = "ALIAS_B";
    ExpectedValueProvider<WindowNode.Specification> specificationA = specification(ImmutableList.of(columnAAlias), ImmutableList.of(), ImmutableMap.of());
    ExpectedValueProvider<WindowNode.Specification> specificationAB = specification(ImmutableList.of(columnAAlias, columnBAlias), ImmutableList.of(), ImmutableMap.of());
    tester().assertThat(new GatherAndMergeWindows.SwapAdjacentWindowsBySpecifications(0)).on(p -> p.window(new WindowNode.Specification(ImmutableList.of(p.symbol("a")), Optional.empty()), ImmutableMap.of(p.symbol("avg_1", DOUBLE), new WindowNode.Function(resolvedFunction, ImmutableList.of(new SymbolReference("a")), DEFAULT_FRAME, false)), p.window(new WindowNode.Specification(ImmutableList.of(p.symbol("a"), p.symbol("b")), Optional.empty()), ImmutableMap.of(p.symbol("avg_2", DOUBLE), new WindowNode.Function(resolvedFunction, ImmutableList.of(new SymbolReference("b")), DEFAULT_FRAME, false)), p.values(p.symbol("a"), p.symbol("b"))))).matches(window(windowMatcherBuilder -> windowMatcherBuilder.specification(specificationAB).addFunction(functionCall("avg", Optional.empty(), ImmutableList.of(columnBAlias))), window(windowMatcherBuilder -> windowMatcherBuilder.specification(specificationA).addFunction(functionCall("avg", Optional.empty(), ImmutableList.of(columnAAlias))), values(ImmutableMap.of(columnAAlias, 0, columnBAlias, 1)))));
}
Also used : ImmutableMap(com.google.common.collect.ImmutableMap) BaseRuleTest(io.trino.sql.planner.iterative.rule.test.BaseRuleTest) ResolvedFunction(io.trino.metadata.ResolvedFunction) TypeSignatureProvider.fromTypes(io.trino.sql.analyzer.TypeSignatureProvider.fromTypes) PlanMatchPattern.window(io.trino.sql.planner.assertions.PlanMatchPattern.window) TestingFunctionResolution(io.trino.metadata.TestingFunctionResolution) Test(org.testng.annotations.Test) PlanMatchPattern.values(io.trino.sql.planner.assertions.PlanMatchPattern.values) PlanMatchPattern.specification(io.trino.sql.planner.assertions.PlanMatchPattern.specification) DEFAULT_FRAME(io.trino.sql.planner.plan.WindowNode.Frame.DEFAULT_FRAME) PlanMatchPattern.functionCall(io.trino.sql.planner.assertions.PlanMatchPattern.functionCall) QualifiedName(io.trino.sql.tree.QualifiedName) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) ExpectedValueProvider(io.trino.sql.planner.assertions.ExpectedValueProvider) ImmutableList(com.google.common.collect.ImmutableList) BIGINT(io.trino.spi.type.BigintType.BIGINT) SymbolReference(io.trino.sql.tree.SymbolReference) Optional(java.util.Optional) WindowNode(io.trino.sql.planner.plan.WindowNode) WindowNode(io.trino.sql.planner.plan.WindowNode) ResolvedFunction(io.trino.metadata.ResolvedFunction) SymbolReference(io.trino.sql.tree.SymbolReference) BaseRuleTest(io.trino.sql.planner.iterative.rule.test.BaseRuleTest) Test(org.testng.annotations.Test)

Example 8 with DOUBLE

use of io.trino.spi.type.DoubleType.DOUBLE in project trino by trinodb.

the class FormatFunction method valueConverter.

private static BiFunction<ConnectorSession, Block, Object> valueConverter(FunctionDependencies functionDependencies, Type type, int position) {
    if (type.equals(UNKNOWN)) {
        return (session, block) -> null;
    }
    if (type.equals(BOOLEAN)) {
        return (session, block) -> type.getBoolean(block, position);
    }
    if (type.equals(TINYINT) || type.equals(SMALLINT) || type.equals(INTEGER) || type.equals(BIGINT)) {
        return (session, block) -> type.getLong(block, position);
    }
    if (type.equals(REAL)) {
        return (session, block) -> intBitsToFloat(toIntExact(type.getLong(block, position)));
    }
    if (type.equals(DOUBLE)) {
        return (session, block) -> type.getDouble(block, position);
    }
    if (type.equals(DATE)) {
        return (session, block) -> LocalDate.ofEpochDay(type.getLong(block, position));
    }
    if (type instanceof TimestampWithTimeZoneType) {
        return (session, block) -> toZonedDateTime(((TimestampWithTimeZoneType) type), block, position);
    }
    if (type instanceof TimestampType) {
        return (session, block) -> toLocalDateTime(((TimestampType) type), block, position);
    }
    if (type instanceof TimeType) {
        return (session, block) -> toLocalTime(type.getLong(block, position));
    }
    // TODO: support TIME WITH TIME ZONE by https://github.com/trinodb/trino/issues/191 + mapping to java.time.OffsetTime
    if (type.equals(JSON)) {
        MethodHandle handle = functionDependencies.getFunctionInvoker(QualifiedName.of("json_format"), ImmutableList.of(JSON), simpleConvention(FAIL_ON_NULL, NEVER_NULL)).getMethodHandle();
        return (session, block) -> convertToString(handle, type.getSlice(block, position));
    }
    if (isShortDecimal(type)) {
        int scale = ((DecimalType) type).getScale();
        return (session, block) -> BigDecimal.valueOf(type.getLong(block, position), scale);
    }
    if (isLongDecimal(type)) {
        int scale = ((DecimalType) type).getScale();
        return (session, block) -> new BigDecimal(((Int128) type.getObject(block, position)).toBigInteger(), scale);
    }
    if (type instanceof VarcharType) {
        return (session, block) -> type.getSlice(block, position).toStringUtf8();
    }
    if (type instanceof CharType) {
        CharType charType = (CharType) type;
        return (session, block) -> padSpaces(type.getSlice(block, position), charType).toStringUtf8();
    }
    BiFunction<ConnectorSession, Block, Object> function;
    if (type.getJavaType() == long.class) {
        function = (session, block) -> type.getLong(block, position);
    } else if (type.getJavaType() == double.class) {
        function = (session, block) -> type.getDouble(block, position);
    } else if (type.getJavaType() == boolean.class) {
        function = (session, block) -> type.getBoolean(block, position);
    } else if (type.getJavaType() == Slice.class) {
        function = (session, block) -> type.getSlice(block, position);
    } else {
        function = (session, block) -> type.getObject(block, position);
    }
    MethodHandle handle = functionDependencies.getCastInvoker(type, VARCHAR, simpleConvention(FAIL_ON_NULL, NEVER_NULL)).getMethodHandle();
    return (session, block) -> convertToString(handle, function.apply(session, block));
}
Also used : FunctionDependencies(io.trino.metadata.FunctionDependencies) SCALAR(io.trino.metadata.FunctionKind.SCALAR) FunctionDependencyDeclarationBuilder(io.trino.metadata.FunctionDependencyDeclaration.FunctionDependencyDeclarationBuilder) FAIL_ON_NULL(io.trino.spi.function.InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL) BiFunction(java.util.function.BiFunction) FunctionNullability(io.trino.metadata.FunctionNullability) UNKNOWN(io.trino.type.UnknownType.UNKNOWN) InvocationConvention.simpleConvention(io.trino.spi.function.InvocationConvention.simpleConvention) Timestamps.roundDiv(io.trino.spi.type.Timestamps.roundDiv) BigDecimal(java.math.BigDecimal) TimestampWithTimeZoneType(io.trino.spi.type.TimestampWithTimeZoneType) Block(io.trino.spi.block.Block) LocalTime(java.time.LocalTime) IllegalFormatException(java.util.IllegalFormatException) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) INTEGER(io.trino.spi.type.IntegerType.INTEGER) FunctionMetadata(io.trino.metadata.FunctionMetadata) SMALLINT(io.trino.spi.type.SmallintType.SMALLINT) TypeSignature(io.trino.spi.type.TypeSignature) DateTimes.toLocalDateTime(io.trino.type.DateTimes.toLocalDateTime) FunctionDependencyDeclaration(io.trino.metadata.FunctionDependencyDeclaration) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) PICOSECONDS_PER_NANOSECOND(io.trino.type.DateTimes.PICOSECONDS_PER_NANOSECOND) TrinoException(io.trino.spi.TrinoException) String.format(java.lang.String.format) List(java.util.List) BIGINT(io.trino.spi.type.BigintType.BIGINT) INVALID_FUNCTION_ARGUMENT(io.trino.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) LocalDate(java.time.LocalDate) DecimalType(io.trino.spi.type.DecimalType) NEVER_NULL(io.trino.spi.function.InvocationConvention.InvocationArgumentConvention.NEVER_NULL) DATE(io.trino.spi.type.DateType.DATE) REAL(io.trino.spi.type.RealType.REAL) MethodHandle(java.lang.invoke.MethodHandle) Slice(io.airlift.slice.Slice) TimeType(io.trino.spi.type.TimeType) Decimals.isLongDecimal(io.trino.spi.type.Decimals.isLongDecimal) Type(io.trino.spi.type.Type) BOOLEAN(io.trino.spi.type.BooleanType.BOOLEAN) Float.intBitsToFloat(java.lang.Float.intBitsToFloat) DateTimes.toZonedDateTime(io.trino.type.DateTimes.toZonedDateTime) TimestampType(io.trino.spi.type.TimestampType) VarcharType(io.trino.spi.type.VarcharType) VARCHAR(io.trino.spi.type.VarcharType.VARCHAR) ImmutableList(com.google.common.collect.ImmutableList) Chars.padSpaces(io.trino.spi.type.Chars.padSpaces) Math.toIntExact(java.lang.Math.toIntExact) Signature(io.trino.metadata.Signature) Decimals.isShortDecimal(io.trino.spi.type.Decimals.isShortDecimal) Int128(io.trino.spi.type.Int128) Streams.mapWithIndex(com.google.common.collect.Streams.mapWithIndex) ConnectorSession(io.trino.spi.connector.ConnectorSession) Signature.withVariadicBound(io.trino.metadata.Signature.withVariadicBound) UsedByGeneratedCode(io.trino.annotation.UsedByGeneratedCode) SqlScalarFunction(io.trino.metadata.SqlScalarFunction) Failures.internalError(io.trino.util.Failures.internalError) QualifiedName(io.trino.sql.tree.QualifiedName) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) CharType(io.trino.spi.type.CharType) BoundSignature(io.trino.metadata.BoundSignature) TINYINT(io.trino.spi.type.TinyintType.TINYINT) JSON(io.trino.type.JsonType.JSON) Reflection.methodHandle(io.trino.util.Reflection.methodHandle) VarcharType(io.trino.spi.type.VarcharType) BigDecimal(java.math.BigDecimal) TimeType(io.trino.spi.type.TimeType) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) Slice(io.airlift.slice.Slice) TimestampWithTimeZoneType(io.trino.spi.type.TimestampWithTimeZoneType) TimestampType(io.trino.spi.type.TimestampType) DecimalType(io.trino.spi.type.DecimalType) Block(io.trino.spi.block.Block) ConnectorSession(io.trino.spi.connector.ConnectorSession) CharType(io.trino.spi.type.CharType) MethodHandle(java.lang.invoke.MethodHandle)

Example 9 with DOUBLE

use of io.trino.spi.type.DoubleType.DOUBLE in project trino by trinodb.

the class TestFilterStatsRule method testUnestimatableFunction.

@Test
public void testUnestimatableFunction() {
    // can't estimate function and default filter factor is turned off
    ComparisonExpression unestimatableExpression = new ComparisonExpression(Operator.EQUAL, new TestingFunctionResolution().functionCallBuilder(QualifiedName.of("sin")).addArgument(DOUBLE, new SymbolReference("i1")).build(), new DoubleLiteral("1"));
    tester().assertStatsFor(pb -> pb.filter(unestimatableExpression, pb.values(pb.symbol("i1"), pb.symbol("i2"), pb.symbol("i3")))).withSourceStats(0, PlanNodeStatsEstimate.builder().setOutputRowCount(10).addSymbolStatistics(new Symbol("i1"), SymbolStatsEstimate.builder().setLowValue(1).setHighValue(10).setDistinctValuesCount(5).setNullsFraction(0).build()).addSymbolStatistics(new Symbol("i2"), SymbolStatsEstimate.builder().setLowValue(0).setHighValue(3).setDistinctValuesCount(4).setNullsFraction(0).build()).addSymbolStatistics(new Symbol("i3"), SymbolStatsEstimate.builder().setLowValue(10).setHighValue(15).setDistinctValuesCount(4).setNullsFraction(0.1).build()).build()).check(PlanNodeStatsAssertion::outputRowsCountUnknown);
    // can't estimate function, but default filter factor is turned on
    defaultFilterTester.assertStatsFor(pb -> pb.filter(unestimatableExpression, pb.values(pb.symbol("i1"), pb.symbol("i2"), pb.symbol("i3")))).withSourceStats(0, PlanNodeStatsEstimate.builder().setOutputRowCount(10).addSymbolStatistics(new Symbol("i1"), SymbolStatsEstimate.builder().setLowValue(1).setHighValue(10).setDistinctValuesCount(5).setNullsFraction(0).build()).addSymbolStatistics(new Symbol("i2"), SymbolStatsEstimate.builder().setLowValue(0).setHighValue(3).setDistinctValuesCount(4).setNullsFraction(0).build()).addSymbolStatistics(new Symbol("i3"), SymbolStatsEstimate.builder().setLowValue(10).setHighValue(15).setDistinctValuesCount(4).setNullsFraction(0.1).build()).build()).check(check -> check.outputRowsCount(9).symbolStats("i1", assertion -> assertion.lowValue(1).highValue(10).dataSizeUnknown().distinctValuesCount(5).nullsFraction(0)).symbolStats("i2", assertion -> assertion.lowValue(0).highValue(3).dataSizeUnknown().distinctValuesCount(4).nullsFraction(0)).symbolStats("i3", assertion -> assertion.lowValue(10).highValue(15).dataSizeUnknown().distinctValuesCount(4).nullsFraction(0.1)));
}
Also used : TestingFunctionResolution(io.trino.metadata.TestingFunctionResolution) Symbol(io.trino.sql.planner.Symbol) AfterClass(org.testng.annotations.AfterClass) BeforeClass(org.testng.annotations.BeforeClass) TestingFunctionResolution(io.trino.metadata.TestingFunctionResolution) Test(org.testng.annotations.Test) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) DoubleLiteral(io.trino.sql.tree.DoubleLiteral) QualifiedName(io.trino.sql.tree.QualifiedName) DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) TestingSession.testSessionBuilder(io.trino.testing.TestingSession.testSessionBuilder) SymbolReference(io.trino.sql.tree.SymbolReference) Operator(io.trino.sql.tree.ComparisonExpression.Operator) PlanBuilder.expression(io.trino.sql.planner.iterative.rule.test.PlanBuilder.expression) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) SymbolReference(io.trino.sql.tree.SymbolReference) Symbol(io.trino.sql.planner.Symbol) DoubleLiteral(io.trino.sql.tree.DoubleLiteral) Test(org.testng.annotations.Test)

Example 10 with DOUBLE

use of io.trino.spi.type.DoubleType.DOUBLE in project trino by trinodb.

the class TestOutputNodeStats method testStatsForOutputNode.

@Test
public void testStatsForOutputNode() {
    PlanNodeStatsEstimate stats = PlanNodeStatsEstimate.builder().setOutputRowCount(100).addSymbolStatistics(new Symbol("a"), SymbolStatsEstimate.builder().setNullsFraction(0.3).setLowValue(1).setHighValue(30).setDistinctValuesCount(20).build()).addSymbolStatistics(new Symbol("b"), SymbolStatsEstimate.builder().setNullsFraction(0.6).setLowValue(13.5).setHighValue(POSITIVE_INFINITY).setDistinctValuesCount(40).build()).build();
    tester().assertStatsFor(pb -> pb.output(outputBuilder -> {
        Symbol a = pb.symbol("a", BIGINT);
        Symbol b = pb.symbol("b", DOUBLE);
        outputBuilder.source(pb.values(a, b)).column(a, "a1").column(a, "a2").column(b, "b");
    })).withSourceStats(stats).check(outputStats -> outputStats.equalTo(stats));
}
Also used : DOUBLE(io.trino.spi.type.DoubleType.DOUBLE) Symbol(io.trino.sql.planner.Symbol) POSITIVE_INFINITY(java.lang.Double.POSITIVE_INFINITY) BIGINT(io.trino.spi.type.BigintType.BIGINT) Test(org.testng.annotations.Test) Symbol(io.trino.sql.planner.Symbol) Test(org.testng.annotations.Test)

Aggregations

DOUBLE (io.trino.spi.type.DoubleType.DOUBLE)32 BIGINT (io.trino.spi.type.BigintType.BIGINT)28 List (java.util.List)23 Optional (java.util.Optional)22 ImmutableList (com.google.common.collect.ImmutableList)21 ImmutableMap (com.google.common.collect.ImmutableMap)19 Type (io.trino.spi.type.Type)18 Test (org.testng.annotations.Test)18 String.format (java.lang.String.format)17 Map (java.util.Map)17 INTEGER (io.trino.spi.type.IntegerType.INTEGER)15 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)14 DATE (io.trino.spi.type.DateType.DATE)13 SMALLINT (io.trino.spi.type.SmallintType.SMALLINT)13 TINYINT (io.trino.spi.type.TinyintType.TINYINT)13 VarcharType (io.trino.spi.type.VarcharType)13 ArrayList (java.util.ArrayList)13 REAL (io.trino.spi.type.RealType.REAL)12 Slice (io.airlift.slice.Slice)11 BOOLEAN (io.trino.spi.type.BooleanType.BOOLEAN)11