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

The following examples show how to use org.apache.calcite.sql.SqlNumericLiteral. 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: Bats   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SqlNode convert(PrecedenceClimbingParser.Token token) {
  switch (token.type) {
  case ATOM:
    return (SqlNode) token.o;
  case CALL:
    final PrecedenceClimbingParser.Call call =
        (PrecedenceClimbingParser.Call) token;
    final List<SqlNode> list = new ArrayList<>();
    for (PrecedenceClimbingParser.Token arg : call.args) {
      list.add(convert(arg));
    }
    final ToTreeListItem item = (ToTreeListItem) call.op.o;
    if (item.op == SqlStdOperatorTable.UNARY_MINUS
        && list.size() == 1
        && list.get(0) instanceof SqlNumericLiteral) {
      return SqlLiteral.createNegative((SqlNumericLiteral) list.get(0),
          item.pos.plusAll(list));
    }
    if (item.op == SqlStdOperatorTable.UNARY_PLUS
        && list.size() == 1
        && list.get(0) instanceof SqlNumericLiteral) {
      return list.get(0);
    }
    return item.op.createCall(item.pos.plusAll(list), list);
  default:
    throw new AssertionError(token);
  }
}
 
Example 2
Source Project: Bats   Source File: SqlStdOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  call.operand(0).unparse(writer, this.getLeftPrec(), this.getRightPrec());
  int startNum = ((SqlNumericLiteral) call.operand(1)).intValue(true);
  SqlNumericLiteral endRepNum = call.operand(2);
  boolean isReluctant = ((SqlLiteral) call.operand(3)).booleanValue();
  int endNum = endRepNum.intValue(true);
  if (startNum == endNum) {
    writer.keyword("{ " + startNum + " }");
  } else {
    if (endNum == -1) {
      if (startNum == 0) {
        writer.keyword("*");
      } else if (startNum == 1) {
        writer.keyword("+");
      } else {
        writer.keyword("{ " + startNum + ", }");
      }
    } else {
      if (startNum == 0 && endNum == 1) {
        writer.keyword("?");
      } else if (startNum == -1) {
        writer.keyword("{ , " + endNum + " }");
      } else {
        writer.keyword("{ " + startNum + ", " + endNum + " }");
      }
    }
    if (isReluctant) {
      writer.keyword("?");
    }
  }
}
 
Example 3
Source Project: Bats   Source File: SqlAnalyzeTable.java    License: Apache License 2.0 5 votes vote down vote up
public SqlAnalyzeTable(SqlParserPos pos, SqlIdentifier tblName, SqlLiteral estimate,
    SqlNodeList fieldList, SqlNumericLiteral samplePercent) {
  super(pos);
  this.tblName = tblName;
  this.estimate = estimate;
  this.fieldList = fieldList;
  this.samplePercent = samplePercent;
}
 
Example 4
Source Project: Bats   Source File: DrillSqlWorker.java    License: Apache License 2.0 5 votes vote down vote up
private static SqlNode wrapWithAutoLimit(SqlNode sqlNode, int queryMaxRows) {
  SqlNumericLiteral autoLimitLiteral = SqlLiteral.createExactNumeric(String.valueOf(queryMaxRows), SqlParserPos.ZERO);
  if (sqlNode.getKind() == SqlKind.ORDER_BY) {
    SqlOrderBy orderBy = (SqlOrderBy) sqlNode;
    return new SqlOrderBy(orderBy.getParserPosition(), orderBy.query, orderBy.orderList, orderBy.offset, autoLimitLiteral);
  }
  return new SqlOrderBy(SqlParserPos.ZERO, sqlNode, SqlNodeList.EMPTY, null, autoLimitLiteral);
}
 
Example 5
Source Project: Bats   Source File: TypeInferenceUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  if (opBinding instanceof SqlCallBinding && (((SqlCallBinding) opBinding).operand(1) instanceof  SqlNumericLiteral)) {
    int precision = ((SqlNumericLiteral) ((SqlCallBinding) opBinding).operand(1)).intValue(true);
    RelDataType sqlType = opBinding.getTypeFactory().createSqlType(SqlTypeName.VARCHAR, Math.max(precision, 0));
    return opBinding.getTypeFactory().createTypeWithNullability(sqlType, isNullable(opBinding.collectOperandTypes()));
  }

  return createCalciteTypeWithNullability(
      opBinding.getTypeFactory(),
      SqlTypeName.VARCHAR,
      isNullable(opBinding.collectOperandTypes()));

}
 
Example 6
Source Project: kylin-on-parquet-v2   Source File: ConvSqlWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void doWriteFetchNext(SqlNode fetch, SqlNode offset) {
    if (offset == null && !configurer.allowNoOffset())
        offset = SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO);

    if (fetch != null && !configurer.allowNoOrderByWithFetch() && lastFrame != null
            && lastFrame.getFrameType() != FrameTypeEnum.ORDER_BY_LIST) { // MSSQL requires ORDER_BY list for FETCH clause, so must append one here.
        DUMMY_ORDER_BY_NODE.unparse(this, 0, 0);
    }

    if (offset != null) {
        this.newlineAndIndent();
        final Frame offsetFrame = this.startList(FrameTypeEnum.OFFSET);
        this.keyword("OFFSET");
        offset.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.endList(offsetFrame);
    }
    if (fetch != null) {
        if (!configurer.allowFetchNoRows() && fetch instanceof SqlNumericLiteral)
            if (((SqlNumericLiteral) fetch).toValue().equals("0"))
                fetch = SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO);

        this.newlineAndIndent();
        final Frame fetchFrame = this.startList(FrameTypeEnum.FETCH);
        this.keyword("FETCH");
        this.keyword("NEXT");
        fetch.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.keyword("ONLY");
        this.endList(fetchFrame);
    }
}
 
Example 7
Source Project: kylin   Source File: ConvSqlWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void doWriteFetchNext(SqlNode fetch, SqlNode offset) {
    if (offset == null && !configurer.allowNoOffset())
        offset = SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO);

    if (fetch != null && !configurer.allowNoOrderByWithFetch() && lastFrame != null
            && lastFrame.getFrameType() != FrameTypeEnum.ORDER_BY_LIST) { // MSSQL requires ORDER_BY list for FETCH clause, so must append one here.
        DUMMY_ORDER_BY_NODE.unparse(this, 0, 0);
    }

    if (offset != null) {
        this.newlineAndIndent();
        final Frame offsetFrame = this.startList(FrameTypeEnum.OFFSET);
        this.keyword("OFFSET");
        offset.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.endList(offsetFrame);
    }
    if (fetch != null) {
        if (!configurer.allowFetchNoRows() && fetch instanceof SqlNumericLiteral)
            if (((SqlNumericLiteral) fetch).toValue().equals("0"))
                fetch = SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO);

        this.newlineAndIndent();
        final Frame fetchFrame = this.startList(FrameTypeEnum.FETCH);
        this.keyword("FETCH");
        this.keyword("NEXT");
        fetch.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.keyword("ONLY");
        this.endList(fetchFrame);
    }
}
 
Example 8
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SqlNode convert(PrecedenceClimbingParser.Token token) {
  switch (token.type) {
  case ATOM:
    return (SqlNode) token.o;
  case CALL:
    final PrecedenceClimbingParser.Call call =
        (PrecedenceClimbingParser.Call) token;
    final List<SqlNode> list = new ArrayList<>();
    for (PrecedenceClimbingParser.Token arg : call.args) {
      list.add(convert(arg));
    }
    final ToTreeListItem item = (ToTreeListItem) call.op.o;
    if (item.op == SqlStdOperatorTable.UNARY_MINUS
        && list.size() == 1
        && list.get(0) instanceof SqlNumericLiteral) {
      return SqlLiteral.createNegative((SqlNumericLiteral) list.get(0),
          item.pos.plusAll(list));
    }
    if (item.op == SqlStdOperatorTable.UNARY_PLUS
        && list.size() == 1
        && list.get(0) instanceof SqlNumericLiteral) {
      return list.get(0);
    }
    return item.op.createCall(item.pos.plusAll(list), list);
  default:
    throw new AssertionError(token);
  }
}
 
Example 9
Source Project: calcite   Source File: SqlStdOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  call.operand(0).unparse(writer, this.getLeftPrec(), this.getRightPrec());
  int startNum = ((SqlNumericLiteral) call.operand(1)).intValue(true);
  SqlNumericLiteral endRepNum = call.operand(2);
  boolean isReluctant = ((SqlLiteral) call.operand(3)).booleanValue();
  int endNum = endRepNum.intValue(true);
  if (startNum == endNum) {
    writer.keyword("{ " + startNum + " }");
  } else {
    if (endNum == -1) {
      if (startNum == 0) {
        writer.keyword("*");
      } else if (startNum == 1) {
        writer.keyword("+");
      } else {
        writer.keyword("{ " + startNum + ", }");
      }
    } else {
      if (startNum == 0 && endNum == 1) {
        writer.keyword("?");
      } else if (startNum == -1) {
        writer.keyword("{ , " + endNum + " }");
      } else {
        writer.keyword("{ " + startNum + ", " + endNum + " }");
      }
    }
    if (isReluctant) {
      writer.keyword("?");
    }
  }
}
 
Example 10
Source Project: incubator-pinot   Source File: RequestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Expression getLiteralExpression(SqlLiteral node) {
  Expression expression = new Expression(ExpressionType.LITERAL);
  Literal literal = new Literal();
  if (node instanceof SqlNumericLiteral) {
    if (((SqlNumericLiteral) node).isInteger()) {
      literal.setLongValue(node.bigDecimalValue().longValue());
    } else {
      literal.setDoubleValue(node.bigDecimalValue().doubleValue());
    }
  } else {
    literal.setStringValue(node.toString().replaceAll("^'|'$", "").replace("''", "'"));
  }
  expression.setLiteral(literal);
  return expression;
}
 
Example 11
Source Project: Bats   Source File: SqlAnalyzeTable.java    License: Apache License 2.0 4 votes vote down vote up
public SqlCall createCall(SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) {
  Preconditions.checkArgument(operands.length == 4, "SqlAnalyzeTable.createCall() has to get 4 operands!");
  return new SqlAnalyzeTable(pos, (SqlIdentifier) operands[0], (SqlLiteral) operands[1],
      (SqlNodeList) operands[2], (SqlNumericLiteral) operands[3]
  );
}
 
Example 12
Source Project: Bats   Source File: DrillAvgVarianceConvertlet.java    License: Apache License 2.0 4 votes vote down vote up
private SqlNode expandVariance(
    final SqlNode arg,
    boolean biased,
    boolean sqrt) {
  /* stddev_pop(x) ==>
   *   power(
   *    (sum(x * x) - sum(x) * sum(x) / count(x))
   *    / count(x),
   *    .5)

   * stddev_samp(x) ==>
   *  power(
   *    (sum(x * x) - sum(x) * sum(x) / count(x))
   *    / (count(x) - 1),
   *    .5)

   * var_pop(x) ==>
   *    (sum(x * x) - sum(x) * sum(x) / count(x))
   *    / count(x)

   * var_samp(x) ==>
   *    (sum(x * x) - sum(x) * sum(x) / count(x))
   *    / (count(x) - 1)
   */
  final SqlParserPos pos = SqlParserPos.ZERO;

  // cast the argument to double
  final SqlNode castHighArg = CastHighOp.createCall(pos, arg);
  final SqlNode argSquared =
      SqlStdOperatorTable.MULTIPLY.createCall(pos, castHighArg, castHighArg);
  final SqlNode sumArgSquared =
      DrillCalciteSqlAggFunctionWrapper.SUM.createCall(pos, argSquared);
  final SqlNode sum =
      DrillCalciteSqlAggFunctionWrapper.SUM.createCall(pos, castHighArg);
  final SqlNode sumSquared =
      SqlStdOperatorTable.MULTIPLY.createCall(pos, sum, sum);
  final SqlNode count =
      SqlStdOperatorTable.COUNT.createCall(pos, castHighArg);
  final SqlNode avgSumSquared =
      SqlStdOperatorTable.DIVIDE.createCall(
          pos, sumSquared, count);
  final SqlNode diff =
      SqlStdOperatorTable.MINUS.createCall(
          pos, sumArgSquared, avgSumSquared);
  final SqlNode denominator;
  if (biased) {
    denominator = count;
  } else {
    final SqlNumericLiteral one =
        SqlLiteral.createExactNumeric("1", pos);
    denominator =
        SqlStdOperatorTable.MINUS.createCall(
            pos, count, one);
  }
  final SqlNode diffAsDouble =
      CastHighOp.createCall(pos, diff);
  final SqlNode div =
      SqlStdOperatorTable.DIVIDE.createCall(
          pos, diffAsDouble, denominator);
  SqlNode result = div;
  if (sqrt) {
    final SqlNumericLiteral half =
        SqlLiteral.createExactNumeric("0.5", pos);
    result =
        SqlStdOperatorTable.POWER.createCall(pos, div, half);
  }
  return result;
}
 
Example 13
Source Project: quark   Source File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
public int executeAlterDataSource(SqlAlterQuarkDataSource sqlNode) throws SQLException {
  DBI dbi = getDbi();
  DataSourceDAO dataSourceDAO = dbi.onDemand(DataSourceDAO.class);
  JdbcSourceDAO jdbcDAO = dbi.onDemand(JdbcSourceDAO.class);
  QuboleDbSourceDAO quboleDAO = dbi.onDemand(QuboleDbSourceDAO.class);
  DataSource dataSource = jdbcDAO.findByName(sqlNode.getIdentifier().getSimple(),
      connection.getDSSet().getId());
  if (dataSource == null) {
    dataSource = quboleDAO.findByName(sqlNode.getIdentifier().getSimple(),
        connection.getDSSet().getId());
  }
  if (dataSource == null) {
    return 0;
  }
  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  int i = 0;
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "name":
          dataSource.setName(rowList.get(i).toString());
          break;
        case "type":
          dataSource.setType(rowList.get(i).toString());
          break;
        case "url":
          dataSource.setUrl(rowList.get(i).toString());
          break;
        case "ds_set_id":
          break;
        case "datasource_type":
          dataSource.setDatasourceType(rowList.get(i).toString());
          break;
        case "username":
          if (dataSource instanceof JdbcSource) {
            ((JdbcSource) dataSource)
                .setUsername(rowList.get(i).toString());
          }
          break;
        case "password":
          if (dataSource instanceof JdbcSource) {
            ((JdbcSource) dataSource)
                .setPassword(rowList.get(i).toString());
          }
          break;
        case "dbtap_id":
          if (dataSource instanceof QuboleDbSource) {
            if (rowList.get(i) instanceof SqlNumericLiteral) {
              ((QuboleDbSource) dataSource).setDbTapId(
                  ((SqlNumericLiteral) rowList.get(i)).intValue(true));
            } else {
              throw new SQLException("Incorrect argument type to variable"
                  + " 'dbtap_id'");
            }
          }
          break;
        case "auth_token":
          if (dataSource instanceof QuboleDbSource) {
            ((QuboleDbSource) dataSource)
                .setAuthToken(rowList.get(i).toString());
          }
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  Encrypt encrypt;
  if (Boolean.parseBoolean(info.getProperty("encrypt", "false"))) {
    encrypt = new AESEncrypt(info.getProperty("encryptionKey"));
  } else {
    encrypt = new NoopEncrypt();
  }
  if (dataSource instanceof JdbcSource) {
    return jdbcDAO.update((JdbcSource) dataSource, dataSourceDAO, encrypt);
  } else {
    return quboleDAO.update((QuboleDbSource) dataSource, dataSourceDAO, encrypt);
  }
}
 
Example 14
Source Project: quark   Source File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
private int executeCreateDataSource(SqlCreateQuarkDataSource sqlNode) throws SQLException {
  DBI dbi = getDbi();

  Map<String, Object> commonColumns = new HashMap<>();
  Map<String, Object> dbSpecificColumns = new HashMap<>();
  DataSourceDAO dataSourceDAO = dbi.onDemand(DataSourceDAO.class);
  JdbcSourceDAO jdbcSourceDAO = null;
  QuboleDbSourceDAO quboleDbSourceDAO = null;

  int i = 0;
  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "type":
          commonColumns.put("type", rowList.get(i).toString());
          break;
        case "url":
          commonColumns.put("url", rowList.get(i).toString());
          break;
        case "ds_set_id":
          break;
        case "datasource_type":
          if (rowList.get(i).toString().toUpperCase().equals("JDBC")) {
            jdbcSourceDAO = dbi.onDemand(JdbcSourceDAO.class);
          } else if (rowList.get(i).toString().toUpperCase().equals("QUBOLEDB")) {
            quboleDbSourceDAO = dbi.onDemand(QuboleDbSourceDAO.class);
          } else {
            throw new SQLException("Incorrect argument type <" + rowList.get(i).toString()
                + "> to variable 'datasource_type'");
          }
          commonColumns.put("datasource_type", rowList.get(i).toString());
          break;
        case "username":
          dbSpecificColumns.put("username", rowList.get(i).toString());
          break;
        case "password":
          dbSpecificColumns.put("password", rowList.get(i).toString());
          break;
        case "dbtap_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            dbSpecificColumns.put("dbtap_id",
                ((SqlNumericLiteral) rowList.get(i)).intValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable"
                + " 'dbtap_id'");
          }
          break;
        case "auth_token":
          dbSpecificColumns.put("auth_token", rowList.get(i).toString());
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  Encrypt encrypt;
  if (Boolean.parseBoolean(info.getProperty("encrypt", "false"))) {
    encrypt = new AESEncrypt(info.getProperty("encryptionKey"));
  } else {
    encrypt = new NoopEncrypt();
  }

  if ((jdbcSourceDAO == null && quboleDbSourceDAO == null)
      || (jdbcSourceDAO != null && quboleDbSourceDAO != null)) {
    throw new RuntimeException("Need to pass exact values to create"
        + " data source of type jdbc or quboleDb");
  } else if (jdbcSourceDAO != null) {
    return dataSourceDAO.insertJDBC((String) sqlNode.getIdentifier().getSimple(),
        (String) commonColumns.get("type"),
        (String) commonColumns.get("url"),
        connection.getDSSet().getId(),
        (String) commonColumns.get("datasource_type"),
        jdbcSourceDAO,
        (String) dbSpecificColumns.get("username"),
        (dbSpecificColumns.get("password") == null) ? ""
            : (String) dbSpecificColumns.get("password"),
        encrypt);
  } else {
    return dataSourceDAO.insertQuboleDB((String) sqlNode.getIdentifier().getSimple(),
        (String) commonColumns.get("type"),
        (String) commonColumns.get("url"),
        connection.getDSSet().getId(),
        (String) commonColumns.get("datasource_type"),
        quboleDbSourceDAO,
        (int) dbSpecificColumns.get("dbtap_id"),
        (String) dbSpecificColumns.get("auth_token"),
        encrypt);
  }
}
 
Example 15
Source Project: quark   Source File: QuarkDDLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
public int executeAlterView(SqlAlterQuarkView sqlNode) throws SQLException {
  DBI dbi = getDbi();
  ViewDAO viewDAO = dbi.onDemand(ViewDAO.class);

  View view = viewDAO.findByName(sqlNode.getIdentifier().getSimple(),
      connection.getDSSet().getId());
  if (view == null) {
    return 0;
  }

  SqlNodeList rowList = sqlNode.getSourceExpressionList();
  int i = 0;
  for (SqlNode node : sqlNode.getTargetColumnList()) {
    if (node instanceof SqlIdentifier) {
      switch (((SqlIdentifier) node).getSimple()) {
        case "name":
          view.setName(rowList.get(i).toString());
          break;
        case "description":
          view.setDescription(rowList.get(i).toString());
          break;
        case "query":
          view.setQuery(rowList.get(i).toString());
          break;
        case "schema_name":
          view.setSchema(rowList.get(i).toString());
          break;
        case "table_name":
          view.setTable(rowList.get(i).toString());
          break;
        case "ds_set_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setDsSetId(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'ds_set_id'");
          }
          break;
        case "cost":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setCost(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'cost'");
          }
          break;
        case "destination_id":
          if (rowList.get(i) instanceof SqlNumericLiteral) {
            view.setDestinationId(((SqlNumericLiteral) rowList.get(i)).longValue(true));
          } else {
            throw new SQLException("Incorrect argument type to variable 'destination_id'");
          }
          break;
        default:
          throw new SQLException("Unknown parameter: " + ((SqlIdentifier) node).getSimple());
      }
      i++;
    }
  }

  return viewDAO.update(view, connection.getDSSet().getId());
}