Search in sources :

Example 1 with DOUBLE

use of io.prestosql.spi.type.DoubleType.DOUBLE in project hetu-core by openlookeng.

the class TestPruneIndexSourceColumns method buildProjectedIndexSource.

private static PlanNode buildProjectedIndexSource(PlanBuilder p, Predicate<Symbol> projectionFilter) {
    Symbol orderkey = p.symbol("orderkey", INTEGER);
    Symbol custkey = p.symbol("custkey", INTEGER);
    Symbol totalprice = p.symbol("totalprice", DOUBLE);
    ColumnHandle orderkeyHandle = new TpchColumnHandle(orderkey.getName(), INTEGER);
    ColumnHandle custkeyHandle = new TpchColumnHandle(custkey.getName(), INTEGER);
    ColumnHandle totalpriceHandle = new TpchColumnHandle(totalprice.getName(), DOUBLE);
    return p.project(Assignments.copyOf(ImmutableList.of(orderkey, custkey, totalprice).stream().filter(projectionFilter).collect(Collectors.toMap(v -> v, v -> p.variable(v.getName())))), p.indexSource(new TableHandle(new CatalogName("local"), new TpchTableHandle("orders", TINY_SCALE_FACTOR), TpchTransactionHandle.INSTANCE, Optional.empty()), ImmutableSet.of(orderkey, custkey), ImmutableList.of(orderkey, custkey, totalprice), ImmutableMap.of(orderkey, orderkeyHandle, custkey, custkeyHandle, totalprice, totalpriceHandle), TupleDomain.fromFixedValues(ImmutableMap.of(totalpriceHandle, asNull(DOUBLE)))));
}
Also used : BaseRuleTest(io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest) TpchTableHandle(io.prestosql.plugin.tpch.TpchTableHandle) TpchColumnHandle(io.prestosql.plugin.tpch.TpchColumnHandle) Test(org.testng.annotations.Test) INTEGER(io.prestosql.spi.type.IntegerType.INTEGER) TableHandle(io.prestosql.spi.metadata.TableHandle) ImmutableList(com.google.common.collect.ImmutableList) Predicates(com.google.common.base.Predicates) DOUBLE(io.prestosql.spi.type.DoubleType.DOUBLE) TpchTransactionHandle(io.prestosql.plugin.tpch.TpchTransactionHandle) PlanMatchPattern.expression(io.prestosql.sql.planner.assertions.PlanMatchPattern.expression) Symbol(io.prestosql.spi.plan.Symbol) TINY_SCALE_FACTOR(io.prestosql.plugin.tpch.TpchMetadata.TINY_SCALE_FACTOR) PlanMatchPattern.constrainedIndexSource(io.prestosql.sql.planner.assertions.PlanMatchPattern.constrainedIndexSource) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Assignments(io.prestosql.spi.plan.Assignments) PlanMatchPattern.strictProject(io.prestosql.sql.planner.assertions.PlanMatchPattern.strictProject) Predicate(java.util.function.Predicate) TupleDomain(io.prestosql.spi.predicate.TupleDomain) CatalogName(io.prestosql.spi.connector.CatalogName) PlanNode(io.prestosql.spi.plan.PlanNode) Collectors(java.util.stream.Collectors) NullableValue.asNull(io.prestosql.spi.predicate.NullableValue.asNull) ColumnHandle(io.prestosql.spi.connector.ColumnHandle) Domain(io.prestosql.spi.predicate.Domain) Optional(java.util.Optional) PlanBuilder(io.prestosql.sql.planner.iterative.rule.test.PlanBuilder) TpchColumnHandle(io.prestosql.plugin.tpch.TpchColumnHandle) ColumnHandle(io.prestosql.spi.connector.ColumnHandle) TpchColumnHandle(io.prestosql.plugin.tpch.TpchColumnHandle) Symbol(io.prestosql.spi.plan.Symbol) TpchTableHandle(io.prestosql.plugin.tpch.TpchTableHandle) TableHandle(io.prestosql.spi.metadata.TableHandle) CatalogName(io.prestosql.spi.connector.CatalogName) TpchTableHandle(io.prestosql.plugin.tpch.TpchTableHandle)

Example 2 with DOUBLE

use of io.prestosql.spi.type.DoubleType.DOUBLE in project hetu-core by openlookeng.

the class RcFileTester method preprocessWriteValueOld.

private static Object preprocessWriteValueOld(Format format, Type type, Object value) {
    if (value == null) {
        return null;
    }
    if (type.equals(BOOLEAN)) {
        return value;
    }
    if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    }
    if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    }
    if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    }
    if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    }
    if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    }
    if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    if (type instanceof VarcharType) {
        return value;
    }
    if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    }
    if (type.equals(DATE)) {
        return Date.ofEpochDay(((SqlDate) value).getDays());
    }
    if (type.equals(TIMESTAMP)) {
        long millis = ((SqlTimestamp) value).getMillis();
        if (format == Format.BINARY) {
            millis = HIVE_STORAGE_TIME_ZONE.convertLocalToUTC(millis, false);
        }
        return Timestamp.ofEpochMilli(millis);
    }
    if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    }
    if (type.getTypeSignature().getBase().equals(ARRAY)) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream().map(element -> preprocessWriteValueOld(format, elementType, element)).collect(toList());
    }
    if (type.getTypeSignature().getBase().equals(MAP)) {
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueOld(format, keyType, entry.getKey()), preprocessWriteValueOld(format, valueType, entry.getValue()));
        }
        return newMap;
    }
    if (type.getTypeSignature().getBase().equals(ROW)) {
        List<?> fieldValues = (List<?>) value;
        List<Type> fieldTypes = type.getTypeParameters();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueOld(format, fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
Also used : SnappyCodec(org.apache.hadoop.io.compress.SnappyCodec) DateTimeZone(org.joda.time.DateTimeZone) PrimitiveObjectInspectorFactory.javaByteObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteObjectInspector) Text(org.apache.hadoop.io.Text) PrimitiveObjectInspectorFactory.javaLongObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaLongObjectInspector) Writable(org.apache.hadoop.io.Writable) PrimitiveObjectInspectorFactory.javaTimestampObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaTimestampObjectInspector) Date(org.apache.hadoop.hive.common.type.Date) PrimitiveObjectInspectorFactory.javaDateObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDateObjectInspector) FileSplit(org.apache.hadoop.mapred.FileSplit) RCFileInputFormat(org.apache.hadoop.hive.ql.io.RCFileInputFormat) Files.createTempDirectory(java.nio.file.Files.createTempDirectory) Slices(io.airlift.slice.Slices) Configuration(org.apache.hadoop.conf.Configuration) Map(java.util.Map) RowType(io.prestosql.spi.type.RowType) NONE(io.prestosql.rcfile.RcFileTester.Compression.NONE) BigInteger(java.math.BigInteger) ObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector) Assert.assertFalse(org.testng.Assert.assertFalse) LazyBinaryArray(org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryArray) IntWritable(org.apache.hadoop.io.IntWritable) SERIALIZATION_LIB(org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_LIB) PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector) BytesRefArrayWritable(org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable) META_TABLE_COLUMN_TYPES(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES) PrimitiveObjectInspectorFactory.javaFloatObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaFloatObjectInspector) LazyMap(org.apache.hadoop.hive.serde2.lazy.LazyMap) PrimitiveObjectInspectorFactory.javaDoubleObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDoubleObjectInspector) LazyArray(org.apache.hadoop.hive.serde2.lazy.LazyArray) Set(java.util.Set) READ_ALL_COLUMNS(org.apache.hadoop.hive.serde2.ColumnProjectionUtils.READ_ALL_COLUMNS) TIMESTAMP(io.prestosql.spi.type.TimestampType.TIMESTAMP) Metadata(io.prestosql.metadata.Metadata) UncheckedIOException(java.io.UncheckedIOException) LzoCodec(com.hadoop.compression.lzo.LzoCodec) BooleanWritable(org.apache.hadoop.io.BooleanWritable) RecordReader(org.apache.hadoop.mapred.RecordReader) PrimitiveObjectInspectorFactory.javaIntObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaIntObjectInspector) StructField(org.apache.hadoop.hive.serde2.objectinspector.StructField) Lz4Codec(org.apache.hadoop.io.compress.Lz4Codec) Iterables(com.google.common.collect.Iterables) Slice(io.airlift.slice.Slice) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) StructObject(org.apache.hadoop.hive.serde2.StructObject) Functions.constant(com.google.common.base.Functions.constant) TypeSignatureParameter(io.prestosql.spi.type.TypeSignatureParameter) META_TABLE_COLUMNS(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS) Decimals.rescale(io.prestosql.spi.type.Decimals.rescale) ArrayList(java.util.ArrayList) MapType(io.prestosql.spi.type.MapType) Lists(com.google.common.collect.Lists) ALLOW_INSECURE(com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE) VARCHAR(io.prestosql.spi.type.VarcharType.VARCHAR) PrimitiveObjectInspectorFactory.javaShortObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaShortObjectInspector) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) DOUBLE(io.prestosql.spi.type.DoubleType.DOUBLE) ROW(io.prestosql.spi.type.StandardTypes.ROW) LinkedHashSet(java.util.LinkedHashSet) HadoopNative(io.prestosql.hadoop.HadoopNative) Properties(java.util.Properties) RcFileDecoderUtils.findFirstSyncPosition(io.prestosql.rcfile.RcFileDecoderUtils.findFirstSyncPosition) AbstractIterator(com.google.common.collect.AbstractIterator) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ObjectInspectorFactory.getStandardStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector) DecimalTypeInfo(org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo) File(java.io.File) NULL(org.apache.hadoop.mapred.Reporter.NULL) SettableStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector) VARBINARY(io.prestosql.spi.type.VarbinaryType.VARBINARY) DateTimeTestingUtils.sqlTimestampOf(io.prestosql.testing.DateTimeTestingUtils.sqlTimestampOf) SIZE_OF_LONG(io.airlift.slice.SizeOf.SIZE_OF_LONG) Deserializer(org.apache.hadoop.hive.serde2.Deserializer) SerDeException(org.apache.hadoop.hive.serde2.SerDeException) FloatWritable(org.apache.hadoop.io.FloatWritable) VarcharType(io.prestosql.spi.type.VarcharType) RecordWriter(org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter) Iterables.transform(com.google.common.collect.Iterables.transform) LazyBinaryColumnarSerDe(org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe) MoreFiles.deleteRecursively(com.google.common.io.MoreFiles.deleteRecursively) DecimalType(io.prestosql.spi.type.DecimalType) GzipCodec(org.apache.hadoop.io.compress.GzipCodec) LongWritable(org.apache.hadoop.io.LongWritable) TimestampWritableV2(org.apache.hadoop.hive.serde2.io.TimestampWritableV2) InputFormat(org.apache.hadoop.mapred.InputFormat) Path(org.apache.hadoop.fs.Path) BOOLEAN(io.prestosql.spi.type.BooleanType.BOOLEAN) KILOBYTE(io.airlift.units.DataSize.Unit.KILOBYTE) Type(io.prestosql.spi.type.Type) ShortWritable(org.apache.hadoop.hive.serde2.io.ShortWritable) BIGINT(io.prestosql.spi.type.BigintType.BIGINT) SIZE_OF_INT(io.airlift.slice.SizeOf.SIZE_OF_INT) ARRAY(io.prestosql.spi.type.StandardTypes.ARRAY) ImmutableSet(com.google.common.collect.ImmutableSet) DateWritableV2(org.apache.hadoop.hive.serde2.io.DateWritableV2) ImmutableMap(com.google.common.collect.ImmutableMap) BlockBuilder(io.prestosql.spi.block.BlockBuilder) MetadataManager.createTestMetadataManager(io.prestosql.metadata.MetadataManager.createTestMetadataManager) Collections.nCopies(java.util.Collections.nCopies) ArrayType(io.prestosql.spi.type.ArrayType) RCFileOutputFormat(org.apache.hadoop.hive.ql.io.RCFileOutputFormat) TINYINT(io.prestosql.spi.type.TinyintType.TINYINT) StructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector) ColumnarSerDe(org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe) Objects(java.util.Objects) DataSize(io.airlift.units.DataSize) List(java.util.List) PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY(io.prestosql.rcfile.RcFileWriter.PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY) ZLIB(io.prestosql.rcfile.RcFileTester.Compression.ZLIB) Entry(java.util.Map.Entry) Optional(java.util.Optional) READ_COLUMN_IDS_CONF_STR(org.apache.hadoop.hive.serde2.ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR) SqlTimestamp(io.prestosql.spi.type.SqlTimestamp) LazyPrimitive(org.apache.hadoop.hive.serde2.lazy.LazyPrimitive) Assert.assertNull(org.testng.Assert.assertNull) SESSION(io.prestosql.testing.TestingConnectorSession.SESSION) TextRcFileEncoding(io.prestosql.rcfile.text.TextRcFileEncoding) LazyBinaryMap(org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryMap) PrimitiveObjectInspectorFactory.javaBooleanObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaBooleanObjectInspector) SqlDate(io.prestosql.spi.type.SqlDate) Assert.assertEquals(org.testng.Assert.assertEquals) Decimals(io.prestosql.spi.type.Decimals) HashMap(java.util.HashMap) INTEGER(io.prestosql.spi.type.IntegerType.INTEGER) SqlDecimal(io.prestosql.spi.type.SqlDecimal) DoubleWritable(org.apache.hadoop.io.DoubleWritable) PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector) SqlVarbinary(io.prestosql.spi.type.SqlVarbinary) OutputStreamSliceOutput(io.airlift.slice.OutputStreamSliceOutput) COMPRESS_CODEC(org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.COMPRESS_CODEC) PRESTO_RCFILE_WRITER_VERSION(io.prestosql.rcfile.RcFileWriter.PRESTO_RCFILE_WRITER_VERSION) ImmutableList(com.google.common.collect.ImmutableList) ByteWritable(org.apache.hadoop.io.ByteWritable) MAP(io.prestosql.spi.type.StandardTypes.MAP) BytesWritable(org.apache.hadoop.io.BytesWritable) DATE(io.prestosql.spi.type.DateType.DATE) REAL(io.prestosql.spi.type.RealType.REAL) Math.toIntExact(java.lang.Math.toIntExact) Block(io.prestosql.spi.block.Block) Iterator(java.util.Iterator) Timestamp(org.apache.hadoop.hive.common.type.Timestamp) Iterators.advance(com.google.common.collect.Iterators.advance) Page(io.prestosql.spi.Page) FileInputStream(java.io.FileInputStream) BinaryRcFileEncoding(io.prestosql.rcfile.binary.BinaryRcFileEncoding) BZIP2(io.prestosql.rcfile.RcFileTester.Compression.BZIP2) LZ4(io.prestosql.rcfile.RcFileTester.Compression.LZ4) JobConf(org.apache.hadoop.mapred.JobConf) BZip2Codec(org.apache.hadoop.io.compress.BZip2Codec) Collectors.toList(java.util.stream.Collectors.toList) ObjectInspectorFactory(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory) SMALLINT(io.prestosql.spi.type.SmallintType.SMALLINT) Serializer(org.apache.hadoop.hive.serde2.Serializer) HiveDecimal(org.apache.hadoop.hive.common.type.HiveDecimal) Closeable(java.io.Closeable) Assert.assertTrue(org.testng.Assert.assertTrue) SNAPPY(io.prestosql.rcfile.RcFileTester.Compression.SNAPPY) PrimitiveObjectInspectorFactory.javaStringObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaStringObjectInspector) HiveDecimalWritable(org.apache.hadoop.hive.serde2.io.HiveDecimalWritable) Collections(java.util.Collections) BYTE(io.airlift.units.DataSize.Unit.BYTE) InputStream(java.io.InputStream) VarcharType(io.prestosql.spi.type.VarcharType) HashMap(java.util.HashMap) SqlVarbinary(io.prestosql.spi.type.SqlVarbinary) ArrayList(java.util.ArrayList) SqlTimestamp(io.prestosql.spi.type.SqlTimestamp) RowType(io.prestosql.spi.type.RowType) MapType(io.prestosql.spi.type.MapType) VarcharType(io.prestosql.spi.type.VarcharType) DecimalType(io.prestosql.spi.type.DecimalType) Type(io.prestosql.spi.type.Type) ArrayType(io.prestosql.spi.type.ArrayType) DecimalType(io.prestosql.spi.type.DecimalType) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) StructObject(org.apache.hadoop.hive.serde2.StructObject) Map(java.util.Map) LazyMap(org.apache.hadoop.hive.serde2.lazy.LazyMap) ImmutableMap(com.google.common.collect.ImmutableMap) LazyBinaryMap(org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryMap) HashMap(java.util.HashMap)

Example 3 with DOUBLE

use of io.prestosql.spi.type.DoubleType.DOUBLE in project hetu-core by openlookeng.

the class PagesSpatialIndexSupplier method buildRTree.

private static STRtree buildRTree(LongArrayList addresses, List<List<Block>> channels, int geometryChannel, Optional<Integer> radiusChannel, Optional<Integer> partitionChannel) {
    STRtree stRtree = new STRtree();
    Operator relateOperator = OperatorFactoryLocal.getInstance().getOperator(Operator.Type.Relate);
    for (int position = 0; position < addresses.size(); position++) {
        long pageAddress = addresses.getLong(position);
        int blockIndex = decodeSliceIndex(pageAddress);
        int blockPosition = decodePosition(pageAddress);
        Block block = channels.get(geometryChannel).get(blockIndex);
        // TODO Consider pushing is-null and is-empty checks into a filter below the join
        if (block.isNull(blockPosition)) {
            continue;
        }
        Slice slice = block.getSlice(blockPosition, 0, block.getSliceLength(blockPosition));
        OGCGeometry ogcGeometry = deserialize(slice);
        verify(ogcGeometry != null);
        if (ogcGeometry.isEmpty()) {
            continue;
        }
        double radius = radiusChannel.map(channel -> DOUBLE.getDouble(channels.get(channel).get(blockIndex), blockPosition)).orElse(0.0);
        if (radius < 0) {
            continue;
        }
        if (!radiusChannel.isPresent()) {
            // If radiusChannel is supplied, this is a distance query, for which our acceleration won't help.
            accelerateGeometry(ogcGeometry, relateOperator);
        }
        int partition = -1;
        if (partitionChannel.isPresent()) {
            Block partitionBlock = channels.get(partitionChannel.get()).get(blockIndex);
            partition = toIntExact(INTEGER.getLong(partitionBlock, blockPosition));
        }
        stRtree.insert(getEnvelope(ogcGeometry, radius), new GeometryWithPosition(ogcGeometry, partition, position));
    }
    stRtree.build();
    return stRtree;
}
Also used : Operator(com.esri.core.geometry.Operator) OGCGeometry(com.esri.core.geometry.ogc.OGCGeometry) GeometrySerde.deserialize(io.prestosql.geospatial.serde.GeometrySerde.deserialize) Slice(io.airlift.slice.Slice) Rectangle(io.prestosql.geospatial.Rectangle) OGCGeometry(com.esri.core.geometry.ogc.OGCGeometry) LongArrayList(it.unimi.dsi.fastutil.longs.LongArrayList) GeometryCursor(com.esri.core.geometry.GeometryCursor) INTEGER(io.prestosql.spi.type.IntegerType.INTEGER) Supplier(java.util.function.Supplier) Verify.verify(com.google.common.base.Verify.verify) Map(java.util.Map) Session(io.prestosql.Session) GeometryWithPosition(io.prestosql.operator.PagesRTreeIndex.GeometryWithPosition) DOUBLE(io.prestosql.spi.type.DoubleType.DOUBLE) EMPTY_INDEX(io.prestosql.operator.PagesSpatialIndex.EMPTY_INDEX) Type(io.prestosql.spi.type.Type) Math.toIntExact(java.lang.Math.toIntExact) SpatialPredicate(io.prestosql.operator.SpatialIndexBuilderOperator.SpatialPredicate) Block(io.prestosql.spi.block.Block) Operator(com.esri.core.geometry.Operator) OperatorFactoryLocal(com.esri.core.geometry.OperatorFactoryLocal) SyntheticAddress.decodeSliceIndex(io.prestosql.operator.SyntheticAddress.decodeSliceIndex) ItemBoundable(org.locationtech.jts.index.strtree.ItemBoundable) Geometry(com.esri.core.geometry.Geometry) SyntheticAddress.decodePosition(io.prestosql.operator.SyntheticAddress.decodePosition) DataSize(io.airlift.units.DataSize) AbstractNode(org.locationtech.jts.index.strtree.AbstractNode) List(java.util.List) ClassLayout(org.openjdk.jol.info.ClassLayout) JoinFilterFunctionCompiler(io.prestosql.sql.gen.JoinFilterFunctionCompiler) Optional(java.util.Optional) Envelope(org.locationtech.jts.geom.Envelope) BYTE(io.airlift.units.DataSize.Unit.BYTE) STRtree(org.locationtech.jts.index.strtree.STRtree) Slice(io.airlift.slice.Slice) GeometryWithPosition(io.prestosql.operator.PagesRTreeIndex.GeometryWithPosition) STRtree(org.locationtech.jts.index.strtree.STRtree) Block(io.prestosql.spi.block.Block)

Example 4 with DOUBLE

use of io.prestosql.spi.type.DoubleType.DOUBLE in project hetu-core by openlookeng.

the class FormatFunction method valueConverter.

private static BiFunction<ConnectorSession, Block, Object> valueConverter(FunctionAndTypeManager functionAndTypeManager, 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.equals(TIMESTAMP_WITH_TIME_ZONE)) {
        return (session, block) -> toZonedDateTime(type.getLong(block, position));
    }
    if (type.equals(TIMESTAMP)) {
        return (session, block) -> toLocalDateTime(type.getLong(block, position));
    }
    if (type.equals(TIME)) {
        return (session, block) -> toLocalTime(session, type.getLong(block, position));
    }
    // TODO: support TIME WITH TIME ZONE by making SqlTimeWithTimeZone implement TemporalAccessor
    if (type.equals(JSON)) {
        FunctionHandle functionHandle = functionAndTypeManager.resolveFunction(Optional.empty(), QualifiedObjectName.valueOf(DEFAULT_NAMESPACE, "json_format"), fromTypes(JSON));
        MethodHandle handle = functionAndTypeManager.getBuiltInScalarFunctionImplementation(functionHandle).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(decodeUnscaledValue(type.getSlice(block, position)), scale);
    }
    if (isVarcharType(type) || isCharType(type)) {
        return (session, block) -> type.getSlice(block, position).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 = castToVarchar(functionAndTypeManager, type);
    if ((handle == null) || (handle.type().parameterCount() != 1)) {
        throw new PrestoException(NOT_SUPPORTED, "Type not supported for formatting: " + type.getDisplayName());
    }
    return (session, block) -> convertToString(handle, function.apply(session, block));
}
Also used : DateTimeEncoding.unpackZoneKey(io.prestosql.spi.type.DateTimeEncoding.unpackZoneKey) Varchars.isVarcharType(io.prestosql.spi.type.Varchars.isVarcharType) ZonedDateTime(java.time.ZonedDateTime) BiFunction(java.util.function.BiFunction) SCALAR(io.prestosql.spi.function.FunctionKind.SCALAR) OperatorNotFoundException(io.prestosql.metadata.OperatorNotFoundException) INVALID_FUNCTION_ARGUMENT(io.prestosql.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) DecimalType(io.prestosql.spi.type.DecimalType) BoundVariables(io.prestosql.metadata.BoundVariables) DEFAULT_NAMESPACE(io.prestosql.spi.connector.CatalogSchemaName.DEFAULT_NAMESPACE) UsedByGeneratedCode(io.prestosql.spi.annotation.UsedByGeneratedCode) BigDecimal(java.math.BigDecimal) TypeSignature.parseTypeSignature(io.prestosql.spi.type.TypeSignature.parseTypeSignature) ConnectorSession(io.prestosql.spi.connector.ConnectorSession) LocalTime(java.time.LocalTime) IllegalFormatException(java.util.IllegalFormatException) BOOLEAN(io.prestosql.spi.type.BooleanType.BOOLEAN) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) JSON(io.prestosql.type.JsonType.JSON) Type(io.prestosql.spi.type.Type) ZoneOffset(java.time.ZoneOffset) BIGINT(io.prestosql.spi.type.BigintType.BIGINT) Chars.isCharType(io.prestosql.spi.type.Chars.isCharType) PrestoException(io.prestosql.spi.PrestoException) DateTimeEncoding.unpackMillisUtc(io.prestosql.spi.type.DateTimeEncoding.unpackMillisUtc) CastType(io.prestosql.metadata.CastType) SqlScalarFunction(io.prestosql.metadata.SqlScalarFunction) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TIME(io.prestosql.spi.type.TimeType.TIME) Reflection.methodHandle(io.prestosql.spi.util.Reflection.methodHandle) Decimals.isLongDecimal(io.prestosql.spi.type.Decimals.isLongDecimal) TIMESTAMP(io.prestosql.spi.type.TimestampType.TIMESTAMP) TINYINT(io.prestosql.spi.type.TinyintType.TINYINT) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Instant(java.time.Instant) ZoneId(java.time.ZoneId) String.format(java.lang.String.format) FunctionHandle(io.prestosql.spi.function.FunctionHandle) Decimals.isShortDecimal(io.prestosql.spi.type.Decimals.isShortDecimal) List(java.util.List) LocalDate(java.time.LocalDate) ArgumentProperty.valueTypeArgumentProperty(io.prestosql.spi.function.BuiltInScalarFunctionImplementation.ArgumentProperty.valueTypeArgumentProperty) Optional(java.util.Optional) NOT_SUPPORTED(io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED) TIMESTAMP_WITH_TIME_ZONE(io.prestosql.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE) Signature.withVariadicBound(io.prestosql.spi.function.Signature.withVariadicBound) FunctionAndTypeManager(io.prestosql.metadata.FunctionAndTypeManager) UNKNOWN(io.prestosql.spi.type.UnknownType.UNKNOWN) BuiltInScalarFunctionImplementation(io.prestosql.spi.function.BuiltInScalarFunctionImplementation) MethodHandle(java.lang.invoke.MethodHandle) Slice(io.airlift.slice.Slice) LocalDateTime(java.time.LocalDateTime) INTEGER(io.prestosql.spi.type.IntegerType.INTEGER) Float.intBitsToFloat(java.lang.Float.intBitsToFloat) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) VARCHAR(io.prestosql.spi.type.VarcharType.VARCHAR) Failures.internalError(io.prestosql.util.Failures.internalError) ImmutableList(com.google.common.collect.ImmutableList) RETURN_NULL_ON_NULL(io.prestosql.spi.function.BuiltInScalarFunctionImplementation.NullConvention.RETURN_NULL_ON_NULL) DOUBLE(io.prestosql.spi.type.DoubleType.DOUBLE) DATE(io.prestosql.spi.type.DateType.DATE) REAL(io.prestosql.spi.type.RealType.REAL) Math.toIntExact(java.lang.Math.toIntExact) Signature(io.prestosql.spi.function.Signature) Block(io.prestosql.spi.block.Block) Streams.mapWithIndex(com.google.common.collect.Streams.mapWithIndex) TypeSignatureProvider.fromTypes(io.prestosql.sql.analyzer.TypeSignatureProvider.fromTypes) Decimals.decodeUnscaledValue(io.prestosql.spi.type.Decimals.decodeUnscaledValue) SMALLINT(io.prestosql.spi.type.SmallintType.SMALLINT) Slices.utf8Slice(io.airlift.slice.Slices.utf8Slice) Slice(io.airlift.slice.Slice) DecimalType(io.prestosql.spi.type.DecimalType) Block(io.prestosql.spi.block.Block) ConnectorSession(io.prestosql.spi.connector.ConnectorSession) PrestoException(io.prestosql.spi.PrestoException) FunctionHandle(io.prestosql.spi.function.FunctionHandle) BigDecimal(java.math.BigDecimal) MethodHandle(java.lang.invoke.MethodHandle)

Example 5 with DOUBLE

use of io.prestosql.spi.type.DoubleType.DOUBLE in project hetu-core by openlookeng.

the class TestHivePageSink method writeTestFile.

private static long writeTestFile(HiveConfig config, HiveMetastore metastore, String outputPath) {
    HiveTransactionHandle transaction = new HiveTransactionHandle();
    HiveWriterStats stats = new HiveWriterStats();
    ConnectorPageSink pageSink = createPageSink(transaction, config, metastore, new Path("file:///" + outputPath), stats);
    List<LineItemColumn> columns = getTestColumns();
    List<Type> columnTypes = columns.stream().map(LineItemColumn::getType).map(TestHivePageSink::getHiveType).map(hiveType -> hiveType.getType(HiveTestUtils.TYPE_MANAGER)).collect(toList());
    PageBuilder pageBuilder = new PageBuilder(columnTypes);
    int rows = 0;
    for (LineItem lineItem : new LineItemGenerator(0.01, 1, 1)) {
        rows++;
        if (rows >= NUM_ROWS) {
            break;
        }
        pageBuilder.declarePosition();
        for (int i = 0; i < columns.size(); i++) {
            LineItemColumn column = columns.get(i);
            BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i);
            switch(column.getType().getBase()) {
                case IDENTIFIER:
                    BIGINT.writeLong(blockBuilder, column.getIdentifier(lineItem));
                    break;
                case INTEGER:
                    INTEGER.writeLong(blockBuilder, column.getInteger(lineItem));
                    break;
                case DATE:
                    DATE.writeLong(blockBuilder, column.getDate(lineItem));
                    break;
                case DOUBLE:
                    DOUBLE.writeDouble(blockBuilder, column.getDouble(lineItem));
                    break;
                case VARCHAR:
                    createUnboundedVarcharType().writeSlice(blockBuilder, Slices.utf8Slice(column.getString(lineItem)));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported type " + column.getType());
            }
        }
    }
    Page page = pageBuilder.build();
    pageSink.appendPage(page);
    getFutureValue(pageSink.finish());
    File outputDir = new File(outputPath);
    List<File> files = ImmutableList.copyOf(outputDir.listFiles((dir, name) -> !name.endsWith(".crc")));
    File outputFile = getOnlyElement(files);
    long length = outputFile.length();
    ConnectorPageSource pageSource = createPageSource(transaction, config, outputFile);
    List<Page> pages = new ArrayList<>();
    while (!pageSource.isFinished()) {
        Page nextPage = pageSource.getNextPage();
        if (nextPage != null) {
            pages.add(nextPage.getLoadedPage());
        }
    }
    MaterializedResult expectedResults = toMaterializedResult(getSession(config), columnTypes, ImmutableList.of(page));
    MaterializedResult results = toMaterializedResult(getSession(config), columnTypes, pages);
    assertEquals(results, expectedResults);
    assertEquals(round(stats.getInputPageSizeInBytes().getAllTime().getMax()), page.getRetainedSizeInBytes());
    return length;
}
Also used : Path(org.apache.hadoop.fs.Path) NONE(io.prestosql.plugin.hive.HiveCompressionCodec.NONE) HiveTestUtils.getDefaultHiveSelectiveFactories(io.prestosql.plugin.hive.HiveTestUtils.getDefaultHiveSelectiveFactories) MoreFiles.deleteRecursively(com.google.common.io.MoreFiles.deleteRecursively) Assertions.assertGreaterThan(io.airlift.testing.Assertions.assertGreaterThan) ConnectorPageSink(io.prestosql.spi.connector.ConnectorPageSink) Test(org.testng.annotations.Test) TpchColumnTypes(io.airlift.tpch.TpchColumnTypes) MaterializedResult(io.prestosql.testing.MaterializedResult) Assert.assertEquals(io.prestosql.testing.assertions.Assert.assertEquals) ConnectorSession(io.prestosql.spi.connector.ConnectorSession) Math.round(java.lang.Math.round) Files.createTempDirectory(java.nio.file.Files.createTempDirectory) Slices(io.airlift.slice.Slices) HIVE_STRING(io.prestosql.plugin.hive.HiveType.HIVE_STRING) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Path(org.apache.hadoop.fs.Path) Matchers.anyInt(org.mockito.Matchers.anyInt) Type(io.prestosql.spi.type.Type) BIGINT(io.prestosql.spi.type.BigintType.BIGINT) HIVE_INT(io.prestosql.plugin.hive.HiveType.HIVE_INT) SERIALIZATION_LIB(org.apache.hadoop.hive.serde.serdeConstants.SERIALIZATION_LIB) TpchColumnType(io.airlift.tpch.TpchColumnType) PageIndexerFactory(io.prestosql.spi.PageIndexerFactory) HIVE_LONG(io.prestosql.plugin.hive.HiveType.HIVE_LONG) ImmutableMap(com.google.common.collect.ImmutableMap) BlockBuilder(io.prestosql.spi.block.BlockBuilder) MetadataManager.createTestMetadataManager(io.prestosql.metadata.MetadataManager.createTestMetadataManager) PageBuilder(io.prestosql.spi.PageBuilder) String.format(java.lang.String.format) LineItemGenerator(io.airlift.tpch.LineItemGenerator) PageIndexer(io.prestosql.spi.PageIndexer) List(java.util.List) ConnectorPageSource(io.prestosql.spi.connector.ConnectorPageSource) Stream(java.util.stream.Stream) VarcharType.createUnboundedVarcharType(io.prestosql.spi.type.VarcharType.createUnboundedVarcharType) Optional(java.util.Optional) TestingNodeManager(io.prestosql.testing.TestingNodeManager) Joiner(com.google.common.base.Joiner) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) JsonCodec(io.airlift.json.JsonCodec) Mockito.mock(org.mockito.Mockito.mock) LineItem(io.airlift.tpch.LineItem) HivePageSinkMetadata(io.prestosql.plugin.hive.metastore.HivePageSinkMetadata) INTEGER(io.prestosql.spi.type.IntegerType.INTEGER) OptionalInt(java.util.OptionalInt) DIRECT_TO_TARGET_NEW_DIRECTORY(io.prestosql.plugin.hive.LocationHandle.WriteMode.DIRECT_TO_TARGET_NEW_DIRECTORY) ArrayList(java.util.ArrayList) GroupByHashPageIndexerFactory(io.prestosql.GroupByHashPageIndexerFactory) SchemaTableName(io.prestosql.spi.connector.SchemaTableName) REGULAR(io.prestosql.plugin.hive.HiveColumnHandle.ColumnType.REGULAR) GenericExceptionAction(io.prestosql.plugin.hive.authentication.GenericExceptionAction) ALLOW_INSECURE(com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE) ImmutableList(com.google.common.collect.ImmutableList) Matchers.anyObject(org.mockito.Matchers.anyObject) LineItemColumn(io.airlift.tpch.LineItemColumn) DOUBLE(io.prestosql.spi.type.DoubleType.DOUBLE) DATE(io.prestosql.spi.type.DateType.DATE) FileHiveMetastore.createTestingFileHiveMetastore(io.prestosql.plugin.hive.metastore.file.FileHiveMetastore.createTestingFileHiveMetastore) HiveMetastore(io.prestosql.plugin.hive.metastore.HiveMetastore) HiveIdentity(io.prestosql.plugin.hive.authentication.HiveIdentity) Properties(java.util.Properties) ConnectorTableHandle(io.prestosql.spi.connector.ConnectorTableHandle) TypeManager(io.prestosql.spi.type.TypeManager) Page(io.prestosql.spi.Page) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) Mockito.when(org.mockito.Mockito.when) MoreFutures.getFutureValue(io.airlift.concurrent.MoreFutures.getFutureValue) File(java.io.File) Collectors.toList(java.util.stream.Collectors.toList) IntArrayBlock(io.prestosql.spi.block.IntArrayBlock) HIVE_DATE(io.prestosql.plugin.hive.HiveType.HIVE_DATE) HIVE_DOUBLE(io.prestosql.plugin.hive.HiveType.HIVE_DOUBLE) JoinCompiler(io.prestosql.sql.gen.JoinCompiler) FILE_INPUT_FORMAT(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.FILE_INPUT_FORMAT) Assert.assertTrue(org.testng.Assert.assertTrue) TestingConnectorSession(io.prestosql.testing.TestingConnectorSession) Collections(java.util.Collections) LineItemColumn(io.airlift.tpch.LineItemColumn) ArrayList(java.util.ArrayList) LineItem(io.airlift.tpch.LineItem) Page(io.prestosql.spi.Page) PageBuilder(io.prestosql.spi.PageBuilder) ConnectorPageSource(io.prestosql.spi.connector.ConnectorPageSource) Type(io.prestosql.spi.type.Type) TpchColumnType(io.airlift.tpch.TpchColumnType) VarcharType.createUnboundedVarcharType(io.prestosql.spi.type.VarcharType.createUnboundedVarcharType) ConnectorPageSink(io.prestosql.spi.connector.ConnectorPageSink) MaterializedResult(io.prestosql.testing.MaterializedResult) File(java.io.File) LineItemGenerator(io.airlift.tpch.LineItemGenerator) BlockBuilder(io.prestosql.spi.block.BlockBuilder)

Aggregations

DOUBLE (io.prestosql.spi.type.DoubleType.DOUBLE)22 BIGINT (io.prestosql.spi.type.BigintType.BIGINT)19 Optional (java.util.Optional)17 ImmutableList (com.google.common.collect.ImmutableList)16 List (java.util.List)16 ImmutableMap (com.google.common.collect.ImmutableMap)15 Type (io.prestosql.spi.type.Type)15 INTEGER (io.prestosql.spi.type.IntegerType.INTEGER)13 Test (org.testng.annotations.Test)12 Map (java.util.Map)11 SMALLINT (io.prestosql.spi.type.SmallintType.SMALLINT)10 ArrayList (java.util.ArrayList)10 Slice (io.airlift.slice.Slice)9 TINYINT (io.prestosql.spi.type.TinyintType.TINYINT)9 ConnectorSession (io.prestosql.spi.connector.ConnectorSession)8 DATE (io.prestosql.spi.type.DateType.DATE)8 DecimalType (io.prestosql.spi.type.DecimalType)8 REAL (io.prestosql.spi.type.RealType.REAL)8 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)7 String.format (java.lang.String.format)7