Executes a SQL query on the database.

@param string $queryString SPARQL- or SQL query to execute

@return \PDOStatement instance of PDOStatement which contains the result of the previous query

@throws \Exception If $queryString is invalid
333684
public function sqlQuery($queryString)
    {
        try {
            // execute query
            $query = $this->connection->prepare(
                $queryString,
                [\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY]
            );
            $query->execute();

            return $query;
        } catch (\PDOException $e) {
            throw new \Exception($e->getMessage());
        }
    }
800616
private static function mergeQueryString(?string $queryString, array $queryArray, bool $replace): ?string
    {
        if (!$queryArray) {
            return $queryString;
        }

        $query = [];

        if (null !== $queryString) {
            foreach (explode('&', $queryString) as $v) {
                if ('' !== $v) {
                    $k = urldecode(explode('=', $v, 2)[0]);
                    $query[$k] = (isset($query[$k]) ? $query[$k].'&' : '').$v;
                }
            }
        }

        foreach ($queryArray as $k => $v) {
            if (is_scalar($v)) {
                $queryArray[$k] = rawurlencode($k).'='.rawurlencode($v);
            } elseif (null === $v) {
                unset($queryArray[$k]);

                if ($replace) {
                    unset($query[$k]);
                }
            } else {
                throw new InvalidArgumentException(sprintf('Unsupported value for query parameter "%s": scalar or null expected, %s given.', $k, \gettype($v)));
            }
        }

        return implode('&', $replace ? array_replace($query, $queryArray) : ($query + $queryArray));
    }
523867
public function query($searchString)
    {
        $this->searchString = substr(\DB::connection()->getPdo()->quote($searchString), 1, -1);

        return $this;
    }
254272
private function execute()
    {
        // Let the generator do his work now,
        if ($this->queryType !== self::QUERY_INSERT && $this->queryType !== self::QUERY_UPDATE && $this->queryType !== self::QUERY_DELETE) {
            throw new QueryException("Can only do apply() on INSERT and UPDATE mode!", 0, $this->exception); // @codeCoverageIgnore
        }

        // Validate all variables
        if ($this->queryType === self::QUERY_INSERT) {
            // We should have the table, all required data.
            if (count($this->changeData) === 0 || empty($this->table)) {
                throw new QueryException("When inserting you should at least give a table and the inserting data!", 0, $this->exception); // @codeCoverageIgnore
            }
        }
        if ($this->queryType === self::QUERY_UPDATE) {
            // We should have a where with at least one condition, data, and a table
            if (count($this->whereConditions) === 0 || count($this->changeData) === 0 || empty($this->table)) {
                throw new QueryException("When updating you should at least give a table, at least one where condition and the updating data!", 0, $this->exception); // @codeCoverageIgnore
            }
        }
        if ($this->queryType === self::QUERY_DELETE) {
            // We should have a where and table
            if (count($this->whereConditions) === 0 || empty($this->table)) {
                throw new QueryException("When deleting you should at least give a table and at least one where condition!", 0, $this->exception); // @codeCoverageIgnore
            }
        }

        $this->bindValues = array();
        $this->bindTypes = array();

        // Generate parts
        if ($this->queryType === self::QUERY_INSERT) {
            $this->generator->generateInsert($this->columnOrder, $this->changeData, $this->start, $this->data, $this->bindValues, $this->bindTypes);
        }

        if ($this->queryType === self::QUERY_UPDATE) {
            $this->generator->generateJoin($this->joinTables, $this->join);
            $this->generator->generateUpdate($this->changeData, $this->data, $this->bindValues, $this->bindTypes);
            $this->generator->generateWhere($this->whereConditions, $this->where, $this->bindValues, $this->bindTypes);
        }

        if ($this->queryType === self::QUERY_DELETE) {
            $this->generator->generateJoin($this->joinTables, $this->join);
            $this->generator->generateWhere($this->whereConditions, $this->where, $this->bindValues, $this->bindTypes);
        }

        $this->query = "";
        $this->combineQuery();

        // Verify if bind has same number as the number of question marks in the query
        // TODO: Implement this when stable
        //$this->verifyQuery();

        $connection = ConnectionManager::getConnection();
        $query = $connection->prepare($this->query);

        // Bind all values
        $idx = 1;
        foreach ($this->bindValues as $key => $value) {
            $query->bindValue($idx, $value, $this->bindTypes[$key]);
            $idx++;
        }

        // Execute
        $status = $query->execute();

        if ($status && $this->queryType === self::QUERY_INSERT) {
            return $connection->lastInsertId();
        }
        return $status;
    }
636286
public function execute()
        {
            $values = ($this->getQuery() instanceof QueryInterface) ? $this->getQuery()->getValues() : array();
            if (Core::isDebugMode()) {
                if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                    \caspar\core\Logging::log('executing PDO query (' . Core::getSQLCount() . ') - ' . (($this->getQuery() instanceof Criteria) ? $this->getQuery()->getAction() : 'unknown'), 'B2DB');
                }

                $previous_time = Core::getDebugTime();
            }

            $res = $this->statement->execute($values);

            if (!$res) {
                $error = $this->statement->errorInfo();
                if (Core::isDebugMode()) {
                    Core::sqlHit($this, $previous_time);
                }
                throw new Exception($error[2], $this->printSQL());
            }
            if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                \caspar\core\Logging::log('done', 'B2DB');
            }

            if ($this->getQuery() instanceof Query && $this->getQuery()->isInsert()) {
                if (Core::getDriver() == Core::DRIVER_MYSQL) {
                    $this->insert_id = Core::getDBLink()->lastInsertId();
                } elseif (Core::getDriver() == Core::DRIVER_POSTGRES) {
                    $this->insert_id = Core::getDBLink()->lastInsertId(Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq');
                    if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                        \caspar\core\Logging::log('sequence: ' . Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq', 'b2db');
                        \caspar\core\Logging::log('id is: ' . $this->insert_id, 'b2db');
                    }
                }
            }

            $return_value = new Resultset($this);

            if (Core::isDebugMode()) {
                Core::sqlHit($this, $previous_time);
            }

            if (!$this->getQuery() || $this->getQuery()->isSelect()) {
                $this->statement->closeCursor();
            }

            return $return_value;
        }
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;
    }
871291
protected function buildUserSearchQuery($searchString = null)
    {
        $builder = $this->createQueryBuilder('u');

        if (!empty($searchString)) {
            $builder
                ->where($builder->expr()->like('u.email', ':searchString'))
                ->orWhere($builder->expr()->like('u.displayName', ':searchString'))
                ->setParameter('searchString', '%' .$searchString . '%');
        }

        return $builder;
    }
186130
public function query($statement) {
		try {
			$stmt = $this->pdo->query($statement);
			return new QueryResult($stmt, $this->pdo);
		} catch (PDOException $e) {
			throw $this->exceptionAdapter->adapt($e, $statement);
		}
	}
179038
public function query(string $query_string, array $params = [], array $options = []) : DAO
    {
        // Reset in case a previous query was attempted.
        $this->query_succeeded = false;

        // Connect to the database
        if (!$this->is_connected) {
            $this->connect();
        }

        try {
            $stmt = $this->getStatement($query_string);
            $this->stmt = $stmt;
            $stmt->execute($params);
        } catch (DatabaseQueryException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw new DatabaseQueryException($e->getMessage() . '|| QUERY: ' . $query_string);
        }

        $this->query_succeeded = $this->stmt->querySucceeded();

        return $this;
    }
1309318
public function affectingStatement( $query, $bindings = [] )
	{
		$new_query = $this->bind_params( $query, $bindings, true );

		$result = $this->db->query( $new_query );

		if ( $result === false || $this->db->last_error ) {
			throw new QueryException( $new_query, $bindings, new \Exception( $this->db->last_error ) );
		}

		return intval( $result );
	}
278771
public function execute($config = null)
    {

        if(null == $config){
            $pdo = Config::getDefault()->getPdo();
        }else if($config instanceof \PDO){
            $pdo = $config;
        }else if($config instanceof Config){
            $pdo = $config->getPdo();
        }else{
            throw new BadParameterException('First parameter of FQuery::execute is not correct');
        }

        $stmt = $this->getPdoStatement($pdo);

        if ($stmt->execute()) {
            return $stmt;

        } else {
            // TODO : handle errors ".__FILE__.":".__LINE__;
            throw new QueryFailedException($stmt);
            //return false;
        }

    }
25073
public function createConditionalAvailabilitySkuSearchQuery(?string $searchString): QueryInterface
    {
        $searchQuery = $this->getConditionalAvailabilitySkuSearchQueryPlugin();
        if ($searchQuery instanceof SearchStringSetterInterface) {
            $searchQuery->setSearchString($searchString);
        }

        return $searchQuery;
    }
291744
protected function callApi($queryString, $postData = null)
    {
        $this->setPostData($postData);

        $url = $this->apiUrl . '?' . $queryString . '&format=php';

        curl_setopt($this->curl, CURLOPT_URL, $url);

        $response = curl_exec($this->curl);
        $responseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);

        if (200 !== $responseCode) {
            throw new BuildException('Wiki webapi call failed (http response ' . $responseCode . ')');
        }

        $result = @unserialize($response);
        if (false === $result) {
            throw new BuildException('Couldn\'t unserialize Wiki webapi response');
        }

        return $result;
    }
597897
public function getQuery(): Query
    {
        if (count($this->what) == 0) {
            throw new Exception('Can not build UPDATE query, SET is not defined');
        }

        if ($this->table === null) {
            throw new Exception('Can not build UPDATE query when table name is not set');
        }

        $sql = "UPDATE {$this->table}\nSET\n";

        foreach ($this->what as $field => $value) {
            $sql .= "\t{$field} = ";
            if ($value instanceof Expr) {
                $sql .= "{$value},\n";
            } else {
                //$key = $this->bind($field, $value);
	            $key = $this->getBindings()->makeAndSet($field, $value);
                $sql .= ":{$key},\n";
            }
        }

        $sql = substr($sql, 0, -2);

        if ($this->hasWhere()) {
            $sql .= "\nWHERE{$this->getWhereSql()}";
        }

        if (count($this->orderBy) > 0) {
            $sql .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $sql .= "\n\t{$r['field']} {$r['direction']},";
            }
            $sql = substr($sql, 0, -1);
        }

        return new Query($sql, $this->getBindings(), $this->getAdapterConnection());
    }
348848
private static function httpParseQuery(string $queryString, string $argSeparator = '&', int $decType = PHP_QUERY_RFC1738): array
    {
        $result = [];
        $parts = explode($argSeparator, $queryString);

        foreach ($parts as $part) {
            list($paramName, $paramValue) = explode('=', $part, 2);

            switch ($decType) {
                case PHP_QUERY_RFC3986:
                    $paramName = rawurldecode($paramName);
                    $paramValue = rawurldecode($paramValue);
                    break;
                case PHP_QUERY_RFC1738:
                default:
                    $paramName = urldecode($paramName);
                    $paramValue = urldecode($paramValue);
                    break;
            }

            if (preg_match_all('/\[([^\]]*)\]/m', $paramName, $matches)) {
                $paramName = substr($paramName, 0, strpos($paramName, '['));
                $keys = array_merge([$paramName], $matches[1]);
            } else {
                $keys = [$paramName];
            }

            $target = &$result;

            foreach ($keys as $index) {
                if ('' === $index) {
                    if (is_array($target)) {
                        $intKeys = array_filter(array_keys($target), 'is_int');
                        $index = count($intKeys) ? max($intKeys) + 1 : 0;
                    } else {
                        $target = [$target];
                        $index = 1;
                    }
                } elseif (isset($target[$index]) && !is_array($target[$index])) {
                    $target[$index] = [$target[$index]];
                }

                $target = &$target[$index];
            }

            if (is_array($target)) {
                $target[] = $paramValue;
            } else {
                $target = $paramValue;
            }
        }

        return $result;
    }
936887
private function parseQueryString($queryString)
    {
        parse_str($queryString, $parsed);

        $supported = $this->getSupportedParams();
        foreach ($parsed as $param => $value) {
            if (!isset($supported[$param])) {
                throw RestException::unsupportedQueryParam($param, array_keys($supported));
            }
        }

        $this->extractInclusions($parsed);
        $this->extractSorting($parsed);
        $this->extractFields($parsed);
        $this->extractPagination($parsed);
        $this->extractFilters($parsed);
        return $this;
    }
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;
    }