Query builder - gets the row for the query
DB::qbr("table"=>$table,"where"=>$where=array(),"order"=>$order=array(),"cols"=>$cols=array(),"groupby"=>$groupby=array(),"having"=>$having=array(),"offset"=>$offset=0,"time"=>$time=null)
173504
public static function qbr($table, $mixed = array()) {
        DB::connect();
        if (!$table) throw new \AsyncWeb\Exceptions\DBException("DB Error: Table name required! (0x0019249149)");
        $where = array();
        $order = array();
        $cols = array();
        $groupby = array();
        $having = array();
        $offset = 0;
        $time = null;
        if (!$table) throw new \AsyncWeb\Exceptions\DBException("DB Error, Table name required! (0x0019249149)");
        if (isset($mixed["where"])) $where = $mixed["where"];
        if (isset($mixed["order"])) $order = $mixed["order"];
        if (isset($mixed["cols"])) $cols = $mixed["cols"];
        if (isset($mixed["groupby"])) $groupby = $mixed["groupby"];
        if (isset($mixed["having"])) $having = $mixed["having"];
        if (isset($mixed["offset"])) $offset = $mixed["offset"];
        if (isset($mixed["time"])) $time = $mixed["time"];
        return DB::$connection->gr($table, $where, $order, $cols, $groupby, $having, $offset, $time);
    }
680380
public function get($q = [], $data = [])
    {
        extract($this->defaults);
        extract($q);

        if (!$table)
            throw new Exception("table [$tabel] not defined", 1);


        if (is_array($limit)) {
            $offset = $limit[1];
            $limit = $limit[0];
        }

        $sql =
            'SELECT '    . $select .
            ' FROM '     . $table .
            ($where ?   ' WHERE '    . $where   : '' ).
            ($orderby ? ' ORDER BY ' . $orderby : '' ).
            ' LIMIT '    . $offset . ',' . $limit;

        return $this->query($sql, $data);
    }
415410
public function getSqlPart($qb, $partName)
    {
        return $qb instanceof ORMQueryBuilder ? $qb->getDQLPart($partName) : $qb->getQueryPart($partName);
    }
1028354
function fetchAll()
    {
        if ( $this->items !== null )
            return $this->items;

        if ( $this->query === null )
        {
            $this->query = $this->generateSQL();
        }
        if ( $this->query === false )
            return array();
        $query = "SELECT * {$this->query} ORDER BY {$this->order}";
        $params = array( 'offset' => $this->offset,
                         'limit'  => $this->limit );
        $db = eZDB::instance();
        $rows = $db->arrayQuery( $query, $params );
        if ( count( $rows ) == 0 )
            $this->items = array();
        else
            $this->items = eZURLAliasQuery::makeList( $rows );
        return $this->items;
    }
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);
    }
460249
public function setupQb(QueryBuilder $qb, $filters)
    {
        $this->qb = $qb;
        $this->c = 0;
        $this->bind = array();

        $filters = $this->_unify($filters);

        $this->_setupOrderyBy($qb, $filters['orderby']);

        $this->_setFilters($qb, $filters['filters']);

        $filters['offset'] and $qb->setFirstResult($filters['offset']);

        $filters['limit'] and $qb->setMaxResults($filters['limit']);

        return $qb;
    }
369164
def where(cls, where_clause="", start_position="", max_results="", qb=None):
        
        if where_clause:
            where_clause = "WHERE " + where_clause

        if start_position:
            start_position = " STARTPOSITION " + str(start_position)

        if max_results:
            max_results = " MAXRESULTS " + str(max_results)

        select = "SELECT * FROM {0} {1}{2}{3}".format(
            cls.qbo_object_name, where_clause, start_position, max_results)

        return cls.query(select, qb=qb)
435684
public function getColumnQuery() {
        // prepare column types
        $type_val = $this->getTypeVal();
        // build query
        $query = $this->db->quotekey($this->name).' '.$type_val.' '.
            $this->getNullable();
        // unify default for booleans
        if (preg_match('/bool/i', $type_val) && $this->default!==null)
            $this->default = (int) $this->default;
        // default value
        if ($this->default !== false) {
            $def_cmds = array(
                'sqlite2?|mysql|pgsql' => 'DEFAULT',
                'mssql|sybase|dblib|odbc|sqlsrv' => 'constraint DF_'.$this->table->name.'_'.$this->name.' DEFAULT',
                'ibm' => 'WITH DEFAULT',
            );
            $def_cmd = $this->findQuery($def_cmds).' '.$this->getDefault();
            $query .= ' '.$def_cmd;
        }
        if (!empty($this->after) && $this->table instanceof TableModifier) {
            // `after` feature only works for mysql
            if (preg_match('/mysql/', $this->db->driver())) {
                $after_cmd = 'AFTER '.$this->db->quotekey($this->after);
                $query .= ' '.$after_cmd;
            }
        }
        return $query;
    }
629930
public function qb($table, $mixed = array()) {
        $where = array();
        $offset = null;
        $count = null;
        $order = array();
        $cols = array();
        $groupby = array();
        $having = array();
        $distinct = false;
        $time = null;
        if (!$table) throw new \AsyncWeb\Exceptions\DBException("DB Error: Table name required! (0x0029249148)");
        if (isset($mixed["Where"])) $where = $mixed["Where"];
        if (isset($mixed["Offset"])) $offset = $mixed["Offset"];
        if (isset($mixed["Count"])) $count = $mixed["Count"];
        if (isset($mixed["Limit"])) $count = $mixed["Limit"];
        if (isset($mixed["Sort"])) $order = $mixed["Order"];
        if (isset($mixed["Cols"])) $cols = $mixed["Cols"];
        if (isset($mixed["GroupBy"])) $groupby = $mixed["GroupBy"];
        if (isset($mixed["Having"])) $having = $mixed["Having"];
        if (isset($mixed["Distinct"])) $distinct = $mixed["Distinct"];
        if (isset($mixed["Time"])) $time = $mixed["Time"];
        if (isset($mixed["where"])) $where = $mixed["where"];
        if (isset($mixed["offset"])) $offset = $mixed["offset"];
        if (isset($mixed["count"])) $count = $mixed["count"];
        if (isset($mixed["limit"])) $count = $mixed["limit"];
        if (isset($mixed["order"])) $order = $mixed["order"];
        if (isset($mixed["cols"])) $cols = $mixed["cols"];
        if (isset($mixed["groupby"])) $groupby = $mixed["groupby"];
        if (isset($mixed["having"])) $having = $mixed["having"];
        if (isset($mixed["distinct"])) $distinct = $mixed["distinct"];
        if (isset($mixed["time"])) $time = $mixed["time"];
        return $this->g($table, $where, $offset, $count, $order, $cols, $groupby, $having, $distinct, $time);
    }
258287
protected function getQueryBuilderForDemand(): QueryBuilder
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder
            ->select('*')
            ->from('sys_redirect')
            ->orderBy('source_host')
            ->addOrderBy('source_path');

        $constraints = [];
        if ($this->demand->hasSourceHost()) {
            $constraints[] =$queryBuilder->expr()->eq(
                'source_host',
                $queryBuilder->createNamedParameter($this->demand->getSourceHost(), \PDO::PARAM_STR)
            );
        }

        if ($this->demand->hasSourcePath()) {
            $escapedLikeString = '%' . $queryBuilder->escapeLikeWildcards($this->demand->getSourcePath()) . '%';
            $constraints[] = $queryBuilder->expr()->like(
                'source_path',
                $queryBuilder->createNamedParameter($escapedLikeString, \PDO::PARAM_STR)
            );
        }

        if ($this->demand->hasTarget()) {
            $escapedLikeString = '%' . $queryBuilder->escapeLikeWildcards($this->demand->getTarget()) . '%';
            $constraints[] = $queryBuilder->expr()->like(
                'target',
                $queryBuilder->createNamedParameter($escapedLikeString, \PDO::PARAM_STR)
            );
        }

        if ($this->demand->hasStatusCode()) {
            $constraints[] =$queryBuilder->expr()->eq(
                'target_statuscode',
                $queryBuilder->createNamedParameter($this->demand->getStatusCode(), \PDO::PARAM_INT)
            );
        }

        if (!empty($constraints)) {
            $queryBuilder->where(...$constraints);
        }
        return $queryBuilder;
    }
668904
public function getFindByQuery(array $criteria = null, array $orderBy = null, $limit = null, $offset = null)
    {
        /** @var \Doctrine\ORM\QueryBuilder $qb */
        $qb = $this->createQueryBuilder('e');

        $firstCriteria = true;
        if (!empty($criteria)) {
            foreach ($criteria as $field => $value) {
                if ($firstCriteria) {
                    if ($value === null or $value === 'null') {
                        $qb->where("e.$field IS NULL");
                    } elseif ($value === 'not null') {
                        $qb->where("e.$field IS NOT NULL");
                    } else {
                        $qb->where("e.$field = :$field");
                        $qb->setParameter($field, $value);
                    }

                    $firstCriteria = false;
                } else {
                    if ($value === null or $value === 'null') {
                        $qb->andWhere("e.$field IS NULL");
                    } elseif ($value === 'not null') {
                        $qb->andWhere("e.$field IS NOT NULL");
                    } else {
                        $qb->andWhere("e.$field = :$field");
                        $qb->setParameter($field, $value);
                    }
                }
            }
        }

        $firstOrderBy = true;
        if (!empty($orderBy)) {
            foreach ($orderBy as $field => $value) {
                if ($firstOrderBy) {
                    $qb->orderBy("e.$field", $value);
                    $firstOrderBy = false;
                } else {
                    $qb->addOrderBy("e.$field", $value);
                }
            }
        }

        if (!empty($limit)) {
            $qb->setMaxResults($limit);
        }

        if (!empty($offset)) {
            $qb->setFirstResult($offset);
        }

        return $qb->getQuery();
    }
1186230
public function count()
    {
        if ($this->rowCount !== null) {
            return $this->rowCount;
        }

        $qbOriginal = $this->getQueryBuilder();
        $qb = clone $qbOriginal;

        $dqlParts = $qb->getDQLParts();
        $groupParts = $dqlParts['groupBy'];

        /*
         * Reset things
         */
        $qb->setFirstResult(null)
            ->setMaxResults(null)
            ->resetDQLParts([
            'orderBy',
            'select',
            ]);

        if (count($groupParts) > 1) {
            /*
             * UGLY WORKAROUND!!! @todo
             */
            // more than one group part...tricky!
            // @todo finde something better...
            $qb->resetDQLPart('groupBy');
            $qb->select('CONCAT('.implode(',', $groupParts).') as uniqueParts');

            $items = [];
            $result = $qb->getQuery()->getResult();
            foreach ($result as $row) {
                $items[] = $row['uniqueParts'];
            }
            $uniqueItems = array_unique($items);

            $this->rowCount = count($uniqueItems);
        } elseif (count($groupParts) == 1) {
            $groupPart = $groupParts[0];

            $qb->resetDQLPart('groupBy');
            $qb->select('COUNT(DISTINCT '.$groupPart.')');

            $this->rowCount = $qb->getQuery()->getSingleScalarResult();
        } else {
            // NO GROUP BY
            $countOneFunction = $qb->getEntityManager()
                ->getConfiguration()
                ->getCustomStringFunction('COUNT_ONE');
            if ($countOneFunction !== null) {
                $qb->select('COUNT_ONE() AS rowCount');
            } else {
                $fromPart = $dqlParts['from'];
                $qb->select('COUNT('.$fromPart[0]->getAlias().')');
            }

            $this->rowCount = $qb->getQuery()->getSingleScalarResult();
        }

        return $this->rowCount;
    }
522832
protected function query_row ( $sql )
	{
		$sql = $this->sql_printf(func_get_args());
		if (!($res = mysqli_query( $this->conn, $sql)))
		{
			$this->sql_errcheck($sql);
		}
		if ($row = mysqli_fetch_array($res))
		{
			$rs = $row;
		}
		else
		{
			$rs = false;
		}
		((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
		return $rs;
	}
3355
public function getPaginator( $where        = null,
                                  $order        = null,
                                  $columns      = null,
                                  $joins        = null,
                                  $quantifier   = null )
    {
        $joins = array_merge( (array) $joins, array(
            'user_group' => array(
                'table'     => $this->getTableInSchema( 'user_group' ),
                'where'     => 'user.groupId = user_group.id',
                'columns'   => array(
                    'groupName' => 'name',
                ),
            ),
        ) );

        return parent::getPaginator( $where, $order, $columns, $joins, $quantifier );
    }
203627
public function applyFilters(QueryBuilder $qb)
    {
        foreach ($this->getFilters() as $filter) {

            $type = null;
            $placeholder = $filter['valuePlaceholder'];
            if (is_array($filter['value'])) {
                $type = Connection::PARAM_STR_ARRAY;
                $filter['valuePlaceholder'] = '(' . $placeholder . ')';
            }

            $qb->andWhere($filter['column'] .' '. $filter['operator'] .' '. $filter['valuePlaceholder'])
                ->setParameter($placeholder, $filter['value'], $type);
        }

        return $qb;
    }
677123
public function getSearchResultByMySQL()
    {
        $queryParts = $this->getQueryParts();

        // build query
        $queryBuilder = self::getQueryBuilder('tx_kesearch_index');
        $queryBuilder->getRestrictions()->removeAll();
        $resultQuery = $queryBuilder
            ->add('select', $queryParts['SELECT'])
            ->from($queryParts['FROM'])
            ->add('where', $queryParts['WHERE']);
        if (!empty($queryParts['GROUPBY'])) {
            $resultQuery->add('groupBy', $queryParts['GROUPBY']);
        }
        if (!empty($queryParts['ORDERBY'])) {
            $resultQuery->add('orderBy', $queryParts['ORDERBY']);
        }

        $limit = $this->getLimit();
        if (is_array($limit)) {
            $resultQuery->setMaxResults(10);
            $resultQuery->setFirstResult($limit[0]);
        }

        // execute query
        $this->searchResults = $resultQuery->execute()->fetchAll();

        // log query
        if ($this->conf['logQuery']) {
            // @TODO use logging api https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Logging/Writers/Index.html
            GeneralUtility::devLog(
                'Search result query',
                $this->pObj->extKey,
                0,
                array($resultQuery->getSQL())
            );
        }

        $queryBuilder = self::getQueryBuilder('tx_kesearch_index');
        $queryBuilder->getRestrictions()->removeAll();
        $numRows = $queryBuilder
            ->add('select', 'FOUND_ROWS()')
            ->execute()
            ->fetchColumn(0);

        $this->numberOfResults = $numRows;

    }
1121852
private function getBuilderFor($qb)
    {
        foreach ($this->builders as $builder) {
            if ($builder->supports($qb)) {
                return $builder;
            }
        }

        throw new UnsupportedQueryBuilderException($qb);
    }