Internal method to start a new query execution thread type defines the
query type SELECT, ASK, CONSTRUCT, or DESCRIBE
181768
private <R extends OBDAResultSet, Q extends InputQuery<R>> R executeInThread(Q inputQuery, Evaluator<R, Q> evaluator)
			throws OntopReformulationException, OntopQueryEvaluationException {

		log.debug("Executing SPARQL query: \n{}", inputQuery);

		CountDownLatch monitor = new CountDownLatch(1);
		ExecutableQuery executableQuery = engine.reformulateIntoNativeQuery(inputQuery);

		QueryExecutionThread<R, Q> executionthread = new QueryExecutionThread<>(inputQuery, executableQuery, evaluator,
				monitor);

		this.executionThread = executionthread;
		executionthread.start();
		try {
			monitor.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (executionthread.errorStatus()) {
			Exception ex = executionthread.getException();
			if (ex instanceof OntopReformulationException) {
				throw (OntopReformulationException) ex;
			}
			else if (ex instanceof OntopQueryEvaluationException) {
				throw (OntopQueryEvaluationException) ex;
			}
			else {
				throw new OntopQueryEvaluationException(ex);
			}
		}

		if (canceled) {
			canceled = false;
			throw new OntopQueryEvaluationException("Query execution was cancelled");
		}
		return executionthread.getResultSet();
	}
216944
@Override
	public <R extends OBDAResultSet> R execute(InputQuery<R> inputQuery) throws OntopConnectionException,
            OntopReformulationException, OntopQueryEvaluationException, OntopResultConversionException {
		if (inputQuery instanceof SelectQuery) {
			return (R) executeInThread((SelectQuery) inputQuery, this::executeSelectQuery);
		}
		else if (inputQuery instanceof AskQuery) {
			return (R) executeInThread((AskQuery) inputQuery, this::executeBooleanQuery);
		}
		else if (inputQuery instanceof ConstructQuery) {
			return (R) executeInThread((ConstructQuery) inputQuery, this::executeConstructQuery);
		}
		else if (inputQuery instanceof DescribeQuery) {
			return (R) executeDescribeQuery((DescribeQuery) inputQuery);
		}
		else {
			throw new OntopUnsupportedInputQueryException("Unsupported query type: " + inputQuery);
		}
	}
489149
function runQuery(connection, query, options, done) {
  options = _.isObject(options) ? options :
    connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {};

  connection.query(query, options)
    .then(function(results) {
      done(null, results);
    })
    .catch(function(error) {
      if (error) {
        output.error("Query error.  SQL has been written to .tables.debug.  Use a smaller batchSize to more easily find the issue.");
        output.error(error);
        fs.writeFileSync(".tables.debug", query);
      }

      done(error);
    });
}
23225
@Override
    public <T> Query<T> createQuery(Class<T> entityType, Object queryObject) {
        Assert.notNull(entityType, "entityType must not null");
        Assert.notNull(queryObject, "queryObject must not null");
        return query(entityType, queryObject);
    }
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);
        }
    }
1200437
final DataSet executeQuery(CallInfo callInfo, boolean takeSnapshot) {
    DataSet data = new DataSet(this);
    return db.access(callInfo, () -> {
      try (WrappedStatement ws = db.compile(getSQLForQuery())) {
        proceedWithQuery(ws.getStatement(), data);
        if (takeSnapshot) {
          setSnapshot(data);
          db.logSnapshot(callInfo, data);
        } else {
          db.logQuery(callInfo, data);
        }
      }
      return data;
    });
  }
1278554
private InputStream runSparqlQuery(String query) throws IOException {
		try {
			String queryString = "query=" + URLEncoder.encode(query, "UTF-8")
					+ "&format=json";
			URL url = new URL("https://query.wikidata.org/sparql?"
					+ queryString);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");

			return connection.getInputStream();
		} catch (UnsupportedEncodingException | MalformedURLException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
932180
async def select(query):
    
    assert isinstance(query, peewee.SelectQuery),\
        ("Error, trying to run select coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)

    result = AsyncQueryWrapper(cursor=cursor, query=query)

    try:
        while True:
            await result.fetchone()
    except GeneratorExit:
        pass
    finally:
        await cursor.release()

    return result
996593
private org.hibernate.Query query(String hql, Class<?>... type)
  {
    org.hibernate.Query q = session.createQuery(hql);
    for(int i = 0; i < positionedParameters.length; i++) {
      q.setParameter(i, positionedParameters[i]);
    }
    for(Map.Entry<String, Object> entry : namedParameters.entrySet()) {
      Object value = entry.getValue();
      if(Types.isArray(value)) {
        Object[] parameter = (Object[])value;
        if(parameter.length == 0) {
          throw new HibernateException(String.format("Invalid named parameter |%s|. Empty array.", entry.getKey()));
        }
        q.setParameterList(entry.getKey(), parameter);
      }
      else if(Types.isCollection(value)) {
        Collection<?> parameter = (Collection<?>)value;
        if(parameter.isEmpty()) {
          throw new HibernateException(String.format("Invalid named parameter |%s|. Empty list.", entry.getKey()));
        }
        q.setParameterList(entry.getKey(), parameter);
      }
      else {
        q.setParameter(entry.getKey(), value);
      }
    }
    if(offset > 0) {
      q.setFirstResult(offset);
    }
    if(rowsCount > 0) {
      q.setMaxResults(rowsCount);
    }

    if(type.length > 0) {
      q.setResultTransformer(Transformers.aliasToBean(type[0]));
    }
    return q;
  }
1061486
public QueryResult executeQuery(String query) throws FMSException {

        IntuitMessage intuitMessage = prepareQuery(query);

        // execute interceptors
        executeInterceptors(intuitMessage);

        QueryResult queryResult = null;

        // Iterate the IntuitObjects list in QueryResponse and convert to <T> entity
        IntuitResponse intuitResponse = (IntuitResponse) intuitMessage.getResponseElements().getResponse();
        if (intuitResponse != null) {
            QueryResponse queryResponse = intuitResponse.getQueryResponse();
            if (queryResponse != null) {
                queryResult = getQueryResult(queryResponse);
            }
        }
        return queryResult;
    }
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);
    }
  });
}
1163343
function runQuery(query, connection) {
  let incomplete = false;
  const rows = [];

  const drillConfig = {
    host: connection.host,
    port: connection.port,
    user: connection.username,
    password: connection.password,
    defaultSchema: connection.drillDefaultSchema,
    ssl: connection.ssl || false
  };
  const client = new drill.Client(drillConfig);

  return client.query(drillConfig, query).then(result => {
    if (!result) {
      throw new Error('No result returned');
    } else if (result.errorMessage && result.errorMessage.length > 0) {
      console.log('Error with query: ' + query);
      console.log(result.errorMessage);
      throw new Error(result.errorMessage.split('\n')[0]);
    }
    if (result.length > connection.maxRows) {
      incomplete = true;
      result['rows'] = result['rows'].slice(0, connection.maxRows);
    }
    for (let r = 0; r < result['rows'].length; r++) {
      const row = {};
      for (let c = 0; c < result['columns'].length; c++) {
        row[result['columns'][c]] = result['rows'][r][result['columns'][c]];
      }
      rows.push(row);
    }
    return { rows, incomplete };
  });
}
978085
public FutureAPIResponse sendQueryAsFuture(Map<String, Object> query)
      throws ExecutionException, InterruptedException, IOException {
    RequestBuilder builder = new RequestBuilder("POST");
    builder.setUrl(apiUrl + "/queries.json");

    // handle DateTime separately
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeAdapter());
    Gson gson = gsonBuilder.create();

    String requestJsonString = gson.toJson(query);
    builder.setBody(requestJsonString);
    builder.setHeader("Content-Type", "application/json");
    builder.setHeader("Content-Length", "" + requestJsonString.length());
    return new FutureAPIResponse(client.executeRequest(builder.build(), getHandler()));
  }
678094
function query (query, params, options, session) {
    // require string for query
    if (typeof query !== 'string') {
        throw new Error('query error: query must be string')
    }
    // validate optional args - create objects if not passed in
    options = requireValidOptionalObject(options)
    params = requireValidOptionalObject(params)
    session = requireValidOptionalObject(session)
    // if the no insert flag is set then do not run insert queries
    if (session.noInsert && query.match(/^\s*INSERT/i)) {
        return Promise.resolve()
    }
    // get unique if for query
    var dbQueryId = randomUniqueId()
    // log query start
    this.logQuery(query, params, options, session, dbQueryId)
    // perform query using promisified interface
    return this.client.queryPromise(query, params, options)
    // success
    .then(res => {
        // perform formatting on response data
        formatResponse(res)
        // log response
        this.logQueryResponse(dbQueryId, options, res)
        // resolve with response data
        return res
    })
    // error
    .catch(err => {
        // log error
        this.logQueryError(dbQueryId, options, err)
        // reject with error
        return Promise.reject(err)
    })
}
222869
@When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
    public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
        try {
            commonspec.setResultsType("mongo");
            String retrievedData = commonspec.retrieveData(query, type);
            String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
            commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
            DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
            DBObject dbObject = (DBObject) JSON.parse(modifiedData);
            DBCursor cursor = dbCollection.find(dbObject);
            commonspec.setMongoResults(cursor);
        } catch (Exception e) {
            commonspec.getExceptions().add(e);
        }
    }
230508
def _run_queries(self, agent_strs, stmt_types, params, persist):
        """"""
        self._query_over_statement_types(agent_strs, stmt_types, params)

        assert len(self.__done_dict) == len(stmt_types) \
            or None in self.__done_dict.keys(), \
            "Done dict was not initiated for all stmt_type's."

        # Check if we want to keep going.
        if not persist:
            self._compile_statements()
            return

        # Get the rest of the content.
        while not self._all_done():
            self._query_over_statement_types(agent_strs, stmt_types, params)

        # Create the actual statements.
        self._compile_statements()
        return
717134
private void invokeQuery(QueryRequest request, CompletableFuture<byte[]> future) {
    invoke(new QueryAttempt(sequencer.nextRequest(), request, future));
  }