Run query for connection
Should return { rows, incomplete }
@param {string} query
@param {object} connection
559940
function runQuery(query, connection) {
  const pgConfig = {
    user: connection.username,
    password: connection.password,
    database: connection.database,
    host: connection.host,
    ssl: connection.postgresSsl,
    stream: createSocksConnection(connection)
  };
  // TODO cache key/cert values
  if (connection.postgresKey && connection.postgresCert) {
    pgConfig.ssl = {
      key: fs.readFileSync(connection.postgresKey),
      cert: fs.readFileSync(connection.postgresCert)
    };
    if (connection.postgresCA) {
      pgConfig.ssl['ca'] = fs.readFileSync(connection.postgresCA);
    }
  }
  if (connection.port) pgConfig.port = connection.port;

  return new Promise((resolve, reject) => {
    const client = new pg.Client(pgConfig);
    client.connect(err => {
      if (err) {
        client.end();
        return reject(err);
      }
      const cursor = client.query(new PgCursor(query));
      return cursor.read(connection.maxRows + 1, (err, rows) => {
        if (err) {
          // pg_cursor can't handle multi-statements at the moment
          // as a work around we'll retry the query the old way, but we lose the maxRows protection
          return client.query(query, (err, result) => {
            client.end();
            if (err) {
              return reject(err);
            }
            return resolve({ rows: result.rows });
          });
        }
        let incomplete = false;
        if (rows.length === connection.maxRows + 1) {
          incomplete = true;
          rows.pop(); // get rid of that extra record. we only get 1 more than the max to see if there would have been more...
        }
        if (err) {
          reject(err);
        } else {
          resolve({ rows, incomplete });
        }
        cursor.close(err => {
          if (err) {
            console.log('error closing pg-cursor:');
            console.log(err);
          }
          // Calling end() without setImmediate causes error within node-pg
          setImmediate(() => {
            client.end(error => {
              if (error) {
                console.error(error);
              }
            });
          });
        });
      });
    });
  });
}
1034367
function (queryKey, params, fn) {
    this.connection.query(templates[queryKey], params, function (err, result) {
      if (err) {
        fn(err, null);
      } else {
        fn(null, result.length ? result[0] : null);
      }
    });
  }
855361
function _checkConnection(conn) {
  // Return Promise for getConnection callback wrapping
  return new Promise((resolve, reject) => {
    if (conn) {
      resolve(conn);
    } else {
      _pool.getConnection((err, conn) => {
        if (err) reject(err); // Reject this error
        else resolve(conn); // Resolve the connection
      })
    }
  });
}
365631
function query (query) {
    // if cache is not connected immediately execute query and do not cache
    if (!this.redis.connected) {
        debug(`cache:${this.model.name}:false:redis:disconnected`)
        return query.executeQuery()
    }
    // build args for cache query instance
    var cacheQueryArgs = {
        cache: this,
        query: query,
    }
    // cache query object
    var cacheQuery
    // if query has views then cache after views are applied
    if (defined(query.modelViewEngine)) {
        // view query where underlying query is by id
        if (query.select.isSelectById) {
            // collection view is being applied
            if (query.modelViewEngine.hasCollection) {
                debug('cache:${this.model.name}:view:id:collection:true')
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdCollection(cacheQueryArgs)
            }
            // only record view(s) being applied
            else {
                debug(`cache:${this.model.name}:view:id:record:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdRecord(cacheQueryArgs)
            }
        }
        // view query where underlying query is select
        else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
            // if collection view is applied then cache result - if only
            // record view(s) are applied they are cached by id queries
            if (query.modelViewEngine.hasCollection) {
                debug(`cache:${this.model.name}:view:select:collection:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewSelectCollection(cacheQueryArgs)
            }
        }
    }
    // if query is select by id then cache result
    else if (query.select.isSelectById) {
        debug(`cache:${this.model.name}:id:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQueryId(cacheQueryArgs)
    }
    // if query has views then cache after views are applied
    else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
        debug(`cache:${this.model.name}:select:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQuerySelect(cacheQueryArgs)
    }
    // execute cache query if available
    if (defined(cacheQuery)) {
        return cacheQuery.cacheQuery()
    }
    // execute original query uncached
    else {
        debug(`cache:${this.model.name}:false:unsupported`)
        return query.executeQuery()
    }
}
968144
def query(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            for row in conn.query(sql, *args, **kwargs):
                yield row
1190337
function load(query, callback) {
      if (!query.length) return callback();

      pagelet.complete(query, function complete(err, results) {
        if (err) return callback();

        callback(results);
      });
    }
402896
function run_search(query) {
      	 var cache_key = query + computeURL();
          //var cached_results = cache.get(cache_key);
          /*if (cached_results) {
              if ($.isFunction($(input).data("settings").onCachedResult)) {
                cached_results = $(input).data("settings").onCachedResult.call(hidden_input, cached_results);
              }
              populate_dropdown(query, cached_results);
          } else {*/
              // Are we doing an ajax search or local data search?
              if($(input).data("settings").url) {
                  var url = computeURL();
                  // Extract existing get params
                  var ajax_params = {};
                  ajax_params.data = {};
                  if(url.indexOf("?") > -1) {
                      var parts = url.split("?");
                      ajax_params.url = parts[0];

                      var param_array = parts[1].split("&");
                      $.each(param_array, function (index, value) {
                          var kv = value.split("=");
                          ajax_params.data[kv[0]] = kv[1];
                      });
                  } else {
                      ajax_params.url = url;
                  }

                  // Prepare the request
                  ajax_params.data[$(input).data("settings").queryParam] = query;
                  ajax_params.type = $(input).data("settings").method;
                  ajax_params.dataType = $(input).data("settings").contentType;
                  if ($(input).data("settings").crossDomain) {
                      ajax_params.dataType = "jsonp";
                  }

                  // exclude current tokens?
                  // send exclude list to the server, so it can also exclude existing tokens
                  if ($(input).data("settings").excludeCurrent) {
                      var currentTokens = $(input).data("tokenInputObject").getTokens();
                      var tokenList = $.map(currentTokens, function (el) {
                          if(typeof $(input).data("settings").tokenValue == 'function')
                              return $(input).data("settings").tokenValue.call(this, el);

                          return el[$(input).data("settings").tokenValue];
                      });

                      ajax_params.data[$(input).data("settings").excludeCurrentParameter] = tokenList.join($(input).data("settings").tokenDelimiter);
                  }

                  // Attach the success callback
                  ajax_params.success = function(results) {
                    cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
                    if($.isFunction($(input).data("settings").onResult)) {
                        results = $(input).data("settings").onResult.call(hidden_input, results);
                    }

                    // only populate the dropdown if the results are associated with the active search query
                    if(input_box.val() === query) {
                        populate_dropdown(query, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
                    }
                  };

                  // Provide a beforeSend callback
                  if (settings.onSend) {
                    settings.onSend(ajax_params);
                  }

                  // Make the request
                  $.ajax(ajax_params);
              } else if($(input).data("settings").local_data) {
                  // Do the search through local data
                 var results = $.grep($(input).data("settings").local_data, function (row) {
                      return row[$(input).data("settings").propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
                  });

                  cache.add(cache_key, results);
                  if($.isFunction($(input).data("settings").onResult)) {
                      results = $(input).data("settings").onResult.call(hidden_input, results);
                  }
                  populate_dropdown(query, results);
              }
          //}
      }
1034251
function(query) {
	//	console.log(query);
	// Loop over all sources
	// Todo: make this loop smaller and more graspable
	for (var k = 0, klen = query.sources.length; k < klen; k++) {
		var source = query.sources[k];
		delete source.ix;
		// If there is indexation rule
		//console.log('preIndex', source);
		//console.log(source);
		if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
			// If there is no table.indices - create it
			if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
				if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
					query.database.tables[source.tableid].indices = {};
				// Check if index already exists
				var ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					];
				if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
					source.ix = ixx;
				}
			}

			if (!source.ix) {
				source.ix = {};
				// Walking over source data
				var scope = {};
				var i = 0;
				var ilen = source.data.length;
				var dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					scope[tableid] = dataw;

					//				for(var i=0, ilen=source.data.length; i<ilen; i++) {
					// Prepare scope for indexation
					scope[source.alias || source.tableid] = dataw;

					// Check if it apply to where function
					if (source.srcwherefn(scope, query.params, alasql)) {
						// Create index entry for each address
						var addr = source.onrightfn(scope, query.params, alasql);
						var group = source.ix[addr];
						if (!group) {
							group = source.ix[addr] = [];
						}
						group.push(dataw);
					}
					i++;
				}

				if (
					source.databaseid &&
					alasql.databases[source.databaseid].tables[source.tableid]
				) {
					// Save index to original table
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					] =
						source.ix;
				}
			}
			//console.log(38,274,source.ix);

			// Optimization for WHERE column = expression
		} else if (source.wxleftfn) {
			if (!alasql.databases[source.databaseid].engineid) {
				// Check if index exists
				ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					];
			}
			if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
				// Use old index if exists
				source.ix = ixx;
				// Reduce data (apply filter)
				source.data = source.ix[source.wxrightfn(null, query.params, alasql)];
			} else {
				// Create new index
				source.ix = {};
				// Prepare scope
				scope = {};
				// Walking on each source line
				i = 0;
				ilen = source.data.length;
				dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					for(var i=0, ilen=source.data.length; i<ilen; i++) {
					scope[source.alias || source.tableid] = source.data[i];
					// Create index entry
					addr = source.wxleftfn(scope, query.params, alasql);
					group = source.ix[addr];
					if (!group) {
						group = source.ix[addr] = [];
					}
					group.push(source.data[i]);
					i++;
				}
				//					query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
				if (!alasql.databases[source.databaseid].engineid) {
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					] =
						source.ix;
				}
			}
			// Apply where filter to reduces rows
			if (source.srcwherefns) {
				if (source.data) {
					scope = {};
					source.data = source.data.filter(function(r) {
						scope[source.alias] = r;
						return source.srcwherefn(scope, query.params, alasql);
					});
				} else {
					source.data = [];
				}
			}
			//			}
			// If there is no any optimization than apply srcwhere filter
		} else if (source.srcwherefns && !source.dontcache) {
			if (source.data) {
				var scope = {};
				// TODO!!!!! Data as Function

				source.data = source.data.filter(function(r) {
					scope[source.alias] = r;
					//					console.log(288,source);
					return source.srcwherefn(scope, query.params, alasql);
				});

				scope = {};
				i = 0;
				ilen = source.data.length;
				//var dataw;
				var res = [];
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					scope[source.alias] = dataw;
					if (source.srcwherefn(scope, query.params, alasql)) res.push(dataw);
					i++;
				}
				source.data = res;
			} else {
				source.data = [];
			}
		}
		// Change this to another place (this is a wrong)
		if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
			//query.database.tables[source.tableid].dirty = false;
		} else {
			// this is a subquery?
		}
	}
}
6830
public SparqlResult runQuery(String endpoint, String query) {
    return SparqlClient.execute(endpoint, query, username, password);
  }
160228
function run(server, query) {
			if(server.options && typeof server.options.defs === 'object') {
				return server.options.defs;
			}
			return null;
		}
1002806
function(sql, callback){
    pg.connect(this.conn, function(err, client, done) {
      if(err) {
        return console.error('!error fetching client from pool', err);
      }
      client.query(sql, function(err, result) {
        //call `done()` to release the client back to the pool
        done();
        if ( callback ) {
          callback(err, result);
        }
      });
    });

  }
386134
function(query) {
                    tsdb.searchLookup(query, true, null, function (data) {
                        receivedResponses++;
                        results.push(perResultFn(query,data));
                        if (receivedResponses == expectedResponses) {
                            if (errorsReceived.length == 0) {
                                successFn(results);
                            }
                            else {
                                errorFn(errorsReceived, results);
                            }

                        }
                    }, function (error) {
                        receivedResponses++;
                        errorsReceived.push({query:query,msg:error});
                        if (receivedResponses == expectedResponses) {
                            errorFn(errorsReceived, results);
                        }
                    });
                }
745279
function runQuery(query, connection) {
  const { contactPoints, keyspace, maxRows } = connection;

  const client = new cassandra.Client({
    contactPoints: contactPoints.split(',').map(cp => cp.trim()),
    keyspace
  });

  return client
    .execute(query, [], { fetchSize: maxRows })
    .then(result => {
      shutdownClient(client);
      const incomplete = result.rows && result.rows.length === maxRows;
      return { rows: result.rows, incomplete };
    })
    .catch(error => {
      shutdownClient(client);
      throw error;
    });
}
164310
function getSchema(connection) {
  return runQuery(SCHEMA_SQL_V1, connection)
    .then(queryResult => formatSchemaQueryResults(queryResult))
    .catch(() =>
      runQuery(SCHEMA_SQL_V0, connection).then(queryResult =>
        formatSchemaQueryResults(queryResult)
      )
    );
}
1185724
def perform_query(self, query, **params):
        """"""
        try:
            return self.engine.execute(query, params)
        except:
            print("Error with query: {}".format(query))
            raise
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);
    }
  });
}
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);
		}
	}