handleQuery handles request to execute a query.
482621
public void handleQuery(ChaincodeMessage message) {
		// Query does not transition state. It can happen anytime after Ready
		Runnable task = () -> {
			ChaincodeMessage serialSendMessage = null;
			try {
				// Get the function and args from Payload
				ChaincodeInput input;
				try {
					input = ChaincodeInput.parseFrom(message.getPayload());
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Incorrect payload format. Sending %s",
							shortID(message), QUERY_ERROR));
					serialSendMessage = ChaincodeMessage.newBuilder()
							.setType(QUERY_ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				}

				// Mark as a query (do not allow put/del state)
				markIsTransaction(message.getTxid(), false);

				// Call chaincode's Query
				// Create the ChaincodeStub which the chaincode can use to callback
				ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this, message.getSecurityContext());
				ByteString response;
				try {
					response = chaincode.queryHelper(stub, getFunction(input.getArgsList()), getParameters(input.getArgsList()));
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Query execution failed. Sending %s",
							shortID(message), QUERY_ERROR));
					serialSendMessage = ChaincodeMessage.newBuilder()
							.setType(QUERY_ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				} finally {
					deleteIsTransaction(message.getTxid());
				}

				// Send COMPLETED message to chaincode support
				logger.debug("["+ shortID(message)+"]Query completed. Sending "+ QUERY_COMPLETED);
				serialSendMessage = ChaincodeMessage.newBuilder()
						.setType(QUERY_COMPLETED)
						.setPayload(response)
						.setTxid(message.getTxid())
						.build();
			} finally {
				serialSend(serialSendMessage);
			}
		};

		new Thread(task).start();
	}
815540
public QueryResponse executeQueryPost(Query query) throws ApiException {
        ApiResponse<QueryResponse> resp = executeQueryPostWithHttpInfo(query);
        return resp.getData();
    }
651398
private void handleRequest(long requestId, Object request, HandlerHolder handler) {
    @SuppressWarnings("unchecked")
    CompletableFuture<Object> responseFuture = handler.handler.apply(request);
    if (responseFuture != null) {
      responseFuture.whenComplete((response, error) -> {
        ThreadContext context = ThreadContext.currentContext();
        if (context == null) {
          this.context.executor().execute(() -> {
            if (error == null) {
              handleRequestSuccess(requestId, response, this.context);
            } else {
              handleRequestFailure(requestId, error, this.context);
            }
          });
        } else {
          if (error == null) {
            handleRequestSuccess(requestId, response, context);
          } else {
            handleRequestFailure(requestId, error, context);
          }
        }
      });
    }
  }
645587
def _get_query(self, query, params):
        
        if "apikey" not in params:
            params["apikey"] = self.api_key

        response = requests.get(query, params=params)
        return response.json()
1304606
function runQuery(query, connection) {
  const { maxRows } = connection;
  const limit = maxRows < CRATE_LIMIT ? maxRows : CRATE_LIMIT;

  if (connection.port) {
    crate.connect(connection.host, connection.port);
  } else {
    crate.connect(connection.host);
  }

  return crate
    .execute(query)
    .then(res => {
      const results = {
        rows: res.json,
        incomplete: false
      };

      if (results.rows.length >= limit) {
        results.incomplete = true;
        results.rows = results.rows.slice(0, limit);
      }

      return results;
    })
    .catch(err => {
      throw new Error(err.message);
    });
}
755565
public <V> V executeAndFetch(ResultSetHandler<V> handler) {
        try (ResultSet rs = executeQuery()) {
            return handler.apply(rs);
        } catch (SQLException ex) {
            throw new ApplicationException(Code.BACKEND_ERROR, ex);
        }
    }
905974
function query(queryString, args, callback) {
  getClient(function (err, client) {
    if (err) { callback(err); }

    if (!client) {
      callback('Could not connect to the database');
    }
    else {
      runQuery(client, queryString, args, callback);
    }
  });
}
954051
function handleQueryParameters(request, response, next) {
	if (args.query === true && Object.keys(request.query).length > 0) {
		request.path += '/' + Object.keys(request.query).join('_') + '.json';
	}
	return next();
}
462187
def _handle_request(self, msg_id, method, params):
        """"""
        try:
            handler = self._dispatcher[method]
        except KeyError:
            raise JsonRpcMethodNotFound.of(method)

        handler_result = handler(params)

        if callable(handler_result):
            log.debug("Executing async request handler %s", handler_result)
            request_future = self._executor_service.submit(handler_result)
            self._client_request_futures[msg_id] = request_future
            request_future.add_done_callback(self._request_callback(msg_id))
        else:
            log.debug("Got result from synchronous request handler: %s", handler_result)
            self._consumer({
                'jsonrpc': JSONRPC_VERSION,
                'id': msg_id,
                'result': handler_result
            })
843228
def _process_query(self, query):
        """"""
        key, val = query
        field_name, field_action = split_field_action(key)

        # Boost by name__action overrides boost by name.
        boost = self.field_boosts.get(key)
        if boost is None:
            boost = self.field_boosts.get(field_name)

        handler_name = 'process_query_{0}'.format(field_action)

        if field_action and hasattr(self, handler_name):
            return getattr(self, handler_name)(field_name, val, field_action)

        elif field_action in QUERY_ACTION_MAP:
            return {
                QUERY_ACTION_MAP[field_action]: _boosted_value(
                    field_name, field_action, key, val, boost)
            }

        elif field_action == 'query_string':
            # query_string has different syntax, so it's handled
            # differently.
            #
            # Note: query_string queries are not boosted with
            # .boost()---they're boosted in the query text itself.
            return {
                'query_string': {'default_field': field_name, 'query': val}
            }

        elif field_action in RANGE_ACTIONS:
            # Ranges are special and have a different syntax, so
            # we handle them separately.
            return {
                'range': {field_name: _boosted_value(
                        field_action, field_action, key, val, boost)}
           }

        elif field_action == 'range':
            lower, upper = val
            value = {
                'gte': lower,
                'lte': upper,
            }
            if boost:
                value['boost'] = boost

            return {'range': {field_name: value}}

        raise InvalidFieldActionError(
            '%s is not a valid field action' % field_action)
432323
function runQuery(client, queryString, args, callback) {
  if (activeBackend === 'mysql') {
    queryString = queryString.replace(/\$\d+/, '?');
  }

  client.query(queryString, args, function (err, result) {
    if (err) {
      callback(err, null);
      return;
    }
    if (activeBackend === 'mysql') {
      callback(err, result);
    }
    else if (activeBackend === 'pgsql') {
      var rows = [];
      if (result.rows) {
        rows = result.rows;
      }
      callback(err, rows);
    }
  });
}
50616
private QueryObservable executeQuery(QueryBuilder queryBuilder) {

    // Raw query properties as default
    String sql = queryBuilder.rawStatement;
    Iterable<String> affectedTables = queryBuilder.rawStatementAffectedTables;

    // If SqlFinishedStatement is set then use that one
    if (queryBuilder.statement != null) {

      SqlCompileable.CompileableStatement compileableStatement =
          queryBuilder.statement.asCompileableStatement();

      sql = compileableStatement.sql;
      affectedTables = compileableStatement.tables;
    }

    // Check for auto update
    if (!queryBuilder.autoUpdate || affectedTables == null) {
      affectedTables = Collections.emptySet();
    }

    return db.createQuery(affectedTables, sql, queryBuilder.args);
  }
767314
def execute(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters, kwargs)

        except:
            raise

        finally:
            cursor.close()
927334
function handleGetRequest(request) {
  const objId = request.objectId;
  const className = request.className;
  if (objId) {
    // Object.fetch() query
    const collection = getCollection(className);
    const currentObject = collection[objId];
    if (!currentObject) {
      return Parse.Promise.as(respond(404, {
        code: 101,
        error: 'object not found for update',
      }));
    }
    let match = _.cloneDeep(currentObject);

    if (match) {
      const toOmit = Array.from(getMask(className));
      match = _.omit(match, toOmit);
    }

    return Parse.Promise.as(respond(200, match));
  }
  const data = request.data;
  indirect = data.redirectClassNameForKey;
  let matches = recursivelyMatch(className, data.where);
  let matchesClassName = '';
  if (indirect) {
    matches = outOfBandResults.matches;
    if (outOfBandResults.className) {
      matchesClassName = outOfBandResults.className;
    }
  }

  if (request.data.count) {
    return Parse.Promise.as(respond(200, { count: matches.length }));
  }

  matches = queryMatchesAfterIncluding(matches, data.include);

  const toOmit = Array.from(getMask(className));
  matches = matches.map((match) => _.omit(match, toOmit));

  // TODO: Can we just call toJSON() in order to avoid this?
  matches.forEach(match => {
    if (match.createdAt) {
      match.createdAt = match.createdAt.toJSON();
    }
    if (match.updatedAt) {
      match.updatedAt = match.updatedAt.toJSON();
    }
  });

  // sort results if necessary
  if (data.order && data.order.length > 0 && matches.length > 0) {
    matches = sortQueryresults(matches, data.order);
  }

  const limit = data.limit || DEFAULT_LIMIT;
  const startIndex = data.skip || 0;
  const endIndex = startIndex + limit;
  const response = { results: matches.slice(startIndex, endIndex) };

  // Add the class name for the outgoing objects to the response if sepcified
  if (matchesClassName.length > 0) {
    response.className = matchesClassName;
  }

  return Parse.Promise.as(respond(200, response));
}
488306
def handle_exc(exc):
    

    err = ERRORS_TABLE.get(exc.pgcode)

    if err:
        abort(exceptions.InvalidQueryParams(**{
            'detail': err,
            'parameter': 'filter',
        }))

    abort(exceptions.DatabaseUnavailable)
1016826
def process_request(self, request_object):
        """"""
        resources = (request_object.entity_cls.query
                     .filter(**request_object.filters)
                     .offset((request_object.page - 1) * request_object.per_page)
                     .limit(request_object.per_page)
                     .order_by(request_object.order_by)
                     .all())
        return ResponseSuccess(Status.SUCCESS, resources)
793751
@When("^I execute query '(.+?)'$")
    public void executeQuery(String query) throws Exception {
        Statement myStatement = null;
        int result = 0;
        Connection myConnection = this.commonspec.getConnection();

        try {
            myStatement = myConnection.createStatement();
            result = myStatement.executeUpdate(query);
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            assertThat(result).as(e.getClass().getName() + ": " + e.getMessage()).isNotEqualTo(0);
        }
    }