Handles bulk deletions of a range of annotations (local or global) using
query string or body data
@param tsdb The TSD to which we belong
@param query The query to parse and respond to
10855
void executeBulkDelete(final TSDB tsdb, HttpQuery query) {
    try {
      final AnnotationBulkDelete delete_request;
      if (query.hasContent()) {
        delete_request = query.serializer().parseAnnotationBulkDeleteV1();
      } else {
        delete_request = parseBulkDeleteQS(query);
      }
      
      // validate the start time on the string. Users could request a timestamp of
      // 0 to delete all annotations, BUT we don't want them doing that accidentally
      if (delete_request.start_time == null || delete_request.start_time.isEmpty()) {
        throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, 
            "Missing the start time value");
      }
      if (!delete_request.global && 
          (delete_request.tsuids == null || delete_request.tsuids.isEmpty())) {
        throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, 
            "Missing the TSUIDs or global annotations flag");
      }
      
      final int pre_allocate = delete_request.tsuids != null ? 
          delete_request.tsuids.size() + 1 : 1;
      List<Deferred<Integer>> deletes = new ArrayList<Deferred<Integer>>(pre_allocate);
      if (delete_request.global) {
        deletes.add(Annotation.deleteRange(tsdb, null, 
            delete_request.getStartTime(), delete_request.getEndTime()));
      }
      if (delete_request.tsuids != null) {
        for (String tsuid : delete_request.tsuids) {
          deletes.add(Annotation.deleteRange(tsdb, UniqueId.stringToUid(tsuid), 
              delete_request.getStartTime(), delete_request.getEndTime()));
        }
      }
      
      Deferred.group(deletes).joinUninterruptibly();
      delete_request.total_deleted = 0; // just in case the caller set it
      for (Deferred<Integer> count : deletes) {
        delete_request.total_deleted += count.joinUninterruptibly();
      }
      query.sendReply(query.serializer()
          .formatAnnotationBulkDeleteV1(delete_request));
    } catch (BadRequestException e) {
      throw e;
    } catch (IllegalArgumentException e) {
      throw new BadRequestException(e);
    } catch (RuntimeException e) {
      throw new BadRequestException(e);
    } catch (Exception e) {
      throw new RuntimeException("Shouldn't be here", e);
    }
  }
671914
private void validateSelectQuery(final String selectQuery) {
        final SimpleDBParser parser = new SimpleDBParser(selectQuery);
        try {
            parser.selectQuery();
        } catch (Exception e) {
            throw new InvalidSimpleDBQueryException("The following query is an invalid SimpleDB query: " + selectQuery,
                    e);
        }
    }
960222
@Override
  public void execute(final TSDB tsdb, final HttpQuery query)
          throws IOException {
    http_requests.incrementAndGet();
    
    // only accept POST
    if (query.method() != HttpMethod.POST) {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED,
          "Method not allowed", "The HTTP method [" + query.method().getName() +
          "] is not permitted for this endpoint");
    }

    final List<RollUpDataPoint> dps = query.serializer()
        .parsePutV1(RollUpDataPoint.class, HttpJsonSerializer.TR_ROLLUP);
    processDataPoint(tsdb, query, dps);
  }
882928
private void executeQuery(
      long index,
      long sequence,
      long timestamp,
      RaftSession session,
      PrimitiveOperation operation,
      CompletableFuture<OperationResult> future) {
    // If the service has been deleted then throw an unknown service exception.
    if (deleted) {
      log.warn("Service {} has been deleted by another process", serviceName);
      future.completeExceptionally(new RaftException.UnknownService("Service " + serviceName + " has been deleted"));
      return;
    }

    // If the session is not open, fail the request.
    if (!session.getState().active()) {
      log.warn("Inactive session: " + session.sessionId());
      future.completeExceptionally(new RaftException.UnknownSession("Unknown session: " + session.sessionId()));
      return;
    }

    // Otherwise, sequence the query.
    sequenceQuery(index, sequence, timestamp, session, operation, future);
  }
212659
public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeQuery: " + query);
        }
        /*
		 * MBAIRD: we should create a scrollable resultset if the start at
		 * index or end at index is set
		 */
        boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));
        /*
		 * OR if the prefetching of relationships is being used.
		 */
        if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())
        {
            scrollable = true;
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try
        {
            final int queryFetchSize = query.getFetchSize();
            final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());
            stmt = sm.getPreparedStatement(cld, sql.getStatement() ,
                    scrollable, queryFetchSize, isStoredProcedure);
            if (isStoredProcedure)
            {
                // Query implemented as a stored procedure, which must return a result set.
                // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
                getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
                sm.bindStatement(stmt, query, cld, 2);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                stmt.execute();
                rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
            }
            else
            {
                sm.bindStatement(stmt, query, cld, 1);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                rs = stmt.executeQuery();
            }

            return new ResultSetAndStatement(sm, stmt, rs, sql);
        }
        catch (PersistenceBrokerException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            logger.error("PersistenceBrokerException during the execution of the query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);
        }
    }
141146
public JSONObject deleteBy(Query query, RequestOptions requestOptions) throws AlgoliaException {
    String paramsString = query.getQueryString();
    JSONObject body = new JSONObject();
    try {
      body.put("params", paramsString);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }
    return client.postRequest("/1/indexes/" + encodedIndexName + "/deleteByQuery", body.toString(), false, false, requestOptions);
  }
17359
public void search(String query) {
        final Query newQuery = searcher.getQuery().setQuery(query);
        searcher.setQuery(newQuery).search();
    }
882377
@Override
	public final void deleteTemporaryTopic(String topicName) throws JMSException
    {
        DeleteTemporaryTopicQuery query = new DeleteTemporaryTopicQuery();
        query.setTopicName(topicName);
        transportEndpoint.blockingRequest(query);
    }
986917
@SuppressWarnings("unchecked")
    @Override
    public <R> R query(TemporalQuery<R> query) {
        if (query == TemporalQueries.chronology()) {
            return (R) getChronology();
        } else if (query == TemporalQueries.precision()) {
            return (R) NANOS;
        } else if (query == TemporalQueries.localDate()) {
            return (R) LocalDate.ofEpochDay(toLocalDate().toEpochDay());
        } else if (query == TemporalQueries.localTime()) {
            return (R) toLocalTime();
        } else if (query == TemporalQueries.zone() || query == TemporalQueries.zoneId() || query == TemporalQueries.offset()) {
            return null;
        }
        return super.query(query);
    }
278492
def delete_by_query(query)
      rsp = post("<delete><query>#{query}</query></delete>")
      success?(rsp.body) or log_error(rsp.body)
    end
711033
@Override
  public DataPoints[] evaluate(TSQuery data_query, List<DataPoints[]> results, List<String> params) {
    //not 100% sure what to do here -> do I need to think of the case where I have no data points
    if (results == null || results.isEmpty()) {
      return new DataPoints[]{};
    }
    if (params == null || params.isEmpty()) {
      throw new IllegalArgumentException("Need amount of timeshift to perform timeshift");
    }

    String param = params.get(0);
    if (param == null || param.length() == 0) {
      throw new IllegalArgumentException("Invalid timeshift='" + param + "'");
    }

    param = param.trim();

    long timeshift = -1;
    if (param.startsWith("'") && param.endsWith("'")) {
      timeshift = parseParam(param);
    } else {
      throw new RuntimeException("Invalid timeshift parameter: eg '10min'");
    }

    if (timeshift <= 0) {
      throw new RuntimeException("timeshift <= 0");
    }

    return performShift(results.get(0), timeshift);
  }
542296
private TSMeta parseTSMetaQS(final HttpQuery query) {
    final String tsuid = query.getQueryStringParam("tsuid");
    final TSMeta meta;
    if (tsuid != null && !tsuid.isEmpty()) {
      meta = new TSMeta(tsuid);
    } else {
      meta = new TSMeta();
    }
    
    final String display_name = query.getQueryStringParam("display_name");
    if (display_name != null) {
      meta.setDisplayName(display_name);
    }
  
    final String description = query.getQueryStringParam("description");
    if (description != null) {
      meta.setDescription(description);
    }
    
    final String notes = query.getQueryStringParam("notes");
    if (notes != null) {
      meta.setNotes(notes);
    }
    
    final String units = query.getQueryStringParam("units");
    if (units != null) {
      meta.setUnits(units);
    }
    
    final String data_type = query.getQueryStringParam("data_type");
    if (data_type != null) {
      meta.setDataType(data_type);
    }
    
    final String retention = query.getQueryStringParam("retention");
    if (retention != null && !retention.isEmpty()) {
      try {
        meta.setRetention(Integer.parseInt(retention));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'retention' value");
      }
    }
    
    final String max = query.getQueryStringParam("max");
    if (max != null && !max.isEmpty()) {
      try {
        meta.setMax(Float.parseFloat(max));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'max' value");
      }
    }
    
    final String min = query.getQueryStringParam("min");
    if (min != null && !min.isEmpty()) {
      try {
        meta.setMin(Float.parseFloat(min));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'min' value");
      }
    }
    
    return meta;
  }
141927
function (state, payload) {
        if (payload && payload.entity) {
            (new Query(state, payload.entity)).deleteAll();
            return;
        }
        Query.deleteAll(state);
    }
824171
@Override
  protected void deleteEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    // get statement
    String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass());
    ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement);

    LOG.executeDatabaseOperation("DELETE", dbEntity);

    // execute the delete
    int nrOfRowsDeleted = executeDelete(deleteStatement, dbEntity);
    operation.setRowsAffected(nrOfRowsDeleted);

    // It only makes sense to check for optimistic locking exceptions for objects that actually have a revision
    if (dbEntity instanceof HasDbRevision && nrOfRowsDeleted == 0) {
      operation.setFailed(true);
      return;
    }

    // perform post delete action
    entityDeleted(dbEntity);
  }
446353
private void cleanupQueryStates() {
        completeRequestSpan(currentRequest());
        finishedDecoding();
        queryInfoObservable = null;
        queryRowObservable = null;
        queryErrorObservable = null;
        queryStatusObservable = null;
        querySignatureObservable = null;
        queryParsingState = QUERY_STATE_INITIAL;
    }
784957
public Integer executeDeletePost(Query query) throws ApiException {
        ApiResponse<Integer> resp = executeDeletePostWithHttpInfo(query);
        return resp.getData();
    }
126114
private void handleExpressionQuery(final TSDB tsdb, final HttpQuery query) {
    final net.opentsdb.query.pojo.Query v2_query = 
        JSON.parseToObject(query.getContent(), net.opentsdb.query.pojo.Query.class);
    v2_query.validate();

    checkAuthorization(tsdb, query.channel(), v2_query);

    final QueryExecutor executor = new QueryExecutor(tsdb, v2_query);
    executor.execute(query);
  }