Java Code Examples for org.apache.calcite.sql.SqlNodeList#size()

The following examples show how to use org.apache.calcite.sql.SqlNodeList#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SelectScope.java    From calcite with Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  SqlMonotonicity monotonicity = expr.getMonotonicity(this);
  if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
    return monotonicity;
  }

  // TODO: compare fully qualified names
  final SqlNodeList orderList = getOrderList();
  if (orderList.size() > 0) {
    SqlNode order0 = orderList.get(0);
    monotonicity = SqlMonotonicity.INCREASING;
    if ((order0 instanceof SqlCall)
        && (((SqlCall) order0).getOperator()
        == SqlStdOperatorTable.DESC)) {
      monotonicity = monotonicity.reverse();
      order0 = ((SqlCall) order0).operand(0);
    }
    if (expr.equalsDeep(order0, Litmus.IGNORE)) {
      return monotonicity;
    }
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 2
Source File: SelectScope.java    From Bats with Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  SqlMonotonicity monotonicity = expr.getMonotonicity(this);
  if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
    return monotonicity;
  }

  // TODO: compare fully qualified names
  final SqlNodeList orderList = getOrderList();
  if (orderList.size() > 0) {
    SqlNode order0 = orderList.get(0);
    monotonicity = SqlMonotonicity.INCREASING;
    if ((order0 instanceof SqlCall)
        && (((SqlCall) order0).getOperator()
        == SqlStdOperatorTable.DESC)) {
      monotonicity = monotonicity.reverse();
      order0 = ((SqlCall) order0).operand(0);
    }
    if (expr.equalsDeep(order0, Litmus.IGNORE)) {
      return monotonicity;
    }
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 3
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
public SqlNodeList expandStar(
	SqlNodeList selectList,
	SqlSelect select,
	boolean includeSystemVars) {
	final List<SqlNode> list = new ArrayList<>();
	final List<Map.Entry<String, RelDataType>> types = new ArrayList<>();
	for (int i = 0; i < selectList.size(); i++) {
		final SqlNode selectItem = selectList.get(i);
		final RelDataType originalType = getValidatedNodeTypeIfKnown(selectItem);
		expandSelectItem(
			selectItem,
			select,
			Util.first(originalType, unknownType),
			list,
			catalogReader.nameMatcher().createSet(),
			types,
			includeSystemVars);
	}
	getRawSelectScope(select).setExpandedSelectList(list);
	return new SqlNodeList(list, SqlParserPos.ZERO);
}
 
Example 4
Source File: SideParser.java    From alchemy with Apache License 2.0 6 votes vote down vote up
private static SqlNodeList reduce(SqlNodeList sqlNodes, String alias) {
    if (sqlNodes == null) {
        return sqlNodes;
    }
    SqlNodeList nodes = sqlNodes.clone(new SqlParserPos(0, 0));
    List<SqlNode> newNodes = new ArrayList<>(nodes.size());
    Iterator<SqlNode> sqlNodeIterable = nodes.iterator();
    while (sqlNodeIterable.hasNext()) {
        SqlNode sqlNode = sqlNodeIterable.next();
        sqlNode = reduce(sqlNode, alias);
        if (sqlNode != null) {
            newNodes.add(sqlNode);
        }
    }
    if (newNodes.size() > 0) {
        return new SqlNodeList(newNodes, nodes.getParserPosition());
    } else {
        return null;
    }
}
 
Example 5
Source File: SqlAlterHiveTableChangeColumn.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
	writer.keyword("ALTER TABLE");
	tableIdentifier.unparse(writer, leftPrec, rightPrec);
	SqlNodeList partitionSpec = getPartitionSpec();
	if (partitionSpec != null && partitionSpec.size() > 0) {
		writer.keyword("PARTITION");
		partitionSpec.unparse(writer, getOperator().getLeftPrec(), getOperator().getRightPrec());
	}
	writer.keyword("CHANGE COLUMN");
	getOldName().unparse(writer, leftPrec, rightPrec);
	origNewColumn.unparse(writer, leftPrec, rightPrec);
	if (isFirst()) {
		writer.keyword("FIRST");
	}
	if (getAfter() != null) {
		writer.keyword("AFTER");
		getAfter().unparse(writer, leftPrec, rightPrec);
	}
	if (cascade) {
		writer.keyword("CASCADE");
	} else {
		writer.keyword("RESTRICT");
	}
}
 
Example 6
Source File: HiveDDLUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public SqlNode visit(SqlNodeList nodeList) {
	for (int i = 0; i < nodeList.size(); i++) {
		SqlNode unescaped = nodeList.get(i).accept(this);
		nodeList.set(i, unescaped);
	}
	return nodeList;
}
 
Example 7
Source File: UnparseUtil.java    From streamline with Apache License 2.0 5 votes vote down vote up
UnparseUtil nodeList(SqlNodeList l) {
  writer.keyword("(");
  if (l.size() > 0) {
    l.get(0).unparse(writer, leftPrec, rightPrec);
    for (int i = 1; i < l.size(); ++i) {
      writer.keyword(",");
      l.get(i).unparse(writer, leftPrec, rightPrec);
    }
  }
  writer.keyword(")");
  return this;
}
 
Example 8
Source File: SqlAlterHiveTableAddReplaceColumn.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
	writer.keyword("ALTER TABLE");
	tableIdentifier.unparse(writer, leftPrec, rightPrec);
	SqlNodeList partitionSpec = getPartitionSpec();
	if (partitionSpec != null && partitionSpec.size() > 0) {
		writer.keyword("PARTITION");
		partitionSpec.unparse(writer, getOperator().getLeftPrec(), getOperator().getRightPrec());
	}
	if (isReplace()) {
		writer.keyword("REPLACE");
	} else {
		writer.keyword("ADD");
	}
	writer.keyword("COLUMNS");
	SqlWriter.Frame frame = writer.startList(SqlWriter.FrameTypeEnum.create("sds"), "(", ")");
	for (SqlNode column : origColumns) {
		printIndent(writer);
		column.unparse(writer, leftPrec, rightPrec);
	}
	writer.newlineAndIndent();
	writer.endList(frame);
	if (cascade) {
		writer.keyword("CASCADE");
	} else {
		writer.keyword("RESTRICT");
	}
}
 
Example 9
Source File: SqlAlterTable.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
	writer.keyword("ALTER TABLE");
	tableIdentifier.unparse(writer, leftPrec, rightPrec);
	SqlNodeList partitionSpec = getPartitionSpec();
	if (partitionSpec != null && partitionSpec.size() > 0) {
		writer.keyword("PARTITION");
		partitionSpec.unparse(writer, getOperator().getLeftPrec(), getOperator().getRightPrec());
	}
}
 
Example 10
Source File: SqlHandlerUtil.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static void unparseSqlNodeList(SqlWriter writer, int leftPrec, int rightPrec, SqlNodeList fieldList) {
  writer.keyword("(");
  fieldList.get(0).unparse(writer, leftPrec, rightPrec);
  for (int i = 1; i<fieldList.size(); i++) {
    writer.keyword(",");
    fieldList.get(i).unparse(writer, leftPrec, rightPrec);
  }
  writer.keyword(")");
}
 
Example 11
Source File: DataAdditionCmdHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to create map of key, value pairs, the value is a Java type object.
 * @param args
 * @return
 */
@VisibleForTesting
public void createStorageOptionsMap(final SqlNodeList args) {
  if (args == null || args.size() == 0) {
    return;
  }

  final ImmutableMap.Builder<String, Object> storageOptions = ImmutableMap.builder();
  for (SqlNode operand : args) {
    if (operand.getKind() != SqlKind.ARGUMENT_ASSIGNMENT) {
      throw UserException.unsupportedError()
        .message("Unsupported argument type. Only assignment arguments (param => value) are supported.")
        .build(logger);
    }
    final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();

    final String name = ((SqlIdentifier) operandList.get(1)).getSimple();
    SqlNode literal = operandList.get(0);
    if (!(literal instanceof SqlLiteral)) {
      throw UserException.unsupportedError()
        .message("Only literals are accepted for storage option values")
        .build(logger);
    }

    Object value = ((SqlLiteral)literal).getValue();
    if (value instanceof NlsString) {
      value = ((NlsString)value).getValue();
    }
    storageOptions.put(name, value);
  }

  this.storageOptionsMap = storageOptions.build();
}
 
Example 12
Source File: UnparseUtil.java    From AthenaX with Apache License 2.0 5 votes vote down vote up
UnparseUtil nodeList(SqlNodeList l) {
  writer.keyword("(");
  if (l.size() > 0) {
    l.get(0).unparse(writer, leftPrec, rightPrec);
    for (int i = 1; i < l.size(); ++i) {
      writer.keyword(",");
      l.get(i).unparse(writer, leftPrec, rightPrec);
    }
  }
  writer.keyword(")");
  return this;
}
 
Example 13
Source File: SqlCreateForeignSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static List<Pair<SqlIdentifier, SqlNode>> options(
    final SqlNodeList optionList) {
  return new AbstractList<Pair<SqlIdentifier, SqlNode>>() {
    public Pair<SqlIdentifier, SqlNode> get(int index) {
      return Pair.of((SqlIdentifier) optionList.get(index * 2),
          optionList.get(index * 2 + 1));
    }

    public int size() {
      return optionList.size() / 2;
    }
  };
}
 
Example 14
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 15
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 16
Source File: SqlAlterHiveTableSerDe.java    From flink with Apache License 2.0 5 votes vote down vote up
private static SqlNodeList appendPrefix(SqlNodeList propList) {
	if (propList != null) {
		for (int i = 0; i < propList.size(); i++) {
			SqlTableOption tableOption = (SqlTableOption) propList.get(i);
			if (!tableOption.getKeyString().equals(ALTER_TABLE_OP)) {
				String key = HiveTableRowFormat.SERDE_INFO_PROP_PREFIX + tableOption.getKeyString();
				tableOption = HiveDDLUtils.toTableOption(key, tableOption.getValue(), tableOption.getParserPosition());
				propList.set(i, tableOption);
			}
		}
	}
	return propList;
}
 
Example 17
Source File: SqlHandlerUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static void unparseSqlNodeList(SqlWriter writer, int leftPrec, int rightPrec, SqlNodeList fieldList) {
    writer.keyword("(");
    fieldList.get(0).unparse(writer, leftPrec, rightPrec);
    for (int i = 1; i < fieldList.size(); i++) {
        writer.keyword(",");
        fieldList.get(i).unparse(writer, leftPrec, rightPrec);
    }
    writer.keyword(")");
}
 
Example 18
Source File: PushDownUtil.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public SqlNode visit(SqlNodeList nodeList) {
    for (int i = 0; i < nodeList.size(); i++) {
        SqlNode node = nodeList.get(i);
        if (node instanceof SqlWithItem) {
            SqlWithItem item = (SqlWithItem) node;
            item.query.accept(this);
        }
    }
    return null;
}
 
Example 19
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 *
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.
 *
 * <p>When you have called
 * {@link Builder#setSelect(SqlNodeList)},
 * {@link Builder#setWhere(SqlNode)} etc. call
 * {@link Builder#result(SqlNode, Collection, RelNode, Map)}
 * to fix the new query.
 *
 * @param rel     Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
  final Clause maxClause = maxClause();
  boolean needNew = false;
  // If old and new clause are equal and belong to below set,
  // then new SELECT wrap is not required
  Set<Clause> nonWrapSet = ImmutableSet.of(Clause.SELECT);
  for (Clause clause : clauses) {
    if (maxClause.ordinal() > clause.ordinal()
      || (maxClause == clause && !nonWrapSet.contains(clause))) {
      needNew = true;
    }
  }
  if (rel instanceof LogicalAggregate
    && !dialect.supportsNestedAggregations()
    && hasNestedAggregations((LogicalAggregate) rel)) {
    needNew = true;
  }

  SqlSelect select;
  Expressions.FluentList<Clause> clauseList = Expressions.list();
  if (needNew) {
    select = subSelect();
  } else {
    select = asSelect();
    clauseList.addAll(this.clauses);
  }
  clauseList.appendAll(clauses);
  Context newContext;
  final SqlNodeList selectList = select.getSelectList();
  if (selectList != null) {
    newContext = new Context(selectList.size()) {
      @Override
      public SqlNode field(int ordinal) {
        final SqlNode selectItem = selectList.get(ordinal);
        switch (selectItem.getKind()) {
          case AS:
            return ((SqlCall) selectItem).operand(0);
        }
        return selectItem;
      }
    };
  } else {
    boolean qualified =
      !dialect.hasImplicitTableAlias() || aliases.size() > 1;
    // basically, we did a subSelect() since needNew is set and neededAlias is not null
    // now, we need to make sure that we need to update the alias context.
    // if our aliases map has a single element:  <neededAlias, rowType>,
    // then we don't need to rewrite the alias but otherwise, it should be updated.
    if (needNew
      && neededAlias != null
      && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {
      final Map<String, RelDataType> newAliases =
        ImmutableMap.of(neededAlias, rel.getInput(0).getRowType());
      newContext = aliasContext(newAliases, qualified);
    } else {
      newContext = aliasContext(aliases, qualified);
    }
  }
  return new Builder(rel, clauseList, select, newContext,
    needNew ? null : aliases);
}
 
Example 20
Source File: SqlImplementor.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Once you have a Result of implementing a child relational expression,
 * call this method to create a Builder to implement the current relational
 * expression by adding additional clauses to the SQL query.
 *
 * <p>You need to declare which clauses you intend to add. If the clauses
 * are "later", you can add to the same query. For example, "GROUP BY" comes
 * after "WHERE". But if they are the same or earlier, this method will
 * start a new SELECT that wraps the previous result.
 *
 * <p>When you have called
 * {@link Builder#setSelect(SqlNodeList)},
 * {@link Builder#setWhere(SqlNode)} etc. call
 * {@link Builder#result(SqlNode, Collection, RelNode, Map)}
 * to fix the new query.
 *
 * @param rel Relational expression being implemented
 * @param clauses Clauses that will be generated to implement current
 *                relational expression
 * @return A builder
 */
public Builder builder(RelNode rel, Clause... clauses) {
    final Clause maxClause = maxClause();
    boolean needNew = false;
    // If old and new clause are equal and belong to below set,
    // then new SELECT wrap is not required
    Set<Clause> nonWrapSet = ImmutableSet.of(Clause.SELECT);
    for (Clause clause : clauses) {
        if (maxClause.ordinal() > clause.ordinal() || (maxClause == clause && !nonWrapSet.contains(clause))) {
            needNew = true;
        }
    }
    if (rel instanceof LogicalAggregate && !dialect.supportsNestedAggregations()
            && hasNestedAggregations((LogicalAggregate) rel)) {
        needNew = true;
    }

    SqlSelect select;
    FluentListUtils.FluentList<Clause> clauseList = FluentListUtils.list();
    if (needNew) {
        select = subSelect();
    } else {
        select = asSelect();
        clauseList.addAll(this.clauses);
    }
    clauseList.appendAll(clauses);
    Context newContext;
    final SqlNodeList selectList = select.getSelectList();
    if (selectList != null) {
        newContext = new Context(dialect, selectList.size()) {
            @Override
            public SqlNode field(int ordinal) {
                final SqlNode selectItem = selectList.get(ordinal);
                switch (selectItem.getKind()) {
                case AS:
                    return ((SqlCall) selectItem).operand(0);
                }
                return selectItem;
            }
        };
    } else {
        boolean qualified = !dialect.hasImplicitTableAlias() || aliases.size() > 1;
        // basically, we did a subSelect() since needNew is set and neededAlias is not null
        // now, we need to make sure that we need to update the alias context.
        // if our aliases map has a single element: <neededAlias, rowType>,
        // then we don't need to rewrite the alias but otherwise, it should be updated.
        if (needNew && neededAlias != null && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {
            final Map<String, RelDataType> newAliases = ImmutableMap.of(neededAlias,
                    rel.getInput(0).getRowType());
            newContext = aliasContext(newAliases, qualified);
        } else {
            newContext = aliasContext(aliases, qualified);
        }
    }
    return new Builder(rel, clauseList, select, newContext, needNew ? null : aliases);
}