Search in sources :

Example 16 with JavaTypeFactory

use of org.apache.calcite.adapter.java.JavaTypeFactory in project calcite by apache.

the class CalcitePrepareImpl method prepare2_.

<T> CalciteSignature<T> prepare2_(Context context, Query<T> query, Type elementType, long maxRowCount, CalciteCatalogReader catalogReader, RelOptPlanner planner) {
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    final EnumerableRel.Prefer prefer;
    if (elementType == Object[].class) {
        prefer = EnumerableRel.Prefer.ARRAY;
    } else {
        prefer = EnumerableRel.Prefer.CUSTOM;
    }
    final Convention resultConvention = enableBindable ? BindableConvention.INSTANCE : EnumerableConvention.INSTANCE;
    final CalcitePreparingStmt preparingStmt = new CalcitePreparingStmt(this, context, catalogReader, typeFactory, context.getRootSchema(), prefer, planner, resultConvention, createConvertletTable());
    final RelDataType x;
    final Prepare.PreparedResult preparedResult;
    final Meta.StatementType statementType;
    if (query.sql != null) {
        final CalciteConnectionConfig config = context.config();
        final SqlParser.ConfigBuilder parserConfig = createParserConfig().setQuotedCasing(config.quotedCasing()).setUnquotedCasing(config.unquotedCasing()).setQuoting(config.quoting()).setConformance(config.conformance()).setCaseSensitive(config.caseSensitive());
        final SqlParserImplFactory parserFactory = config.parserFactory(SqlParserImplFactory.class, null);
        if (parserFactory != null) {
            parserConfig.setParserFactory(parserFactory);
        }
        SqlParser parser = createParser(query.sql, parserConfig);
        SqlNode sqlNode;
        try {
            sqlNode = parser.parseStmt();
            statementType = getStatementType(sqlNode.getKind());
        } catch (SqlParseException e) {
            throw new RuntimeException("parse failed: " + e.getMessage(), e);
        }
        Hook.PARSE_TREE.run(new Object[] { query.sql, sqlNode });
        if (sqlNode.getKind().belongsTo(SqlKind.DDL)) {
            executeDdl(context, sqlNode);
            return new CalciteSignature<>(query.sql, ImmutableList.<AvaticaParameter>of(), ImmutableMap.<String, Object>of(), null, ImmutableList.<ColumnMetaData>of(), Meta.CursorFactory.OBJECT, null, ImmutableList.<RelCollation>of(), -1, null, Meta.StatementType.OTHER_DDL);
        }
        final SqlValidator validator = createSqlValidator(context, catalogReader);
        validator.setIdentifierExpansion(true);
        validator.setDefaultNullCollation(config.defaultNullCollation());
        preparedResult = preparingStmt.prepareSql(sqlNode, Object.class, validator, true);
        switch(sqlNode.getKind()) {
            case INSERT:
            case DELETE:
            case UPDATE:
            case EXPLAIN:
                // FIXME: getValidatedNodeType is wrong for DML
                x = RelOptUtil.createDmlRowType(sqlNode.getKind(), typeFactory);
                break;
            default:
                x = validator.getValidatedNodeType(sqlNode);
        }
    } else if (query.queryable != null) {
        x = context.getTypeFactory().createType(elementType);
        preparedResult = preparingStmt.prepareQueryable(query.queryable, x);
        statementType = getStatementType(preparedResult);
    } else {
        assert query.rel != null;
        x = query.rel.getRowType();
        preparedResult = preparingStmt.prepareRel(query.rel);
        statementType = getStatementType(preparedResult);
    }
    final List<AvaticaParameter> parameters = new ArrayList<>();
    final RelDataType parameterRowType = preparedResult.getParameterRowType();
    for (RelDataTypeField field : parameterRowType.getFieldList()) {
        RelDataType type = field.getType();
        parameters.add(new AvaticaParameter(false, getPrecision(type), getScale(type), getTypeOrdinal(type), getTypeName(type), getClassName(type), field.getName()));
    }
    RelDataType jdbcType = makeStruct(typeFactory, x);
    final List<List<String>> originList = preparedResult.getFieldOrigins();
    final List<ColumnMetaData> columns = getColumnMetaDataList(typeFactory, x, jdbcType, originList);
    Class resultClazz = null;
    if (preparedResult instanceof Typed) {
        resultClazz = (Class) ((Typed) preparedResult).getElementType();
    }
    final Meta.CursorFactory cursorFactory = preparingStmt.resultConvention == BindableConvention.INSTANCE ? Meta.CursorFactory.ARRAY : Meta.CursorFactory.deduce(columns, resultClazz);
    // noinspection unchecked
    final Bindable<T> bindable = preparedResult.getBindable(cursorFactory);
    return new CalciteSignature<>(query.sql, parameters, preparingStmt.internalParameters, jdbcType, columns, cursorFactory, context.getRootSchema(), preparedResult instanceof Prepare.PreparedResultImpl ? ((Prepare.PreparedResultImpl) preparedResult).collations : ImmutableList.<RelCollation>of(), maxRowCount, bindable, statementType);
}
Also used : Meta(org.apache.calcite.avatica.Meta) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) AvaticaParameter(org.apache.calcite.avatica.AvaticaParameter) Typed(org.apache.calcite.runtime.Typed) SqlValidator(org.apache.calcite.sql.validate.SqlValidator) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) CalcitePrepare(org.apache.calcite.jdbc.CalcitePrepare) SqlParserImplFactory(org.apache.calcite.sql.parser.SqlParserImplFactory) ArrayList(java.util.ArrayList) ImmutableIntList(org.apache.calcite.util.ImmutableIntList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ColumnMetaData(org.apache.calcite.avatica.ColumnMetaData) EnumerableRel(org.apache.calcite.adapter.enumerable.EnumerableRel) SqlNode(org.apache.calcite.sql.SqlNode) SqlParseException(org.apache.calcite.sql.parser.SqlParseException) CalciteConnectionConfig(org.apache.calcite.config.CalciteConnectionConfig) SqlParser(org.apache.calcite.sql.parser.SqlParser) BindableConvention(org.apache.calcite.interpreter.BindableConvention) Convention(org.apache.calcite.plan.Convention) EnumerableConvention(org.apache.calcite.adapter.enumerable.EnumerableConvention) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) RelCollation(org.apache.calcite.rel.RelCollation)

Example 17 with JavaTypeFactory

use of org.apache.calcite.adapter.java.JavaTypeFactory in project calcite by apache.

the class CalcitePrepareImpl method perform.

/**
 * Executes a prepare action.
 */
public <R> R perform(CalciteServerStatement statement, Frameworks.PrepareAction<R> action) {
    final CalcitePrepare.Context prepareContext = statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    final CalciteSchema schema = action.getConfig().getDefaultSchema() != null ? CalciteSchema.from(action.getConfig().getDefaultSchema()) : prepareContext.getRootSchema();
    CalciteCatalogReader catalogReader = new CalciteCatalogReader(schema.root(), schema.path(null), typeFactory, prepareContext.config());
    final RexBuilder rexBuilder = new RexBuilder(typeFactory);
    final RelOptPlanner planner = createPlanner(prepareContext, action.getConfig().getContext(), action.getConfig().getCostFactory());
    final RelOptCluster cluster = createCluster(planner, rexBuilder);
    return action.apply(cluster, catalogReader, prepareContext.getRootSchema().plus(), statement);
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) CalcitePrepare(org.apache.calcite.jdbc.CalcitePrepare) RexBuilder(org.apache.calcite.rex.RexBuilder) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner)

Example 18 with JavaTypeFactory

use of org.apache.calcite.adapter.java.JavaTypeFactory in project calcite by apache.

the class PlannerImpl method ready.

private void ready() {
    switch(state) {
        case STATE_0_CLOSED:
            reset();
    }
    ensure(State.STATE_1_RESET);
    Frameworks.withPlanner(new Frameworks.PlannerAction<Void>() {

        public Void apply(RelOptCluster cluster, RelOptSchema relOptSchema, SchemaPlus rootSchema) {
            // use our own defaultSchema
            Util.discard(rootSchema);
            typeFactory = (JavaTypeFactory) cluster.getTypeFactory();
            planner = cluster.getPlanner();
            planner.setExecutor(executor);
            return null;
        }
    }, config);
    state = State.STATE_2_READY;
    // then, register the trait def specified in traitDefs.
    if (this.traitDefs != null) {
        planner.clearRelTraitDefs();
        for (RelTraitDef def : this.traitDefs) {
            planner.addRelTraitDef(def);
        }
    }
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) RelOptSchema(org.apache.calcite.plan.RelOptSchema) RelTraitDef(org.apache.calcite.plan.RelTraitDef) Frameworks(org.apache.calcite.tools.Frameworks) SchemaPlus(org.apache.calcite.schema.SchemaPlus) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory)

Example 19 with JavaTypeFactory

use of org.apache.calcite.adapter.java.JavaTypeFactory in project calcite by apache.

the class TraitPropagationTest method run.

// Created so that we can control when the TraitDefs are defined (e.g.
// before the cluster is created).
private static RelNode run(PropAction action, RuleSet rules) throws Exception {
    FrameworkConfig config = Frameworks.newConfigBuilder().ruleSets(rules).build();
    final Properties info = new Properties();
    final Connection connection = DriverManager.getConnection("jdbc:calcite:", info);
    final CalciteServerStatement statement = connection.createStatement().unwrap(CalciteServerStatement.class);
    final CalcitePrepare.Context prepareContext = statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    CalciteCatalogReader catalogReader = new CalciteCatalogReader(prepareContext.getRootSchema(), prepareContext.getDefaultSchemaPath(), typeFactory, prepareContext.config());
    final RexBuilder rexBuilder = new RexBuilder(typeFactory);
    final RelOptPlanner planner = new VolcanoPlanner(config.getCostFactory(), config.getContext());
    // set up rules before we generate cluster
    planner.clearRelTraitDefs();
    planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
    planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
    planner.clear();
    for (RelOptRule r : rules) {
        planner.addRule(r);
    }
    final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
    return action.apply(cluster, catalogReader, prepareContext.getRootSchema().plus());
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) Connection(java.sql.Connection) CalcitePrepare(org.apache.calcite.jdbc.CalcitePrepare) Properties(java.util.Properties) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) RelOptRule(org.apache.calcite.plan.RelOptRule) CalciteCatalogReader(org.apache.calcite.prepare.CalciteCatalogReader) CalciteServerStatement(org.apache.calcite.server.CalciteServerStatement) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) RexBuilder(org.apache.calcite.rex.RexBuilder) FrameworkConfig(org.apache.calcite.tools.FrameworkConfig)

Example 20 with JavaTypeFactory

use of org.apache.calcite.adapter.java.JavaTypeFactory in project calcite by apache.

the class LookupOperatorOverloadsTest method test.

@Test
public void test() throws SQLException {
    final String schemaName = "MySchema";
    final String funcName = "MyFUNC";
    final String anotherName = "AnotherFunc";
    try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
        CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
        SchemaPlus rootSchema = calciteConnection.getRootSchema();
        SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
        final TableFunction table = TableFunctionImpl.create(Smalls.MAZE_METHOD);
        schema.add(funcName, table);
        schema.add(anotherName, table);
        final TableFunction table2 = TableFunctionImpl.create(Smalls.MAZE3_METHOD);
        schema.add(funcName, table2);
        final CalciteServerStatement statement = connection.createStatement().unwrap(CalciteServerStatement.class);
        final CalcitePrepare.Context prepareContext = statement.createPrepareContext();
        final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
        CalciteCatalogReader reader = new CalciteCatalogReader(prepareContext.getRootSchema(), ImmutableList.<String>of(), typeFactory, prepareContext.config());
        final List<SqlOperator> operatorList = new ArrayList<>();
        SqlIdentifier myFuncIdentifier = new SqlIdentifier(Lists.newArrayList(schemaName, funcName), null, SqlParserPos.ZERO, null);
        reader.lookupOperatorOverloads(myFuncIdentifier, SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION, operatorList);
        checkFunctionType(2, funcName, operatorList);
        operatorList.clear();
        reader.lookupOperatorOverloads(myFuncIdentifier, SqlFunctionCategory.USER_DEFINED_FUNCTION, SqlSyntax.FUNCTION, operatorList);
        checkFunctionType(0, null, operatorList);
        operatorList.clear();
        SqlIdentifier anotherFuncIdentifier = new SqlIdentifier(Lists.newArrayList(schemaName, anotherName), null, SqlParserPos.ZERO, null);
        reader.lookupOperatorOverloads(anotherFuncIdentifier, SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION, operatorList);
        checkFunctionType(1, anotherName, operatorList);
    }
}
Also used : SqlOperator(org.apache.calcite.sql.SqlOperator) Connection(java.sql.Connection) CalciteConnection(org.apache.calcite.jdbc.CalciteConnection) SchemaPlus(org.apache.calcite.schema.SchemaPlus) ArrayList(java.util.ArrayList) CalcitePrepare(org.apache.calcite.jdbc.CalcitePrepare) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) AbstractSchema(org.apache.calcite.schema.impl.AbstractSchema) CalciteServerStatement(org.apache.calcite.server.CalciteServerStatement) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) TableFunction(org.apache.calcite.schema.TableFunction) SqlUserDefinedTableFunction(org.apache.calcite.sql.validate.SqlUserDefinedTableFunction) CalciteConnection(org.apache.calcite.jdbc.CalciteConnection) Test(org.junit.Test)

Aggregations

JavaTypeFactory (org.apache.calcite.adapter.java.JavaTypeFactory)43 JavaTypeFactoryImpl (org.apache.calcite.jdbc.JavaTypeFactoryImpl)18 ArrayList (java.util.ArrayList)15 SchemaPlus (org.apache.calcite.schema.SchemaPlus)15 StreamableTable (org.apache.calcite.schema.StreamableTable)12 Table (org.apache.calcite.schema.Table)12 RelDataType (org.apache.calcite.rel.type.RelDataType)10 Expression (org.apache.calcite.linq4j.tree.Expression)9 BlockBuilder (org.apache.calcite.linq4j.tree.BlockBuilder)8 SqlNode (org.apache.calcite.sql.SqlNode)7 Type (java.lang.reflect.Type)6 ParameterExpression (org.apache.calcite.linq4j.tree.ParameterExpression)6 FrameworkConfig (org.apache.calcite.tools.FrameworkConfig)6 CompilerUtil (org.apache.storm.sql.compiler.CompilerUtil)6 CalciteCatalogReader (org.apache.calcite.prepare.CalciteCatalogReader)5 RelNode (org.apache.calcite.rel.RelNode)5 SqlOperatorTable (org.apache.calcite.sql.SqlOperatorTable)5 ChainedSqlOperatorTable (org.apache.calcite.sql.util.ChainedSqlOperatorTable)5 ImmutableList (com.google.common.collect.ImmutableList)4 CalcitePrepare (org.apache.calcite.jdbc.CalcitePrepare)4