Search in sources :

Example 41 with VarcharType

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

the class Field method toString.

@Override
public String toString() {
    if (value == null) {
        return "null";
    }
    if (Types.isArrayType(type)) {
        Type elementType = Types.getElementType(type);
        StringBuilder builder = new StringBuilder("ARRAY [");
        for (Object element : AccumuloRowSerializer.getArrayFromBlock(elementType, this.getArray())) {
            if (Types.isArrayType(elementType)) {
                Type elementElementType = Types.getElementType(elementType);
                builder.append(new Field(AccumuloRowSerializer.getBlockFromArray(elementElementType, (List<?>) element), elementType)).append(',');
            } else if (Types.isMapType(elementType)) {
                builder.append(new Field(AccumuloRowSerializer.getBlockFromMap(elementType, (Map<?, ?>) element), elementType)).append(',');
            } else {
                builder.append(new Field(element, elementType)).append(',');
            }
        }
        return builder.deleteCharAt(builder.length() - 1).append("]").toString();
    }
    if (Types.isMapType(type)) {
        StringBuilder builder = new StringBuilder("MAP(");
        StringBuilder keys = new StringBuilder("ARRAY [");
        StringBuilder values = new StringBuilder("ARRAY [");
        for (Entry<Object, Object> entry : AccumuloRowSerializer.getMapFromBlock(type, this.getMap()).entrySet()) {
            Type keyType = Types.getKeyType(type);
            if (Types.isArrayType(keyType)) {
                keys.append(new Field(AccumuloRowSerializer.getBlockFromArray(Types.getElementType(keyType), (List<?>) entry.getKey()), keyType)).append(',');
            } else if (Types.isMapType(keyType)) {
                keys.append(new Field(AccumuloRowSerializer.getBlockFromMap(keyType, (Map<?, ?>) entry.getKey()), keyType)).append(',');
            } else {
                keys.append(new Field(entry.getKey(), keyType)).append(',');
            }
            Type valueType = Types.getValueType(type);
            if (Types.isArrayType(valueType)) {
                values.append(new Field(AccumuloRowSerializer.getBlockFromArray(Types.getElementType(valueType), (List<?>) entry.getValue()), valueType)).append(',');
            } else if (Types.isMapType(valueType)) {
                values.append(new Field(AccumuloRowSerializer.getBlockFromMap(valueType, (Map<?, ?>) entry.getValue()), valueType)).append(',');
            } else {
                values.append(new Field(entry.getValue(), valueType)).append(',');
            }
        }
        keys.deleteCharAt(keys.length() - 1).append(']');
        values.deleteCharAt(values.length() - 1).append(']');
        return builder.append(keys).append(", ").append(values).append(")").toString();
    }
    // Validate the object is the given type
    if (type.equals(BIGINT) || type.equals(BOOLEAN) || type.equals(DOUBLE) || type.equals(INTEGER) || type.equals(REAL) || type.equals(TINYINT) || type.equals(SMALLINT)) {
        return value.toString();
    } else if (type.equals(DATE)) {
        return "DATE '" + value.toString() + "'";
    } else if (type.equals(TIME)) {
        return "TIME '" + value.toString() + "'";
    } else if (type.equals(TIMESTAMP)) {
        return "TIMESTAMP '" + value.toString() + "'";
    } else if (type.equals(VARBINARY)) {
        return "CAST('" + new String((byte[]) value, UTF_8).replaceAll("'", "''") + "' AS VARBINARY)";
    } else if (type instanceof VarcharType) {
        return "'" + value.toString().replaceAll("'", "''") + "'";
    } else {
        throw new PrestoException(NOT_SUPPORTED, "Unsupported PrestoType " + type);
    }
}
Also used : Type(com.facebook.presto.common.type.Type) VarcharType(com.facebook.presto.common.type.VarcharType) VarcharType(com.facebook.presto.common.type.VarcharType) List(java.util.List) PrestoException(com.facebook.presto.spi.PrestoException)

Example 42 with VarcharType

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

the class Row method valueFromString.

/**
 * Converts the given String into a Java object based on the given Presto type
 *
 * @param str String to convert
 * @param type Presto Type
 * @return Java object
 * @throws PrestoException If the type is not supported by this function
 */
public static Object valueFromString(String str, Type type) {
    if (str == null || str.isEmpty()) {
        return null;
    } else if (Types.isArrayType(type)) {
        Type elementType = Types.getElementType(type);
        ImmutableList.Builder<Object> listBuilder = ImmutableList.builder();
        for (String element : Splitter.on(',').split(str)) {
            listBuilder.add(valueFromString(element, elementType));
        }
        return AccumuloRowSerializer.getBlockFromArray(elementType, listBuilder.build());
    } else if (Types.isMapType(type)) {
        Type keyType = Types.getKeyType(type);
        Type valueType = Types.getValueType(type);
        ImmutableMap.Builder<Object, Object> mapBuilder = ImmutableMap.builder();
        for (String element : Splitter.on(',').split(str)) {
            ImmutableList.Builder<String> builder = ImmutableList.builder();
            List<String> keyValue = builder.addAll(Splitter.on("->").split(element)).build();
            checkArgument(keyValue.size() == 2, format("Map element %s has %d entries, not 2", element, keyValue.size()));
            mapBuilder.put(valueFromString(keyValue.get(0), keyType), valueFromString(keyValue.get(1), valueType));
        }
        return AccumuloRowSerializer.getBlockFromMap(type, mapBuilder.build());
    } else if (type.equals(BIGINT)) {
        return Long.parseLong(str);
    } else if (type.equals(BOOLEAN)) {
        return Boolean.parseBoolean(str);
    } else if (type.equals(DATE)) {
        return Date.valueOf(LocalDate.parse(str, DATE_PARSER));
    } else if (type.equals(DOUBLE)) {
        return Double.parseDouble(str);
    } else if (type.equals(INTEGER)) {
        return Integer.parseInt(str);
    } else if (type.equals(REAL)) {
        return Float.parseFloat(str);
    } else if (type.equals(SMALLINT)) {
        return Short.parseShort(str);
    } else if (type.equals(TIME)) {
        return Time.valueOf(LocalTime.parse(str, TIME_PARSER));
    } else if (type.equals(TIMESTAMP)) {
        return Timestamp.valueOf(LocalDateTime.parse(str, TIMESTAMP_PARSER));
    } else if (type.equals(TINYINT)) {
        return Byte.valueOf(str);
    } else if (type.equals(VARBINARY)) {
        return str.getBytes(UTF_8);
    } else if (type instanceof VarcharType) {
        return str;
    } else {
        throw new PrestoException(NOT_SUPPORTED, "Unsupported type " + type);
    }
}
Also used : Type(com.facebook.presto.common.type.Type) VarcharType(com.facebook.presto.common.type.VarcharType) VarcharType(com.facebook.presto.common.type.VarcharType) ImmutableList(com.google.common.collect.ImmutableList) PrestoException(com.facebook.presto.spi.PrestoException) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 43 with VarcharType

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

the class PinotPushdownUtils method getLiteralAsString.

// Copied from com.facebook.presto.sql.planner.LiteralInterpreter.evaluate
public static String getLiteralAsString(ConstantExpression node) {
    Type type = node.getType();
    if (node.getValue() == null) {
        throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), String.format("Null constant expression %s with value of type %s", node, type));
    }
    if (type instanceof BooleanType) {
        return String.valueOf(((Boolean) node.getValue()).booleanValue());
    }
    if (type instanceof BigintType || type instanceof TinyintType || type instanceof SmallintType || type instanceof IntegerType) {
        Number number = (Number) node.getValue();
        return format("%d", number.longValue());
    }
    if (type instanceof DoubleType) {
        return node.getValue().toString();
    }
    if (type instanceof RealType) {
        Long number = (Long) node.getValue();
        return format("%f", intBitsToFloat(number.intValue()));
    }
    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        if (decimalType.isShort()) {
            checkState(node.getValue() instanceof Long);
            return decodeDecimal(BigInteger.valueOf((long) node.getValue()), decimalType).toString();
        }
        checkState(node.getValue() instanceof Slice);
        Slice value = (Slice) node.getValue();
        return decodeDecimal(decodeUnscaledValue(value), decimalType).toString();
    }
    if (type instanceof VarcharType || type instanceof CharType) {
        return "'" + ((Slice) node.getValue()).toStringUtf8() + "'";
    }
    if (type instanceof TimestampType || type instanceof DateType) {
        return node.getValue().toString();
    }
    if (type instanceof TimestampWithTimeZoneType) {
        Long millisUtc = DateTimeEncoding.unpackMillisUtc((Long) node.getValue());
        return millisUtc.toString();
    }
    throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), String.format("Cannot handle the constant expression %s with value of type %s", node, type));
}
Also used : VarcharType(com.facebook.presto.common.type.VarcharType) TinyintType(com.facebook.presto.common.type.TinyintType) BooleanType(com.facebook.presto.common.type.BooleanType) RealType(com.facebook.presto.common.type.RealType) BigintType(com.facebook.presto.common.type.BigintType) IntegerType(com.facebook.presto.common.type.IntegerType) DecimalType(com.facebook.presto.common.type.DecimalType) BooleanType(com.facebook.presto.common.type.BooleanType) IntegerType(com.facebook.presto.common.type.IntegerType) CharType(com.facebook.presto.common.type.CharType) Type(com.facebook.presto.common.type.Type) TinyintType(com.facebook.presto.common.type.TinyintType) BigintType(com.facebook.presto.common.type.BigintType) VarcharType(com.facebook.presto.common.type.VarcharType) RealType(com.facebook.presto.common.type.RealType) TimestampWithTimeZoneType(com.facebook.presto.common.type.TimestampWithTimeZoneType) SmallintType(com.facebook.presto.common.type.SmallintType) DateType(com.facebook.presto.common.type.DateType) DoubleType(com.facebook.presto.common.type.DoubleType) TimestampType(com.facebook.presto.common.type.TimestampType) DoubleType(com.facebook.presto.common.type.DoubleType) Slice(io.airlift.slice.Slice) TimestampWithTimeZoneType(com.facebook.presto.common.type.TimestampWithTimeZoneType) DecimalType(com.facebook.presto.common.type.DecimalType) TimestampType(com.facebook.presto.common.type.TimestampType) SmallintType(com.facebook.presto.common.type.SmallintType) CharType(com.facebook.presto.common.type.CharType) DateType(com.facebook.presto.common.type.DateType)

Example 44 with VarcharType

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

the class RcFileTester method preprocessWriteValueOld.

private static Object preprocessWriteValueOld(Type type, Object value) {
    if (value == null) {
        return null;
    }
    if (type.equals(BOOLEAN)) {
        return value;
    } else if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    } else if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    } else if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    } else if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    } else if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    } else if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    } else if (type instanceof VarcharType) {
        return value;
    } else if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    } else if (type.equals(DATE)) {
        int days = ((SqlDate) value).getDays();
        LocalDate localDate = LocalDate.ofEpochDay(days);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        long millis = zonedDateTime.toEpochSecond() * 1000;
        Date date = new Date(0);
        // mills must be set separately to avoid masking
        date.setTime(millis);
        return date;
    } else if (type.equals(TIMESTAMP)) {
        long millisUtc = (int) ((SqlTimestamp) value).getMillisUtc();
        return new Timestamp(millisUtc);
    } else if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    } else if (type.getTypeSignature().getBase().equals(ARRAY)) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream().map(element -> preprocessWriteValueOld(elementType, element)).collect(toList());
    } else 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(keyType, entry.getKey()), preprocessWriteValueOld(valueType, entry.getValue()));
        }
        return newMap;
    } else 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(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
Also used : SnappyCodec(org.apache.hadoop.io.compress.SnappyCodec) Page(com.facebook.presto.common.Page) DateTimeZone(org.joda.time.DateTimeZone) LZ4(com.facebook.presto.rcfile.RcFileTester.Compression.LZ4) ZLIB(com.facebook.presto.rcfile.RcFileTester.Compression.ZLIB) ZonedDateTime(java.time.ZonedDateTime) 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) DateWritable(org.apache.hadoop.hive.serde2.io.DateWritable) Writable(org.apache.hadoop.io.Writable) PrimitiveObjectInspectorFactory.javaTimestampObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaTimestampObjectInspector) ROW(com.facebook.presto.common.type.StandardTypes.ROW) 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) Slices(io.airlift.slice.Slices) Configuration(org.apache.hadoop.conf.Configuration) Map(java.util.Map) 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) BlockBuilder(com.facebook.presto.common.block.BlockBuilder) 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) ZoneId(java.time.ZoneId) ARRAY(com.facebook.presto.common.type.StandardTypes.ARRAY) UncheckedIOException(java.io.UncheckedIOException) LzoCodec(com.hadoop.compression.lzo.LzoCodec) BooleanWritable(org.apache.hadoop.io.BooleanWritable) SqlTimestamp(com.facebook.presto.common.type.SqlTimestamp) Decimals.rescale(com.facebook.presto.common.type.Decimals.rescale) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) 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) StandardTypes(com.facebook.presto.common.type.StandardTypes) RcFileDecoderUtils.findFirstSyncPosition(com.facebook.presto.rcfile.RcFileDecoderUtils.findFirstSyncPosition) DecimalType(com.facebook.presto.common.type.DecimalType) Slice(io.airlift.slice.Slice) TypeSignatureParameter(com.facebook.presto.common.type.TypeSignatureParameter) TINYINT(com.facebook.presto.common.type.TinyintType.TINYINT) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) StructObject(org.apache.hadoop.hive.serde2.StructObject) Functions.constant(com.google.common.base.Functions.constant) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) META_TABLE_COLUMNS(org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS) PRESTO_RCFILE_WRITER_VERSION(com.facebook.presto.rcfile.RcFileWriter.PRESTO_RCFILE_WRITER_VERSION) FunctionAndTypeManager.createTestFunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager) DATE(com.facebook.presto.common.type.DateType.DATE) REAL(com.facebook.presto.common.type.RealType.REAL) ArrayList(java.util.ArrayList) SqlDate(com.facebook.presto.common.type.SqlDate) Lists(com.google.common.collect.Lists) ALLOW_INSECURE(com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE) PrimitiveObjectInspectorFactory.javaShortObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaShortObjectInspector) SqlVarbinary(com.facebook.presto.common.type.SqlVarbinary) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) ArrayType(com.facebook.presto.common.type.ArrayType) LinkedHashSet(java.util.LinkedHashSet) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Properties(java.util.Properties) AbstractIterator(com.google.common.collect.AbstractIterator) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ObjectInspectorFactory.getStandardStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector) UTC_KEY(com.facebook.presto.common.type.TimeZoneKey.UTC_KEY) 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) BinaryRcFileEncoding(com.facebook.presto.rcfile.binary.BinaryRcFileEncoding) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) 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) RowType(com.facebook.presto.common.type.RowType) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) 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) BZIP2(com.facebook.presto.rcfile.RcFileTester.Compression.BZIP2) GzipCodec(org.apache.hadoop.io.compress.GzipCodec) LongWritable(org.apache.hadoop.io.LongWritable) MAP(com.facebook.presto.common.type.StandardTypes.MAP) SESSION(com.facebook.presto.testing.TestingConnectorSession.SESSION) InputFormat(org.apache.hadoop.mapred.InputFormat) Path(org.apache.hadoop.fs.Path) KILOBYTE(io.airlift.units.DataSize.Unit.KILOBYTE) SqlDecimal(com.facebook.presto.common.type.SqlDecimal) NONE(com.facebook.presto.rcfile.RcFileTester.Compression.NONE) ShortWritable(org.apache.hadoop.hive.serde2.io.ShortWritable) SIZE_OF_INT(io.airlift.slice.SizeOf.SIZE_OF_INT) ImmutableSet(com.google.common.collect.ImmutableSet) Files.createTempDir(com.google.common.io.Files.createTempDir) ImmutableMap(com.google.common.collect.ImmutableMap) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) Timestamp(java.sql.Timestamp) RCFileOutputFormat(org.apache.hadoop.hive.ql.io.RCFileOutputFormat) VarcharType(com.facebook.presto.common.type.VarcharType) 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) LocalDate(java.time.LocalDate) 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) LazyPrimitive(org.apache.hadoop.hive.serde2.lazy.LazyPrimitive) MapType(com.facebook.presto.common.type.MapType) Assert.assertNull(org.testng.Assert.assertNull) LazyBinaryMap(org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryMap) PrimitiveObjectInspectorFactory.javaBooleanObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaBooleanObjectInspector) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) DoubleWritable(org.apache.hadoop.io.DoubleWritable) PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY(com.facebook.presto.rcfile.RcFileWriter.PRESTO_RCFILE_WRITER_VERSION_METADATA_KEY) PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector) OutputStreamSliceOutput(io.airlift.slice.OutputStreamSliceOutput) COMPRESS_CODEC(org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.COMPRESS_CODEC) ImmutableList(com.google.common.collect.ImmutableList) ByteWritable(org.apache.hadoop.io.ByteWritable) BytesWritable(org.apache.hadoop.io.BytesWritable) TimestampWritable(org.apache.hadoop.hive.serde2.io.TimestampWritable) Math.toIntExact(java.lang.Math.toIntExact) SNAPPY(com.facebook.presto.rcfile.RcFileTester.Compression.SNAPPY) Type(com.facebook.presto.common.type.Type) Iterator(java.util.Iterator) Iterators.advance(com.google.common.collect.Iterators.advance) HadoopNative(com.facebook.presto.hadoop.HadoopNative) FileInputStream(java.io.FileInputStream) Decimals(com.facebook.presto.common.type.Decimals) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) Date(java.sql.Date) TextRcFileEncoding(com.facebook.presto.rcfile.text.TextRcFileEncoding) 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) 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) PrimitiveObjectInspectorFactory.javaStringObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaStringObjectInspector) Block(com.facebook.presto.common.block.Block) HiveDecimalWritable(org.apache.hadoop.hive.serde2.io.HiveDecimalWritable) Collections(java.util.Collections) BYTE(io.airlift.units.DataSize.Unit.BYTE) InputStream(java.io.InputStream) VarcharType(com.facebook.presto.common.type.VarcharType) SqlVarbinary(com.facebook.presto.common.type.SqlVarbinary) ArrayList(java.util.ArrayList) SqlDecimal(com.facebook.presto.common.type.SqlDecimal) LocalDate(java.time.LocalDate) SqlTimestamp(com.facebook.presto.common.type.SqlTimestamp) Timestamp(java.sql.Timestamp) SqlDate(com.facebook.presto.common.type.SqlDate) LocalDate(java.time.LocalDate) Date(java.sql.Date) DecimalType(com.facebook.presto.common.type.DecimalType) ArrayType(com.facebook.presto.common.type.ArrayType) RowType(com.facebook.presto.common.type.RowType) VarcharType(com.facebook.presto.common.type.VarcharType) MapType(com.facebook.presto.common.type.MapType) Type(com.facebook.presto.common.type.Type) Entry(java.util.Map.Entry) ZonedDateTime(java.time.ZonedDateTime) DecimalType(com.facebook.presto.common.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 45 with VarcharType

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

the class H2QueryRunner method insertRows.

private static void insertRows(ConnectorTableMetadata tableMetadata, Handle handle, RecordSet data) {
    List<ColumnMetadata> columns = tableMetadata.getColumns().stream().filter(columnMetadata -> !columnMetadata.isHidden()).collect(toImmutableList());
    String vars = Joiner.on(',').join(nCopies(columns.size(), "?"));
    String sql = format("INSERT INTO %s VALUES (%s)", tableMetadata.getTable().getTableName(), vars);
    RecordCursor cursor = data.cursor();
    while (true) {
        // insert 1000 rows at a time
        PreparedBatch batch = handle.prepareBatch(sql);
        for (int row = 0; row < 1000; row++) {
            if (!cursor.advanceNextPosition()) {
                if (batch.size() > 0) {
                    batch.execute();
                }
                return;
            }
            for (int column = 0; column < columns.size(); column++) {
                Type type = columns.get(column).getType();
                if (BOOLEAN.equals(type)) {
                    batch.bind(column, cursor.getBoolean(column));
                } else if (BIGINT.equals(type)) {
                    batch.bind(column, cursor.getLong(column));
                } else if (INTEGER.equals(type)) {
                    batch.bind(column, (int) cursor.getLong(column));
                } else if (DOUBLE.equals(type)) {
                    batch.bind(column, cursor.getDouble(column));
                } else if (type instanceof VarcharType) {
                    batch.bind(column, cursor.getSlice(column).toStringUtf8());
                } else if (DATE.equals(type)) {
                    long millisUtc = TimeUnit.DAYS.toMillis(cursor.getLong(column));
                    // H2 expects dates in to be millis at midnight in the JVM timezone
                    long localMillis = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), millisUtc);
                    batch.bind(column, new Date(localMillis));
                } else {
                    throw new IllegalArgumentException("Unsupported type " + type);
                }
            }
            batch.add();
        }
        batch.execute();
    }
}
Also used : DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) TpchRecordSet.createTpchRecordSet(com.facebook.presto.tpch.TpchRecordSet.createTpchRecordSet) LINE_ITEM(io.airlift.tpch.TpchTable.LINE_ITEM) Array(java.sql.Array) BigDecimal(java.math.BigDecimal) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ParsedSql(org.jdbi.v3.core.statement.ParsedSql) ResultSet(java.sql.ResultSet) Handle(org.jdbi.v3.core.Handle) LocalTime(java.time.LocalTime) Varchars.isVarcharType(com.facebook.presto.common.type.Varchars.isVarcharType) REGION(io.airlift.tpch.TpchTable.REGION) TIME(com.facebook.presto.common.type.TimeType.TIME) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) MathContext(java.math.MathContext) PART_SUPPLIER(io.airlift.tpch.TpchTable.PART_SUPPLIER) Collections.nCopies(java.util.Collections.nCopies) Timestamp(java.sql.Timestamp) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) VarcharType(com.facebook.presto.common.type.VarcharType) TpchMetadata(com.facebook.presto.tpch.TpchMetadata) TINY_SCHEMA_NAME(com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME) String.format(java.lang.String.format) StatementContext(org.jdbi.v3.core.statement.StatementContext) Preconditions.checkState(com.google.common.base.Preconditions.checkState) TpchTable(io.airlift.tpch.TpchTable) RecordCursor(com.facebook.presto.spi.RecordCursor) TpchTableHandle(com.facebook.presto.tpch.TpchTableHandle) List(java.util.List) UNKNOWN(com.facebook.presto.common.type.UnknownType.UNKNOWN) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) LocalDate(java.time.LocalDate) Optional(java.util.Optional) TIME_WITH_TIME_ZONE(com.facebook.presto.common.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE) TimestampType(com.facebook.presto.common.type.TimestampType) ExpectedQueryRunner(com.facebook.presto.testing.ExpectedQueryRunner) Joiner(com.google.common.base.Joiner) Strings.padEnd(com.google.common.base.Strings.padEnd) NATION(io.airlift.tpch.TpchTable.NATION) DecimalType(com.facebook.presto.common.type.DecimalType) Chars.isCharType(com.facebook.presto.common.type.Chars.isCharType) ORDERS(io.airlift.tpch.TpchTable.ORDERS) TIMESTAMP_WITH_TIME_ZONE(com.facebook.presto.common.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE) TINYINT(com.facebook.presto.common.type.TinyintType.TINYINT) LocalDateTime(java.time.LocalDateTime) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) PART(io.airlift.tpch.TpchTable.PART) DATE(com.facebook.presto.common.type.DateType.DATE) REAL(com.facebook.presto.common.type.RealType.REAL) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) ArrayType(com.facebook.presto.common.type.ArrayType) CharType(com.facebook.presto.common.type.CharType) Type(com.facebook.presto.common.type.Type) TypeWithName(com.facebook.presto.common.type.TypeWithName) RowMapper(org.jdbi.v3.core.mapper.RowMapper) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) Jdbi(org.jdbi.v3.core.Jdbi) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Language(org.intellij.lang.annotations.Language) Session(com.facebook.presto.Session) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) RecordSet(com.facebook.presto.spi.RecordSet) Date(java.sql.Date) TimeUnit(java.util.concurrent.TimeUnit) MaterializedResult(com.facebook.presto.testing.MaterializedResult) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) MaterializedRow(com.facebook.presto.testing.MaterializedRow) SqlParser(org.jdbi.v3.core.statement.SqlParser) RowType(com.facebook.presto.common.type.RowType) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) Varchars.isVarcharType(com.facebook.presto.common.type.Varchars.isVarcharType) VarcharType(com.facebook.presto.common.type.VarcharType) TimestampType(com.facebook.presto.common.type.TimestampType) DecimalType(com.facebook.presto.common.type.DecimalType) Chars.isCharType(com.facebook.presto.common.type.Chars.isCharType) ArrayType(com.facebook.presto.common.type.ArrayType) CharType(com.facebook.presto.common.type.CharType) Type(com.facebook.presto.common.type.Type) RowType(com.facebook.presto.common.type.RowType) RecordCursor(com.facebook.presto.spi.RecordCursor) Varchars.isVarcharType(com.facebook.presto.common.type.Varchars.isVarcharType) VarcharType(com.facebook.presto.common.type.VarcharType) PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) LocalDate(java.time.LocalDate) Date(java.sql.Date)

Aggregations

VarcharType (com.facebook.presto.common.type.VarcharType)48 DecimalType (com.facebook.presto.common.type.DecimalType)30 Type (com.facebook.presto.common.type.Type)26 CharType (com.facebook.presto.common.type.CharType)23 PrestoException (com.facebook.presto.spi.PrestoException)16 Slice (io.airlift.slice.Slice)16 ArrayType (com.facebook.presto.common.type.ArrayType)14 RowType (com.facebook.presto.common.type.RowType)13 MapType (com.facebook.presto.common.type.MapType)12 ArrayList (java.util.ArrayList)12 ImmutableList (com.google.common.collect.ImmutableList)11 List (java.util.List)11 IntegerType (com.facebook.presto.common.type.IntegerType)10 TimestampType (com.facebook.presto.common.type.TimestampType)10 VarbinaryType (com.facebook.presto.common.type.VarbinaryType)10 BigintType (com.facebook.presto.common.type.BigintType)9 BooleanType (com.facebook.presto.common.type.BooleanType)9 DoubleType (com.facebook.presto.common.type.DoubleType)9 RealType (com.facebook.presto.common.type.RealType)9 SmallintType (com.facebook.presto.common.type.SmallintType)9