org.apache.calcite.sql.SqlNodeList Java Examples

The following examples show how to use org.apache.calcite.sql.SqlNodeList. 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: SqlDropPartitions.java    From flink with 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 #2
Source File: ValidatorTest.java    From AthenaX with 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 #3
Source File: SqlCase.java    From Bats with 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 #4
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 #5
Source File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #6
Source File: SqlValidatorImpl.java    From flink with 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 #7
Source File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #8
Source File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #9
Source File: SqlShuttle.java    From calcite with 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 #10
Source File: RelToSqlConverter.java    From Bats with 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 #11
Source File: SqlAlterQuark.java    From quark with 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 #12
Source File: SqlCreateHiveView.java    From flink with 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 #13
Source File: RelToSqlConverter.java    From dremio-oss with 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 #14
Source File: SqlAddHivePartitions.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);
	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 #15
Source File: SqlRollupOperator.java    From calcite with 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 #16
Source File: RelToSqlConverter.java    From calcite with 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 #17
Source File: SqlCreateView.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlCreateView(SqlParserPos pos, SqlIdentifier viewName, SqlNodeList fieldList,
                     SqlNode query, SqlLiteral createType) {
  super(pos);
  this.viewName = viewName;
  this.query = query;
  this.fieldList = fieldList;
  this.createType = createType;
}
 
Example #18
Source File: AggregatingSelectScope.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Resolved resolve() {
  final ImmutableList.Builder<ImmutableList<ImmutableBitSet>> builder =
      ImmutableList.builder();
  List<SqlNode> extraExprs = ImmutableList.of();
  Map<Integer, Integer> groupExprProjection = ImmutableMap.of();
  if (select.getGroup() != null) {
    final SqlNodeList groupList = select.getGroup();
    final SqlValidatorUtil.GroupAnalyzer groupAnalyzer =
        new SqlValidatorUtil.GroupAnalyzer(temporaryGroupExprList);
    for (SqlNode groupExpr : groupList) {
      SqlValidatorUtil.analyzeGroupItem(this, groupAnalyzer, builder,
          groupExpr);
    }
    extraExprs = groupAnalyzer.extraExprs;
    groupExprProjection = groupAnalyzer.groupExprProjection;
  }

  final SortedMap<ImmutableBitSet, Integer> flatGroupSetCount =
      Maps.newTreeMap(ImmutableBitSet.COMPARATOR);
  for (List<ImmutableBitSet> groupSet : Linq4j.product(builder.build())) {
    final ImmutableBitSet set = ImmutableBitSet.union(groupSet);
    flatGroupSetCount.put(set, flatGroupSetCount.getOrDefault(set, 0) + 1);
  }

  // For GROUP BY (), we need a singleton grouping set.
  if (flatGroupSetCount.isEmpty()) {
    flatGroupSetCount.put(ImmutableBitSet.of(), 1);
  }

  return new Resolved(extraExprs, temporaryGroupExprList, flatGroupSetCount.keySet(),
      flatGroupSetCount, groupExprProjection);
}
 
Example #19
Source File: RefreshMetadataHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private Set<String> getColumnRootSegments(SqlNodeList columnList) {
  Set<String> columnSet = new HashSet<>();
  if (columnList != null) {
    for (SqlNode column : columnList.getList()) {
      // Add only the root segment. Collect metadata for all the columns under that root segment
      columnSet.add(SchemaPath.parseFromString(column.toString()).getRootSegmentPath());
    }
  }
  return columnSet;
}
 
Example #20
Source File: OrderByScope.java    From calcite with 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 #21
Source File: SqlAlterHiveTableChangeColumn.java    From flink with Apache License 2.0 5 votes vote down vote up
public SqlAlterHiveTableChangeColumn(SqlParserPos pos, SqlIdentifier tableName, boolean cascade,
		SqlIdentifier oldName, SqlTableColumn newColumn, boolean first, SqlIdentifier after) throws ParseException {
	super(pos, tableName, oldName, newColumn, after, first, new SqlNodeList(pos));
	this.origNewColumn = HiveDDLUtils.deepCopyTableColumn(newColumn);
	HiveDDLUtils.convertDataTypes(newColumn);
	this.cascade = cascade;
	// set ALTER OP
	getProperties().add(HiveDDLUtils.toTableOption(
			SqlAlterHiveTable.ALTER_TABLE_OP, SqlAlterHiveTable.AlterTableOp.ALTER_COLUMNS.name(), pos));
	// set cascade
	if (cascade) {
		getProperties().add(HiveDDLUtils.toTableOption(SqlAlterHiveTable.ALTER_COL_CASCADE, "true", pos));
	}
}
 
Example #22
Source File: SqlCreateTableExtension.java    From kareldb with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a SqlCreateTable.
 */
public SqlCreateTableExtension(SqlParserPos pos, boolean replace, boolean ifNotExists,
                               SqlIdentifier name, SqlNodeList columnList, SqlNode query) {
    super(pos, replace, ifNotExists, name, columnList, query);
    this.name = Objects.requireNonNull(name);
    this.columnList = columnList; // may be null
    this.query = query; // for "CREATE TABLE ... AS query"; may be null
}
 
Example #23
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 #24
Source File: RelToSqlConverter.java    From quark with Apache License 2.0 5 votes vote down vote up
private Result setOpToSql(SqlSetOperator operator, RelNode rel) {
  List<SqlNode> list = Expressions.list();
  for (Ord<RelNode> input : Ord.zip(rel.getInputs())) {
    final Result result = this.visitChild(input.i, input.e);
    list.add(result.asSelect());
  }
  final SqlCall node = operator.createCall(new SqlNodeList(list, POS));
  final List<Clause> clauses =
      Expressions.list(Clause.SET_OP);
  return result(node, clauses, rel);
}
 
Example #25
Source File: SqlCreateForeignSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a SqlCreateForeignSchema. */
SqlCreateForeignSchema(SqlParserPos pos, boolean replace, boolean ifNotExists,
    SqlIdentifier name, SqlNode type, SqlNode library,
    SqlNodeList optionList) {
  super(OPERATOR, pos, replace, ifNotExists);
  this.name = Objects.requireNonNull(name);
  this.type = type;
  this.library = library;
  Preconditions.checkArgument((type == null) != (library == null),
      "of type and library, exactly one must be specified");
  this.optionList = optionList; // may be null
}
 
Example #26
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlNode visit(SqlNodeList list) {
  SqlNodeList copy = new SqlNodeList(list.getParserPosition());
  for (SqlNode node : list) {
    copy.add(node.accept(this));
  }
  return copy;
}
 
Example #27
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected SqlNode createLeftCall(SqlOperator op, List<SqlNode> nodeList) {
  if (nodeList.size() == 2) {
    return op.createCall(new SqlNodeList(nodeList, POS));
  }
  final List<SqlNode> butLast = Util.skipLast(nodeList);
  final SqlNode last = nodeList.get(nodeList.size() - 1);
  final SqlNode call = createLeftCall(op, butLast);
  return op.createCall(new SqlNodeList(ImmutableList.of(call, last), POS));
}
 
Example #28
Source File: RichSqlInsert.java    From flink with Apache License 2.0 5 votes vote down vote up
public RichSqlInsert(SqlParserPos pos,
		SqlNodeList keywords,
		SqlNodeList extendedKeywords,
		SqlNode targetTable,
		SqlNode source,
		SqlNodeList columnList,
		SqlNodeList staticPartitions) {
	super(pos, keywords, targetTable, source, columnList);
	this.extendedKeywords = extendedKeywords;
	this.staticPartitions = staticPartitions;
}
 
Example #29
Source File: TableNamespace.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * 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 SqlNode extColNode =
            Iterables.find(extendList.getList(),
                sqlNode -> sqlNode instanceof SqlIdentifier
                    && Util.last(((SqlIdentifier) sqlNode).names).equals(
                        extendedField.getName()));

        throw validator.getValidationErrorFunction().apply(extColNode,
            RESOURCE.typeNotAssignable(
                baseFields.get(baseIndex).getName(), baseType.getFullTypeString(),
                extendedField.getName(), extType.getFullTypeString()));
      }
    }
  }
}
 
Example #30
Source File: CalciteParser.java    From kylin-on-parquet-v2 with 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);
}