Search in sources :

Example 21 with SqlIdentifier

use of org.apache.calcite.sql.SqlIdentifier in project calcite by apache.

the class SqlValidatorUtil method analyzeGroupExpr.

/**
 * Analyzes a component of a tuple in a GROUPING SETS clause.
 */
private static ImmutableBitSet analyzeGroupExpr(SqlValidatorScope scope, GroupAnalyzer groupAnalyzer, SqlNode groupExpr) {
    final SqlNode expandedGroupExpr = scope.getValidator().expand(groupExpr, scope);
    switch(expandedGroupExpr.getKind()) {
        case ROW:
            return ImmutableBitSet.union(analyzeGroupTuple(scope, groupAnalyzer, ((SqlCall) expandedGroupExpr).getOperandList()));
        case OTHER:
            if (expandedGroupExpr instanceof SqlNodeList && ((SqlNodeList) expandedGroupExpr).size() == 0) {
                return ImmutableBitSet.of();
            }
    }
    final int ref = lookupGroupExpr(groupAnalyzer, groupExpr);
    if (expandedGroupExpr instanceof SqlIdentifier) {
        // SQL 2003 does not allow expressions of column references
        SqlIdentifier expr = (SqlIdentifier) expandedGroupExpr;
        // column references should be fully qualified.
        assert expr.names.size() == 2;
        String originalRelName = expr.names.get(0);
        String originalFieldName = expr.names.get(1);
        final SqlNameMatcher nameMatcher = scope.getValidator().getCatalogReader().nameMatcher();
        final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl();
        scope.resolve(ImmutableList.of(originalRelName), nameMatcher, false, resolved);
        assert resolved.count() == 1;
        final SqlValidatorScope.Resolve resolve = resolved.only();
        final RelDataType rowType = resolve.rowType();
        final int childNamespaceIndex = resolve.path.steps().get(0).i;
        int namespaceOffset = 0;
        if (childNamespaceIndex > 0) {
            // If not the first child, need to figure out the width of
            // output types from all the preceding namespaces
            final SqlValidatorScope ancestorScope = resolve.scope;
            assert ancestorScope instanceof ListScope;
            List<SqlValidatorNamespace> children = ((ListScope) ancestorScope).getChildren();
            for (int j = 0; j < childNamespaceIndex; j++) {
                namespaceOffset += children.get(j).getRowType().getFieldCount();
            }
        }
        RelDataTypeField field = nameMatcher.field(rowType, originalFieldName);
        int origPos = namespaceOffset + field.getIndex();
        groupAnalyzer.groupExprProjection.put(origPos, ref);
    }
    return ImmutableBitSet.of(ref);
}
Also used : SqlCall(org.apache.calcite.sql.SqlCall) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlNode(org.apache.calcite.sql.SqlNode)

Example 22 with SqlIdentifier

use of org.apache.calcite.sql.SqlIdentifier in project calcite by apache.

the class SqlValidatorUtil method addAlias.

/**
 * Converts an expression "expr" into "expr AS alias".
 */
public static SqlNode addAlias(SqlNode expr, String alias) {
    final SqlParserPos pos = expr.getParserPosition();
    final SqlIdentifier id = new SqlIdentifier(alias, pos);
    return SqlStdOperatorTable.AS.createCall(pos, expr, id);
}
Also used : SqlParserPos(org.apache.calcite.sql.parser.SqlParserPos) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier)

Example 23 with SqlIdentifier

use of org.apache.calcite.sql.SqlIdentifier in project calcite by apache.

the class TableNamespace method checkExtendedColumnTypes.

/**
 * Ensures that extended columns that have the same name as a base column also
 * have the same data-type.
 */
private void checkExtendedColumnTypes(SqlNodeList extendList) {
    final List<RelDataTypeField> extendedFields = SqlValidatorUtil.getExtendedColumns(validator.getTypeFactory(), table, extendList);
    final List<RelDataTypeField> baseFields = getBaseRowType().getFieldList();
    final Map<String, Integer> nameToIndex = SqlValidatorUtil.mapNameToIndex(baseFields);
    for (final RelDataTypeField extendedField : extendedFields) {
        final String extFieldName = extendedField.getName();
        if (nameToIndex.containsKey(extFieldName)) {
            final Integer baseIndex = nameToIndex.get(extFieldName);
            final RelDataType baseType = baseFields.get(baseIndex).getType();
            final RelDataType extType = extendedField.getType();
            if (!extType.equals(baseType)) {
                // Get the extended column node that failed validation.
                final Predicate<SqlNode> nameMatches = new PredicateImpl<SqlNode>() {

                    @Override
                    public boolean test(SqlNode sqlNode) {
                        if (sqlNode instanceof SqlIdentifier) {
                            final SqlIdentifier identifier = (SqlIdentifier) sqlNode;
                            return Util.last(identifier.names).equals(extendedField.getName());
                        }
                        return false;
                    }
                };
                final SqlNode extColNode = Iterables.find(extendList.getList(), nameMatches);
                throw validator.getValidationErrorFunction().apply(extColNode, RESOURCE.typeNotAssignable(baseFields.get(baseIndex).getName(), baseType.getFullTypeString(), extendedField.getName(), extType.getFullTypeString()));
            }
        }
    }
}
Also used : RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) PredicateImpl(org.apache.calcite.runtime.PredicateImpl) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode)

Example 24 with SqlIdentifier

use of org.apache.calcite.sql.SqlIdentifier in project calcite by apache.

the class SelectScope method lookupWindow.

public SqlWindow lookupWindow(String name) {
    final SqlNodeList windowList = select.getWindowList();
    for (int i = 0; i < windowList.size(); i++) {
        SqlWindow window = (SqlWindow) windowList.get(i);
        final SqlIdentifier declId = window.getDeclName();
        assert declId.isSimple();
        if (declId.names.get(0).equals(name)) {
            return window;
        }
    }
    // if not in the select scope, then check window scope
    if (windowParent != null) {
        return windowParent.lookupWindow(name);
    } else {
        return null;
    }
}
Also used : SqlWindow(org.apache.calcite.sql.SqlWindow) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier)

Example 25 with SqlIdentifier

use of org.apache.calcite.sql.SqlIdentifier 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)

Aggregations

SqlIdentifier (org.apache.calcite.sql.SqlIdentifier)131 SqlNode (org.apache.calcite.sql.SqlNode)84 RelDataType (org.apache.calcite.rel.type.RelDataType)46 SqlNodeList (org.apache.calcite.sql.SqlNodeList)43 ArrayList (java.util.ArrayList)41 SqlCall (org.apache.calcite.sql.SqlCall)32 BitString (org.apache.calcite.util.BitString)28 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)21 SqlSelect (org.apache.calcite.sql.SqlSelect)21 SqlParserPos (org.apache.calcite.sql.parser.SqlParserPos)12 SchemaPlus (org.apache.calcite.schema.SchemaPlus)11 SqlOperator (org.apache.calcite.sql.SqlOperator)11 NlsString (org.apache.calcite.util.NlsString)11 List (java.util.List)9 Map (java.util.Map)9 RelOptTable (org.apache.calcite.plan.RelOptTable)9 RexNode (org.apache.calcite.rex.RexNode)9 AbstractSchema (org.apache.drill.exec.store.AbstractSchema)9 ImmutableList (com.google.common.collect.ImmutableList)8 RelNode (org.apache.calcite.rel.RelNode)7