Search in sources :

Example 6 with SqlIdentifier

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

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(Match e) {
    final RelNode input = e.getInput();
    final Result x = visitChild(0, input);
    final Context context = matchRecognizeContext(x.qualifiedContext());
    SqlNode tableRef = x.asQueryOrValues();
    final List<SqlNode> partitionSqlList = new ArrayList<>();
    if (e.getPartitionKeys() != null) {
        for (RexNode rex : e.getPartitionKeys()) {
            SqlNode sqlNode = context.toSql(null, rex);
            partitionSqlList.add(sqlNode);
        }
    }
    final SqlNodeList partitionList = new SqlNodeList(partitionSqlList, POS);
    final List<SqlNode> orderBySqlList = new ArrayList<>();
    if (e.getOrderKeys() != null) {
        for (RelFieldCollation fc : e.getOrderKeys().getFieldCollations()) {
            if (fc.nullDirection != RelFieldCollation.NullDirection.UNSPECIFIED) {
                boolean first = fc.nullDirection == RelFieldCollation.NullDirection.FIRST;
                SqlNode nullDirectionNode = dialect.emulateNullDirection(context.field(fc.getFieldIndex()), first, fc.direction.isDescending());
                if (nullDirectionNode != null) {
                    orderBySqlList.add(nullDirectionNode);
                    fc = new RelFieldCollation(fc.getFieldIndex(), fc.getDirection(), RelFieldCollation.NullDirection.UNSPECIFIED);
                }
            }
            orderBySqlList.add(context.toSql(fc));
        }
    }
    final SqlNodeList orderByList = new SqlNodeList(orderBySqlList, SqlParserPos.ZERO);
    final SqlLiteral rowsPerMatch = e.isAllRows() ? SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS.symbol(POS) : SqlMatchRecognize.RowsPerMatchOption.ONE_ROW.symbol(POS);
    final SqlNode after;
    if (e.getAfter() instanceof RexLiteral) {
        SqlMatchRecognize.AfterOption value = (SqlMatchRecognize.AfterOption) ((RexLiteral) e.getAfter()).getValue2();
        after = SqlLiteral.createSymbol(value, POS);
    } else {
        RexCall call = (RexCall) e.getAfter();
        String operand = RexLiteral.stringValue(call.getOperands().get(0));
        after = call.getOperator().createCall(POS, new SqlIdentifier(operand, POS));
    }
    RexNode rexPattern = e.getPattern();
    final SqlNode pattern = context.toSql(null, rexPattern);
    final SqlLiteral strictStart = SqlLiteral.createBoolean(e.isStrictStart(), POS);
    final SqlLiteral strictEnd = SqlLiteral.createBoolean(e.isStrictEnd(), POS);
    RexLiteral rexInterval = (RexLiteral) e.getInterval();
    SqlIntervalLiteral interval = null;
    if (rexInterval != null) {
        interval = (SqlIntervalLiteral) context.toSql(null, rexInterval);
    }
    final SqlNodeList subsetList = new SqlNodeList(POS);
    for (Map.Entry<String, SortedSet<String>> entry : e.getSubsets().entrySet()) {
        SqlNode left = new SqlIdentifier(entry.getKey(), POS);
        List<SqlNode> rhl = Lists.newArrayList();
        for (String right : entry.getValue()) {
            rhl.add(new SqlIdentifier(right, POS));
        }
        subsetList.add(SqlStdOperatorTable.EQUALS.createCall(POS, left, new SqlNodeList(rhl, POS)));
    }
    final SqlNodeList measureList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getMeasures().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        measureList.add(as(sqlNode, alias));
    }
    final SqlNodeList patternDefList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getPatternDefinitions().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        patternDefList.add(as(sqlNode, alias));
    }
    final SqlNode matchRecognize = new SqlMatchRecognize(POS, tableRef, pattern, strictStart, strictEnd, patternDefList, measureList, after, subsetList, rowsPerMatch, partitionList, orderByList, interval);
    return result(matchRecognize, Expressions.list(Clause.FROM), e, null);
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) SqlIntervalLiteral(org.apache.calcite.sql.SqlIntervalLiteral) ArrayList(java.util.ArrayList) SqlMatchRecognize(org.apache.calcite.sql.SqlMatchRecognize) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SortedSet(java.util.SortedSet) RexCall(org.apache.calcite.rex.RexCall) RelNode(org.apache.calcite.rel.RelNode) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlLiteral(org.apache.calcite.sql.SqlLiteral) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) SqlNode(org.apache.calcite.sql.SqlNode) RexNode(org.apache.calcite.rex.RexNode)

Example 7 with SqlIdentifier

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

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(TableModify modify) {
    final Map<String, RelDataType> pairs = ImmutableMap.of();
    final Context context = aliasContext(pairs, false);
    // Target Table Name
    final SqlIdentifier sqlTargetTable = new SqlIdentifier(modify.getTable().getQualifiedName(), POS);
    switch(modify.getOperation()) {
        case INSERT:
            {
                // Convert the input to a SELECT query or keep as VALUES. Not all
                // dialects support naked VALUES, but all support VALUES inside INSERT.
                final SqlNode sqlSource = visitChild(0, modify.getInput()).asQueryOrValues();
                final SqlInsert sqlInsert = new SqlInsert(POS, SqlNodeList.EMPTY, sqlTargetTable, sqlSource, identifierList(modify.getInput().getRowType().getFieldNames()));
                return result(sqlInsert, ImmutableList.<Clause>of(), modify, null);
            }
        case UPDATE:
            {
                final Result input = visitChild(0, modify.getInput());
                final SqlUpdate sqlUpdate = new SqlUpdate(POS, sqlTargetTable, identifierList(modify.getUpdateColumnList()), exprList(context, modify.getSourceExpressionList()), ((SqlSelect) input.node).getWhere(), input.asSelect(), null);
                return result(sqlUpdate, input.clauses, modify, null);
            }
        case DELETE:
            {
                final Result input = visitChild(0, modify.getInput());
                final SqlDelete sqlDelete = new SqlDelete(POS, sqlTargetTable, input.asSelect().getWhere(), input.asSelect(), null);
                return result(sqlDelete, input.clauses, modify, null);
            }
        case MERGE:
        default:
            throw new AssertionError("not implemented: " + modify);
    }
}
Also used : RelDataType(org.apache.calcite.rel.type.RelDataType) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlInsert(org.apache.calcite.sql.SqlInsert) SqlUpdate(org.apache.calcite.sql.SqlUpdate) SqlSelect(org.apache.calcite.sql.SqlSelect) SqlDelete(org.apache.calcite.sql.SqlDelete) SqlNode(org.apache.calcite.sql.SqlNode)

Example 8 with SqlIdentifier

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

the class SqlValidatorImpl method expandSelectItem.

/**
 * If <code>selectItem</code> is "*" or "TABLE.*", expands it and returns
 * true; otherwise writes the unexpanded item.
 *
 * @param selectItem        Select-list item
 * @param select            Containing select clause
 * @param selectItems       List that expanded items are written to
 * @param aliases           Set of aliases
 * @param types             List of data types in alias order
 * @param includeSystemVars If true include system vars in lists
 * @return Whether the node was expanded
 */
private boolean expandSelectItem(final SqlNode selectItem, SqlSelect select, RelDataType targetType, List<SqlNode> selectItems, Set<String> aliases, List<Map.Entry<String, RelDataType>> types, final boolean includeSystemVars) {
    final SelectScope scope = (SelectScope) getWhereScope(select);
    if (expandStar(selectItems, aliases, types, includeSystemVars, scope, selectItem)) {
        return true;
    }
    // Expand the select item: fully-qualify columns, and convert
    // parentheses-free functions such as LOCALTIME into explicit function
    // calls.
    SqlNode expanded = expand(selectItem, scope);
    final String alias = deriveAlias(selectItem, aliases.size());
    // If expansion has altered the natural alias, supply an explicit 'AS'.
    final SqlValidatorScope selectScope = getSelectScope(select);
    if (expanded != selectItem) {
        String newAlias = deriveAlias(expanded, aliases.size());
        if (!newAlias.equals(alias)) {
            expanded = SqlStdOperatorTable.AS.createCall(selectItem.getParserPosition(), expanded, new SqlIdentifier(alias, SqlParserPos.ZERO));
            deriveTypeImpl(selectScope, expanded);
        }
    }
    selectItems.add(expanded);
    aliases.add(alias);
    inferUnknownTypes(targetType, scope, expanded);
    final RelDataType type = deriveType(selectScope, expanded);
    setValidatedNodeType(expanded, type);
    types.add(Pair.of(alias, type));
    return false;
}
Also used : RelDataType(org.apache.calcite.rel.type.RelDataType) BitString(org.apache.calcite.util.BitString) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SqlNode(org.apache.calcite.sql.SqlNode)

Example 9 with SqlIdentifier

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

the class SqlValidatorImpl method lookupFromHints.

private void lookupFromHints(SqlNode node, SqlValidatorScope scope, SqlParserPos pos, Collection<SqlMoniker> hintList) {
    final SqlValidatorNamespace ns = getNamespace(node);
    if (ns.isWrapperFor(IdentifierNamespace.class)) {
        IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class);
        final SqlIdentifier id = idNs.getId();
        for (int i = 0; i < id.names.size(); i++) {
            if (pos.toString().equals(id.getComponent(i).getParserPosition().toString())) {
                final List<SqlMoniker> objNames = new ArrayList<>();
                SqlValidatorUtil.getSchemaObjectMonikers(getCatalogReader(), id.names.subList(0, i + 1), objNames);
                for (SqlMoniker objName : objNames) {
                    if (objName.getType() != SqlMonikerType.FUNCTION) {
                        hintList.add(objName);
                    }
                }
                return;
            }
        }
    }
    switch(node.getKind()) {
        case JOIN:
            lookupJoinHints((SqlJoin) node, scope, pos, hintList);
            break;
        default:
            lookupSelectHints(ns, pos, hintList);
            break;
    }
}
Also used : ArrayList(java.util.ArrayList) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier)

Example 10 with SqlIdentifier

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

the class SqlValidatorImpl method createTargetRowType.

/**
 * Derives a row-type for INSERT and UPDATE operations.
 *
 * @param table            Target table for INSERT/UPDATE
 * @param targetColumnList List of target columns, or null if not specified
 * @param append           Whether to append fields to those in <code>
 *                         baseRowType</code>
 * @return Rowtype
 */
protected RelDataType createTargetRowType(SqlValidatorTable table, SqlNodeList targetColumnList, boolean append) {
    RelDataType baseRowType = table.getRowType();
    if (targetColumnList == null) {
        return baseRowType;
    }
    List<RelDataTypeField> targetFields = baseRowType.getFieldList();
    final List<Map.Entry<String, RelDataType>> types = new ArrayList<>();
    if (append) {
        for (RelDataTypeField targetField : targetFields) {
            types.add(Pair.of(SqlUtil.deriveAliasFromOrdinal(types.size()), targetField.getType()));
        }
    }
    final Set<Integer> assignedFields = new HashSet<>();
    final RelOptTable relOptTable = table instanceof RelOptTable ? ((RelOptTable) table) : null;
    for (SqlNode node : targetColumnList) {
        SqlIdentifier id = (SqlIdentifier) node;
        RelDataTypeField targetField = SqlValidatorUtil.getTargetField(baseRowType, typeFactory, id, catalogReader, relOptTable);
        if (targetField == null) {
            throw newValidationError(id, RESOURCE.unknownTargetColumn(id.toString()));
        }
        if (!assignedFields.add(targetField.getIndex())) {
            throw newValidationError(id, RESOURCE.duplicateTargetColumn(targetField.getName()));
        }
        types.add(targetField);
    }
    return typeFactory.createStructType(types);
}
Also used : BigInteger(java.math.BigInteger) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) RelOptTable(org.apache.calcite.plan.RelOptTable) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) SqlNode(org.apache.calcite.sql.SqlNode)

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