org.apache.calcite.sql.parser.SqlParserPos Java Examples

The following examples show how to use org.apache.calcite.sql.parser.SqlParserPos. 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: SqlConverter.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param sql
 *          the SQL sent to the server
 * @param pos
 *          the position of the error
 * @return The sql with a ^ character under the error
 */
static String formatSQLParsingError(String sql, SqlParserPos pos) {
  if (pos == null) {
    return sql;
  }
  StringBuilder sb = new StringBuilder();
  String[] lines = sql.split("\n");
  for (int i = 0; i < lines.length; i++) {
    String line = lines[i];
    sb.append(line).append("\n");
    if (i == (pos.getLineNum() - 1)) {
      for (int j = 0; j < pos.getColumnNum() - 1; j++) {
        sb.append(" ");
      }
      sb.append("^\n");
    }
  }
  return sb.toString();
}
 
Example #2
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 #3
Source File: SqlCreateTable.java    From flink with Apache License 2.0 6 votes vote down vote up
public SqlCreateTable(
		SqlParserPos pos,
		SqlIdentifier tableName,
		SqlNodeList columnList,
		SqlNodeList primaryKeyList,
		List<SqlNodeList> uniqueKeysList,
		SqlNodeList propertyList,
		SqlNodeList partitionKeyList,
		SqlCharStringLiteral comment) {
	super(OPERATOR, pos, false, false);
	this.tableName = requireNonNull(tableName, "Table name is missing");
	this.columnList = requireNonNull(columnList, "Column list should not be null");
	this.primaryKeyList = primaryKeyList;
	this.uniqueKeysList = uniqueKeysList;
	this.propertyList = propertyList;
	this.partitionKeyList = partitionKeyList;
	this.comment = comment;
}
 
Example #4
Source File: SqlCreateTable.java    From flink with Apache License 2.0 6 votes vote down vote up
public SqlCreateTable(
		SqlParserPos pos,
		SqlIdentifier tableName,
		SqlNodeList columnList,
		List<SqlTableConstraint> tableConstraints,
		SqlNodeList propertyList,
		SqlNodeList partitionKeyList,
		@Nullable SqlWatermark watermark,
		@Nullable SqlCharStringLiteral comment,
		@Nullable SqlTableLike tableLike,
		boolean isTemporary) {
	super(OPERATOR, pos, false, false);
	this.tableName = requireNonNull(tableName, "tableName should not be null");
	this.columnList = requireNonNull(columnList, "columnList should not be null");
	this.tableConstraints = requireNonNull(tableConstraints, "table constraints should not be null");
	this.propertyList = requireNonNull(propertyList, "propertyList should not be null");
	this.partitionKeyList = requireNonNull(partitionKeyList, "partitionKeyList should not be null");
	this.watermark = watermark;
	this.comment = comment;
	this.tableLike = tableLike;
	this.isTemporary = isTemporary;
}
 
Example #5
Source File: SqlSelect.java    From Bats with Apache License 2.0 6 votes vote down vote up
public SqlSelect(SqlParserPos pos,
    SqlNodeList keywordList,
    SqlNodeList selectList,
    SqlNode from,
    SqlNode where,
    SqlNodeList groupBy,
    SqlNode having,
    SqlNodeList windowDecls,
    SqlNodeList orderBy,
    SqlNode offset,
    SqlNode fetch) {
  super(pos);
  this.keywordList = Objects.requireNonNull(keywordList != null
      ? keywordList : new SqlNodeList(pos));
  this.selectList = selectList;
  this.from = from;
  this.where = where;
  this.groupBy = groupBy;
  this.having = having;
  this.windowDecls = Objects.requireNonNull(windowDecls != null
      ? windowDecls : new SqlNodeList(pos));
  this.orderBy = orderBy;
  this.offset = offset;
  this.fetch = fetch;
}
 
Example #6
Source File: SqlMatchRecognize.java    From Bats with Apache License 2.0 6 votes vote down vote up
/** Creates a SqlMatchRecognize. */
public SqlMatchRecognize(SqlParserPos pos, SqlNode tableRef, SqlNode pattern,
    SqlLiteral strictStart, SqlLiteral strictEnd, SqlNodeList patternDefList,
    SqlNodeList measureList, SqlNode after, SqlNodeList subsetList,
    SqlLiteral rowsPerMatch, SqlNodeList partitionList,
    SqlNodeList orderList, SqlLiteral interval) {
  super(pos);
  this.tableRef = Objects.requireNonNull(tableRef);
  this.pattern = Objects.requireNonNull(pattern);
  this.strictStart = strictStart;
  this.strictEnd = strictEnd;
  this.patternDefList = Objects.requireNonNull(patternDefList);
  Preconditions.checkArgument(patternDefList.size() > 0);
  this.measureList = Objects.requireNonNull(measureList);
  this.after = after;
  this.subsetList = subsetList;
  Preconditions.checkArgument(rowsPerMatch == null
      || rowsPerMatch.value instanceof RowsPerMatchOption);
  this.rowsPerMatch = rowsPerMatch;
  this.partitionList = Objects.requireNonNull(partitionList);
  this.orderList = Objects.requireNonNull(orderList);
  this.interval = interval;
}
 
Example #7
Source File: SqlProcedureCallOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  // for now, rewrite "CALL f(x)" to "SELECT f(x) FROM VALUES(0)"
  // TODO jvs 18-Jan-2005:  rewrite to SELECT * FROM TABLE f(x)
  // once we support function calls as tables
  return new SqlSelect(SqlParserPos.ZERO,
      null,
      new SqlNodeList(
          Collections.singletonList(call.operand(0)),
          SqlParserPos.ZERO),
      SqlStdOperatorTable.VALUES.createCall(
          SqlParserPos.ZERO,
          SqlStdOperatorTable.ROW.createCall(
              SqlParserPos.ZERO,
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO))),
      null,
      null,
      null,
      null,
      null,
      null,
      null,
      null);
}
 
Example #8
Source File: SqlSelectOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
public SqlCall createCall(
    SqlLiteral functionQualifier,
    SqlParserPos pos,
    SqlNode... operands) {
  assert functionQualifier == null;
  return new SqlSelect(pos,
      (SqlNodeList) operands[0],
      (SqlNodeList) operands[1],
      operands[2],
      operands[3],
      (SqlNodeList) operands[4],
      operands[5],
      (SqlNodeList) operands[6],
      (SqlNodeList) operands[7],
      operands[8],
      operands[9]);
}
 
Example #9
Source File: SqlAlterFunction.java    From flink with Apache License 2.0 6 votes vote down vote up
public SqlAlterFunction(
		SqlParserPos pos,
		SqlIdentifier functionIdentifier,
		SqlCharStringLiteral functionClassName,
		String functionLanguage,
		boolean ifExists,
		boolean isTemporary,
		boolean isSystemFunction) {
	super(pos);
	this.functionIdentifier = requireNonNull(functionIdentifier, "functionIdentifier should not be null");
	this.functionClassName = requireNonNull(functionClassName, "functionClassName should not be null");
	this.isSystemFunction = requireNonNull(isSystemFunction);
	this.isTemporary = isTemporary;
	this.functionLanguage = functionLanguage;
	this.ifExists = ifExists;

}
 
Example #10
Source File: RexSqlStandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlNode convertCall(RexToSqlNodeConverter converter, RexCall call) {
  SqlNode[] operands = convertExpressionList(converter, call.getOperands());
  if (operands == null) {
    return null;
  }
  return new SqlBasicCall(op, operands, SqlParserPos.ZERO);
}
 
Example #11
Source File: SqlLiteral.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static SqlTimeLiteral createTime(
    Calendar calendar,
    int precision,
    SqlParserPos pos) {
  return createTime(TimeString.fromCalendarFields(calendar), precision, pos);
}
 
Example #12
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlNode getCastedSqlNode(SqlNode argInput, RelDataType varType,
    SqlParserPos pos, RexNode argRex) {
  SqlNode arg;
  if (argRex != null && !argRex.getType().equals(varType)) {
    arg = SqlStdOperatorTable.CAST.createCall(
        pos, argInput, SqlTypeUtil.convertTypeToSpec(varType));
  } else {
    arg = argInput;
  }
  return arg;
}
 
Example #13
Source File: HsqldbSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteSingleValueExpr(SqlNode aggCall) {
  final SqlNode operand = ((SqlBasicCall) aggCall).operand(0);
  final SqlLiteral nullLiteral = SqlLiteral.createNull(SqlParserPos.ZERO);
  final SqlNode unionOperand = SqlStdOperatorTable.VALUES.createCall(SqlParserPos.ZERO,
      SqlLiteral.createApproxNumeric("0", SqlParserPos.ZERO));
  // For hsqldb, generate
  //   CASE COUNT(*)
  //   WHEN 0 THEN NULL
  //   WHEN 1 THEN MIN(<result>)
  //   ELSE (VALUES 1 UNION ALL VALUES 1)
  //   END
  final SqlNode caseExpr =
      new SqlCase(SqlParserPos.ZERO,
          SqlStdOperatorTable.COUNT.createCall(SqlParserPos.ZERO, operand),
          SqlNodeList.of(
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO),
              SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO)),
          SqlNodeList.of(
              nullLiteral,
              SqlStdOperatorTable.MIN.createCall(SqlParserPos.ZERO, operand)),
          SqlStdOperatorTable.SCALAR_QUERY.createCall(SqlParserPos.ZERO,
              SqlStdOperatorTable.UNION_ALL
                  .createCall(SqlParserPos.ZERO, unionOperand, unionOperand)));

  LOGGER.debug("SINGLE_VALUE rewritten into [{}]", caseExpr);

  return caseExpr;
}
 
Example #14
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(SQLExtractExpr x) {
    x.getValue().accept(this);
    TimeUnit timeUnits[] = getTimeUnit(x.getUnit());

    sqlNode = SqlStdOperatorTable.EXTRACT
            .createCall(SqlParserPos.ZERO
                    , new SqlIntervalQualifier(timeUnits[0], timeUnits[1], SqlParserPos.ZERO)
                    , sqlNode);
    return false;
}
 
Example #15
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean visit(SQLTimestampExpr x) {
    String literal = x.getLiteral();
    int precision = 0;
    if (literal.endsWith("00")) {
        char c3 = literal.charAt(literal.length() - 3);
        if (c3 >= '0' && c3 <= '9') {
            literal = literal.substring(0, literal.length() - 2);
            precision = 3;
        }
    }
    TimestampString ts = new TimestampString(literal);
    sqlNode = SqlLiteral.createTimestamp(ts, precision, SqlParserPos.ZERO);
    return false;
}
 
Example #16
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean visit(SQLInListExpr x) {
    SqlNodeList sqlNodes = convertToSqlNodeList(x.getTargetList());
    SqlOperator sqlOperator = x.isNot() ? SqlStdOperatorTable.NOT_IN : SqlStdOperatorTable.IN;
    sqlNode = new SqlBasicCall(sqlOperator, new SqlNode[] { convertToSqlNode(x.getExpr()), sqlNodes },
                               SqlParserPos.ZERO);

    return false;
}
 
Example #17
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean visit(SQLExistsExpr x) {
    SqlOperator sqlOperator = SqlStdOperatorTable.EXISTS;
    SqlNode sqlNode = sqlOperator.createCall(SqlParserPos.ZERO,
            convertToSqlNode(x.getSubQuery()));
    if(x.isNot()){
        sqlNode = SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO,sqlNode);
    }
    this.sqlNode = sqlNode;
    return false;
}
 
Example #18
Source File: SqlSetOption.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public List<SqlNode> getOperandList() {
  final List<SqlNode> operandList = new ArrayList<>();
  if (scope == null) {
    operandList.add(null);
  } else {
    operandList.add(new SqlIdentifier(scope, SqlParserPos.ZERO));
  }
  operandList.add(name);
  operandList.add(value);
  return ImmutableNullableList.copyOf(operandList);
}
 
Example #19
Source File: SqlSelect.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlSelect(SqlParserPos pos,
    SqlNodeList keywordList,
    SqlNodeList selectList,
    SqlNode from,
    SqlNode where,
    SqlNodeList groupBy,
    SqlNode having,
    SqlNodeList windowDecls,
    SqlNodeList orderBy,
    SqlNode offset,
    SqlNode fetch,
    SqlNodeList hints) {
  super(pos);
  this.keywordList = Objects.requireNonNull(keywordList != null
      ? keywordList : new SqlNodeList(pos));
  this.selectList = selectList;
  this.from = from;
  this.where = where;
  this.groupBy = groupBy;
  this.having = having;
  this.windowDecls = Objects.requireNonNull(windowDecls != null
      ? windowDecls : new SqlNodeList(pos));
  this.orderBy = orderBy;
  this.offset = offset;
  this.fetch = fetch;
  this.hints = hints;
}
 
Example #20
Source File: SqlIdentifier.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Returns an identifier that is the same as this except with a component
 * added at a given position. Does not modify this identifier. */
public SqlIdentifier add(int i, String name, SqlParserPos pos) {
  final List<String> names2 = new ArrayList<>(names);
  names2.add(i, name);
  final List<SqlParserPos> pos2;
  if (componentPositions == null) {
    pos2 = null;
  } else {
    pos2 = new ArrayList<>(componentPositions);
    pos2.add(i, pos);
  }
  return new SqlIdentifier(names2, collation, pos, pos2);
}
 
Example #21
Source File: Hoist.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Variable(String originalSql, int ordinal, SqlNode node) {
  this.originalSql = Objects.requireNonNull(originalSql);
  this.ordinal = ordinal;
  this.node = Objects.requireNonNull(node);
  final SqlParserPos pos = node.getParserPosition();
  start = SqlParserUtil.lineColToIndex(originalSql,
      pos.getLineNum(), pos.getColumnNum());
  end = SqlParserUtil.lineColToIndex(originalSql,
      pos.getEndLineNum(), pos.getEndColumnNum()) + 1;

  Preconditions.checkArgument(ordinal >= 0);
  Preconditions.checkArgument(start >= 0);
  Preconditions.checkArgument(start <= end);
  Preconditions.checkArgument(end <= originalSql.length());
}
 
Example #22
Source File: SqlJdbcFunctionCall.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlCall getLookupCall() {
  if (null == lookupCall) {
    lookupCall =
        lookupMakeCallObj.createCall(SqlParserPos.ZERO, thisOperands);
  }
  return lookupCall;
}
 
Example #23
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean visit(SQLBinaryOpExprGroup x) {
    SqlOperator operator = null;
    switch (x.getOperator()) {
        case BooleanAnd:
            operator = SqlStdOperatorTable.AND;
            break;
        case BooleanOr:
            operator = SqlStdOperatorTable.OR;
            break;
        default:
            break;
    }

    final List<SQLExpr> items = x.getItems();
    SqlNode group = null;
    for (int i = 0; i < items.size(); i++) {
        SQLExpr item = items.get(i);
        final SqlNode calciteNode = convertToSqlNode(item);
        if (group == null) {
            group = calciteNode;
        } else {
            group = new SqlBasicCall(operator, new SqlNode[] {group, calciteNode}, SqlParserPos.ZERO);;
        }
    }
    this.sqlNode = group;
    return false;
}
 
Example #24
Source File: SqlAlterHivePartitionRename.java    From flink with Apache License 2.0 5 votes vote down vote up
public SqlAlterHivePartitionRename(SqlParserPos pos, SqlIdentifier tableName,
		SqlNodeList partSpec, SqlNodeList newPartSpec) throws ParseException {
	super(pos, tableName, partSpec);
	if (partSpec == null || newPartSpec == null) {
		throw new ParseException("Both old and new partition spec have to be specified");
	}
	HiveDDLUtils.unescapePartitionSpec(partSpec);
	HiveDDLUtils.unescapePartitionSpec(newPartSpec);
	this.newPartSpec = newPartSpec;
}
 
Example #25
Source File: SqlOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a call to this operand with a list of operands.
 *
 * <p>The position of the resulting call is the union of the <code>
 * pos</code> and the positions of all of the operands.
 */
public final SqlCall createCall(
    SqlParserPos pos,
    List<? extends SqlNode> operandList) {
  return createCall(
      null,
      pos,
      operandList.toArray(new SqlNode[0]));
}
 
Example #26
Source File: SqlIntervalQualifier.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against an HOUR TO MINUTE interval
 * qualifier.
 *
 * @throws org.apache.calcite.util.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsHourToMinute(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal hour;
  BigDecimal minute;

  // validate as HOUR(startPrecision) TO MINUTE, e.g. 'HH:MM'
  String intervalPattern = "(\\d+):(\\d{1,2})";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      hour = parseField(m, 1);
      minute = parseField(m, 2);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, hour, TimeUnit.HOUR, pos);
    if (!(isSecondaryFieldInRange(minute, TimeUnit.MINUTE))) {
      throw invalidValueException(pos, originalValue);
    }

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, hour, minute, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}
 
Example #27
Source File: SideParser.java    From alchemy with Apache License 2.0 5 votes vote down vote up
public static SqlNode[] createEqualNodes(SqlKind sqlKind) {
    SqlNode[] nodes = new SqlNode[2];
    if (SqlKind.AND == sqlKind) {
        nodes[0] = SqlLiteral.createExactNumeric("1", new SqlParserPos(0, 0));
        nodes[1] = SqlLiteral.createExactNumeric("1", new SqlParserPos(0, 0));
    } else {
        nodes[0] = SqlLiteral.createExactNumeric("0", new SqlParserPos(0, 0));
        nodes[1] = SqlLiteral.createExactNumeric("1", new SqlParserPos(0, 0));
    }
    return nodes;
}
 
Example #28
Source File: SqlDatePartFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final SqlParserPos pos = call.getParserPosition();
  return SqlStdOperatorTable.EXTRACT.createCall(pos,
      new SqlIntervalQualifier(timeUnit, null, SqlParserPos.ZERO),
      operands.get(0));
}
 
Example #29
Source File: SqlHint.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlHint(
    SqlParserPos pos,
    SqlIdentifier name,
    SqlNodeList options,
    HintOptionFormat optionFormat) {
  super(pos);
  this.name = name;
  this.optionFormat = optionFormat;
  this.options = options;
}
 
Example #30
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an INTERVAL literal against an HOUR interval qualifier.
 *
 * @throws org.apache.calcite.runtime.CalciteContextException if the interval
 * value is illegal
 */
private int[] evaluateIntervalLiteralAsHour(
    RelDataTypeSystem typeSystem, int sign,
    String value,
    String originalValue,
    SqlParserPos pos) {
  BigDecimal hour;

  // validate as HOUR(startPrecision), e.g. 'HH'
  String intervalPattern = "(\\d+)";

  Matcher m = Pattern.compile(intervalPattern).matcher(value);
  if (m.matches()) {
    // Break out  field values
    try {
      hour = parseField(m, 1);
    } catch (NumberFormatException e) {
      throw invalidValueException(pos, originalValue);
    }

    // Validate individual fields
    checkLeadFieldInRange(typeSystem, sign, hour, TimeUnit.HOUR, pos);

    // package values up for return
    return fillIntervalValueArray(sign, ZERO, hour, ZERO, ZERO, ZERO);
  } else {
    throw invalidValueException(pos, originalValue);
  }
}