Write the results of the query.

@param server
@param query   - the query and its results.
@param results
489969
@Override
	public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
		this.startOutput();
		for (String formattedResult : messageFormatter.formatResults(results, server)) {
				log.debug("Sending result: {}", formattedResult);
				this.sendOutput(formattedResult);
		}
		this.finishOutput();
	}
85855
private void printQueryStats(final HttpQuery query) {
    switch (query.apiVersion()) {
    case 0:
    case 1:
      query.sendReply(query.serializer().formatQueryStatsV1(
          QueryStats.getRunningAndCompleteStats()));
      break;
    default: 
      throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
          "Requested API version not implemented", "Version " + 
          query.apiVersion() + " is not implemented");
    }
  }
1359781
public synchronized void setWriteServer(final Server writeServer) {
        logger.debug("[setWriteServer] uri = {}", (writeServer == null) ? "NULL" : writeServer.getDataUri());

        if (this.writeServer != null && writeServer != null && this.writeServer.equals(writeServer)) return;

        this.writeServer = writeServer;
        refreshServers();
    }
874462
function(s_query) {

			// execute function
			var f_exec = function(f_okay) {
				submit_query(s_query, f_okay);
			};

			var d_self = {
				exec: f_exec,
				results: function(f_okay) {
					f_exec(function(h_res) {
						f_okay && f_okay(h_res.results.bindings);
					});
				},
				each: function(f_each, f_okay) {
					f_exec(function(h_res) {
						if(!f_each) return;
						var a_rows = h_res.results.bindings;
						for(var i=0,l=a_rows.length; i<l; i++) {
							var h_row = a_rows[i];
							var h_this = {};
							for(var e in h_row) h_this[e] = h_row[e].value;
							f_each.apply(h_this, [i, h_row]);
						}
						f_okay && f_okay();
					});
				},
			};

			return d_self;
		}
240534
function Query(server, query, options, token) {
  this.server = server;
  this.query = query;
  // Used to track the presence of r.args (workaround)
  this.originalQuery = util.deepCopy(query);
  this.options = {};
  this.context = {};
  this.frames = [];
  this.nowValue = ReqlDate.now();
  this.complete = false;
  this.token = token;

}
581371
@Override
    public void write(Iterable<QueryResult> results) {
        logger.debug("Export to '{}' results {}", graphiteHttpUrl, results);
        HttpURLConnection urlConnection = null;
        OutputStreamWriter urlWriter;
        try {
            StringBuilder sbUrlWriter = new StringBuilder("");
            for (QueryResult result : results) {
                String msg = metricPathPrefix + result.getName() + " " + result.getValue() + " " + result.getEpoch(TimeUnit.SECONDS) + "\n";
                logger.debug("Export '{}'", msg);
                sbUrlWriter.append(msg);
            }
            if (sbUrlWriter.length() > 0) {
                sbUrlWriter.insert(0, "data=");
                urlConnection = (HttpURLConnection) graphiteHttpUrl.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlWriter = new OutputStreamWriter(urlConnection.getOutputStream(), Charset.forName("UTF-8"));
                urlWriter.write(sbUrlWriter.toString());
                urlWriter.flush();
                IoUtils2.closeQuietly(urlWriter);
                int responseCode = urlConnection.getResponseCode();
                if (responseCode != 200) {
                    logger.warn("Failure {}:'{}' to send result to Graphite HTTP proxy'{}' ", responseCode, urlConnection.getResponseMessage(), graphiteHttpUrl);
                }
                if (logger.isTraceEnabled()) {
                    IoUtils2.copy(urlConnection.getInputStream(), System.out);
                }
            }
        } catch (Exception e) {
            logger.warn("Failure to send result to Graphite HTTP proxy '{}'", graphiteHttpUrl, e);
        } finally {
            // Release the connection.
            if (urlConnection != null) {
                try {
                    InputStream in = urlConnection.getInputStream();
                    IoUtils2.copy(in, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(in);
                    InputStream err = urlConnection.getErrorStream();
                    if (err != null) {
                        IoUtils2.copy(err, IoUtils2.nullOutputStream());
                        IoUtils2.closeQuietly(err);
                    }
                } catch (IOException e) {
                    logger.warn("Exception flushing http connection", e);
                }
            }
        }
    }
736973
private List<Entity> runQuery(Query query) throws DatastoreException {
    RunQueryRequest.Builder request = RunQueryRequest.newBuilder();
    request.setQuery(query);
    RunQueryResponse response = datastore.runQuery(request.build());

    if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {
      System.err.println("WARNING: partial results\n");
    }
    List<EntityResult> results = response.getBatch().getEntityResultsList();
    List<Entity> entities = new ArrayList<Entity>(results.size());
    for (EntityResult result : results) {
      entities.add(result.getEntity());
    }
    return entities;
  }
1192202
public boolean execute(Map<String, String> params, String query) {
        final AtomicBoolean result = new AtomicBoolean(false);
        Tuple2<DataSource, Connection> conn = null;
        try {
            conn = getConnection();
            NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
            jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
                @Override
                public Void doInPreparedStatement(PreparedStatement ps) {
                    try {
                        result.set(ps.execute());
                    } catch(SQLException e) {
                        result.set(false);
                    }
                    return null;
                }
            });
        } catch (Exception ex) {
            Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex);
            result.set(false);
        } finally {
            returnConnection(conn);
        }
        return result.get();
    }
949743
public void delete(Query query) {
        Log.debug("Deleting by query %s", query);
        try {
            indexWriter.deleteDocuments(query);
        } catch (IOException e) {
            Log.error(e, "Error while deleting by query %s", query);
            throw new RuntimeException(e);
        }
    }
122004
public PaginatedResult execute(final Query query) {
        final long count = getCount(query);
        decorate(query);
        return new PaginatedResult()
                .objects(query.execute())
                .total(count);
    }
938471
private void returnResults() {
    final StringBuilder sb = new StringBuilder();
    for (final String result : this.results) {
      sb.append(result);
    }
    this.results.clear();
    LOG.log(Level.INFO, "Return results to the client:\n{0}", sb);
    httpCallbackHandler.onNext(CODEC.encode(sb.toString()));
  }
825951
private void executeBatchMulti(Results results, final ClientPrepareResult clientPrepareResult,
      final List<ParameterHolder[]> parametersList) throws SQLException {

    cmdPrologue();
    initializeBatchReader();
    new AbstractMultiSend(this, writer, results, clientPrepareResult, parametersList) {

      @Override
      public void sendCmd(PacketOutputStream writer, Results results,
          List<ParameterHolder[]> parametersList, List<String> queries, int paramCount,
          BulkStatus status,
          PrepareResult prepareResult)
          throws IOException {

        ParameterHolder[] parameters = parametersList.get(status.sendCmdCounter);
        writer.startPacket(0);
        ComQuery.sendSubCmd(writer, clientPrepareResult, parameters, -1);
        writer.flush();
      }


      @Override
      public SQLException handleResultException(SQLException qex, Results results,
          List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter,
          int sendCmdCounter, int paramCount, PrepareResult prepareResult) {

        int counter = results.getCurrentStatNumber() - 1;
        ParameterHolder[] parameters = parametersList.get(counter);
        List<byte[]> queryParts = clientPrepareResult.getQueryParts();
        StringBuilder sql = new StringBuilder(new String(queryParts.get(0)));

        for (int i = 0; i < paramCount; i++) {
          sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 1)));
        }

        return logQuery.exceptionWithQuery(sql.toString(), qex, explicitClosed);
      }


      @Override
      public int getParamCount() {
        return clientPrepareResult.getQueryParts().size() - 1;
      }


      @Override
      public int getTotalExecutionNumber() {
        return parametersList.size();
      }

    }.executeBatch();

  }
1113876
public ExecutionResult execute(String query) {
        ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                .query(query)
                .build();
        return execute(executionInput);
    }
618722
public void execute(final HttpQuery query) {
    http_query = query;
    final QueryStats query_stats = 
        new QueryStats(query.getRemoteAddress(), ts_query, query.getHeaders());
    ts_query.setQueryStats(query_stats);
    
    /**
     * Sends the serialized results to the caller. This should be the very
     * last callback executed.
     */
    class CompleteCB implements Callback<Object, ChannelBuffer> {
      @Override
      public Object call(final ChannelBuffer cb) throws Exception {
        query.sendReply(cb);
        return null;
      }
    }
    
    /**
     * After all of the queries have run and we have data (or not) then we
     * need to compile the iterators.
     * This class could probably be improved:
     * First we iterate over the results AND for each result, iterate over
     * the expressions, giving a time synced iterator to each expression that 
     * needs the result set.
     * THEN we iterate over the expressions again and build a DAG to determine
     * if any of the expressions require the output of an expression. If so
     * then we add the expressions to the proper parent and compile them in
     * order.
     * After all of that we're ready to start serializing and iterating
     * over the results.
     */
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
      public Object call(final ArrayList<DataPoints[]> query_results) 
        throws Exception {
        
        for (int i = 0; i < query_results.size(); i++) {
          final TSSubQuery sub = ts_query.getQueries().get(i);
          
          Iterator<Entry<String, TSSubQuery>> it = sub_queries.entrySet().iterator();
          while (it.hasNext()) {
            final Entry<String, TSSubQuery> entry = it.next();
            if (entry.getValue().equals(sub)) {
              sub_query_results.put(entry.getKey(), query_results.get(i));
              for (final ExpressionIterator ei : expressions.values()) {
                if (ei.getVariableNames().contains(entry.getKey())) {
                  final TimeSyncedIterator tsi = new TimeSyncedIterator(
                      entry.getKey(), sub.getFilterTagKs(), 
                      query_results.get(i));
                  final NumericFillPolicy fill = fills.get(entry.getKey());
                  if (fill != null) {
                    tsi.setFillPolicy(fill);
                  }
                  ei.addResults(entry.getKey(), tsi);
                  if (LOG.isDebugEnabled()) {
                    LOG.debug("Added results for " + entry.getKey() + 
                        " to " + ei.getId());
                  }
                }
              }
            }
          }
        }

        // handle nested expressions
        final DirectedAcyclicGraph<String, DefaultEdge> graph = 
            new DirectedAcyclicGraph<String, DefaultEdge>(DefaultEdge.class);

        for (final Entry<String, ExpressionIterator> eii : expressions.entrySet()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression entry key is %s, value is %s", 
                eii.getKey(), eii.getValue().toString()));
            LOG.debug(String.format("Time to loop through the variable names "
                + "for %s", eii.getKey()));
          }

          if (!graph.containsVertex(eii.getKey())) {
            if (LOG.isDebugEnabled()) {
              LOG.debug("Adding vertex " + eii.getKey());
            }
            graph.addVertex(eii.getKey());
          }

          for (final String var : eii.getValue().getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("var is %s", var));
            }

            final ExpressionIterator ei = expressions.get(var);

            if (ei != null) {
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The expression iterator for %s is %s", 
                    var, ei.toString()));
              }

              // TODO - really ought to calculate this earlier
              if (eii.getKey().equals(var)) {
                throw new IllegalArgumentException(
                    "Self referencing expression found: " + eii.getKey());
              }

              if (LOG.isDebugEnabled()) {
                LOG.debug("Nested expression detected. " + eii.getKey() + 
                    " depends on " + var);
              }

              if (!graph.containsVertex(eii.getKey())) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + eii.getKey());
                }
                graph.addVertex(eii.getKey());
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + eii.getKey());
              }

              if (!graph.containsVertex(var)) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + var);
                }
                graph.addVertex(var);
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + var);
              }

              try {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added Edge " + eii.getKey() + " - " + var);
                }
                graph.addDagEdge(eii.getKey(), var);
              } catch (CycleFoundException cfe) {
                throw new IllegalArgumentException("Circular reference found: " + 
                    eii.getKey(), cfe);
              }
            } else if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("The expression iterator for %s is null", var));
            }
          }
        }

        // compile all of the expressions
        final long intersect_start = DateTime.currentTimeMillis();

        final Integer expressionLength = expressions.size();
        final ExpressionIterator[] compile_stack = 
            new ExpressionIterator[expressionLength];
        final TopologicalOrderIterator<String, DefaultEdge> it = 
            new TopologicalOrderIterator<String, DefaultEdge>(graph);

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("Expressions Size is %d", expressionLength));
          LOG.debug(String.format("Topology Iterator %s", it.toString()));
        }

        int i = 0;
        while (it.hasNext()) {
          String next = it.next();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression: %s", next));
          }
          ExpressionIterator ei = expressions.get(next);
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression Iterator: %s", ei.toString()));
          }
          if (ei == null) {
            LOG.error(String.format("The expression iterator for %s is null", next));
          }
          compile_stack[i] = ei;
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Added expression %s to compile_stack[%d]", 
                next, i));
          }
          i++;
        }

        if (i != expressionLength) {
          throw new IOException(String.format(" Internal Error: Fewer "
              + "expressions where added to the compile stack than "
              + "expressions.size (%d instead of %d)", i, expressionLength));
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("compile stack length: %d", compile_stack.length));
        }

        for (int x = compile_stack.length - 1; x >= 0; x--) {
          if (compile_stack[x] == null) {
            throw new NullPointerException(String.format("Item %d in "
                + "compile_stack[] is null", x));
          }
          // look for and add expressions
          for (final String var : compile_stack[x].getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("Looking for variable %s for %s", var, 
                  compile_stack[x].getId()));
            }
            ExpressionIterator source = expressions.get(var);
            if (source != null) {
              compile_stack[x].addResults(var, source.getCopy());
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("Adding expression %s to %s", 
                    source.getId(), compile_stack[x].getId()));
              }
            }
          }
          compile_stack[x].compile();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Successfully compiled %s", 
                compile_stack[x].getId()));
          }
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Finished compilations in " +
              (DateTime.currentTimeMillis() - intersect_start) + " ms");
        }
        
        return serialize()
            .addCallback(new CompleteCB())
            .addErrback(new ErrorCB());
      }
    }
    
    /**
     * Callback executed after we have resolved the metric, tag names and tag
     * values to their respective UIDs. This callback then runs the actual 
     * queries and fetches their results.
     */
    class BuildCB implements Callback<Deferred<Object>, net.opentsdb.core.Query[]> {
      @Override
      public Deferred<Object> call(final net.opentsdb.core.Query[] queries) {
        final ArrayList<Deferred<DataPoints[]>> deferreds = 
            new ArrayList<Deferred<DataPoints[]>>(queries.length);
        
        for (final net.opentsdb.core.Query query : queries) {
          deferreds.add(query.runAsync());
        }
        return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB())
            .addErrback(new ErrorCB());
      }
    }
    
    // TODO - only run the ones that will be involved in an output. Folks WILL
    // ask for stuff they don't need.... *sigh*
    ts_query.buildQueriesAsync(tsdb)
      .addCallback(new BuildCB())
      .addErrback(new ErrorCB());
  }
161470
void writeResult(final RpcResult<?, ?> result, final HttpServletResponse resp)
			throws IOException {
		if (result.isSuccess()) {
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.setContentType(JSON_CONTENT_TYPE);
		} else {
			resp.setStatus(APPLICATION_EXC_STATUS);
			resp.setContentType(JSON_CONTENT_TYPE);
		}

		PrintWriter writer = resp.getWriter();
		result.toJson(writer, true);
		writer.flush();
	}
1208363
public void exec(String sql, Object []params, Result<Object> result)
  {
    QueryBuilderKraken query = QueryParserKraken.parse(this, sql);
      
    query.build(result.then((q,r)->q.exec(r, params)));
  }
1246373
private void validateQueryResults(String query, N1qlQueryResult result)
    {
        LOGGER.debug("Query output status: " + result.finalSuccess());

        if (!result.finalSuccess())
        {
            StringBuilder errorBuilder = new StringBuilder();
            for (JsonObject obj : result.errors())
            {
                errorBuilder.append(obj.toString());
                errorBuilder.append("\n");
            }
            errorBuilder.deleteCharAt(errorBuilder.length() - 1);
            String errors = errorBuilder.toString();
            LOGGER.error(errors);
            throw new KunderaException("Not able to execute query/statement:" + query + ". More details : " + errors);
        }
    }