Java Code Examples for io.prestosql.spi.type.Type#getTypeParameters()

The following examples show how to use io.prestosql.spi.type.Type#getTypeParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OrcTester.java    From presto with Apache License 2.0 6 votes vote down vote up
private static List<Object> decodeRecordReaderStruct(Type type, List<?> fields)
{
    List<Type> fieldTypes = type.getTypeParameters();
    List<Object> newFields = new ArrayList<>(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        Type fieldType = fieldTypes.get(i);
        Object field = fields.get(i);
        newFields.add(decodeRecordReaderValue(fieldType, field));
    }

    for (int j = fields.size(); j < fieldTypes.size(); j++) {
        newFields.add(null);
    }

    return newFields;
}
 
Example 2
Source File: AvroColumnDecoder.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Block serializeList(BlockBuilder parentBlockBuilder, Object value, Type type, String columnName)
{
    if (value == null) {
        checkState(parentBlockBuilder != null, "parentBlockBuilder is null");
        parentBlockBuilder.appendNull();
        return null;
    }
    List<?> list = (List<?>) value;
    List<Type> typeParameters = type.getTypeParameters();
    Type elementType = typeParameters.get(0);

    BlockBuilder blockBuilder = elementType.createBlockBuilder(null, list.size());
    for (Object element : list) {
        serializeObject(blockBuilder, element, elementType, columnName);
    }
    if (parentBlockBuilder != null) {
        type.writeObject(parentBlockBuilder, blockBuilder.build());
        return null;
    }
    return blockBuilder.build();
}
 
Example 3
Source File: TypeCoercion.java    From presto with Apache License 2.0 6 votes vote down vote up
private TypeCompatibility typeCompatibilityForCovariantParametrizedType(Type fromType, Type toType)
{
    checkState(fromType.getClass().equals(toType.getClass()));
    ImmutableList.Builder<TypeSignatureParameter> commonParameterTypes = ImmutableList.builder();
    List<Type> fromTypeParameters = fromType.getTypeParameters();
    List<Type> toTypeParameters = toType.getTypeParameters();

    if (fromTypeParameters.size() != toTypeParameters.size()) {
        return TypeCompatibility.incompatible();
    }

    boolean coercible = true;
    for (int i = 0; i < fromTypeParameters.size(); i++) {
        TypeCompatibility compatibility = compatibility(fromTypeParameters.get(i), toTypeParameters.get(i));
        if (!compatibility.isCompatible()) {
            return TypeCompatibility.incompatible();
        }
        coercible &= compatibility.isCoercible();
        commonParameterTypes.add(TypeSignatureParameter.typeParameter(compatibility.getCommonSuperType().getTypeSignature()));
    }
    String typeBase = fromType.getBaseName();
    return TypeCompatibility.compatible(lookupType.apply(new TypeSignature(typeBase, commonParameterTypes.build())), coercible);
}
 
Example 4
Source File: RowToJsonCast.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    checkArgument(arity == 1, "Expected arity to be 1");
    Type type = boundVariables.getTypeVariable("T");
    checkCondition(canCastToJson(type), INVALID_CAST_ARGUMENT, "Cannot cast %s to JSON", type);

    List<Type> fieldTypes = type.getTypeParameters();
    List<JsonGeneratorWriter> fieldWriters = new ArrayList<>(fieldTypes.size());
    for (int i = 0; i < fieldTypes.size(); i++) {
        fieldWriters.add(createJsonGeneratorWriter(fieldTypes.get(i)));
    }
    MethodHandle methodHandle = METHOD_HANDLE.bindTo(fieldWriters);

    return new ScalarFunctionImplementation(
            false,
            ImmutableList.of(valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
            methodHandle);
}
 
Example 5
Source File: SerDeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Block serializeMap(Type type, BlockBuilder builder, Object object, MapObjectInspector inspector, boolean filterNullMapKeys)
{
    Map<?, ?> map = inspector.getMap(object);
    if (map == null) {
        requireNonNull(builder, "parent builder is null").appendNull();
        return null;
    }

    List<Type> typeParameters = type.getTypeParameters();
    checkArgument(typeParameters.size() == 2, "map must have exactly 2 type parameter");
    Type keyType = typeParameters.get(0);
    Type valueType = typeParameters.get(1);
    ObjectInspector keyInspector = inspector.getMapKeyObjectInspector();
    ObjectInspector valueInspector = inspector.getMapValueObjectInspector();
    BlockBuilder currentBuilder;

    boolean builderSynthesized = false;
    if (builder == null) {
        builderSynthesized = true;
        builder = type.createBlockBuilder(null, 1);
    }
    currentBuilder = builder.beginBlockEntry();

    for (Map.Entry<?, ?> entry : map.entrySet()) {
        // Hive skips map entries with null keys
        if (!filterNullMapKeys || entry.getKey() != null) {
            serializeObject(keyType, currentBuilder, entry.getKey(), keyInspector);
            serializeObject(valueType, currentBuilder, entry.getValue(), valueInspector);
        }
    }

    builder.closeEntry();
    if (builderSynthesized) {
        return (Block) type.getObject(builder, 0);
    }
    else {
        return null;
    }
}
 
Example 6
Source File: SerDeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Block serializeList(Type type, BlockBuilder builder, Object object, ListObjectInspector inspector)
{
    List<?> list = inspector.getList(object);
    if (list == null) {
        requireNonNull(builder, "parent builder is null").appendNull();
        return null;
    }

    List<Type> typeParameters = type.getTypeParameters();
    checkArgument(typeParameters.size() == 1, "list must have exactly 1 type parameter");
    Type elementType = typeParameters.get(0);
    ObjectInspector elementInspector = inspector.getListElementObjectInspector();
    BlockBuilder currentBuilder;
    if (builder != null) {
        currentBuilder = builder.beginBlockEntry();
    }
    else {
        currentBuilder = elementType.createBlockBuilder(null, list.size());
    }

    for (Object element : list) {
        serializeObject(elementType, currentBuilder, element, elementInspector);
    }

    if (builder != null) {
        builder.closeEntry();
        return null;
    }
    else {
        Block resultBlock = currentBuilder.build();
        return resultBlock;
    }
}
 
Example 7
Source File: SerDeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Block serializeUnion(Type type, BlockBuilder builder, Object object, UnionObjectInspector inspector)
{
    if (object == null) {
        requireNonNull(builder, "parent builder is null").appendNull();
        return null;
    }

    boolean builderSynthesized = false;
    if (builder == null) {
        builderSynthesized = true;
        builder = type.createBlockBuilder(null, 1);
    }

    BlockBuilder currentBuilder = builder.beginBlockEntry();

    byte tag = inspector.getTag(object);
    TINYINT.writeLong(currentBuilder, tag);

    List<Type> typeParameters = type.getTypeParameters();
    for (int i = 1; i < typeParameters.size(); i++) {
        if (i == tag + 1) {
            serializeObject(typeParameters.get(i), currentBuilder, inspector.getField(object), inspector.getObjectInspectors().get(tag));
        }
        else {
            currentBuilder.appendNull();
        }
    }

    builder.closeEntry();
    if (builderSynthesized) {
        return (Block) type.getObject(builder, 0);
    }
    return null;
}
 
Example 8
Source File: RcFileTester.java    From presto with Apache License 2.0 5 votes vote down vote up
private static List<Object> decodeRecordReaderStruct(Type type, List<?> fields)
{
    List<Type> fieldTypes = type.getTypeParameters();
    List<Object> newFields = new ArrayList<>(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        Type fieldType = fieldTypes.get(i);
        Object field = fields.get(i);
        newFields.add(decodeRecordReaderValue(fieldType, field));
    }
    return newFields;
}
 
Example 9
Source File: SerDeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Block serializeStruct(Type type, BlockBuilder builder, Object object, StructObjectInspector inspector)
{
    if (object == null) {
        requireNonNull(builder, "parent builder is null").appendNull();
        return null;
    }

    List<Type> typeParameters = type.getTypeParameters();
    List<? extends StructField> allStructFieldRefs = inspector.getAllStructFieldRefs();
    checkArgument(typeParameters.size() == allStructFieldRefs.size());
    BlockBuilder currentBuilder;

    boolean builderSynthesized = false;
    if (builder == null) {
        builderSynthesized = true;
        builder = type.createBlockBuilder(null, 1);
    }
    currentBuilder = builder.beginBlockEntry();

    for (int i = 0; i < typeParameters.size(); i++) {
        StructField field = allStructFieldRefs.get(i);
        serializeObject(typeParameters.get(i), currentBuilder, inspector.getStructFieldData(object, field), field.getFieldObjectInspector());
    }

    builder.closeEntry();
    if (builderSynthesized) {
        return (Block) type.getObject(builder, 0);
    }
    else {
        return null;
    }
}
 
Example 10
Source File: RowConstructorCodeGenerator.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public BytecodeNode generateExpression(ResolvedFunction resolvedFunction, BytecodeGeneratorContext context, Type rowType, List<RowExpression> arguments)
{
    BytecodeBlock block = new BytecodeBlock().setDescription("Constructor for " + rowType.toString());
    CallSiteBinder binder = context.getCallSiteBinder();
    Scope scope = context.getScope();
    List<Type> types = rowType.getTypeParameters();

    block.comment("Create new RowBlockBuilder; beginBlockEntry;");
    Variable blockBuilder = scope.createTempVariable(BlockBuilder.class);
    Variable singleRowBlockWriter = scope.createTempVariable(BlockBuilder.class);
    block.append(blockBuilder.set(
            constantType(binder, rowType).invoke(
                    "createBlockBuilder",
                    BlockBuilder.class,
                    constantNull(BlockBuilderStatus.class),
                    constantInt(1))));
    block.append(singleRowBlockWriter.set(blockBuilder.invoke("beginBlockEntry", BlockBuilder.class)));

    for (int i = 0; i < arguments.size(); ++i) {
        Type fieldType = types.get(i);
        Variable field = scope.createTempVariable(fieldType.getJavaType());
        block.comment("Clean wasNull and Generate + " + i + "-th field of row");
        block.append(context.wasNull().set(constantFalse()));
        block.append(context.generate(arguments.get(i)));
        block.putVariable(field);
        block.append(new IfStatement()
                .condition(context.wasNull())
                .ifTrue(singleRowBlockWriter.invoke("appendNull", BlockBuilder.class).pop())
                .ifFalse(constantType(binder, fieldType).writeValue(singleRowBlockWriter, field).pop()));
    }
    block.comment("closeEntry; slice the SingleRowBlock; wasNull = false;");
    block.append(blockBuilder.invoke("closeEntry", BlockBuilder.class).pop());
    block.append(constantType(binder, rowType).invoke("getObject", Object.class, blockBuilder.cast(Block.class), constantInt(0))
            .cast(Block.class));
    block.append(context.wasNull().set(constantFalse()));
    return block;
}
 
Example 11
Source File: AvroColumnDecoder.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Block serializeMap(BlockBuilder parentBlockBuilder, Object value, Type type, String columnName)
{
    if (value == null) {
        checkState(parentBlockBuilder != null, "parentBlockBuilder is null");
        parentBlockBuilder.appendNull();
        return null;
    }

    Map<?, ?> map = (Map<?, ?>) value;
    List<Type> typeParameters = type.getTypeParameters();
    Type keyType = typeParameters.get(0);
    Type valueType = typeParameters.get(1);

    BlockBuilder blockBuilder;
    if (parentBlockBuilder != null) {
        blockBuilder = parentBlockBuilder;
    }
    else {
        blockBuilder = type.createBlockBuilder(null, 1);
    }

    BlockBuilder entryBuilder = blockBuilder.beginBlockEntry();
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        if (entry.getKey() != null) {
            keyType.writeSlice(entryBuilder, truncateToLength(utf8Slice(entry.getKey().toString()), keyType));
            serializeObject(entryBuilder, entry.getValue(), valueType, columnName);
        }
    }
    blockBuilder.closeEntry();

    if (parentBlockBuilder == null) {
        return blockBuilder.getObject(0, Block.class);
    }
    return null;
}
 
Example 12
Source File: ExpressionAnalyzer.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected Type visitSubscriptExpression(SubscriptExpression node, StackableAstVisitorContext<Context> context)
{
    Type baseType = process(node.getBase(), context);
    // Subscript on Row hasn't got a dedicated operator. Its Type is resolved by hand.
    if (baseType instanceof RowType) {
        if (!(node.getIndex() instanceof LongLiteral)) {
            throw semanticException(EXPRESSION_NOT_CONSTANT, node.getIndex(), "Subscript expression on ROW requires a constant index");
        }
        Type indexType = process(node.getIndex(), context);
        if (!indexType.equals(INTEGER)) {
            throw semanticException(TYPE_MISMATCH, node.getIndex(), "Subscript expression on ROW requires integer index, found %s", indexType);
        }
        int indexValue = toIntExact(((LongLiteral) node.getIndex()).getValue());
        if (indexValue <= 0) {
            throw semanticException(INVALID_FUNCTION_ARGUMENT, node.getIndex(), "Invalid subscript index: %s. ROW indices start at 1", indexValue);
        }
        List<Type> rowTypes = baseType.getTypeParameters();
        if (indexValue > rowTypes.size()) {
            throw semanticException(INVALID_FUNCTION_ARGUMENT, node.getIndex(), "Subscript index out of bounds: %s, max value is %s", indexValue, rowTypes.size());
        }
        return setExpressionType(node, rowTypes.get(indexValue - 1));
    }

    // Subscript on Array or Map uses an operator to resolve Type.
    return getOperator(context, node, SUBSCRIPT, node.getBase(), node.getIndex());
}
 
Example 13
Source File: SqlToRowExpressionTranslator.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected RowExpression visitLambdaExpression(LambdaExpression node, Void context)
{
    RowExpression body = process(node.getBody(), context);

    Type type = getType(node);
    List<Type> typeParameters = type.getTypeParameters();
    List<Type> argumentTypes = typeParameters.subList(0, typeParameters.size() - 1);
    List<String> argumentNames = node.getArguments().stream()
            .map(LambdaArgumentDeclaration::getName)
            .map(Identifier::getValue)
            .collect(toImmutableList());

    return new LambdaDefinitionExpression(argumentTypes, argumentNames, body);
}
 
Example 14
Source File: AvroColumnDecoder.java    From presto with Apache License 2.0 5 votes vote down vote up
private boolean isSupportedType(Type type)
{
    if (isSupportedPrimitive(type)) {
        return true;
    }

    if (type instanceof ArrayType) {
        checkArgument(type.getTypeParameters().size() == 1, "expecting exactly one type parameter for array");
        return isSupportedType(type.getTypeParameters().get(0));
    }

    if (type instanceof MapType) {
        List<Type> typeParameters = type.getTypeParameters();
        checkArgument(typeParameters.size() == 2, "expecting exactly two type parameters for map");
        checkArgument(typeParameters.get(0) instanceof VarcharType, "Unsupported column type '%s' for map key", typeParameters.get(0));
        return isSupportedType(type.getTypeParameters().get(1));
    }

    if (type instanceof RowType) {
        for (Type fieldType : type.getTypeParameters()) {
            if (!isSupportedType(fieldType)) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 15
Source File: RowDistinctFromOperator.java    From presto with Apache License 2.0 5 votes vote down vote up
public static boolean isDistinctFrom(Type rowType, List<MethodHandle> argumentMethods, Block leftRow, boolean leftNull, Block rightRow, boolean rightNull)
{
    if (leftNull != rightNull) {
        return true;
    }
    if (leftNull) {
        return false;
    }
    List<Type> fieldTypes = rowType.getTypeParameters();
    for (int i = 0; i < leftRow.getPositionCount(); i++) {
        Type type = fieldTypes.get(i);
        Object leftValue = readNativeValue(type, leftRow, i);
        boolean leftValueNull = leftValue == null;
        if (leftValueNull) {
            leftValue = defaultValue(type.getJavaType());
        }
        Object rightValue = readNativeValue(type, rightRow, i);
        boolean rightValueNull = rightValue == null;
        if (rightValueNull) {
            rightValue = defaultValue(type.getJavaType());
        }
        try {
            if ((boolean) argumentMethods.get(i).invoke(
                    leftValue,
                    leftValueNull,
                    rightValue,
                    rightValueNull)) {
                return true;
            }
        }
        catch (Throwable t) {
            throw internalError(t);
        }
    }
    return false;
}
 
Example 16
Source File: RowDistinctFromOperator.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    ImmutableList.Builder<MethodHandle> argumentMethods = ImmutableList.builder();
    Type type = boundVariables.getTypeVariable("T");
    for (Type parameterType : type.getTypeParameters()) {
        ResolvedFunction resolvedFunction = metadata.resolveOperator(IS_DISTINCT_FROM, ImmutableList.of(parameterType, parameterType));
        FunctionInvoker functionInvoker = metadata.getScalarFunctionInvoker(
                resolvedFunction,
                Optional.of(new InvocationConvention(
                        ImmutableList.of(NULL_FLAG, NULL_FLAG),
                        InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL,
                        false,
                        false)));
        argumentMethods.add(functionInvoker.getMethodHandle());
    }
    return new ScalarFunctionImplementation(
            ImmutableList.of(
                    new ScalarImplementationChoice(
                            false,
                            ImmutableList.of(valueTypeArgumentProperty(USE_NULL_FLAG), valueTypeArgumentProperty(USE_NULL_FLAG)),
                            METHOD_HANDLE_NULL_FLAG.bindTo(type).bindTo(argumentMethods.build()),
                            Optional.empty()),
                    new ScalarImplementationChoice(
                            false,
                            ImmutableList.of(valueTypeArgumentProperty(BLOCK_AND_POSITION), valueTypeArgumentProperty(BLOCK_AND_POSITION)),
                            METHOD_HANDLE_BLOCK_POSITION.bindTo(type).bindTo(argumentMethods.build()),
                            Optional.empty())));
}
 
Example 17
Source File: JsonUtil.java    From presto with Apache License 2.0 4 votes vote down vote up
static JsonGeneratorWriter createJsonGeneratorWriter(Type type)
{
    if (type instanceof UnknownType) {
        return new UnknownJsonGeneratorWriter();
    }
    if (type instanceof BooleanType) {
        return new BooleanJsonGeneratorWriter();
    }
    if (type instanceof TinyintType || type instanceof SmallintType || type instanceof IntegerType || type instanceof BigintType) {
        return new LongJsonGeneratorWriter(type);
    }
    if (type instanceof RealType) {
        return new RealJsonGeneratorWriter();
    }
    if (type instanceof DoubleType) {
        return new DoubleJsonGeneratorWriter();
    }
    if (type instanceof DecimalType) {
        if (isShortDecimal(type)) {
            return new ShortDecimalJsonGeneratorWriter((DecimalType) type);
        }
        return new LongDeicmalJsonGeneratorWriter((DecimalType) type);
    }
    if (type instanceof VarcharType) {
        return new VarcharJsonGeneratorWriter(type);
    }
    if (type instanceof JsonType) {
        return new JsonJsonGeneratorWriter();
    }
    if (type instanceof TimestampType) {
        return new TimestampJsonGeneratorWriter((TimestampType) type);
    }
    if (type instanceof DateType) {
        return new DateGeneratorWriter();
    }
    if (type instanceof ArrayType) {
        ArrayType arrayType = (ArrayType) type;
        return new ArrayJsonGeneratorWriter(
                arrayType,
                createJsonGeneratorWriter(arrayType.getElementType()));
    }
    if (type instanceof MapType) {
        MapType mapType = (MapType) type;
        return new MapJsonGeneratorWriter(
                mapType,
                createObjectKeyProvider(mapType.getKeyType()),
                createJsonGeneratorWriter(mapType.getValueType()));
    }
    if (type instanceof RowType) {
        List<Type> fieldTypes = type.getTypeParameters();
        List<JsonGeneratorWriter> fieldWriters = new ArrayList<>(fieldTypes.size());
        for (int i = 0; i < fieldTypes.size(); i++) {
            fieldWriters.add(createJsonGeneratorWriter(fieldTypes.get(i)));
        }
        return new RowJsonGeneratorWriter((RowType) type, fieldWriters);
    }

    throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Unsupported type: %s", type));
}
 
Example 18
Source File: SignatureBinder.java    From presto with Apache License 2.0 4 votes vote down vote up
private boolean canCast(Type fromType, Type toType)
{
    if (toType instanceof UnknownType) {
        return true;
    }
    if (fromType instanceof RowType) {
        if (toType instanceof RowType) {
            List<Type> fromTypeParameters = fromType.getTypeParameters();
            List<Type> toTypeParameters = toType.getTypeParameters();
            if (fromTypeParameters.size() != toTypeParameters.size()) {
                return false;
            }
            for (int fieldIndex = 0; fieldIndex < fromTypeParameters.size(); fieldIndex++) {
                if (!canCast(fromTypeParameters.get(fieldIndex), toTypeParameters.get(fieldIndex))) {
                    return false;
                }
            }
            return true;
        }
        else if (toType instanceof JsonType) {
            return fromType.getTypeParameters().stream()
                    .allMatch(fromTypeParameter -> canCast(fromTypeParameter, toType));
        }
        else {
            return false;
        }
    }
    if (fromType instanceof JsonType) {
        if (toType instanceof RowType) {
            return toType.getTypeParameters().stream()
                    .allMatch(toTypeParameter -> canCast(fromType, toTypeParameter));
        }
    }
    try {
        metadata.getCoercion(fromType, toType);
        return true;
    }
    catch (PrestoException e) {
        return false;
    }
}
 
Example 19
Source File: RowToRowCast.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Class<?> generateRowCast(Type fromType, Type toType, Metadata metadata)
{
    List<Type> toTypes = toType.getTypeParameters();
    List<Type> fromTypes = fromType.getTypeParameters();

    CallSiteBinder binder = new CallSiteBinder();

    // Embed the MD5 hash code of input and output types into the generated class name instead of the raw type names,
    // which could prevent the class name from hitting the length limitation and invalid characters.
    byte[] md5Suffix = Hashing.md5().hashBytes((fromType + "$" + toType).getBytes(UTF_8)).asBytes();

    ClassDefinition definition = new ClassDefinition(
            a(PUBLIC, FINAL),
            makeClassName(Joiner.on("$").join("RowCast", BaseEncoding.base16().encode(md5Suffix))),
            type(Object.class));

    Parameter session = arg("session", ConnectorSession.class);
    Parameter value = arg("value", Block.class);

    MethodDefinition method = definition.declareMethod(
            a(PUBLIC, STATIC),
            "castRow",
            type(Block.class),
            session,
            value);

    Scope scope = method.getScope();
    BytecodeBlock body = method.getBody();

    Variable wasNull = scope.declareVariable(boolean.class, "wasNull");
    Variable blockBuilder = scope.createTempVariable(BlockBuilder.class);
    Variable singleRowBlockWriter = scope.createTempVariable(BlockBuilder.class);

    body.append(wasNull.set(constantBoolean(false)));

    CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(definition, binder);

    // create the row block builder
    body.append(blockBuilder.set(
            constantType(binder, toType).invoke(
                    "createBlockBuilder",
                    BlockBuilder.class,
                    constantNull(BlockBuilderStatus.class),
                    constantInt(1))));
    body.append(singleRowBlockWriter.set(blockBuilder.invoke("beginBlockEntry", BlockBuilder.class)));

    // loop through to append member blocks
    for (int i = 0; i < toTypes.size(); i++) {
        ResolvedFunction resolvedFunction = metadata.getCoercion(fromTypes.get(i), toTypes.get(i));
        Type currentFromType = fromTypes.get(i);
        if (currentFromType.equals(UNKNOWN)) {
            body.append(singleRowBlockWriter.invoke("appendNull", BlockBuilder.class).pop());
            continue;
        }
        BytecodeExpression fromElement = constantType(binder, currentFromType).getValue(value, constantInt(i));
        BytecodeExpression toElement = invokeFunction(scope, cachedInstanceBinder, resolvedFunction, metadata, fromElement);
        IfStatement ifElementNull = new IfStatement("if the element in the row type is null...");

        ifElementNull.condition(value.invoke("isNull", boolean.class, constantInt(i)))
                .ifTrue(singleRowBlockWriter.invoke("appendNull", BlockBuilder.class).pop())
                .ifFalse(constantType(binder, toTypes.get(i)).writeValue(singleRowBlockWriter, toElement));

        body.append(ifElementNull);
    }

    // call blockBuilder.closeEntry() and return the single row block
    body.append(blockBuilder.invoke("closeEntry", BlockBuilder.class).pop());
    body.append(constantType(binder, toType)
            .invoke("getObject", Object.class, blockBuilder.cast(Block.class), constantInt(0))
            .cast(Block.class)
            .ret());

    // create constructor
    MethodDefinition constructorDefinition = definition.declareConstructor(a(PUBLIC));
    BytecodeBlock constructorBody = constructorDefinition.getBody();
    Variable thisVariable = constructorDefinition.getThis();
    constructorBody.comment("super();")
            .append(thisVariable)
            .invokeConstructor(Object.class);
    cachedInstanceBinder.generateInitializations(thisVariable, constructorBody);
    constructorBody.ret();

    return defineClass(definition, Object.class, binder.getBindings(), RowToRowCast.class.getClassLoader());
}
 
Example 20
Source File: HiveWriteUtils.java    From presto with Apache License 2.0 4 votes vote down vote up
public static FieldSetter createFieldSetter(SettableStructObjectInspector rowInspector, Object row, StructField field, Type type)
{
    if (type.equals(BooleanType.BOOLEAN)) {
        return new BooleanFieldSetter(rowInspector, row, field);
    }

    if (type.equals(BigintType.BIGINT)) {
        return new BigintFieldBuilder(rowInspector, row, field);
    }

    if (type.equals(IntegerType.INTEGER)) {
        return new IntFieldSetter(rowInspector, row, field);
    }

    if (type.equals(SmallintType.SMALLINT)) {
        return new SmallintFieldSetter(rowInspector, row, field);
    }

    if (type.equals(TinyintType.TINYINT)) {
        return new TinyintFieldSetter(rowInspector, row, field);
    }

    if (type.equals(RealType.REAL)) {
        return new FloatFieldSetter(rowInspector, row, field);
    }

    if (type.equals(DoubleType.DOUBLE)) {
        return new DoubleFieldSetter(rowInspector, row, field);
    }

    if (type instanceof VarcharType) {
        return new VarcharFieldSetter(rowInspector, row, field, type);
    }

    if (type instanceof CharType) {
        return new CharFieldSetter(rowInspector, row, field, type);
    }

    if (type.equals(VarbinaryType.VARBINARY)) {
        return new BinaryFieldSetter(rowInspector, row, field);
    }

    if (type.equals(DateType.DATE)) {
        return new DateFieldSetter(rowInspector, row, field);
    }

    if (type.equals(TimestampType.TIMESTAMP)) {
        return new TimestampFieldSetter(rowInspector, row, field);
    }

    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return new DecimalFieldSetter(rowInspector, row, field, decimalType);
    }

    if (isArrayType(type)) {
        return new ArrayFieldSetter(rowInspector, row, field, type.getTypeParameters().get(0));
    }

    if (isMapType(type)) {
        return new MapFieldSetter(rowInspector, row, field, type.getTypeParameters().get(0), type.getTypeParameters().get(1));
    }

    if (isRowType(type)) {
        return new RowFieldSetter(rowInspector, row, field, type.getTypeParameters());
    }

    throw new IllegalArgumentException("unsupported type: " + type);
}