Search in sources :

Example 1 with TypeSignature

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

the class MySqlClient method getColumns.

@SuppressWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
@Override
public Map<String, ColumnHandle> getColumns(ConnectorSession session, String sql, Map<String, Type> types) {
    try (Connection connection = connectionFactory.openConnection(JdbcIdentity.from(session));
        PreparedStatement statement = connection.prepareStatement(sql)) {
        ResultSetMetaData metaData = statement.getMetaData();
        ImmutableMap.Builder<String, ColumnHandle> columnBuilder = new ImmutableMap.Builder<>();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            String columnName = metaData.getColumnLabel(i);
            String typeName = metaData.getColumnTypeName(i);
            int precision = metaData.getPrecision(i);
            int dataType = metaData.getColumnType(i);
            int scale = metaData.getScale(i);
            // extracted from logical plan during pre-processing
            if (dataType == Types.DECIMAL && (precision > MAX_PRECISION || scale < 0)) {
                // Covert MySql Decimal type to Presto type
                Type type = types.get(columnName.toLowerCase(ENGLISH));
                if (type instanceof AbstractType) {
                    TypeSignature signature = type.getTypeSignature();
                    typeName = signature.getBase().toUpperCase(ENGLISH);
                    dataType = JDBCType.valueOf(typeName).getVendorTypeNumber();
                    if (type instanceof DecimalType) {
                        precision = ((DecimalType) type).getPrecision();
                        scale = ((DecimalType) type).getScale();
                    }
                }
            }
            boolean isNullable = metaData.isNullable(i) != ResultSetMetaData.columnNoNulls;
            JdbcTypeHandle typeHandle = new JdbcTypeHandle(dataType, Optional.ofNullable(typeName), precision, scale, Optional.empty());
            Optional<ColumnMapping> columnMapping;
            try {
                columnMapping = toPrestoType(session, connection, typeHandle);
            } catch (UnsupportedOperationException ex) {
                throw new PrestoException(JDBC_UNSUPPORTED_EXPRESSION, format("Data type [%s] is not support", typeHandle.getJdbcTypeName()));
            }
            // skip unsupported column types
            if (columnMapping.isPresent()) {
                Type type = columnMapping.get().getType();
                JdbcColumnHandle handle = new JdbcColumnHandle(columnName, typeHandle, type, isNullable);
                columnBuilder.put(columnName.toLowerCase(ENGLISH), handle);
            } else {
                return Collections.emptyMap();
            }
        }
        return columnBuilder.build();
    } catch (SQLException | PrestoException e) {
        throw new PrestoException(JDBC_QUERY_GENERATOR_FAILURE, String.format("Query generator failed for [%s]", e.getMessage()));
    }
}
Also used : JdbcColumnHandle(io.prestosql.plugin.jdbc.JdbcColumnHandle) ColumnHandle(io.prestosql.spi.connector.ColumnHandle) SQLException(java.sql.SQLException) Connection(java.sql.Connection) JdbcColumnHandle(io.prestosql.plugin.jdbc.JdbcColumnHandle) PreparedStatement(java.sql.PreparedStatement) PrestoException(io.prestosql.spi.PrestoException) ImmutableMap(com.google.common.collect.ImmutableMap) ResultSetMetaData(java.sql.ResultSetMetaData) Varchars.isVarcharType(io.prestosql.spi.type.Varchars.isVarcharType) DecimalType(io.prestosql.spi.type.DecimalType) Type(io.prestosql.spi.type.Type) AbstractType(io.prestosql.spi.type.AbstractType) JDBCType(java.sql.JDBCType) VarcharType(io.prestosql.spi.type.VarcharType) TypeSignature(io.prestosql.spi.type.TypeSignature) JdbcTypeHandle(io.prestosql.plugin.jdbc.JdbcTypeHandle) AbstractType(io.prestosql.spi.type.AbstractType) DecimalType(io.prestosql.spi.type.DecimalType) ColumnMapping(io.prestosql.plugin.jdbc.ColumnMapping)

Example 2 with TypeSignature

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

the class ConcatFunction method generateConcat.

private static Class<?> generateConcat(TypeSignature type, int arity) {
    checkCondition(arity <= 254, NOT_SUPPORTED, "Too many arguments for string concatenation");
    ClassDefinition definition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName(type.getBase() + "_concat" + arity + "ScalarFunction"), type(Object.class));
    // Generate constructor
    definition.declareDefaultConstructor(a(PRIVATE));
    // Generate concat()
    List<Parameter> parameters = IntStream.range(0, arity).mapToObj(i -> arg("arg" + i, Slice.class)).collect(toImmutableList());
    MethodDefinition method = definition.declareMethod(a(PUBLIC, STATIC), "concat", type(Slice.class), parameters);
    Scope scope = method.getScope();
    BytecodeBlock body = method.getBody();
    Variable length = scope.declareVariable(int.class, "length");
    body.append(length.set(constantInt(0)));
    for (int i = 0; i < arity; ++i) {
        body.append(length.set(generateCheckedAdd(length, parameters.get(i).invoke("length", int.class))));
    }
    Variable result = scope.declareVariable(Slice.class, "result");
    body.append(result.set(invokeStatic(Slices.class, "allocate", Slice.class, length)));
    Variable position = scope.declareVariable(int.class, "position");
    body.append(position.set(constantInt(0)));
    for (int i = 0; i < arity; ++i) {
        body.append(result.invoke("setBytes", void.class, position, parameters.get(i)));
        body.append(position.set(add(position, parameters.get(i).invoke("length", int.class))));
    }
    body.getVariable(result).retObject();
    return defineClass(definition, Object.class, ImmutableMap.of(), new DynamicClassLoader(ConcatFunction.class.getClassLoader()));
}
Also used : BytecodeBlock(io.airlift.bytecode.BytecodeBlock) INVALID_FUNCTION_ARGUMENT(io.prestosql.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT) Scope(io.airlift.bytecode.Scope) DynamicClassLoader(io.airlift.bytecode.DynamicClassLoader) BoundVariables(io.prestosql.metadata.BoundVariables) DEFAULT_NAMESPACE(io.prestosql.spi.connector.CatalogSchemaName.DEFAULT_NAMESPACE) CompilerUtils.makeClassName(io.prestosql.util.CompilerUtils.makeClassName) Access.a(io.airlift.bytecode.Access.a) UsedByGeneratedCode(io.prestosql.spi.annotation.UsedByGeneratedCode) Parameter.arg(io.airlift.bytecode.Parameter.arg) BytecodeExpressions.add(io.airlift.bytecode.expression.BytecodeExpressions.add) Slices(io.airlift.slice.Slices) MethodDefinition(io.airlift.bytecode.MethodDefinition) PrestoException(io.prestosql.spi.PrestoException) ImmutableMap(com.google.common.collect.ImmutableMap) SqlScalarFunction(io.prestosql.metadata.SqlScalarFunction) Collections.nCopies(java.util.Collections.nCopies) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Reflection.methodHandle(io.prestosql.spi.util.Reflection.methodHandle) BytecodeExpression(io.airlift.bytecode.expression.BytecodeExpression) List(java.util.List) PRIVATE(io.airlift.bytecode.Access.PRIVATE) VarcharType.createUnboundedVarcharType(io.prestosql.spi.type.VarcharType.createUnboundedVarcharType) ArgumentProperty.valueTypeArgumentProperty(io.prestosql.spi.function.BuiltInScalarFunctionImplementation.ArgumentProperty.valueTypeArgumentProperty) NOT_SUPPORTED(io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED) TypeSignature(io.prestosql.spi.type.TypeSignature) FunctionAndTypeManager(io.prestosql.metadata.FunctionAndTypeManager) ClassDefinition(io.airlift.bytecode.ClassDefinition) IntStream(java.util.stream.IntStream) ParameterizedType.type(io.airlift.bytecode.ParameterizedType.type) Variable(io.airlift.bytecode.Variable) BuiltInScalarFunctionImplementation(io.prestosql.spi.function.BuiltInScalarFunctionImplementation) MethodHandle(java.lang.invoke.MethodHandle) Slice(io.airlift.slice.Slice) FunctionKind(io.prestosql.spi.function.FunctionKind) BytecodeExpressions.constantInt(io.airlift.bytecode.expression.BytecodeExpressions.constantInt) Parameter(io.airlift.bytecode.Parameter) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) ImmutableList(com.google.common.collect.ImmutableList) Failures.checkCondition(io.prestosql.util.Failures.checkCondition) CompilerUtils.defineClass(io.prestosql.util.CompilerUtils.defineClass) RETURN_NULL_ON_NULL(io.prestosql.spi.function.BuiltInScalarFunctionImplementation.NullConvention.RETURN_NULL_ON_NULL) Signature(io.prestosql.spi.function.Signature) FINAL(io.airlift.bytecode.Access.FINAL) STATIC(io.airlift.bytecode.Access.STATIC) BytecodeExpressions.invokeStatic(io.airlift.bytecode.expression.BytecodeExpressions.invokeStatic) VARBINARY(io.prestosql.spi.type.VarbinaryType.VARBINARY) Math.addExact(java.lang.Math.addExact) PUBLIC(io.airlift.bytecode.Access.PUBLIC) DynamicClassLoader(io.airlift.bytecode.DynamicClassLoader) Variable(io.airlift.bytecode.Variable) Scope(io.airlift.bytecode.Scope) MethodDefinition(io.airlift.bytecode.MethodDefinition) Slice(io.airlift.slice.Slice) BytecodeBlock(io.airlift.bytecode.BytecodeBlock) Parameter(io.airlift.bytecode.Parameter) ClassDefinition(io.airlift.bytecode.ClassDefinition)

Example 3 with TypeSignature

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

the class TestHivePageSourceProvider method testModifyDomainLessThanOrEqual.

@Test
public void testModifyDomainLessThanOrEqual() {
    Collection<Object> valueSet = new HashSet<>();
    valueSet.add(Long.valueOf(40));
    VariableReferenceExpression argument1 = new VariableReferenceExpression("arg_1", BIGINT);
    VariableReferenceExpression argument2 = new VariableReferenceExpression("arg_2", BIGINT);
    QualifiedObjectName objectName = new QualifiedObjectName("presto", "default", "$operator$less_than_or_equal");
    BuiltInFunctionHandle functionHandle = new BuiltInFunctionHandle(new Signature(objectName, FunctionKind.SCALAR, ImmutableList.of(), ImmutableList.of(), new TypeSignature("boolean"), ImmutableList.of(new TypeSignature("bigint"), new TypeSignature("bigint")), false));
    CallExpression filter = new CallExpression("LESS_THAN", functionHandle, BOOLEAN, ImmutableList.of(argument1, argument2));
    Domain domain = Domain.create(ValueSet.copyOf(BIGINT, valueSet), false);
    domain = modifyDomain(domain, Optional.of(filter));
    assertEquals(domain.getValues().getRanges().getSpan().getHigh().getValue(), Long.valueOf(40));
    assertEquals(domain.getValues().getRanges().getSpan().getLow().getValueBlock(), Optional.empty());
}
Also used : TypeSignature(io.prestosql.spi.type.TypeSignature) VariableReferenceExpression(io.prestosql.spi.relation.VariableReferenceExpression) TypeSignature(io.prestosql.spi.type.TypeSignature) Signature(io.prestosql.spi.function.Signature) BuiltInFunctionHandle(io.prestosql.spi.function.BuiltInFunctionHandle) HivePageSourceProvider.modifyDomain(io.prestosql.plugin.hive.HivePageSourceProvider.modifyDomain) Domain(io.prestosql.spi.predicate.Domain) CallExpression(io.prestosql.spi.relation.CallExpression) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 4 with TypeSignature

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

the class TestHivePageSourceProvider method testModifyDomainGreaterThanOrEqual.

@Test
public void testModifyDomainGreaterThanOrEqual() {
    Collection<Object> valueSet = new HashSet<>();
    valueSet.add(Long.valueOf(40));
    VariableReferenceExpression argument1 = new VariableReferenceExpression("arg_1", BIGINT);
    VariableReferenceExpression argument2 = new VariableReferenceExpression("arg_2", BIGINT);
    QualifiedObjectName objectName = new QualifiedObjectName("presto", "default", "$operator$greater_than_or_equal");
    BuiltInFunctionHandle functionHandle = new BuiltInFunctionHandle(new Signature(objectName, FunctionKind.SCALAR, ImmutableList.of(), ImmutableList.of(), new TypeSignature("boolean"), ImmutableList.of(new TypeSignature("bigint"), new TypeSignature("bigint")), false));
    CallExpression filter = new CallExpression("GREATER_THAN_OR_EQUAL", functionHandle, BOOLEAN, ImmutableList.of(argument1, argument2));
    Domain domain = Domain.create(ValueSet.copyOf(BIGINT, valueSet), false);
    domain = modifyDomain(domain, Optional.of(filter));
    assertEquals(domain.getValues().getRanges().getSpan().getHigh().getValueBlock(), Optional.empty());
    assertEquals(domain.getValues().getRanges().getSpan().getLow().getValue(), Long.valueOf(40));
}
Also used : TypeSignature(io.prestosql.spi.type.TypeSignature) VariableReferenceExpression(io.prestosql.spi.relation.VariableReferenceExpression) TypeSignature(io.prestosql.spi.type.TypeSignature) Signature(io.prestosql.spi.function.Signature) BuiltInFunctionHandle(io.prestosql.spi.function.BuiltInFunctionHandle) HivePageSourceProvider.modifyDomain(io.prestosql.plugin.hive.HivePageSourceProvider.modifyDomain) Domain(io.prestosql.spi.predicate.Domain) CallExpression(io.prestosql.spi.relation.CallExpression) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 5 with TypeSignature

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

the class TestHiveWriterFactory method testSortingPath.

@Test
public void testSortingPath() {
    setUp();
    String targetPath = "/tmp";
    String writePath = "/tmp/table";
    Optional<WriteIdInfo> writeIdInfo = Optional.of(new WriteIdInfo(1, 1, 0));
    StorageFormat storageFormat = StorageFormat.fromHiveStorageFormat(ORC);
    Storage storage = new Storage(storageFormat, "", Optional.empty(), false, ImmutableMap.of());
    Table table = new Table("schema", "table", "user", "MANAGED_TABLE", storage, ImmutableList.of(new Column("col_1", HiveType.HIVE_INT, Optional.empty())), ImmutableList.of(), ImmutableMap.of("transactional", "true"), Optional.of("original"), Optional.of("expanded"));
    HiveConfig hiveConfig = getHiveConfig();
    HivePageSinkMetadata hivePageSinkMetadata = new HivePageSinkMetadata(new SchemaTableName("schema", "table"), Optional.of(table), ImmutableMap.of());
    PageSorter pageSorter = new PagesIndexPageSorter(new PagesIndex.TestingFactory(false));
    Metadata metadata = createTestMetadataManager();
    TypeManager typeManager = new InternalTypeManager(metadata.getFunctionAndTypeManager());
    HdfsConfiguration hdfsConfiguration = new HiveHdfsConfiguration(new HdfsConfigurationInitializer(hiveConfig), ImmutableSet.of());
    HdfsEnvironment hdfsEnvironment = new HdfsEnvironment(hdfsConfiguration, hiveConfig, new NoHdfsAuthentication());
    LocationService locationService = new HiveLocationService(hdfsEnvironment);
    ConnectorSession session = newSession();
    HiveWriterFactory hiveWriterFactory = new HiveWriterFactory(getDefaultHiveFileWriterFactories(hiveConfig), "schema", "table", false, HiveACIDWriteType.DELETE, ImmutableList.of(new HiveColumnHandle("col_1", HiveType.HIVE_INT, new TypeSignature("integer", ImmutableList.of()), 0, HiveColumnHandle.ColumnType.REGULAR, Optional.empty())), ORC, ORC, ImmutableMap.of(), OptionalInt.empty(), ImmutableList.of(), new LocationHandle(targetPath, writePath, false, LocationHandle.WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY, writeIdInfo), locationService, session.getQueryId(), new HivePageSinkMetadataProvider(hivePageSinkMetadata, CachingHiveMetastore.memoizeMetastore(metastore, 1000), new HiveIdentity(session)), typeManager, hdfsEnvironment, pageSorter, hiveConfig.getWriterSortBufferSize(), hiveConfig.getMaxOpenSortFiles(), false, UTC, session, new TestingNodeManager("fake-environment"), new HiveEventClient(), new HiveSessionProperties(hiveConfig, new OrcFileWriterConfig(), new ParquetFileWriterConfig()), new HiveWriterStats(), getDefaultOrcFileWriterFactory(hiveConfig));
    HiveWriter hiveWriter = hiveWriterFactory.createWriter(ImmutableList.of(), OptionalInt.empty(), Optional.empty());
    assertEquals(((SortingFileWriter) hiveWriter.getFileWriter()).getTempFilePrefix().getName(), ".tmp-sort.bucket_00000");
}
Also used : HivePageSinkMetadataProvider(io.prestosql.plugin.hive.metastore.HivePageSinkMetadataProvider) HivePageSinkMetadata(io.prestosql.plugin.hive.metastore.HivePageSinkMetadata) Metadata(io.prestosql.metadata.Metadata) StorageFormat(io.prestosql.plugin.hive.metastore.StorageFormat) PagesIndex(io.prestosql.operator.PagesIndex) NoHdfsAuthentication(io.prestosql.plugin.hive.authentication.NoHdfsAuthentication) HiveIdentity(io.prestosql.plugin.hive.authentication.HiveIdentity) PagesIndexPageSorter(io.prestosql.PagesIndexPageSorter) TypeSignature(io.prestosql.spi.type.TypeSignature) Column(io.prestosql.plugin.hive.metastore.Column) TestingNodeManager(io.prestosql.testing.TestingNodeManager) PagesIndexPageSorter(io.prestosql.PagesIndexPageSorter) PageSorter(io.prestosql.spi.PageSorter) ConnectorSession(io.prestosql.spi.connector.ConnectorSession) TestingConnectorSession(io.prestosql.testing.TestingConnectorSession) InternalTypeManager(io.prestosql.type.InternalTypeManager) Table(io.prestosql.plugin.hive.metastore.Table) HivePageSinkMetadata(io.prestosql.plugin.hive.metastore.HivePageSinkMetadata) SchemaTableName(io.prestosql.spi.connector.SchemaTableName) Storage(io.prestosql.plugin.hive.metastore.Storage) InternalTypeManager(io.prestosql.type.InternalTypeManager) TypeManager(io.prestosql.spi.type.TypeManager) Test(org.testng.annotations.Test)

Aggregations

TypeSignature (io.prestosql.spi.type.TypeSignature)55 Signature (io.prestosql.spi.function.Signature)23 TypeSignature.parseTypeSignature (io.prestosql.spi.type.TypeSignature.parseTypeSignature)22 Test (org.testng.annotations.Test)19 ImmutableList (com.google.common.collect.ImmutableList)14 PrestoException (io.prestosql.spi.PrestoException)13 Type (io.prestosql.spi.type.Type)13 List (java.util.List)12 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)8 Slice (io.airlift.slice.Slice)7 QualifiedObjectName (io.prestosql.spi.connector.QualifiedObjectName)7 OperatorType (io.prestosql.spi.function.OperatorType)7 NamedTypeSignature (io.prestosql.spi.type.NamedTypeSignature)7 StandardTypes (io.prestosql.spi.type.StandardTypes)7 ImmutableMap (com.google.common.collect.ImmutableMap)6 ImmutableSet (com.google.common.collect.ImmutableSet)6 DecimalType (io.prestosql.spi.type.DecimalType)6 TypeSignatureParameter (io.prestosql.spi.type.TypeSignatureParameter)6 SqlScalarFunction (io.prestosql.metadata.SqlScalarFunction)4 UsedByGeneratedCode (io.prestosql.spi.annotation.UsedByGeneratedCode)4