/*
Execute a query and return a result
165021
public function query ($sSQL, $log = true)
	{
		$start = microtime (true);
		
		$this->connect ();
		
		// Increase the counter
		$this->query_counter ++;
		
		$result = $this->connection->query (trim ($sSQL));
		
		$duration = microtime (true) - $start;

		if ($log) {
			$this->addQueryLog($sSQL, $duration);
		}
		
		if (!$result)
		{
			//var_dump (debug_backtrace ());
			//$data = debug_backtrace ();
			//print_r ($data);


			echo $sSQL;
			throw new DbException ('MySQL Error: '.$this->connection->error);
		}
		
		elseif ($result instanceof MySQLi_Result)
		{
			return new Result ($result);
		}
		
		// Insert ID will return zero if this query was not insert or update.
		$this->insert_id = intval ($this->connection->insert_id);
		
		// Affected rows
		$this->affected_rows = intval ($this->connection->affected_rows);
		
		if ($this->insert_id > 0)
			return $this->insert_id;
		
		if ($this->affected_rows > 0)
			return $this->affected_rows;
		
		return $result;
	}
108590
private function executeQuery($query, $data = null) {
        $stmt = $this->conn->prepare($query);
        $stmt->execute($data);
        
        return $stmt;
    }
1050810
def execute(self, query, args=None):
        
        self._ensure_conn()
        cur = self._conn.cursor()
        yield cur.execute(query, args)
        raise Return(cur)
1189373
def execute_query_return_result_proxy(query):
    
    context = query._compile_context()
    context.statement.use_labels = False
    if query._autoflush and not query._populate_existing:
        query.session._autoflush()

    conn = query._get_bind_args(
        context,
        query._connection_from_session,
        close_with_result=True)

    return conn.execute(context.statement, query._params)
557485
def execute(self, query, params=None, cursor=None):
        
        conn = yield self._get_conn()
        try:
            cur = conn.cursor(cursor)
            yield cur.execute(query, params)
            yield cur.close()
        except:
            self._close_conn(conn)
            raise
        else:
            self._put_conn(conn)
        raise Return(cur)
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)));
  }
697472
function runQuery(query, connection) {
  const params = {
    host: connection.host,
    port: connection.port ? connection.port : 5433,
    user: connection.username,
    password: connection.password,
    database: connection.database
  };

  return new Promise((resolve, reject) => {
    const client = vertica.connect(params, function(err) {
      if (err) {
        client.disconnect();
        return reject(err);
      }

      let incomplete = false;
      const rows = [];
      let finished = false;
      let columnNames = [];

      const verticaQuery = client.query(query);

      verticaQuery.on('fields', fields => {
        columnNames = fields.map(field => field.name);
      });

      verticaQuery.on('row', function(row) {
        if (rows.length < connection.maxRows) {
          const resultRow = {};
          row.forEach((value, index) => {
            resultRow[columnNames[index]] = value;
          });
          return rows.push(resultRow);
        }
        if (!finished) {
          finished = true;
          client.disconnect();
          incomplete = true;
          return resolve({ rows, incomplete });
        }
      });

      verticaQuery.on('end', function() {
        if (!finished) {
          finished = true;
          client.disconnect();
          return resolve({ rows, incomplete });
        }
      });

      verticaQuery.on('error', function(err) {
        if (!finished) {
          finished = true;
          client.disconnect();
          return reject(err);
        }
      });
    });
  });
}
1113876
public ExecutionResult execute(String query) {
        ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                .query(query)
                .build();
        return execute(executionInput);
    }
277688
function runQuery(query, connection) {
  const incomplete = false;

  return new Promise((resolve, reject) => {
    const client = hdb.createClient({
      host: connection.host,
      port: connection.hanaport,
      database: connection.hanadatabase,
      user: connection.username,
      password: connection.password,
      schema: connection.hanaSchema
    });

    client.on('error', err => {
      console.error('Network connection error', err);
      return reject(err);
    });

    client.connect(err => {
      if (err) {
        console.error('Connect error', err);
        return reject(err);
      }
      return client.execute(query, function(err, rs) {
        let rows = [];

        if (err) {
          client.disconnect();
          return reject(err);
        }

        if (!rs) {
          client.disconnect();
          return resolve({ rows, incomplete });
        }

        if (!rs.createObjectStream) {
          // Could be row count or something
          client.disconnect();
          return resolve({ rows: [{ result: rs }], incomplete });
        }

        const stream = rs.createObjectStream();

        stream.on('data', data => {
          if (rows.length < connection.maxRows) {
            return rows.push(data);
          }
          client.disconnect();
          return resolve({ rows, incomplete: true });
        });

        stream.on('error', error => {
          client.disconnect();
          return reject(error);
        });

        stream.on('finish', () => {
          client.disconnect();
          return resolve({ rows, incomplete });
        });
      });
    });
  });
}
239011
function execute_(callback) {
    var self = this;
    self.migrate(function(err) {
        if (err) { callback(err); return; }
        try {
            var event = { model:self.model, query:self.query, type:'select' };
            var flatten = self.$flatten || (self.getLevels()===0);
            if (!flatten) {
                //get expandable fields
                var expandables = self.model.attributes.filter(function(x) { return x.expandable; });
                //get selected fields
                var selected = self.query.$select[self.model.viewAdapter];
                if (_.isArray(selected)) {
                    //remove hidden fields
                    var hiddens = self.model.attributes.filter(function(x) { return x.hidden; });
                    if (hiddens.length>0) {
                        for (var i = 0; i < selected.length; i++) {
                            /**
                             * @type {QueryField}
                             */
                            var x = selected[i] instanceof QueryField ? selected[i] : new QueryField(selected[i]);
                            var hiddenField = hiddens.find(function(y) {
                                return x.getName() === y.name;
                            });
                            if (hiddenField) {
                                selected.splice(i, 1);
                                i-=1;
                            }
                        }
                    }
                    //expand fields
                    if (expandables.length>0) {
                        selected.forEach(function(x) {
                            //get field
                            var field = expandables.find(function(y) {
                                var f = x instanceof QueryField ? x : new QueryField(x);
                                return f.getName() === y.name;
                            });
                            //add expandable models
                            if (field) {
                                var mapping = self.model.inferMapping(field.name);
                                if (mapping) {
                                    self.$expand = self.$expand || [ ];
                                    var expand1 = self.$expand.find(function(x) {
                                        return x.name === field.name;
                                    });
                                    if (typeof expand1 === 'undefined') {
                                        self.expand(mapping);
                                    }
                                }

                            }
                        });
                    }
                }
            }
        }
        catch(err) {
            return callback(err);
        }

        //merge view filter. if any
        if (self.$view) {
            return self.model.filter({ $filter: self.$view.filter, $order:self.$view.order, $group:self.$view.group }, function(err, q) {
                if (err) {
                    if (err) { callback(err); }
                }
                else {
                    //prepare current filter
                    if (q.query.$prepared) {
                        if (event.query.$where)
                            event.query.prepare();
                        event.query.$where = q.query.$prepared;
                    }
                    if (q.query.$group)
                    //replace group fields
                        event.query.$group = q.query.$group;
                    //add order fields
                    if (q.query.$order) {
                        if (_.isArray(event.query.$order)) {
                            q.query.$order.forEach(function(x) { event.query.$order.push(x); });
                        }
                        else {
                            event.query.$order = q.query.$order;
                        }
                    }
                    //execute query
                    return finalExecuteInternal_.call(self, event, callback);
                }
            });
        }
        else {
            //execute query
            return finalExecuteInternal_.call(self, event, callback);
        }
    });
}
381487
protected function executeQuery($query)
    {
        $query   = null !== $this->getLocale() ? sprintf('%s&language=%s', $query, $this->getLocale()) : $query;
        $content = $this->getAdapter()->get($query)->getBody();

        if (!$data = json_decode($content, true)) {
            throw new NoResult(sprintf('Could not execute query: %s', $query));
        }

        if (!isset($data['Response']) && 'InvalidCredentials' === $data['subtype']) {
            throw new InvalidCredentials(sprintf('Invalid credentials: %s', $data['details']));
        } elseif (!isset($data['Response'])) {
            throw new NoResult(
                sprintf('Error type `%s` returned from api `%s`', $data['subtype'], $data['Details'])
            );
        }

        if (empty($data['Response']['View'])) {
            throw new NoResult(sprintf('Could not find results for given query: %s', $query));
        }

        $locations = $data['Response']['View'][0]['Result'];

        $results = array();
        foreach ($locations as $location) {
            $location       = $location['Location'];
            $coordinates    = isset($location['NavigationPosition'][0]) ? $location['NavigationPosition'][0] : $location['DisplayPosition'];
            $bounds         = $location['MapView'];
            $address        = $location['Address'];
            $additionalData = $location['Address']['AdditionalData'];

            $results[] = array_merge($this->getDefaults(), array(
                'latitude'     => $coordinates['Latitude']  ?: null,
                'longitude'    => $coordinates['Longitude'] ?: null,
                'bounds'       => array(
                    'south' => $bounds['BottomRight']['Latitude']  ?: null,
                    'west'  => $bounds['TopLeft']['Longitude']     ?: null,
                    'north' => $bounds['TopLeft']['Latitude']      ?: null,
                    'east'  => $bounds['BottomRight']['Longitude'] ?: null,
                ),
                'streetNumber' => isset($address['HouseNumber']) ? $address['HouseNumber'] : null,
                'streetName'   => isset($address['Street'])      ? $address['Street']      : null,
                'city'         => isset($address['City'])        ? $address['City']        : null,
                'cityDistrict' => isset($address['District'])    ? $address['District']    : null,
                'zipcode'      => isset($address['PostalCode'])  ? $address['PostalCode']  : null,
                'county'       => isset($address['County'])      ? $address['County']      : null,
                'regionCode'   => isset($address['State'])       ? $address['State']       : null,
                'countryCode'  => isset($address['Country'])     ? $address['Country']     : null,
                'region'       => $this->findByKey('StateName', $additionalData),
                'country'      => $this->findByKey('CountryName', $additionalData),
                'countyCode'   => null,
            ));
        }

        return $results;
    }
1175009
function runQuery(query, connection) {
  const myConnection = mysql.createConnection({
    multipleStatements: true,
    host: connection.host,
    port: connection.port ? connection.port : 3306,
    user: connection.username,
    password: connection.password,
    database: connection.database,
    insecureAuth: connection.mysqlInsecureAuth,
    timezone: 'Z',
    supportBigNumbers: true
  });

  return new Promise((resolve, reject) => {
    let incomplete = false;
    const rows = [];

    myConnection.connect(err => {
      if (err) {
        return reject(err);
      }
      let queryError;
      let resultsSent = false;

      function continueOn() {
        if (!resultsSent) {
          resultsSent = true;
          if (queryError) {
            return reject(queryError);
          }
          return resolve({ rows, incomplete });
        }
      }

      const myQuery = myConnection.query(query);
      myQuery
        .on('error', function(err) {
          // Handle error,
          // an 'end' event will be emitted after this as well
          // so we'll call the callback there.
          queryError = err;
        })
        .on('result', function(row) {
          // If we haven't hit the max yet add row to results
          if (rows.length < connection.maxRows) {
            return rows.push(row);
          }

          // Too many rows
          incomplete = true;

          // Stop the query stream
          myConnection.pause();

          // Destroy the underlying connection
          // Calling end() will wait and eventually time out
          myConnection.destroy();
          continueOn();
        })
        .on('end', function() {
          // all rows have been received
          // This will not fire if we end the connection early
          // myConnection.end()
          // myConnection.destroy()
          myConnection.end(error => {
            if (error) {
              console.error('Error ending MySQL connection', error);
            }
            continueOn();
          });
        });
    });
  });
}
81881
@Override
  public ResultSet executeQuery(String sql) throws SQLException
  {
    raiseSQLExceptionIfStatementIsClosed();
    return executeQueryInternal(sql, 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;
    });
  }
1297730
private static <T> T executeQuery(PreparedStatement ps, RsHandler<T> rsh) throws SQLException {
		ResultSet rs = null;
		try {
			rs = ps.executeQuery();
			return rsh.handle(rs);
		} finally {
			DbUtil.close(rs);
		}
	}
487908
function(query, data, successCallback, failureCallback) {
			if(typeof successCallback != "function") successCallback = function(){};
			if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };

			var i, l, remaining;

			if(!Array.isArray(data[0])) data = [data];
			remaining = data.length;
			var innerSuccessCallback = function(tx, rs) {
				var i, l, output = [];
				remaining = remaining - 1;
				if (!remaining) {
					for (i = 0, l = rs.rows.length; i < l; i = i + 1){
						var j = rs.rows.item(i).json;
						//j = JSON.parse(j);
						output.push(j);
					}
					successCallback(output);
				}
			};
			self.db.transaction(function (tx) {
				for (i = 0, l = data.length; i < l; i = i + 1) {
					tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
				}
			});
		}
903717
function (connectionInfo, query, params) {
    var connection,
        client = new pg.Client(connectionInfo);

    client.connect(function (err) {
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }
            });
        }

        // execute a query on our database
        client.query(query, params, function (err, result) {
            // close the client
            client.end();

            // treat the error
            if (err) {
                return respond({
                    success: false,
                    data: {
                        err: err,
                        query: query,
                        connection: connectionInfo
                    }
                });
            }
            
            // Return the respose
            return respond({
                success: true,
                data: result
            });
        });
    });
}