Java Code Examples for org.apache.calcite.sql.parser.SqlParserPos#ZERO

The following examples show how to use org.apache.calcite.sql.parser.SqlParserPos#ZERO . 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: 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 2
Source File: SqlProcedureCallOperator.java    From Bats 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);
}
 
Example 3
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 4
Source File: MysqlSqlDialect.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode getCastSpec(RelDataType type) {
  switch (type.getSqlTypeName()) {
  case VARCHAR:
    // MySQL doesn't have a VARCHAR type, only CHAR.
    return new SqlDataTypeSpec(new SqlIdentifier("CHAR", SqlParserPos.ZERO),
        type.getPrecision(), -1, null, null, SqlParserPos.ZERO);
  case INTEGER:
  case BIGINT:
    return new SqlDataTypeSpec(new SqlIdentifier("_SIGNED", SqlParserPos.ZERO),
        type.getPrecision(), -1, null, null, SqlParserPos.ZERO);
  }
  return super.getCastSpec(type);
}
 
Example 5
Source File: SqlUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an SqlNode array to a SqlNodeList
 */
public static SqlNodeList toNodeList(SqlNode[] operands) {
  SqlNodeList ret = new SqlNodeList(SqlParserPos.ZERO);
  for (SqlNode node : operands) {
    ret.add(node);
  }
  return ret;
}
 
Example 6
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(MySqlExplainStatement x) {
    x.getStatement().accept(this);
    SqlNode explicandum = this.sqlNode;
    sqlNode = new SqlExplain(SqlParserPos.ZERO
            , explicandum
            , SqlLiteral.createSymbol(SqlExplainLevel.EXPPLAN_ATTRIBUTES, SqlParserPos.ZERO)
            , SqlLiteral.createSymbol(SqlExplain.Depth.PHYSICAL, SqlParserPos.ZERO)
            , SqlLiteral.createSymbol(SqlExplainFormat.TEXT, SqlParserPos.ZERO)
            , 0
    );
    return false;
}
 
Example 7
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * @see #dispatch
 */
public SqlImplementor.Result visit(ScanRelBase scan) {
  List<String> tableQualifiedName = scan.getTable().getQualifiedName();
  int index = tableQualifiedName.size() > 1 ? 1 /* Full path minus plugin name */ : 0;
  SqlIdentifier tableName = new SqlIdentifier(
    ImmutableList.copyOf(scan.getTable().getQualifiedName().listIterator(index)),
    SqlParserPos.ZERO);
  return result(tableName, ImmutableList.of(Clause.FROM), scan, null);
}
 
Example 8
Source File: SqlNodeList.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static SqlNodeList of(SqlNode node1, SqlNode node2, SqlNode... nodes) {
  SqlNodeList list = new SqlNodeList(SqlParserPos.ZERO);
  list.add(node1);
  list.add(node2);
  for (SqlNode node : nodes) {
    list.add(node);
  }
  return list;
}
 
Example 9
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the SELECT statement that putatively feeds rows into a DELETE
 * statement to be deleted.
 *
 * @param call Call to the DELETE operator
 * @return select statement
 */
protected SqlSelect createSourceSelectForDelete(SqlDelete call) {
	final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
	selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));
	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 10
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the SELECT statement that putatively feeds rows into a DELETE
 * statement to be deleted.
 *
 * @param call Call to the DELETE operator
 * @return select statement
 */
protected SqlSelect createSourceSelectForDelete(SqlDelete call) {
	final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
	selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));
	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 11
Source File: DremioSqlDialect.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected static SqlNode getVarcharWithPrecision(DremioSqlDialect dialect, RelDataType type, int precision) {
  return new SqlDataTypeSpec(
    new SqlIdentifier(type.getSqlTypeName().name(), SqlParserPos.ZERO),
    precision,
    type.getScale(),
    type.getCharset() != null && dialect.supportsCharSet()
      ? type.getCharset().name() : null,
    null,
    SqlParserPos.ZERO);
}
 
Example 12
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 13
Source File: SqlAggOperator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public SqlAggOperator(String name, int argCountMin, int argCountMax, SqlReturnTypeInference sqlReturnTypeInference) {
  super(name,
      new SqlIdentifier(name, SqlParserPos.ZERO),
      SqlKind.OTHER_FUNCTION,
      sqlReturnTypeInference,
      null,
      Checker.getChecker(argCountMin, argCountMax),
      SqlFunctionCategory.USER_DEFINED_FUNCTION);
}
 
Example 14
Source File: HiveSqlAggFunction.java    From marble with Apache License 2.0 5 votes vote down vote up
protected HiveSqlAggFunction(String name, boolean requiresOrder,
    boolean requiresOver,
    SqlReturnTypeInference sqlReturnTypeInference) {
  this(name, new SqlIdentifier(name, SqlParserPos.ZERO),
      SqlKind.OTHER_FUNCTION,
      SqlFunctionCategory.USER_DEFINED_FUNCTION,
      requiresOrder, requiresOver, sqlReturnTypeInference);
}
 
Example 15
Source File: MssqlSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}
 *
 * <p>MSSQL does not support NULLS FIRST, so we emulate using CASE
 * expressions. For example,
 *
 * <blockquote>{@code ORDER BY x NULLS FIRST}</blockquote>
 *
 * <p>becomes
 *
 * <blockquote>
 *   {@code ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x}
 * </blockquote>
 */
@Override public SqlNode emulateNullDirection(SqlNode node,
    boolean nullsFirst, boolean desc) {
  // Default ordering preserved
  if (nullCollation.isDefaultOrder(nullsFirst, desc)) {
    return null;
  }

  // Grouping node should preserve grouping, no emulation needed
  if (node.getKind() == SqlKind.GROUPING) {
    return node;
  }

  // Emulate nulls first/last with case ordering
  final SqlParserPos pos = SqlParserPos.ZERO;
  final SqlNodeList whenList =
      SqlNodeList.of(SqlStdOperatorTable.IS_NULL.createCall(pos, node));

  final SqlNode oneLiteral = SqlLiteral.createExactNumeric("1", pos);
  final SqlNode zeroLiteral = SqlLiteral.createExactNumeric("0", pos);

  if (nullsFirst) {
    // IS NULL THEN 0 ELSE 1 END
    return SqlStdOperatorTable.CASE.createCall(null, pos,
        null, whenList, SqlNodeList.of(zeroLiteral), oneLiteral);
  } else {
    // IS NULL THEN 1 ELSE 0 END
    return SqlStdOperatorTable.CASE.createCall(null, pos,
        null, whenList, SqlNodeList.of(oneLiteral), zeroLiteral);
  }
}
 
Example 16
Source File: DrillSqlAggOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected DrillSqlAggOperator(String name, List<DrillFuncHolder> functions, int argCountMin, int argCountMax, SqlReturnTypeInference sqlReturnTypeInference) {
  super(name,
      new SqlIdentifier(name, SqlParserPos.ZERO),
      SqlKind.OTHER_FUNCTION,
      sqlReturnTypeInference,
      null,
      Checker.getChecker(argCountMin, argCountMax),
      SqlFunctionCategory.USER_DEFINED_FUNCTION,
      false,
      false);
  this.functions = functions;
}
 
Example 17
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 4 votes vote down vote up
private SqlIdentifier identifier(String name) {
	return new SqlIdentifier(
		name,
		SqlParserPos.ZERO
	);
}
 
Example 18
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean visit(SQLUnionQuery x) {

    SqlNode[] nodes;
    if (x.getRelations().size() > 2) {
        nodes = new SqlNode[x.getRelations().size()];
        for (int i = 0; i < x.getRelations().size(); i++) {
            nodes[i] = convertToSqlNode(x.getRelations().get(i));
        }
    } else {
        SqlNode left = convertToSqlNode(x.getLeft());
        SqlNode right = convertToSqlNode(x.getRight());

        nodes = new SqlNode[] {left, right};
    }

    //order by
    SqlNodeList orderBySqlNode = null;
    SQLOrderBy orderBy = x.getOrderBy();
    if (orderBy != null) {
        orderBySqlNode = convertOrderby(orderBy);
    }

    //limit
    SqlNode offset = null;
    SqlNode fetch = null;
    SQLLimit limit = x.getLimit();
    if (limit != null) {
        offset = convertToSqlNode(limit.getOffset());
        fetch = convertToSqlNode(limit.getRowCount());
    }

    SQLUnionOperator operator = x.getOperator();

    SqlNode union = null;
    switch (operator) {
        case UNION_ALL:
            union = new SqlBasicCall(SqlStdOperatorTable.UNION_ALL,
                    nodes,
                    SqlParserPos.ZERO);
            break;
        case UNION:
        case DISTINCT:
            union = new SqlBasicCall(SqlStdOperatorTable.UNION,
                    nodes,
                    SqlParserPos.ZERO);
            break;
        case INTERSECT:
            union = new SqlBasicCall(SqlStdOperatorTable.INTERSECT,
                    nodes,
                    SqlParserPos.ZERO);
            break;
        case EXCEPT:
            union = new SqlBasicCall(SqlStdOperatorTable.EXCEPT,
                    nodes,
                    SqlParserPos.ZERO);
            break;
        default:
            throw new FastsqlException("unsupported join type: " + operator);
    }

    if (null == orderBy && null == offset && null == fetch) {
        sqlNode = union;
    } else {
        if (orderBySqlNode == null) {
            orderBySqlNode = SqlNodeList.EMPTY;
        }
        sqlNode = new SqlOrderBy(SqlParserPos.ZERO, union, orderBySqlNode, offset, fetch);
    }

    return false;

}
 
Example 19
Source File: LookupOperatorOverloadsTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void checkInternal(boolean caseSensitive) throws SQLException {
  final SqlNameMatcher nameMatcher =
      SqlNameMatchers.withCaseSensitive(caseSensitive);
  final String schemaName = "MySchema";
  final String funcName = "MyFUNC";
  final String anotherName = "AnotherFunc";

  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
    final TableFunction table = TableFunctionImpl.create(Smalls.MAZE_METHOD);
    schema.add(funcName, table);
    schema.add(anotherName, table);
    final TableFunction table2 =
        TableFunctionImpl.create(Smalls.MAZE3_METHOD);
    schema.add(funcName, table2);

    final CalciteServerStatement statement =
        connection.createStatement().unwrap(CalciteServerStatement.class);
    final CalcitePrepare.Context prepareContext =
        statement.createPrepareContext();
    final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
    CalciteCatalogReader reader =
        new CalciteCatalogReader(prepareContext.getRootSchema(),
            ImmutableList.of(), typeFactory, prepareContext.config());

    final List<SqlOperator> operatorList = new ArrayList<>();
    SqlIdentifier myFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, funcName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(2, funcName, operatorList);

    operatorList.clear();
    reader.lookupOperatorOverloads(myFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(0, null, operatorList);

    operatorList.clear();
    SqlIdentifier anotherFuncIdentifier =
        new SqlIdentifier(Lists.newArrayList(schemaName, anotherName), null,
            SqlParserPos.ZERO, null);
    reader.lookupOperatorOverloads(anotherFuncIdentifier,
        SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION, SqlSyntax.FUNCTION,
        operatorList, nameMatcher);
    checkFunctionType(1, anotherName, operatorList);
  }
}
 
Example 20
Source File: SqlWindow.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new window by combining this one with another.
 *
 * <p>For example,
 *
 * <blockquote><pre>WINDOW (w PARTITION BY x ORDER BY y)
 *   overlay
 *   WINDOW w AS (PARTITION BY z)</pre></blockquote>
 *
 * <p>yields
 *
 * <blockquote><pre>WINDOW (PARTITION BY z ORDER BY y)</pre></blockquote>
 *
 * <p>Does not alter this or the other window.
 *
 * @return A new window
 */
public SqlWindow overlay(SqlWindow that, SqlValidator validator) {
  // check 7.11 rule 10c
  final SqlNodeList partitions = getPartitionList();
  if (0 != partitions.size()) {
    throw validator.newValidationError(partitions.get(0),
        RESOURCE.partitionNotAllowed());
  }

  // 7.11 rule 10d
  final SqlNodeList baseOrder = getOrderList();
  final SqlNodeList refOrder = that.getOrderList();
  if ((0 != baseOrder.size()) && (0 != refOrder.size())) {
    throw validator.newValidationError(baseOrder.get(0),
        RESOURCE.orderByOverlap());
  }

  // 711 rule 10e
  final SqlNode lowerBound = that.getLowerBound();
  final SqlNode upperBound = that.getUpperBound();
  if ((null != lowerBound) || (null != upperBound)) {
    throw validator.newValidationError(that.isRows,
        RESOURCE.refWindowWithFrame());
  }

  SqlIdentifier declNameNew = declName;
  SqlIdentifier refNameNew = refName;
  SqlNodeList partitionListNew = partitionList;
  SqlNodeList orderListNew = orderList;
  SqlLiteral isRowsNew = isRows;
  SqlNode lowerBoundNew = lowerBound;
  SqlNode upperBoundNew = upperBound;
  SqlLiteral allowPartialNew = allowPartial;

  // Clear the reference window, because the reference is now resolved.
  // The overlaying window may have its own reference, of course.
  refNameNew = null;

  // Overlay other parameters.
  if (setOperand(partitionListNew, that.partitionList, validator)) {
    partitionListNew = that.partitionList;
  }
  if (setOperand(orderListNew, that.orderList, validator)) {
    orderListNew = that.orderList;
  }
  if (setOperand(lowerBoundNew, that.lowerBound, validator)) {
    lowerBoundNew = that.lowerBound;
  }
  if (setOperand(upperBoundNew, that.upperBound, validator)) {
    upperBoundNew = that.upperBound;
  }
  return new SqlWindow(
      SqlParserPos.ZERO,
      declNameNew,
      refNameNew,
      partitionListNew,
      orderListNew,
      isRowsNew,
      lowerBoundNew,
      upperBoundNew,
      allowPartialNew);
}