Java Code Examples for org.apache.calcite.sql.SqlNodeList

The following examples show how to use org.apache.calcite.sql.SqlNodeList. These examples are extracted from open source projects. 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 Project: flink   Source File: SqlAddHivePartitions.java    License: 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);
	writer.newlineAndIndent();
	writer.keyword("ADD");
	if (ifNotExists()) {
		writer.keyword("IF NOT EXISTS");
	}
	int opLeftPrec = getOperator().getLeftPrec();
	int opRightPrec = getOperator().getRightPrec();
	for (int i = 0; i < getPartSpecs().size(); i++) {
		writer.newlineAndIndent();
		SqlNodeList partSpec = getPartSpecs().get(i);
		writer.keyword("PARTITION");
		partSpec.unparse(writer, opLeftPrec, opRightPrec);
		SqlCharStringLiteral location = partLocations.get(i);
		if (location != null) {
			writer.keyword("LOCATION");
			location.unparse(writer, opLeftPrec, opRightPrec);
		}
	}
}
 
Example 2
Source Project: quark   Source File: SqlAlterQuark.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void setOperand(int i, SqlNode operand) {

    switch (i) {
      case 0:
        targetColumnList = (SqlNodeList) operand;
        break;
      case 1:
        sourceExpressionList = (SqlNodeList) operand;
        break;
      case 2:
        identifier = (SqlIdentifier) operand;
        break;
      default:
        throw new AssertionError(i);
    }
  }
 
Example 3
Source Project: Bats   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Calc e) {
  Result x = visitChild(0, e.getInput());
  parseCorrelTable(e, x);
  final RexProgram program = e.getProgram();
  Builder builder =
      program.getCondition() != null
          ? x.builder(e, Clause.WHERE)
          : x.builder(e);
  if (!isStar(program)) {
    final List<SqlNode> selectList = new ArrayList<>();
    for (RexLocalRef ref : program.getProjectList()) {
      SqlNode sqlExpr = builder.context.toSql(program, ref);
      addSelect(selectList, sqlExpr, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }

  if (program.getCondition() != null) {
    builder.setWhere(
        builder.context.toSql(program, program.getCondition()));
  }
  return builder.result();
}
 
Example 4
Source Project: calcite   Source File: SqlShuttle.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode visit(SqlNodeList nodeList) {
  boolean update = false;
  List<SqlNode> exprs = nodeList.getList();
  int exprCount = exprs.size();
  List<SqlNode> newList = new ArrayList<>(exprCount);
  for (SqlNode operand : exprs) {
    SqlNode clonedOperand;
    if (operand == null) {
      clonedOperand = null;
    } else {
      clonedOperand = operand.accept(this);
      if (clonedOperand != operand) {
        update = true;
      }
    }
    newList.add(clonedOperand);
  }
  if (update) {
    return new SqlNodeList(newList, nodeList.getParserPosition());
  } else {
    return nodeList;
  }
}
 
Example 5
Source Project: flink   Source File: SqlDropPartitions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
	super.unparse(writer, leftPrec, rightPrec);
	writer.newlineAndIndent();
	writer.keyword("DROP");
	if (ifExists) {
		writer.keyword("IF EXISTS");
	}
	int opLeftPrec = getOperator().getLeftPrec();
	int opRightPrec = getOperator().getRightPrec();
	for (SqlNodeList partSpec : partSpecs) {
		writer.newlineAndIndent();
		writer.keyword("PARTITION");
		partSpec.unparse(writer, opLeftPrec, opRightPrec);
	}
}
 
Example 6
Source Project: calcite   Source File: SqlRollupOperator.java    License: Apache License 2.0 6 votes vote down vote up
private void unparseCube(SqlWriter writer, SqlCall call) {
  writer.keyword(call.getOperator().getName());
  final SqlWriter.Frame frame =
      writer.startList(SqlWriter.FrameTypeEnum.FUN_CALL, "(", ")");
  for (SqlNode operand : call.getOperandList()) {
    writer.sep(",");
    if (operand.getKind() == SqlKind.ROW) {
      final SqlWriter.Frame frame2 =
          writer.startList(SqlWriter.FrameTypeEnum.SIMPLE, "(", ")");
      for (SqlNode operand2 : ((SqlCall) operand).getOperandList()) {
        writer.sep(",");
        operand2.unparse(writer, 0, 0);
      }
      writer.endList(frame2);
    } else if (operand instanceof SqlNodeList
        && ((SqlNodeList) operand).size() == 0) {
      writer.keyword("()");
    } else {
      operand.unparse(writer, 0, 0);
    }
  }
  writer.endList(frame);
}
 
Example 7
Source Project: calcite   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
public Result visit(TableFunctionScan e) {
  final List<SqlNode> inputSqlNodes = new ArrayList<>();
  final int inputSize = e.getInputs().size();
  for (int i = 0; i < inputSize; i++) {
    Result child = visitChild(i, e.getInput(i));
    inputSqlNodes.add(child.asStatement());
  }
  final Context context = tableFunctionScanContext(inputSqlNodes);
  SqlNode callNode = context.toSql(null, e.getCall());
  // Convert to table function call, "TABLE($function_name(xxx))"
  SqlNode tableCall = new SqlBasicCall(
      SqlStdOperatorTable.COLLECTION_TABLE,
      new SqlNode[]{callNode},
      SqlParserPos.ZERO);
  SqlNode select = new SqlSelect(
      SqlParserPos.ZERO, null, null, tableCall,
      null, null, null, null, null, null, null, SqlNodeList.EMPTY);
  return result(select, ImmutableList.of(Clause.SELECT), e, null);
}
 
Example 8
Source Project: Bats   Source File: SqlCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a call to the switched form of the case operator, viz:
 *
 * <blockquote><code>CASE value<br>
 * WHEN whenList[0] THEN thenList[0]<br>
 * WHEN whenList[1] THEN thenList[1]<br>
 * ...<br>
 * ELSE elseClause<br>
 * END</code></blockquote>
 */
public static SqlCase createSwitched(SqlParserPos pos, SqlNode value,
    SqlNodeList whenList, SqlNodeList thenList, SqlNode elseClause) {
  if (null != value) {
    List<SqlNode> list = whenList.getList();
    for (int i = 0; i < list.size(); i++) {
      SqlNode e = list.get(i);
      final SqlCall call;
      if (e instanceof SqlNodeList) {
        call = SqlStdOperatorTable.IN.createCall(pos, value, e);
      } else {
        call = SqlStdOperatorTable.EQUALS.createCall(pos, value, e);
      }
      list.set(i, call);
    }
  }

  if (null == elseClause) {
    elseClause = SqlLiteral.createNull(pos);
  }

  return new SqlCase(pos, null, whenList, thenList, elseClause);
}
 
Example 9
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the <code>ordinal</code>th item in the select list.
 */
private SqlNode nthSelectItem(int ordinal, final SqlParserPos pos) {
	// TODO: Don't expand the list every time. Maybe keep an expanded
	// version of each expression -- select lists and identifiers -- in
	// the validator.

	SqlNodeList expandedSelectList =
		expandStar(
			select.getSelectList(),
			select,
			false);
	SqlNode expr = expandedSelectList.get(ordinal);
	expr = stripAs(expr);
	if (expr instanceof SqlIdentifier) {
		expr = getScope().fullyQualify((SqlIdentifier) expr).identifier;
	}

	// Create a copy of the expression with the position of the order
	// item.
	return expr.clone(pos);
}
 
Example 10
Source Project: flink   Source File: SqlCreateHiveView.java    License: Apache License 2.0 6 votes vote down vote up
public SqlCreateHiveView(SqlParserPos pos, SqlIdentifier viewName, SqlNodeList fieldList, SqlNode query,
		boolean ifNotExists, SqlCharStringLiteral comment, SqlNodeList properties) {
	super(
			pos,
			viewName,
			fieldList,
			query,
			false,
			false,
			ifNotExists,
			HiveDDLUtils.unescapeStringLiteral(comment),
			properties
	);
	HiveDDLUtils.unescapeProperties(properties);
	originPropList = new SqlNodeList(properties.getList(), properties.getParserPosition());
	// mark it as a hive view
	properties.add(HiveDDLUtils.toTableOption(CatalogConfig.IS_GENERIC, "false", pos));
}
 
Example 11
Source Project: calcite   Source File: SelectScope.java    License: 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 12
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates the SELECT statement that putatively feeds rows into an UPDATE
 * statement to be updated.
 *
 * @param call Call to the UPDATE operator
 * @return select statement
 */
protected SqlSelect createSourceSelectForUpdate(SqlUpdate call) {
	final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
	selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));
	int ordinal = 0;
	for (SqlNode exp : call.getSourceExpressionList()) {
		// Force unique aliases to avoid a duplicate for Y with
		// SET X=Y
		String alias = SqlUtil.deriveAliasFromOrdinal(ordinal);
		selectList.add(SqlValidatorUtil.addAlias(exp, alias));
		++ordinal;
	}
	SqlNode sourceTable = call.getTargetTable();
	if (call.getAlias() != null) {
		sourceTable =
			SqlValidatorUtil.addAlias(
				sourceTable,
				call.getAlias().getSimple());
	}
	return new SqlSelect(SqlParserPos.ZERO, null, selectList, sourceTable,
		call.getCondition(), null, null, null, null, null, null);
}
 
Example 13
Source Project: AthenaX   Source File: ValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFunction() throws IOException, ParseException {
  String sql = Joiner.on(";\n").join(
      "CREATE FUNCTION udf AS 'foo.udf'",
      "CREATE FUNCTION udf1 AS 'foo.udf' USING JAR 'mock://foo'",
      "CREATE FUNCTION udf2 AS 'foo.udf' USING JAR 'mock://foo', JAR 'mock://bar'"
  );
  SqlNodeList nodes = Planner.parse(sql);
  Validator validator = new Validator();
  validator.extract(nodes);
  assertEquals(ImmutableList.of(
      URI.create("mock://foo"),
      URI.create("mock://foo"),
      URI.create("mock://bar")
  ), ImmutableList.copyOf(validator.additionalResources()));
}
 
Example 14
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void validateGroupItem(SqlValidatorScope groupScope,
	AggregatingSelectScope aggregatingScope,
	SqlNode groupItem) {
	switch (groupItem.getKind()) {
		case GROUPING_SETS:
		case ROLLUP:
		case CUBE:
			validateGroupingSets(groupScope, aggregatingScope, (SqlCall) groupItem);
			break;
		default:
			if (groupItem instanceof SqlNodeList) {
				break;
			}
			final RelDataType type = deriveType(groupScope, groupItem);
			setValidatedNodeType(groupItem, type);
	}
}
 
Example 15
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the <code>ordinal</code>th item in the select list.
 */
private SqlNode nthSelectItem(int ordinal, final SqlParserPos pos) {
	// TODO: Don't expand the list every time. Maybe keep an expanded
	// version of each expression -- select lists and identifiers -- in
	// the validator.

	SqlNodeList expandedSelectList =
		expandStar(
			select.getSelectList(),
			select,
			false);
	SqlNode expr = expandedSelectList.get(ordinal);
	expr = stripAs(expr);
	if (expr instanceof SqlIdentifier) {
		expr = getScope().fullyQualify((SqlIdentifier) expr).identifier;
	}

	// Create a copy of the expression with the position of the order
	// item.
	return expr.clone(pos);
}
 
Example 16
Source Project: dremio-oss   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #dispatch
 */
public Result visit(Sort e) {
  Result x = visitChild(0, e.getInput());
  Builder builder = x.builder(e, Clause.ORDER_BY);
  List<SqlNode> orderByList = Expressions.list();
  for (RelFieldCollation field : e.getCollation().getFieldCollations()) {
    builder.addOrderItem(orderByList, field);
  }
  if (!orderByList.isEmpty()) {
    builder.setOrderBy(new SqlNodeList(orderByList, POS));
    x = builder.result();
  }
  if (e.fetch != null) {
    builder = x.builder(e, Clause.FETCH);
    builder.setFetch(builder.context.toSql(null, e.fetch));
    x = builder.result();
  }
  if (e.offset != null) {
    builder = x.builder(e, Clause.OFFSET);
    builder.setOffset(builder.context.toSql(null, e.offset));
    x = builder.result();
  }
  return x;
}
 
Example 17
Source Project: AthenaX   Source File: Planner.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static SqlNodeList parse(String sql) throws ParseException {
  // Keep the SQL syntax consistent with Flink
  try (StringReader in = new StringReader(sql)) {
    SqlParserImpl impl = new SqlParserImpl(in);

    // back tick as the quote
    impl.switchTo("BTID");
    impl.setTabSize(1);
    impl.setQuotedCasing(Lex.JAVA.quotedCasing);
    impl.setUnquotedCasing(Lex.JAVA.unquotedCasing);
    impl.setIdentifierMaxLength(DEFAULT_IDENTIFIER_MAX_LENGTH);
    return impl.SqlStmtsEof();
  }
}
 
Example 18
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
/** Wraps a call in a {@link SqlKind#WITHIN_GROUP} call, if
 * {@code orderList} is non-empty. */
private SqlNode withOrder(SqlCall call, SqlNodeList orderList) {
    if (orderList == null || orderList.size() == 0) {
        return call;
    }
    return SqlStdOperatorTable.WITHIN_GROUP.createCall(POS, call, orderList);
}
 
Example 19
Source Project: alchemy   Source File: SqlParseUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void parseSource(SqlSelect sqlSelect, List<String> sources, List<String> udfs)
    throws SqlParseException {
    SqlNodeList selectList = sqlSelect.getSelectList();
    SqlNode from = sqlSelect.getFrom();
    SqlNode where = sqlSelect.getWhere();
    SqlNode having = sqlSelect.getHaving();
    parseSelectList(selectList, sources, udfs);
    parseFrom(from, sources, udfs);
    parseFunction(where, udfs);
    parseFunction(having, udfs);
}
 
Example 20
Source Project: quark   Source File: RelToSqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
public Result visitValues(Values e) {
  final List<String> fields = e.getRowType().getFieldNames();
  final List<Clause> clauses = Collections.singletonList(Clause.SELECT);
  final Context context =
      new AliasContext(Collections.<Pair<String, RelDataType>>emptyList(), false);
  final List<SqlSelect> selects = new ArrayList<>();
  for (List<RexLiteral> tuple : e.getTuples()) {
    final List<SqlNode> selectList = new ArrayList<>();
    for (Pair<RexLiteral, String> literal : Pair.zip(tuple, fields)) {
      selectList.add(
          SqlStdOperatorTable.AS.createCall(
              POS,
              context.toSql(null, literal.left),
              new SqlIdentifier(literal.right, POS)));
    }
    selects.add(
        new SqlSelect(POS, SqlNodeList.EMPTY,
            new SqlNodeList(selectList, POS), null, null, null,
            null, null, null, null, null));
  }
  SqlNode query = null;
  for (SqlSelect select : selects) {
    if (query == null) {
      query = select;
    } else {
      query = SqlStdOperatorTable.UNION_ALL.createCall(POS, query,
          select);
    }
  }
  return result(query, clauses, e);
}
 
Example 21
Source Project: alchemy   Source File: SideParser.java    License: Apache License 2.0 5 votes vote down vote up
private static SqlNodeList creatFullNewSelectList(String alias, SqlNodeList selectList) {
    SqlNodeList newSelectList = new SqlNodeList( selectList.getParserPosition());
    List<String> names = new ArrayList<>(2);
    names.add(alias);
    names.add("");
    newSelectList.add(new SqlIdentifier(names,new SqlParserPos(0,0)));
    return newSelectList;
}
 
Example 22
Source Project: calcite   Source File: SqlCreateFunction.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a SqlCreateFunction. */
public SqlCreateFunction(SqlParserPos pos, boolean replace,
    boolean ifNotExists, SqlIdentifier name,
    SqlNode className, SqlNodeList usingList) {
  super(OPERATOR, pos, replace, ifNotExists);
  this.name = Objects.requireNonNull(name);
  this.className = className;
  this.usingList = Objects.requireNonNull(usingList);
  Preconditions.checkArgument(usingList.size() % 2 == 0);
}
 
Example 23
Source Project: quark   Source File: SqlAlterQuarkDataSource.java    License: Apache License 2.0 5 votes vote down vote up
public SqlAlterQuarkDataSource(SqlParserPos pos,
                     SqlNodeList targetColumnList,
                     SqlNodeList sourceExpressionList,
                     SqlIdentifier identifier) {
  super(pos, targetColumnList, sourceExpressionList, identifier);
  operator = new SqlSpecialOperator("ALTER_DATASOURCE", SqlKind.OTHER_DDL);
  operatorString = "ALTER DATASOURCE";
}
 
Example 24
Source Project: dremio-oss   Source File: SqlHandlerUtil.java    License: 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 25
Source Project: Bats   Source File: IdentifierNamespace.java    License: Apache License 2.0 5 votes vote down vote up
protected static Pair<SqlIdentifier, SqlNodeList> split(SqlNode node) {
  switch (node.getKind()) {
  case EXTEND:
    final SqlCall call = (SqlCall) node;
    return Pair.of((SqlIdentifier) call.getOperandList().get(0),
        (SqlNodeList) call.getOperandList().get(1));
  default:
    return Pair.of((SqlIdentifier) node, null);
  }
}
 
Example 26
Source Project: Bats   Source File: GroupByScope.java    License: Apache License 2.0 5 votes vote down vote up
GroupByScope(
    SqlValidatorScope parent,
    SqlNodeList groupByList,
    SqlSelect select) {
  super(parent);
  this.groupByList = groupByList;
  this.select = select;
}
 
Example 27
Source Project: Bats   Source File: OrderByScope.java    License: Apache License 2.0 5 votes vote down vote up
OrderByScope(
    SqlValidatorScope parent,
    SqlNodeList orderList,
    SqlSelect select) {
  super(parent);
  this.orderList = orderList;
  this.select = select;
}
 
Example 28
Source Project: flink   Source File: SqlAlterTable.java    License: Apache License 2.0 5 votes vote down vote up
public SqlAlterTable(
		SqlParserPos pos,
		SqlIdentifier tableName,
		@Nullable SqlNodeList partitionSpec) {
	super(pos);
	this.tableIdentifier = requireNonNull(tableName, "tableName should not be null");
	this.partitionSpec = partitionSpec;
}
 
Example 29
Source Project: incubator-pinot   Source File: CalciteSqlParser.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Expression> convertSelectList(SqlNodeList selectList) {
  List<Expression> selectExpr = new ArrayList<>();

  final Iterator<SqlNode> iterator = selectList.iterator();
  while (iterator.hasNext()) {
    final SqlNode next = iterator.next();
    selectExpr.add(toExpression(next));
  }

  return selectExpr;
}
 
Example 30
Source Project: kylin-on-parquet-v2   Source File: CalciteParser.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlNode getOnlySelectNode(String sql) {
    SqlNodeList selectList = null;
    try {
        selectList = ((SqlSelect) CalciteParser.parse(sql)).getSelectList();
    } catch (SqlParseException e) {
        throw new RuntimeException(
                "Failed to parse expression \'" + sql + "\', please make sure the expression is valid", e);
    }

    Preconditions.checkArgument(selectList.size() == 1,
            "Expression is invalid because size of select list exceeds one");

    return selectList.get(0);
}