Search in sources :

Example 1 with TranslatableTable

use of org.apache.calcite.schema.TranslatableTable in project calcite by apache.

the class SqlCreateMaterializedView method execute.

public void execute(CalcitePrepare.Context context) {
    final Pair<CalciteSchema, String> pair = SqlDdlNodes.schema(context, true, name);
    if (pair.left.plus().getTable(pair.right) != null) {
        // Materialized view exists.
        if (!ifNotExists) {
            // They did not specify IF NOT EXISTS, so give error.
            throw SqlUtil.newContextException(name.getParserPosition(), RESOURCE.tableExists(pair.right));
        }
        return;
    }
    final SqlNode q = SqlDdlNodes.renameColumns(columnList, query);
    final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
    final List<String> schemaPath = pair.left.path(null);
    final ViewTableMacro viewTableMacro = ViewTable.viewMacro(pair.left.plus(), sql, schemaPath, context.getObjectPath(), false);
    final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
    final RelDataType rowType = x.getRowType(context.getTypeFactory());
    // Table does not exist. Create it.
    final MaterializedViewTable table = new MaterializedViewTable(pair.right, RelDataTypeImpl.proto(rowType));
    pair.left.add(pair.right, table);
    SqlDdlNodes.populate(name, query, context);
    table.key = MaterializationService.instance().defineMaterialization(pair.left, null, sql, schemaPath, pair.right, true, true);
}
Also used : CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) ViewTableMacro(org.apache.calcite.schema.impl.ViewTableMacro) TranslatableTable(org.apache.calcite.schema.TranslatableTable) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlNode(org.apache.calcite.sql.SqlNode)

Example 2 with TranslatableTable

use of org.apache.calcite.schema.TranslatableTable 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 3 with TranslatableTable

use of org.apache.calcite.schema.TranslatableTable in project calcite by apache.

the class QueryableRelBuilder method toRel.

RelNode toRel(Queryable<T> queryable) {
    if (queryable instanceof QueryableDefaults.Replayable) {
        // noinspection unchecked
        ((QueryableDefaults.Replayable) queryable).replay(this);
        return rel;
    }
    if (queryable instanceof AbstractTableQueryable) {
        final AbstractTableQueryable tableQueryable = (AbstractTableQueryable) queryable;
        final QueryableTable table = tableQueryable.table;
        final CalciteSchema.TableEntry tableEntry = CalciteSchema.from(tableQueryable.schema).add(tableQueryable.tableName, tableQueryable.table);
        final RelOptTableImpl relOptTable = RelOptTableImpl.create(null, table.getRowType(translator.typeFactory), tableEntry, null);
        if (table instanceof TranslatableTable) {
            return ((TranslatableTable) table).toRel(translator, relOptTable);
        } else {
            return LogicalTableScan.create(translator.cluster, relOptTable);
        }
    }
    return translator.translate(queryable.getExpression());
}
Also used : QueryableTable(org.apache.calcite.schema.QueryableTable) CalciteSchema(org.apache.calcite.jdbc.CalciteSchema) TranslatableTable(org.apache.calcite.schema.TranslatableTable) AbstractTableQueryable(org.apache.calcite.schema.impl.AbstractTableQueryable)

Example 4 with TranslatableTable

use of org.apache.calcite.schema.TranslatableTable 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 5 with TranslatableTable

use of org.apache.calcite.schema.TranslatableTable in project calcite by apache.

the class MockCatalogReader method init2.

/**
 * Adds some extra tables to the mock catalog. These increase the time and
 * complexity of initializing the catalog (because they contain views whose
 * SQL needs to be parsed) and so are not used for all tests.
 */
public MockCatalogReader init2() {
    MockSchema salesSchema = new MockSchema("SALES");
    // Same as "EMP_20" except it uses ModifiableViewTable which populates
    // constrained columns with default values on INSERT and has a single constraint on DEPTNO.
    List<String> empModifiableViewNames = ImmutableList.of(salesSchema.getCatalogName(), salesSchema.name, "EMP_MODIFIABLEVIEW");
    TableMacro empModifiableViewMacro = MockModifiableViewRelOptTable.viewMacro(rootSchema, "select EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, SLACKER from EMPDEFAULTS" + " where DEPTNO = 20", empModifiableViewNames.subList(0, 2), ImmutableList.of(empModifiableViewNames.get(2)), true);
    TranslatableTable empModifiableView = empModifiableViewMacro.apply(ImmutableList.of());
    MockModifiableViewRelOptTable mockEmpViewTable = MockModifiableViewRelOptTable.create((MockModifiableViewRelOptTable.MockModifiableViewTable) empModifiableView, this, empModifiableViewNames.get(0), empModifiableViewNames.get(1), empModifiableViewNames.get(2), false, 20, null);
    registerTable(mockEmpViewTable);
    // Same as "EMP_MODIFIABLEVIEW" except that all columns are in the view, columns are reordered,
    // and there is an `extra` extended column.
    List<String> empModifiableViewNames2 = ImmutableList.of(salesSchema.getCatalogName(), salesSchema.name, "EMP_MODIFIABLEVIEW2");
    TableMacro empModifiableViewMacro2 = MockModifiableViewRelOptTable.viewMacro(rootSchema, "select ENAME, EMPNO, JOB, DEPTNO, SLACKER, SAL, EXTRA, HIREDATE, MGR, COMM" + " from EMPDEFAULTS extend (EXTRA boolean)" + " where DEPTNO = 20", empModifiableViewNames2.subList(0, 2), ImmutableList.of(empModifiableViewNames.get(2)), true);
    TranslatableTable empModifiableView2 = empModifiableViewMacro2.apply(ImmutableList.of());
    MockModifiableViewRelOptTable mockEmpViewTable2 = MockModifiableViewRelOptTable.create((MockModifiableViewRelOptTable.MockModifiableViewTable) empModifiableView2, this, empModifiableViewNames2.get(0), empModifiableViewNames2.get(1), empModifiableViewNames2.get(2), false, 20, null);
    registerTable(mockEmpViewTable2);
    // Same as "EMP_MODIFIABLEVIEW" except that comm is not in the view.
    List<String> empModifiableViewNames3 = ImmutableList.of(salesSchema.getCatalogName(), salesSchema.name, "EMP_MODIFIABLEVIEW3");
    TableMacro empModifiableViewMacro3 = MockModifiableViewRelOptTable.viewMacro(rootSchema, "select EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, SLACKER from EMPDEFAULTS" + " where DEPTNO = 20", empModifiableViewNames3.subList(0, 2), ImmutableList.of(empModifiableViewNames3.get(2)), true);
    TranslatableTable empModifiableView3 = empModifiableViewMacro3.apply(ImmutableList.of());
    MockModifiableViewRelOptTable mockEmpViewTable3 = MockModifiableViewRelOptTable.create((MockModifiableViewRelOptTable.MockModifiableViewTable) empModifiableView3, this, empModifiableViewNames3.get(0), empModifiableViewNames3.get(1), empModifiableViewNames3.get(2), false, 20, null);
    registerTable(mockEmpViewTable3);
    MockSchema structTypeSchema = new MockSchema("STRUCT");
    registerSchema(structTypeSchema);
    final Fixture f = new Fixture();
    final List<CompoundNameColumn> columnsExtended = Arrays.asList(new CompoundNameColumn("", "K0", f.varchar20TypeNull), new CompoundNameColumn("", "C1", f.varchar20TypeNull), new CompoundNameColumn("F0", "C0", f.intType), new CompoundNameColumn("F1", "C1", f.intTypeNull));
    final List<CompoundNameColumn> extendedColumns = new ArrayList<CompoundNameColumn>(columnsExtended);
    extendedColumns.add(new CompoundNameColumn("F2", "C2", f.varchar20Type));
    final CompoundNameColumnResolver structExtendedTableResolver = new CompoundNameColumnResolver(extendedColumns, "F0");
    final MockTable structExtendedTypeTable = MockTable.create(this, structTypeSchema, "T_EXTEND", false, 100, structExtendedTableResolver);
    for (CompoundNameColumn column : columnsExtended) {
        structExtendedTypeTable.addColumn(column.getName(), column.type);
    }
    registerTable(structExtendedTypeTable);
    return this;
}
Also used : ViewTableMacro(org.apache.calcite.schema.impl.ViewTableMacro) TableMacro(org.apache.calcite.schema.TableMacro) ArrayList(java.util.ArrayList) TranslatableTable(org.apache.calcite.schema.TranslatableTable)

Aggregations

TranslatableTable (org.apache.calcite.schema.TranslatableTable)7 CalciteSchema (org.apache.calcite.jdbc.CalciteSchema)4 RelDataType (org.apache.calcite.rel.type.RelDataType)4 ViewTableMacro (org.apache.calcite.schema.impl.ViewTableMacro)4 SqlNode (org.apache.calcite.sql.SqlNode)4 RelOptTable (org.apache.calcite.plan.RelOptTable)3 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)2 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)2 ColumnStrategy (org.apache.calcite.schema.ColumnStrategy)2 QueryableTable (org.apache.calcite.schema.QueryableTable)2 ImmutableList (com.google.common.collect.ImmutableList)1 Type (java.lang.reflect.Type)1 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 CalciteConnectionConfigImpl (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.config.CalciteConnectionConfigImpl)1 RelOptTable (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.plan.RelOptTable)1 CalciteCatalogReader (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.prepare.CalciteCatalogReader)1 RelOptTableImpl (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.prepare.RelOptTableImpl)1 SchemaPlus (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.SchemaPlus)1 Table (org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.schema.Table)1