Try to perform an operation. If it fails convert the native exception
into a SQLException.

@param Closure $run
@param string $query

@return mixed
335676
protected function attempt(Closure $run, $query='')
    {
        try {
            return $run();
        } catch (Exception $e) {
            throw $this->convertException($e, $query);
        }
    }
931568
public function execute()
	{
		$this->connect();

		if (!is_object($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			// @TODO
			$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query.
		$this->executed = false;

		if ($this->prepared instanceof \PDOStatement)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				foreach ($bounded as $key => $obj)
				{
					$this->prepared->bindParam($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
				}
			}

			$this->executed = $this->prepared->execute();
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			// Get the error number and message before we execute any more queries.
			$errorNum = (int) $this->connection->errorCode();
			$errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) $this->connection->errorCode();
					$this->errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message from before we tried to reconnect.
				$this->errorNum = $errorNum;
				$this->errorMsg = $errorMsg;

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->prepared;
	}
918827
public function execute()
	{
		$this->connect();

		if (!is_resource($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @pg_query($this->connection, $sql);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
					$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message.
				$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
				$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg);
			}
		}

		return $this->cursor;
	}
1044041
protected function sendQuery(string $query)
    {
        if (self::$monitorQueries) {
            self::$queriesCount++;
        }
        $result = $this->link->query($query);
        if ($result === false) {
            throw new SqlException(
                'SQL-error [' . $this->link->errno . ']: ' . $this->link->error . "\nSQL-query: $query",
                $this->link->errno
            );
        }

        return $result === true ? $result : new Query\Result($result);
    }
323342
public function dispatch($query): PromiseInterface
    {
        $deferred = new Deferred();

        $actionEventEmitter = $this->events;

        $actionEvent = $actionEventEmitter->getNewActionEvent(
            self::EVENT_DISPATCH,
            $this,
            [
                self::EVENT_PARAM_MESSAGE => $query,
                self::EVENT_PARAM_DEFERRED => $deferred,
                self::EVENT_PARAM_PROMISE => $deferred->promise(),
            ]
        );

        try {
            $actionEventEmitter->dispatch($actionEvent);

            if (! $actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLED)) {
                throw new RuntimeException(\sprintf('Query %s was not handled', $this->getMessageName($query)));
            }
        } catch (\Throwable $exception) {
            $actionEvent->setParam(self::EVENT_PARAM_EXCEPTION, $exception);
        } finally {
            $actionEvent->stopPropagation(false);
            $this->triggerFinalize($actionEvent);
        }

        return $actionEvent->getParam(self::EVENT_PARAM_PROMISE);
    }
309029
public int executeUpdate(String query) throws Exception {
        int returnVal = 0;
        Statement queryStatement = null;

        try (Connection sqlConnection = getConnection()) {
            queryStatement = sqlConnection.createStatement();
            returnVal = queryStatement.executeUpdate(query);
        } catch (Exception e) {
        } finally {
            try {
                if (queryStatement != null) {
                    queryStatement.close();
                }
            } catch (Exception e) {
            }
        }

        return returnVal;
    }
922446
public function statements(string $query)
    {
        try {
            $this->connection->statements($query);
        } catch (\Throwable $exception) {
            $this->handleException($exception);
        }
    }
185914
public function execute($query = null)
    {
        try {
            $event = new ConnectionEvent($this, $query);
            $this->container->getDispatcher()->dispatch(ConnectionEvent::ON_QUERY, $event);
            $this->affectedRows = parent::exec($query);
        } catch (\Exception $exception) {
            throw new ConnectionException('Executing query has error: [:code] ":error"', [
                'code'  => $exception->getCode(),
                'error' => $exception->getMessage(),
            ]);
        }
        
        return $this;
    }
686562
public static function run($query, $params=array()) {
		
		$self = static::getInstance();
		
		$self->openConnection();
		
		$ret = NULL;
		
		try {
			
			// prepare query
			$stat = $self->handler->prepare($query);

			// bind parameters
			$stat->execute((array)$params);

			// count affected rows
			$affected = $stat->rowCount();
			
		} catch (\PDOException $e) {
			
			// logger
			$self->logParamQuery($query, 0, $params);
			
			switch ($e->getCode()) {
				
				// integrity constraint violation
				/*
				 case '23000':
					 $message = 'Database integrity constraint violation';
					 break;
				 */
				default:
					$message = $e->getMessage();
					break;
			}
			
			$self->addError($message);
			
			$affected = 0;
			
		} catch (\Exception $e) {
			
			// logger
			$self->logParamQuery($query, 0, $params);
			$self->addError($e->getMessage());
			$affected = 0;
			
		}
		
		$stat->closeCursor();
		$self->logParamQuery($query, $affected, $params);
		
		return $affected;
			
	}
967137
public function execute($query = '')
    {
        if (\is_string($query) && $query !== '') {
            $this->currentQuery = $query;
        } elseif ($query instanceof Query) {
            $this->currentQuery = $query->___build();
        } elseif ($this->preparedQuery instanceof Query) {
            $this->currentQuery = $this->preparedQuery->___build();
        }

        if ($this->currentQuery == '') {
            $this->setError(AbstractMySQL::E_NO_SQL, __CLASS__);
            return null;
        }

        $startTime = $this->getMicrotime();
        if (\preg_match('/^CALL/mi', $this->currentQuery)) {
            $this->currentLink->multi_query($this->currentQuery);
            $result = $this->currentLink->store_result();
        } else {
            $result = $this->currentLink->query($this->currentQuery);
        }
        $queryTime = \round($this->getMicrotime() - $startTime, 4);
        $this->sqlQueries[] = ['query' => $this->currentQuery, 'queryTime' => $queryTime];

        if ($this->logHandler !== null) {
            $this->logHandler->logInfo($this->currentQuery, __CLASS__);
        }
        if (!$result && !\preg_match('/^CALL/mi', $this->currentQuery)) {
            $this->setError(AbstractMySQL::E_ENGINE_ERROR, __CLASS__);
        }

        if ($result instanceof \mysqli_result) {
            $ret = [];
            $this->rowCount = $result->num_rows;
            for ($i = 0; $i < $this->rowCount; $i++) {
                $ret[$i] = $result->fetch_assoc();
            }
            $result->close();
            if ($this->currentLink->more_results()) {
                while ($this->currentLink->next_result()) {
                    $result = $this->currentLink->store_result();
                    if ($result instanceof \mysqli_result) {
                        $result->close();
                    }
                }
            }
        } else {
            $this->rowCount = $this->currentLink->affected_rows;
            $ret = \preg_match('/^insert/mi', $this->currentQuery)
                ? $this->currentLink->insert_id
                : $this->rowCount;
        }
        if ($this->showQuery === true) {
            $fetchTime = \round($this->getMicrotime() - $startTime, 4);
            $queryText = \sprintf(
                '<b>Query %s:</b> %s; <b>[Q: %ss, F: %ss]</b><hr />',
                \count($this->sqlQueries),
                $this->currentQuery,
                $queryTime,
                $fetchTime
            );
            echo filter_var($queryText, FILTER_DEFAULT);
        }
        $this->currentQuery = '';

        return $ret;
    }
222875
protected function handleQueryException( $e, $query, $bindings ) {
		if ( $result = apply_filters( 'awethemes.database.handle_query_exception', null, $e, $query, $bindings ) ) {
			return $result;
		}

		throw $e;
	}
170571
private function run(\Closure &$runFunc)
    {
        $__out = new Outer($this->sdopx);
        $_sdopx = $this->sdopx;
        try {
            call_user_func($runFunc, $_sdopx, $__out);
        } catch (\ErrorException $exception) {
            $__out->throw($exception);
        }
        return $__out->getCode();
    }
332589
protected function exec($query)
    {
        if (!$query) {
            throw new Exceptions\RPCException("Empty query.");
        }
        
        $url = sprintf("http://%s:%d", $this->conf["host"], $this->conf["port"]);
        $web = $this->getWebClient();
        $web->setMethod(HttpMethods::POST);
        $web->addHeader("Content-Type", "application/json");
        $web->setBasicAuth($this->conf["user"], $this->conf["pass"]);
        $web->setData($query);
        $response    = $web->request($url);
        $status_code = $response->getCode();
        
        if (isset(self::$exceptions[$status_code])) {
            $error = $this->getResponseError($response, $status_code);
            throw new self::$exceptions[$status_code](
                $error["message"],
                $error["code"]
            );
        }

        return $response;
    }
1352699
public function query($database, $query, $parameters = [])
    {
        $driver = $this->getDriver();

        if (!$driver instanceof QueryDriverInterface) {
            throw new Exception('The currently configured driver does not support query operations');
        }

        if ($database) {
            $parameters['db'] = $database;
        }

        $parameters = [
            'url' => 'query?' . http_build_query(array_merge(['q' => $query], $parameters)),
            'database' => $database,
            'method' => 'get'
        ];

        // add authentication to the driver if needed
        if (!empty($this->username) && !empty($this->password)) {
            $parameters += ['auth' => [$this->username, $this->password]];
        }

        $driver->setParameters($parameters);

        try {
            // store the last query sent
            static::$lastQuery = $query;

            // perform the query and return the resultset
            return $driver->query();

        } catch (\Exception $e) {
            throw new Exception('Query has failed', $e->getCode(), $e);
        }
    }
602052
private function runQuery(Query $query, $executeQueries = false)
    {
        $this->playedQueries[] = $query;
        if ($executeQueries) {
            $this->connection->executeQuery((string)$query);
        }
    }
401323
public function when($condition, $query, $otherwise = null)
    {
        if ($condition instanceof \Closure) {
            $condition = $condition($this);
        }

        if ($condition) {
            if ($query instanceof \Closure) {
                $query($this, $condition);
            } elseif (is_array($query)) {
                $this->where($query);
            }
        } elseif ($otherwise) {
            if ($otherwise instanceof \Closure) {
                $otherwise($this, $condition);
            } elseif (is_array($otherwise)) {
                $this->where($otherwise);
            }
        }

        return $this;
    }
840171
protected function runQueryCallback($query, $bindings, Closure $callback)
    {
        // To execute the statement, we'll simply call the callback, which will actually
        // run the SQL against the PDO connection. Then we can calculate the time it
        // took to execute and log the query SQL, bindings and time in our memory.
        try {
            $result = $callback($query, $bindings);
        }

            // If an exception occurs when attempting to run a query, we'll format the error
            // message to include the bindings with SQL, which will make this exception a
            // lot more helpful to the developer instead of just the database's errors.
        catch (Exception $e) {
            throw new QueryException(
                $query, $bindings, $e
            );
        }

        return $result;
    }