Execute Query and fetch a single record as entity

@return Entity[]|false Entities as successful result or false on not found.
@throws QueryException
495208
public function one()
    {
        if ($this->exception !== null) {
            throw $this->exception;
        }

        return $this->fetch(false, $this->fetchAssoc);
    }
1029672
public function execute()
    {
        $this->dispatcher->fire(self::EVENT_BEFORE);

        $stmt = $this->executeQuery();
        $result = $this->model->entity() ? $this->fetchAsObject($stmt) : $this->fetchAsAssoc($stmt);

        $this->dispatcher->fire(self::EVENT_AFTER, $result);

        foreach ($this->relations as $relation) {
            $result = $relation->read($result);
        }


        return $result;
    }
100548
public function runQuery()
    {
        $filters = $this->filters->get();
        $this->documents  = [];
        if (empty($filters))
            $filters = 'findAll';
        $this->documents = $this->databaseHandler->findAll()->getDocuments();
        if ($filters !== 'findAll')
            $this->filter($filters);
        $this->sort();
        $this->offsetLimit();
        if (is_array($this->fields) && !empty($this->fields))
        {
            foreach($this->documents as $index => $document)
            {
                $fields = new \stdClass();
                foreach($this->fields as $fieldTarget)
                    $fields->{$fieldTarget} = $document->{$fieldTarget};
                $this->documents[$index] = $fields;
            }
        }
        $this->databaseHandler->setDocuments($this->documents);
        return $this->databaseHandler;
    }
806140
public function getQuery(): Query
    {
    	// TODO: Bindings could be defined only locally in this method because it has to be regenerated on every call

        if (count($this->from) == 0) {
            throw new Exception('Can not build SELECT query, there is no FROM table defined');
        }

        $query = "SELECT\n";

        if (sizeof($this->fields) == 0) {
            $query .= "\t*";
        } else {
            foreach ($this->fields as $fld) {
                $field = $fld['name'];
                $as = $fld['as'];

                $query .= "\t{$field}";
                if ($as !== null) {
                    $query .= " as {$as}";
                }

                $query .= ",\n";
            }

            $query = substr($query, 0, -2);
        }

        $query .= "\nFROM";
        foreach ($this->from as $from) {
            if ($from['table'] instanceof static) {
                /* @var $subSelect \Koldy\Db\Query\Select */
                $subSelect = $from['table'];
                $subSql = $subSelect->__toString();
                $subSql = str_replace("\n", "\n\t", $subSql);
                $query .= " (\n\t{$subSql}\n) {$from['alias']}\n";

                $subSelectBindings = $subSelect->getBindings();
                if (!$subSelectBindings->isEmpty()) {
                    $this->getBindings()->addBindingsFromInstance($subSelectBindings);
                }
            } else {
                $query .= "\n\t{$from['table']}";
                if ($from['alias'] !== null) {
                    $query .= " as {$from['alias']},";
                } else {
                    $query .= ',';
                }
            }
        }
        $query = substr($query, 0, -1);

        foreach ($this->joins as $join) {
            $query .= "\n\t{$join['type']} {$join['table']} ON ";

            if (is_array($join['first'])) {
                foreach ($join['first'] as $joinArg) {
                    if ($joinArg instanceof Expr) {
                        $query .= "{$joinArg} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 2) {
                        $query .= "{$joinArg[0]} = {$joinArg[1]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 3) {
                        $query .= "{$joinArg[0]} {$joinArg[1]} {$joinArg[2]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 4) {
                        if (substr($query, -5) == ' AND ') {
                            $query = substr($query, 0, -5);
                        }

                        $query .= " {$joinArg[0]} {$joinArg[1]} {$joinArg[2]} {$joinArg[3]} AND ";

                    } else {
                        throw new Exception('Unknown JOIN argument');

                    }
                }

                $query = substr($query, 0, -5);
            } else {
                if ($join['operator'] === null) {
                    throw new Exception('Operator can\'t be null');
                }

                if ($join['second'] === null) {
                    throw new Exception('Second parameter can\'t be null');
                }

                $query .= "{$join['first']} {$join['operator']} {$join['second']}";
            }
        }

        if ($this->hasWhere()) {
            $query .= "\nWHERE\n\t" . trim($this->getWhereSql());
        }

        if (sizeof($this->groupBy) > 0) {
            $query .= "\nGROUP BY";
            foreach ($this->groupBy as $r) {
                $query .= " {$r['field']},";
            }
            $query = substr($query, 0, -1);
        }

        $sizeofHaving = count($this->having);
        if ($sizeofHaving > 0) {
            $query .= "\nHAVING";
            if ($sizeofHaving == 1) {
                $nl = ' ';
            } else {
                $nl = "\n\t";
            }

            foreach ($this->having as $index => $having) {
                $link = ($index > 0) ? "{$having['link']} " : '';
                if ($having['value'] instanceof Expr) {
                    $query .= "{$nl}{$link}{$having['field']} {$having['operator']} {$having['value']}";
                } else {
	                //$bindName = $this->bind($having['field'], $having['value'], 'h');
	                $bindName = $this->getBindings()->makeAndSet('h' . $having['field'], $having['value']);
	                $query .= "{$nl}{$link}{$having['field']} {$having['operator']} :{$bindName}";
                }
            }
        }

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

        if ($this->limit !== null) {
            $query .= "\nLIMIT {$this->limit->howMuch} OFFSET {$this->limit->start}";
        }

        return new Query($query, $this->getBindings(), $this->getAdapterConnection());
    }
303418
public function query($entity, $query)
	{
		$retValue = array();

		if (! is_null($this->_db)){
			try{
				$mongo = $this->_db->selectCollection($entity);

				// Find by query
				$cursor = $mongo->find($query);

				if (is_null($cursor))
					$retValue = array();
				else
					$retValue = iterator_to_array($cursor);
			}
			catch(Exception $e) {
				$this->_log->addError($e->getMessage());
			}	
		}

		return $retValue;
	}
59906
public function query()
    {
        // Pre-execute callbacks
        if( !empty($this->preExecuteCallbacks) ) {
            foreach( $this->preExecuteCallbacks as $callable ) {
                call_user_func($callable, $this);
            }
        }
        // Execute
        if( $this->database ) {
            //$this->interpolateParams();
            $result = $this->database->query($this);
        } else if( $this->queryCallback ) {
            $query = $this->toString();
            $params = $this->params();
            if( $this->interpolation ) {
                $result = call_user_func($this->queryCallback, $query);
            } else {
                $result = call_user_func($this->queryCallback, $query, $params);
            }
        } else {
            throw new LogicException('query() called when no callback or database adapter set');
        }
        // Post-execute callbacks
        if( !empty($this->postExecuteCallbacks) ) {
            foreach( $this->postExecuteCallbacks as $callable ) {
                call_user_func($callable, $result, $this);
            }
        }
        return $result;
    }
1366256
public function getAll()
    {
        $query = $this->createQuery();
        $result = $this->database->query($query);

        $entities = [];
        if ($result) {
            $result = $result->fetchAll(\PDO::FETCH_ASSOC);
            $entities = $this->handleResult($result);
        }
        if ($this->returnOne && is_array($entities)) {
            return current($entities);
        }
        return $entities;
    }
767640
public function execute() {
		$query = $this->buildQueryString();
		$result = $this->indexClient->executeStatement($query, $this->parameterMap);

		if (empty($result)) {
			return array();
		}

		return array_values($result);
	}
847963
public function fetch($query, $parameters = array())
    {
        try {
            $sth = $this->query($query, $parameters);
            if ($sth === false) {
                return false;
            }
            return $sth->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            throw new DbException("Error query: " . $e->getMessage());
        }
    }
1237841
public function fetch()
    {
        $this->logQueryStart();
        $results = null;

        if (is_array($this->termLookupMode)) {
            $queryLog = "get_term_by(" . Debugger::export($this->termLookupMode[0]) . ", " . Debugger::export($this->termLookupMode[1]) . ", " . Debugger::export($this->taxnomony) . ")";
            $results = get_term_by($this->termLookupMode[0], $this->termLookupMode[1], $this->taxnomony);
        } elseif (is_null($this->postId)) {
            $queryLog = "get_terms(" . Debugger::export($this->taxnomony) . ", " . Debugger::export($this->filters) . ")";
            $results = get_terms($this->taxnomony, $this->filters);
        } else {
            $queryLog = "get_the_terms(" . Debugger::export($this->postId) . ", " . Debugger::export($this->taxnomony) . ", " . Debugger::export($this->filters) . ")";
            $results = get_the_terms($this->postId, $this->taxnomony, $this->filters);
        }

        $this->logQueryCompletion($queryLog);

        if ($results === false) {
            return array();
        }

        if (!is_array($results)) {
            $results = array($results);
        }

        return $results;
    }
335992
public function getQuery() {
		$output	= $this->get('output');
		
		try  {
			$this->set('output', SQLAdapter::SQLQUERY);
			$result = $this->run();
		} catch( \Exception $e ) {
			
		}
		
		$this->set('output', $output);
		
		if( isset($e) ) {
			throw $e;
		}
		
		return $result;
	}
613129
protected function fetchData()
    {
        if (null === $this->_lastScrollId) {
            //first query - do search
            $options = ['scroll' => $this->scrollWindow];
            if(!$this->query->orderBy) {
                $options['search_type'] = 'scan';
            }
            $result = $this->query->createCommand($this->db)->search($options);

            //if using "scan" mode, make another request immediately
            //(search request returned 0 results)
            if(!$this->query->orderBy) {
                $result = $this->query->createCommand($this->db)->scroll([
                    'scroll_id' => $result['_scroll_id'],
                    'scroll' => $this->scrollWindow,
                ]);
            }
        } else {
            //subsequent queries - do scroll
            $result = $this->query->createCommand($this->db)->scroll([
                'scroll_id' => $this->_lastScrollId,
                'scroll' => $this->scrollWindow,
            ]);
        }

        //get last scroll id
        $this->_lastScrollId = $result['_scroll_id'];

        //get data
        return $this->query->populate($result['hits']['hits']);
    }
419011
private function execute()
    {
        $query = $this->qb->getQuery();

        if (true === $this->configs['translation_query_hints']) {
            if (true === $this->doctrineExtensions) {
                $query->setHint(
                    \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
                    'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
                );

                $query->setHint(
                    \Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
                    $this->locale
                );

                $query->setHint(
                    \Gedmo\Translatable\TranslatableListener::HINT_FALLBACK,
                    1
                );
            } else {
                throw new \Exception('execute(): "DoctrineExtensions" does not exist.');
            }
        }

        $query->setHydrationMode(Query::HYDRATE_OBJECT);

        return $query;
    }
220146
public function selectOnce()
    {
        if (is_null($this->sth)) {
            throw new QueryFailedException();
        }

        $result = $this->sth->fetch(\PDO::FETCH_OBJ);

        if ($result) {
            return $result;
        }

        return null;
    }
1143217
public function getData()
    {
        $request    = $this->request;
        $dql_fields = array_values($this->fields);

        // add sorting
        if ($request->get('iSortCol_0') !== null)
        {
            $order_field = current(explode(' as ', $dql_fields[$request->get('iSortCol_0')]));
        }
        else
        {
            $order_field = null;
        }
        $qb = clone $this->queryBuilder;
        if (!is_null($order_field))
        {
            $qb->orderBy($order_field, $request->get('sSortDir_0', 'asc'));
        }
        else
        {
            $qb->resetDQLPart('orderBy');
        }

        // extract alias selectors
        $select = array($this->entity_alias);
        foreach ($this->joins as $join)
        {
            $select[] = $join[1];
        }
        $qb->select(implode(',', $select));

        // add search
        $this->_addSearch($qb);

        // get results and process data formatting
        $query          = $qb->getQuery();
        $iDisplayLength = (int) $request->get('iDisplayLength');
        if ($iDisplayLength > 0)
        {
            $query->setMaxResults($iDisplayLength)->setFirstResult($request->get('iDisplayStart'));
        }
        $objects         = $query->getResult(Query::HYDRATE_OBJECT);
        $data            = array();
        $entity_alias    = $this->entity_alias;
        $joins           = $this->joins;
        $__getParentChain = function($field) use($entity_alias, $joins, &$__getParentChain) {
            foreach ($joins as $join)
            {
                if ($join[1] == $field[0])
                {
                    if ($join[0][0] == $entity_alias)
                    {
                        return substr($join[0], 2);
                    }
                    else
                    {
                        $f = $join[0];
                        if (strpos($f, ' '))
                        {
                            $_f = substr($f, 2, strpos($f, ' '));
                        }
                        else
                        {

                            $_f = substr($f, 2);
                        }
                        return $__getParentChain($join[0]) . '.' . $_f;
                    }
                }
            }
        };
        $__getKey = function($field) use($entity_alias, $__getParentChain) {
            $has_alias = preg_match_all('~([A-z]?\.[A-z]+)?\sas~', $field, $matches);
            $_f        = ( $has_alias > 0 ) ? $matches[1][0] : $field;
            $_f        = explode('.', $_f)[1];
            if ($field[0] != $entity_alias)
            {
                return $__getParentChain($field) . '.' . $_f;
            }
            return $_f;
        };
        $fields = array();
        foreach ($this->fields as $field)
        {
            $fields[] = $__getKey($field);
        }
        $__getValue = function($prop, $object)use(&$__getValue) {
            if (strpos($prop, '.'))
            {
                $_prop     = substr($prop, 0, strpos($prop, '.'));
                $ref_class = new \ReflectionClass($object);
                $property  = $ref_class->getProperty($_prop);
                $property->setAccessible(true);
                return $__getValue(substr($prop, strpos($prop, '.') + 1), $property->getValue($object));
            }
            $ref_class = new \ReflectionClass($object);
            $property  = $ref_class->getProperty($prop);
            $property->setAccessible(true);
            return $property->getValue($object);
        };
        foreach ($objects as $object)
        {
            $item = array();
            foreach ($fields as $_field)
            {
                $item[] = $__getValue($_field, $object);
            }
            $data[] = $item;
        }
        return array($data, $objects);
    }
1338959
public function getQuery()
    {
        switch ($this->queryClass) {
            case DeleteItem::class:
                return $this->makeDelete();
            case GetItem::class:
                return $this->makeGet();
            case PutItem::class:
                return $this->makePut();
            case Scan::class:
                return $this->makeScan();
            case UpdateItem::class:
                return $this->makeUpdate();
            case Query::class:
                return $this->makeQuery();
        }

        throw new \LogicException;
    }
308931
public function get(): array
    {
        try {
            $query = $this->apply($this->database->getTablePrefixer());
            $compiled = $this->database->getGrammar()->compileSelect($query);
            return $this->database->select($compiled->getSQL(), $compiled->getBindings());
        } catch (\Throwable $exception) {
            return $this->handleException($exception);
        }
    }