Search in sources :

Example 11 with JavaTypeFactory

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

the class EnumerableMergeJoin method implement.

public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
    BlockBuilder builder = new BlockBuilder();
    final Result leftResult = implementor.visitChild(this, 0, (EnumerableRel) left, pref);
    final Expression leftExpression = builder.append("left", leftResult.block);
    final ParameterExpression left_ = Expressions.parameter(leftResult.physType.getJavaRowType(), "left");
    final Result rightResult = implementor.visitChild(this, 1, (EnumerableRel) right, pref);
    final Expression rightExpression = builder.append("right", rightResult.block);
    final ParameterExpression right_ = Expressions.parameter(rightResult.physType.getJavaRowType(), "right");
    final JavaTypeFactory typeFactory = implementor.getTypeFactory();
    final PhysType physType = PhysTypeImpl.of(typeFactory, getRowType(), pref.preferArray());
    final List<Expression> leftExpressions = new ArrayList<>();
    final List<Expression> rightExpressions = new ArrayList<>();
    for (Pair<Integer, Integer> pair : Pair.zip(leftKeys, rightKeys)) {
        final RelDataType keyType = typeFactory.leastRestrictive(ImmutableList.of(left.getRowType().getFieldList().get(pair.left).getType(), right.getRowType().getFieldList().get(pair.right).getType()));
        final Type keyClass = typeFactory.getJavaClass(keyType);
        leftExpressions.add(Types.castIfNecessary(keyClass, leftResult.physType.fieldReference(left_, pair.left)));
        rightExpressions.add(Types.castIfNecessary(keyClass, rightResult.physType.fieldReference(right_, pair.right)));
    }
    final PhysType leftKeyPhysType = leftResult.physType.project(leftKeys, JavaRowFormat.LIST);
    final PhysType rightKeyPhysType = rightResult.physType.project(rightKeys, JavaRowFormat.LIST);
    return implementor.result(physType, builder.append(Expressions.call(BuiltInMethod.MERGE_JOIN.method, Expressions.list(leftExpression, rightExpression, Expressions.lambda(leftKeyPhysType.record(leftExpressions), left_), Expressions.lambda(rightKeyPhysType.record(rightExpressions), right_), EnumUtils.joinSelector(joinType, physType, ImmutableList.of(leftResult.physType, rightResult.physType)), Expressions.constant(joinType.generatesNullsOnLeft()), Expressions.constant(joinType.generatesNullsOnRight())))).toBlock());
}
Also used : RelDataType(org.apache.calcite.rel.type.RelDataType) Type(java.lang.reflect.Type) JoinRelType(org.apache.calcite.rel.core.JoinRelType) Expression(org.apache.calcite.linq4j.tree.Expression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) BlockBuilder(org.apache.calcite.linq4j.tree.BlockBuilder)

Example 12 with JavaTypeFactory

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

the class SqlCreateTable method execute.

public void execute(CalcitePrepare.Context context) {
    final Pair<CalciteSchema, String> pair = SqlDdlNodes.schema(context, true, name);
    final JavaTypeFactory typeFactory = new JavaTypeFactoryImpl();
    final RelDataType queryRowType;
    if (query != null) {
        // A bit of a hack: pretend it's a view, to get its row type
        final String sql = query.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
        final ViewTableMacro viewTableMacro = ViewTable.viewMacro(pair.left.plus(), sql, pair.left.path(null), context.getObjectPath(), false);
        final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
        queryRowType = x.getRowType(typeFactory);
        if (columnList != null && queryRowType.getFieldCount() != columnList.size()) {
            throw SqlUtil.newContextException(columnList.getParserPosition(), RESOURCE.columnCountMismatch());
        }
    } else {
        queryRowType = null;
    }
    final List<SqlNode> columnList;
    if (this.columnList != null) {
        columnList = this.columnList.getList();
    } else {
        if (queryRowType == null) {
            // a list of column names and types, "CREATE TABLE t (INT c)".
            throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.createTableRequiresColumnList());
        }
        columnList = new ArrayList<>();
        for (String name : queryRowType.getFieldNames()) {
            columnList.add(new SqlIdentifier(name, SqlParserPos.ZERO));
        }
    }
    final ImmutableList.Builder<ColumnDef> b = ImmutableList.builder();
    final RelDataTypeFactory.Builder builder = typeFactory.builder();
    final RelDataTypeFactory.Builder storedBuilder = typeFactory.builder();
    for (Ord<SqlNode> c : Ord.zip(columnList)) {
        if (c.e instanceof SqlColumnDeclaration) {
            final SqlColumnDeclaration d = (SqlColumnDeclaration) c.e;
            final RelDataType type = d.dataType.deriveType(typeFactory, true);
            builder.add(d.name.getSimple(), type);
            if (d.strategy != ColumnStrategy.VIRTUAL) {
                storedBuilder.add(d.name.getSimple(), type);
            }
            b.add(ColumnDef.of(d.expression, type, d.strategy));
        } else if (c.e instanceof SqlIdentifier) {
            final SqlIdentifier id = (SqlIdentifier) c.e;
            if (queryRowType == null) {
                throw SqlUtil.newContextException(id.getParserPosition(), RESOURCE.createTableRequiresColumnTypes(id.getSimple()));
            }
            final RelDataTypeField f = queryRowType.getFieldList().get(c.i);
            final ColumnStrategy strategy = f.getType().isNullable() ? ColumnStrategy.NULLABLE : ColumnStrategy.NOT_NULLABLE;
            b.add(ColumnDef.of(c.e, f.getType(), strategy));
            builder.add(id.getSimple(), f.getType());
            storedBuilder.add(id.getSimple(), f.getType());
        } else {
            throw new AssertionError(c.e.getClass());
        }
    }
    final RelDataType rowType = builder.build();
    final RelDataType storedRowType = storedBuilder.build();
    final List<ColumnDef> columns = b.build();
    final InitializerExpressionFactory ief = new NullInitializerExpressionFactory() {

        @Override
        public ColumnStrategy generationStrategy(RelOptTable table, int iColumn) {
            return columns.get(iColumn).strategy;
        }

        @Override
        public RexNode newColumnDefaultValue(RelOptTable table, int iColumn, InitializerContext context) {
            final ColumnDef c = columns.get(iColumn);
            if (c.expr != null) {
                return context.convertExpression(c.expr);
            }
            return super.newColumnDefaultValue(table, iColumn, context);
        }
    };
    if (pair.left.plus().getTable(pair.right) != null) {
        // Table exists.
        if (!ifNotExists) {
            // They did not specify IF NOT EXISTS, so give error.
            throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.tableExists(pair.right));
        }
        return;
    }
    // Table does not exist. Create it.
    pair.left.add(pair.right, new MutableArrayTable(pair.right, RelDataTypeImpl.proto(storedRowType), RelDataTypeImpl.proto(rowType), ief));
    if (query != null) {
        SqlDdlNodes.populate(name, query, context);
    }
}
Also used : NullInitializerExpressionFactory(org.apache.calcite.sql2rel.NullInitializerExpressionFactory) NullInitializerExpressionFactory(org.apache.calcite.sql2rel.NullInitializerExpressionFactory) InitializerExpressionFactory(org.apache.calcite.sql2rel.InitializerExpressionFactory) ImmutableList(com.google.common.collect.ImmutableList) ViewTableMacro(org.apache.calcite.schema.impl.ViewTableMacro) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) JavaTypeFactoryImpl(org.apache.calcite.jdbc.JavaTypeFactoryImpl) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) TranslatableTable(org.apache.calcite.schema.TranslatableTable) SqlNode(org.apache.calcite.sql.SqlNode) ColumnStrategy(org.apache.calcite.schema.ColumnStrategy) InitializerContext(org.apache.calcite.sql2rel.InitializerContext) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) RelOptTable(org.apache.calcite.plan.RelOptTable)

Example 13 with JavaTypeFactory

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

the class CalcitePrepareImpl method prepare_.

<T> CalciteSignature<T> prepare_(Context context, Query<T> query, Type elementType, long maxRowCount) {
    if (SIMPLE_SQLS.contains(query.sql)) {
        return simplePrepare(context, query.sql);
    }
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    CalciteCatalogReader catalogReader = new CalciteCatalogReader(context.getRootSchema(), context.getDefaultSchemaPath(), typeFactory, context.config());
    final List<Function1<Context, RelOptPlanner>> plannerFactories = createPlannerFactories();
    if (plannerFactories.isEmpty()) {
        throw new AssertionError("no planner factories");
    }
    RuntimeException exception = Util.FoundOne.NULL;
    for (Function1<Context, RelOptPlanner> plannerFactory : plannerFactories) {
        final RelOptPlanner planner = plannerFactory.apply(context);
        if (planner == null) {
            throw new AssertionError("factory returned null planner");
        }
        try {
            return prepare2_(context, query, elementType, maxRowCount, catalogReader, planner);
        } catch (RelOptPlanner.CannotPlanException e) {
            exception = e;
        }
    }
    throw exception;
}
Also used : DataContext(org.apache.calcite.DataContext) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) Function1(org.apache.calcite.linq4j.function.Function1) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner)

Example 14 with JavaTypeFactory

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

the class CalcitePrepareImpl method parse_.

/**
 * Shared implementation for {@link #parse}, {@link #convert} and
 * {@link #analyzeView}.
 */
private ParseResult parse_(Context context, String sql, boolean convert, boolean analyze, boolean fail) {
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    CalciteCatalogReader catalogReader = new CalciteCatalogReader(context.getRootSchema(), context.getDefaultSchemaPath(), typeFactory, context.config());
    SqlParser parser = createParser(sql);
    SqlNode sqlNode;
    try {
        sqlNode = parser.parseStmt();
    } catch (SqlParseException e) {
        throw new RuntimeException("parse failed", e);
    }
    final SqlValidator validator = createSqlValidator(context, catalogReader);
    SqlNode sqlNode1 = validator.validate(sqlNode);
    if (convert) {
        return convert_(context, sql, analyze, fail, catalogReader, validator, sqlNode1);
    }
    return new ParseResult(this, validator, sql, sqlNode1, validator.getValidatedNodeType(sqlNode1));
}
Also used : SqlParseException(org.apache.calcite.sql.parser.SqlParseException) SqlValidator(org.apache.calcite.sql.validate.SqlValidator) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) SqlParser(org.apache.calcite.sql.parser.SqlParser) SqlNode(org.apache.calcite.sql.SqlNode)

Example 15 with JavaTypeFactory

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

the class CalcitePrepareImpl method createSqlValidator.

private SqlValidator createSqlValidator(Context context, CalciteCatalogReader catalogReader) {
    final SqlOperatorTable opTab0 = context.config().fun(SqlOperatorTable.class, SqlStdOperatorTable.instance());
    final SqlOperatorTable opTab = ChainedSqlOperatorTable.of(opTab0, catalogReader);
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    final SqlConformance conformance = context.config().conformance();
    return new CalciteSqlValidator(opTab, catalogReader, typeFactory, conformance);
}
Also used : ChainedSqlOperatorTable(org.apache.calcite.sql.util.ChainedSqlOperatorTable) SqlOperatorTable(org.apache.calcite.sql.SqlOperatorTable) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) SqlConformance(org.apache.calcite.sql.validate.SqlConformance)

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