Execute a query and fetch first row as associative array

@param  string $query
@param  array  $parameters Query parameters
@return array Returns a single row from database
@throws \Phramework\Exceptions\DatabaseException
189702
public function executeAndFetch($query, $parameters = [], $castModel = null)
    {
        $statement = $this->link->prepare($query);

        $statement->execute($parameters);
        $data = $statement->fetch(PDO::FETCH_ASSOC);
        $statement->closeCursor();

        return (
            $castModel && $data
            ? $data
            : $data
        );
    }
79585
public function exec($query, $params=array()) {

		$this->openConnection();
		
		$this->query = $query;
		
		try {

			$stat = $this->handler->prepare($this->query);
			$stat->execute((array)$params);
			$affected = $stat->rowCount();

		} catch (\PDOException $e) {

			// logger
			$this->logParamQuery($this->query, 0, $params);

			switch ($e->getCode()) {
				
				// integrity constraint violation
				/*
				case '23000':
					$message = 'Database integrity constraint violation';
					break;
				*/
				default:
					$message = $e->getMessage();
					break;
			}
			
			$this->addError($message);
				
			$affected = 0;
		
		} catch (\Exception $e) {
			
			// logger
			$this->logParamQuery($this->query, 0, $params);
			$this->addError($e->getMessage());
			$affected = 0;
		
		}
		
		$stat->closeCursor();
		$this->logParamQuery($this->query, $affected, $params);
		
		return $affected;
		
	}
414290
public function getArray($sql = null, $parameters = array()) {
		$this->execute($sql, $parameters);
		return $this->result->fetchAll(\PDO::FETCH_ASSOC);
	}
920027
public function exec($sql, array $parameters = [])
    {
        $statement = $this->executeQuery($sql, $parameters);

        return $statement->rowCount();
    }
1339523
public function execute(string $query, array $parameters): CollectionInterface
    {
        $numServers = count($this->availableServers) - 1;

        for ($i = 0; $i <= $numServers; $i++) {
            // always get the first available server
            $server = $this->availableServers[0];

            // Move the selected server to the end of the stack
            $this->availableServers[] = array_shift($this->availableServers);

            $options = array_merge($this->httpOptions, [
                'base_uri' => sprintf('%s://%s', $this->protocol, $server),
                'json'     => [
                    'stmt' => $query,
                    'args' => $parameters,
                ],
            ]);

            try {
                $response     = $this->httpClient->request('POST', '/_sql', $options);
                $responseBody = json_decode((string)$response->getBody(), true);

                return new Collection(
                    $responseBody['rows'],
                    $responseBody['cols'],
                    $responseBody['duration'],
                    $responseBody['rowcount']
                );
            } catch (ConnectException $exception) {
                // Catch it before the BadResponseException but do nothing.
                continue;
            } catch (BadResponseException $exception) {
                $body = (string)$exception->getResponse()->getBody();
                $json = json_decode($body, true);

                if ($json === null && json_last_error() !== JSON_ERROR_NONE) {
                    throw new RuntimeException(sprintf('Server returned non-JSON response: %s', $body), 0, $exception);
                }

                $errorCode    = $json['error']['code'];
                $errorMessage = $json['error']['message'];

                throw new RuntimeException($errorMessage, $errorCode, $exception);
            }
        }

        throw new ConnectException(
            sprintf('No more servers available, exception from last server: %s', $exception->getMessage()),
            $exception->getRequest(),
            $exception
        );
    }
256367
public function first(string $query, array $params = [], ...$fetchMode)
	{
		$prepared = $this->prepare($query, $params);

		$this->execute($prepared);

		if(!empty($fetchMode))
		{
			$prepared['statement']->setFetchMode(...$fetchMode);
		}

		return $prepared['statement']->fetch();
	}
311843
protected function execute($query, $parameters = "")
    {
        try {
            $this->sQuery = @$this->pdo->prepare($query);
            $this->bindMore($parameters);
            if (!empty($this->parameters)) {
                foreach ($this->parameters as $param) {
                    $parameters = explode("\x7F", $param);
                    $this->sQuery->bindParam($parameters[0], $parameters[1]);
                }
            }
            $this->success = $this->sQuery->execute();
        } catch (PDOException $e) {
            // 服务端断开时重连一次
            if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
                $this->closeConnection();
                $this->connect();

                try {
                    $this->sQuery = $this->pdo->prepare($query);
                    $this->bindMore($parameters);
                    if (!empty($this->parameters)) {
                        foreach ($this->parameters as $param) {
                            $parameters = explode("\x7F", $param);
                            $this->sQuery->bindParam($parameters[0], $parameters[1]);
                        }
                    }
                    $this->success = $this->sQuery->execute();
                } catch (PDOException $ex) {
                    $this->rollBackTrans();
                    throw $ex;
                }
            } else {
                $this->rollBackTrans();
                $msg = $e->getMessage();
                $err_msg = "SQL:".$this->lastSQL()." ".$msg;
                $exception = new \PDOException($err_msg, (int)$e->getCode());
                throw $exception;
            }
        }
        $this->parameters = array();
    }
718238
public function fetchPairs($query, array $parameters = array())
    {
        $parameters = $this->parameterTransformer->transform($parameters);
        return $this->db->fetchPairs($query, $parameters);
    }
886803
public function query(
        Query $query,
        array $parameters = []
    ): Result {
        $this->load();

        return parent::query($query);
    }
247421
private function resolvePreparedStatement($query = '', array $parameters = [])
    {

        // the instance of database connection
        $connection = $this->getConnection();
        $prepare = $connection->prepare($query);

        if ($prepare instanceof PDOStatement) {
            $resolved = $this->resolvePdoPreparedStatement($prepare, $parameters);
        } elseif ($prepare instanceof mysqli_stmt) {
            $resolved = $this->resolveMysqliPreparedStatement($prepare, $parameters);
        }

        return [$prepare, $resolved];
    }
11220
public function pairs(string $query, array $params = []): array
	{
		return $this->all($query, $params, PDO::FETCH_KEY_PAIR);
	}
832847
public function buildSQL(SQLExpression $query, &$parameters)
    {
        $sql = null;
        $parameters = array();

        // Ignore null queries
        if ($query->isEmpty()) {
            return null;
        }

        if ($query instanceof SQLSelect) {
            $sql = $this->buildSelectQuery($query, $parameters);
        } elseif ($query instanceof SQLDelete) {
            $sql = $this->buildDeleteQuery($query, $parameters);
        } elseif ($query instanceof SQLInsert) {
            $sql = $this->buildInsertQuery($query, $parameters);
        } elseif ($query instanceof SQLUpdate) {
            $sql = $this->buildUpdateQuery($query, $parameters);
        } else {
            throw new InvalidArgumentException(
                "Not implemented: query generation for type " . get_class($query)
            );
        }
        return $sql;
    }
391957
private function executeQuery(string $query, array $parameters) : bool
    {
        $statement = $this->pdo->prepare($query);
        $statement->execute($parameters);

        return $statement->rowCount() !== 0;
    }
189518
public function results(string $query, array $params = [])
    {
        // Prepares the query, then stores it
        $PDOStatement = $this->pdo->prepare($query);

        // Executes the prepared query
        $PDOStatement->execute($params);

        // Fetchs all results, then returns them
        return $PDOStatement->fetchAll();
    }
667242
public function executeLastInsertId($query, $parameters = [])
    {
        $statement = $this->link->prepare($query);
        $statement->execute($parameters);
        return $this->link->lastInsertId();
    }
1334320
public static function FetchAll($statement, $parameters = array(), $fetchMode = PDO::FETCH_ASSOC)
	{
		$db = self::connect($fetchMode);

		try
		{
			$query = $db->prepare($statement);
			
			if($query)
			{
				foreach($parameters as $key => $parameter)
				{
					if(!isset($parameter["type"]))
						$parameter["type"] = PDO::PARAM_STR;
					
					$query->bindParam($key,$parameter["value"],$parameter["type"]);
				}
				
				$query->execute();
			}
			else
			{
				throw new \Exception("Sorry, there was a problem with the query statement.");
			}
		}
		catch (PDOException $e)
		{
			$exception = "Sorry, there was a problem with the query. ({$e->getMessage()})";
		}

		if($exception) throw new \Exception($exception);
		
		return $query->fetchAll($fetchMode);
	}
1169731
public function findAllByQuery($query, array $params = array()) {
		//Not using the parent findAllByQuery() implementation, becaus
		//it performs one-by-one EAV fetching, which is very bad for performance.
		//Instead, we find all main records with 1 query. And then fine all EAV entries (for all),
		//with a single additional query (instead of one per main record).

		$records = array();
		$recordIds = array();
		foreach ($this->db->fetchAll($query, $params) as $data) {
			$records[] = $data;
			$recordIds[] = $data['_id'];
		}

		$dataPerNamespaceFlattened = $this->pullEavDataForAll($recordIds);

		$results = array();
		foreach ($records as $data) {
			$data['__eav_data__'] = $dataPerNamespaceFlattened[$data['_id']];
			$results[] = $this->loadModel($data);
		}

		return $results;
	}