Search in sources :

Example 41 with RelOptTable

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable in project calcite by apache.

the class EnumerableTableScanRule method convert.

@Override
public RelNode convert(RelNode rel) {
    LogicalTableScan scan = (LogicalTableScan) rel;
    final RelOptTable relOptTable = scan.getTable();
    final Table table = relOptTable.unwrap(Table.class);
    if (!EnumerableTableScan.canHandle(table)) {
        return null;
    }
    final Expression expression = relOptTable.getExpression(Object.class);
    if (expression == null) {
        return null;
    }
    return EnumerableTableScan.create(scan.getCluster(), relOptTable);
}
Also used : Table(org.apache.calcite.schema.Table) RelOptTable(org.apache.calcite.plan.RelOptTable) Expression(org.apache.calcite.linq4j.tree.Expression) RelOptTable(org.apache.calcite.plan.RelOptTable) LogicalTableScan(org.apache.calcite.rel.logical.LogicalTableScan)

Example 42 with RelOptTable

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable in project calcite by apache.

the class TableScanNode method createQueryable.

private static TableScanNode createQueryable(Compiler compiler, TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects, QueryableTable queryableTable) {
    final DataContext root = compiler.getDataContext();
    final RelOptTable relOptTable = rel.getTable();
    final Type elementType = queryableTable.getElementType();
    SchemaPlus schema = root.getRootSchema();
    for (String name : Util.skipLast(relOptTable.getQualifiedName())) {
        schema = schema.getSubSchema(name);
    }
    final Enumerable<Row> rowEnumerable;
    if (elementType instanceof Class) {
        // noinspection unchecked
        final Queryable<Object> queryable = Schemas.queryable(root, (Class) elementType, relOptTable.getQualifiedName());
        ImmutableList.Builder<Field> fieldBuilder = ImmutableList.builder();
        Class type = (Class) elementType;
        for (Field field : type.getFields()) {
            if (Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) {
                fieldBuilder.add(field);
            }
        }
        final List<Field> fields = fieldBuilder.build();
        rowEnumerable = queryable.select(new Function1<Object, Row>() {

            public Row apply(Object o) {
                final Object[] values = new Object[fields.size()];
                for (int i = 0; i < fields.size(); i++) {
                    Field field = fields.get(i);
                    try {
                        values[i] = field.get(o);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
                return new Row(values);
            }
        });
    } else {
        rowEnumerable = Schemas.queryable(root, Row.class, relOptTable.getQualifiedName());
    }
    return createEnumerable(compiler, rel, rowEnumerable, null, filters, projects);
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) SchemaPlus(org.apache.calcite.schema.SchemaPlus) Function1(org.apache.calcite.linq4j.function.Function1) Field(java.lang.reflect.Field) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) DataContext(org.apache.calcite.DataContext) RelDataType(org.apache.calcite.rel.type.RelDataType) Type(java.lang.reflect.Type) RelOptTable(org.apache.calcite.plan.RelOptTable)

Example 43 with RelOptTable

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable in project calcite by apache.

the class CalcitePrepareImpl method analyze_.

private AnalyzeViewResult analyze_(SqlValidator validator, String sql, SqlNode sqlNode, RelRoot root, boolean fail) {
    final RexBuilder rexBuilder = root.rel.getCluster().getRexBuilder();
    RelNode rel = root.rel;
    final RelNode viewRel = rel;
    Project project;
    if (rel instanceof Project) {
        project = (Project) rel;
        rel = project.getInput();
    } else {
        project = null;
    }
    Filter filter;
    if (rel instanceof Filter) {
        filter = (Filter) rel;
        rel = filter.getInput();
    } else {
        filter = null;
    }
    TableScan scan;
    if (rel instanceof TableScan) {
        scan = (TableScan) rel;
    } else {
        scan = null;
    }
    if (scan == null) {
        if (fail) {
            throw validator.newValidationError(sqlNode, RESOURCE.modifiableViewMustBeBasedOnSingleTable());
        }
        return new AnalyzeViewResult(this, validator, sql, sqlNode, validator.getValidatedNodeType(sqlNode), root, null, null, null, null, false);
    }
    final RelOptTable targetRelTable = scan.getTable();
    final RelDataType targetRowType = targetRelTable.getRowType();
    final Table table = targetRelTable.unwrap(Table.class);
    final List<String> tablePath = targetRelTable.getQualifiedName();
    assert table != null;
    List<Integer> columnMapping;
    final Map<Integer, RexNode> projectMap = new HashMap<>();
    if (project == null) {
        columnMapping = ImmutableIntList.range(0, targetRowType.getFieldCount());
    } else {
        columnMapping = new ArrayList<>();
        for (Ord<RexNode> node : Ord.zip(project.getProjects())) {
            if (node.e instanceof RexInputRef) {
                RexInputRef rexInputRef = (RexInputRef) node.e;
                int index = rexInputRef.getIndex();
                if (projectMap.get(index) != null) {
                    if (fail) {
                        throw validator.newValidationError(sqlNode, RESOURCE.moreThanOneMappedColumn(targetRowType.getFieldList().get(index).getName(), Util.last(tablePath)));
                    }
                    return new AnalyzeViewResult(this, validator, sql, sqlNode, validator.getValidatedNodeType(sqlNode), root, null, null, null, null, false);
                }
                projectMap.put(index, rexBuilder.makeInputRef(viewRel, node.i));
                columnMapping.add(index);
            } else {
                columnMapping.add(-1);
            }
        }
    }
    final RexNode constraint;
    if (filter != null) {
        constraint = filter.getCondition();
    } else {
        constraint = rexBuilder.makeLiteral(true);
    }
    final List<RexNode> filters = new ArrayList<>();
    // If we put a constraint in projectMap above, then filters will not be empty despite
    // being a modifiable view.
    final List<RexNode> filters2 = new ArrayList<>();
    boolean retry = false;
    RelOptUtil.inferViewPredicates(projectMap, filters, constraint);
    if (fail && !filters.isEmpty()) {
        final Map<Integer, RexNode> projectMap2 = new HashMap<>();
        RelOptUtil.inferViewPredicates(projectMap2, filters2, constraint);
        if (!filters2.isEmpty()) {
            throw validator.newValidationError(sqlNode, RESOURCE.modifiableViewMustHaveOnlyEqualityPredicates());
        }
        retry = true;
    }
    // Check that all columns that are not projected have a constant value
    for (RelDataTypeField field : targetRowType.getFieldList()) {
        final int x = columnMapping.indexOf(field.getIndex());
        if (x >= 0) {
            assert Util.skip(columnMapping, x + 1).indexOf(field.getIndex()) < 0 : "column projected more than once; should have checked above";
            // target column is projected
            continue;
        }
        if (projectMap.get(field.getIndex()) != null) {
            // constant expression
            continue;
        }
        if (field.getType().isNullable()) {
            // don't need expression for nullable columns; NULL suffices
            continue;
        }
        if (fail) {
            throw validator.newValidationError(sqlNode, RESOURCE.noValueSuppliedForViewColumn(field.getName(), Util.last(tablePath)));
        }
        return new AnalyzeViewResult(this, validator, sql, sqlNode, validator.getValidatedNodeType(sqlNode), root, null, null, null, null, false);
    }
    final boolean modifiable = filters.isEmpty() || retry && filters2.isEmpty();
    return new AnalyzeViewResult(this, validator, sql, sqlNode, validator.getValidatedNodeType(sqlNode), root, modifiable ? table : null, ImmutableList.copyOf(tablePath), constraint, ImmutableIntList.copyOf(columnMapping), modifiable);
}
Also used : TableScan(org.apache.calcite.rel.core.TableScan) Table(org.apache.calcite.schema.Table) StandardConvertletTable(org.apache.calcite.sql2rel.StandardConvertletTable) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) RelOptTable(org.apache.calcite.plan.RelOptTable) ChainedSqlOperatorTable(org.apache.calcite.sql.util.ChainedSqlOperatorTable) SqlOperatorTable(org.apache.calcite.sql.SqlOperatorTable) SqlRexConvertletTable(org.apache.calcite.sql2rel.SqlRexConvertletTable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) Project(org.apache.calcite.rel.core.Project) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) RelNode(org.apache.calcite.rel.RelNode) Filter(org.apache.calcite.rel.core.Filter) RexBuilder(org.apache.calcite.rex.RexBuilder) RexInputRef(org.apache.calcite.rex.RexInputRef) RelOptTable(org.apache.calcite.plan.RelOptTable) RexNode(org.apache.calcite.rex.RexNode)

Example 44 with RelOptTable

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable in project calcite by apache.

the class RelOptTableImpl method toRel.

public RelNode toRel(ToRelContext context) {
    // RelOptTable by replacing with immutable RelRecordType using the same field list.
    if (this.getRowType().isDynamicStruct()) {
        final RelDataType staticRowType = new RelRecordType(getRowType().getFieldList());
        final RelOptTable relOptTable = this.copy(staticRowType);
        return relOptTable.toRel(context);
    }
    // If there are any virtual columns, create a copy of this table without
    // those virtual columns.
    final List<ColumnStrategy> strategies = getColumnStrategies();
    if (strategies.contains(ColumnStrategy.VIRTUAL)) {
        final RelDataTypeFactory.Builder b = context.getCluster().getTypeFactory().builder();
        for (RelDataTypeField field : rowType.getFieldList()) {
            if (strategies.get(field.getIndex()) != ColumnStrategy.VIRTUAL) {
                b.add(field.getName(), field.getType());
            }
        }
        final RelOptTable relOptTable = new RelOptTableImpl(this.schema, b.build(), this.names, this.table, this.expressionFunction, this.rowCount) {

            @Override
            public <T> T unwrap(Class<T> clazz) {
                if (clazz.isAssignableFrom(InitializerExpressionFactory.class)) {
                    return clazz.cast(NullInitializerExpressionFactory.INSTANCE);
                }
                return super.unwrap(clazz);
            }
        };
        return relOptTable.toRel(context);
    }
    if (table instanceof TranslatableTable) {
        return ((TranslatableTable) table).toRel(context, this);
    }
    final RelOptCluster cluster = context.getCluster();
    if (Hook.ENABLE_BINDABLE.get(false)) {
        return LogicalTableScan.create(cluster, this);
    }
    if (CalcitePrepareImpl.ENABLE_ENUMERABLE && table instanceof QueryableTable) {
        return EnumerableTableScan.create(cluster, this);
    }
    if (table instanceof ScannableTable || table instanceof FilterableTable || table instanceof ProjectableFilterableTable) {
        return LogicalTableScan.create(cluster, this);
    }
    if (CalcitePrepareImpl.ENABLE_ENUMERABLE) {
        return EnumerableTableScan.create(cluster, this);
    }
    throw new AssertionError();
}
Also used : ColumnStrategy(org.apache.calcite.schema.ColumnStrategy) RelOptCluster(org.apache.calcite.plan.RelOptCluster) ProjectableFilterableTable(org.apache.calcite.schema.ProjectableFilterableTable) FilterableTable(org.apache.calcite.schema.FilterableTable) RelDataType(org.apache.calcite.rel.type.RelDataType) RelRecordType(org.apache.calcite.rel.type.RelRecordType) QueryableTable(org.apache.calcite.schema.QueryableTable) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) TranslatableTable(org.apache.calcite.schema.TranslatableTable) ProjectableFilterableTable(org.apache.calcite.schema.ProjectableFilterableTable) RelOptTable(org.apache.calcite.plan.RelOptTable) ScannableTable(org.apache.calcite.schema.ScannableTable)

Example 45 with RelOptTable

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable in project calcite by apache.

the class RelMetadataTest method testCollation.

/**
 * Unit test for
 * {@link org.apache.calcite.rel.metadata.RelMdCollation#project}
 * and other helper functions for deducing collations.
 */
@Test
public void testCollation() {
    final Project rel = (Project) convertSql("select * from emp, dept");
    final Join join = (Join) rel.getInput();
    final RelOptTable empTable = join.getInput(0).getTable();
    final RelOptTable deptTable = join.getInput(1).getTable();
    Frameworks.withPlanner(new Frameworks.PlannerAction<Void>() {

        public Void apply(RelOptCluster cluster, RelOptSchema relOptSchema, SchemaPlus rootSchema) {
            checkCollation(cluster, empTable, deptTable);
            return null;
        }
    });
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) Project(org.apache.calcite.rel.core.Project) LogicalProject(org.apache.calcite.rel.logical.LogicalProject) RelOptSchema(org.apache.calcite.plan.RelOptSchema) Frameworks(org.apache.calcite.tools.Frameworks) SchemaPlus(org.apache.calcite.schema.SchemaPlus) SemiJoin(org.apache.calcite.rel.core.SemiJoin) Join(org.apache.calcite.rel.core.Join) LogicalJoin(org.apache.calcite.rel.logical.LogicalJoin) EnumerableMergeJoin(org.apache.calcite.adapter.enumerable.EnumerableMergeJoin) RelOptTable(org.apache.calcite.plan.RelOptTable) Test(org.junit.Test)

Aggregations

RelOptTable (org.apache.calcite.plan.RelOptTable)63 RelDataType (org.apache.calcite.rel.type.RelDataType)20 RexNode (org.apache.calcite.rex.RexNode)18 RelNode (org.apache.calcite.rel.RelNode)17 Table (org.apache.calcite.schema.Table)15 ArrayList (java.util.ArrayList)14 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)12 RelTraitSet (org.apache.calcite.plan.RelTraitSet)10 SqlNode (org.apache.calcite.sql.SqlNode)10 RelOptCluster (org.apache.calcite.plan.RelOptCluster)9 ImmutableList (com.google.common.collect.ImmutableList)8 NlsString (org.apache.calcite.util.NlsString)8 List (java.util.List)6 LogicalJoin (org.apache.calcite.rel.logical.LogicalJoin)6 SchemaPlus (org.apache.calcite.schema.SchemaPlus)6 RelOptSchema (org.apache.calcite.plan.RelOptSchema)5 Project (org.apache.calcite.rel.core.Project)5 LogicalProject (org.apache.calcite.rel.logical.LogicalProject)5 ProjectableFilterableTable (org.apache.calcite.schema.ProjectableFilterableTable)5 Test (org.junit.Test)5