{@inheritDoc}
@throws \Lexide\Reposition\Exception\QueryException
353431
public function interpret(Query $query)
    {
        switch ($query->getAction()) {
            case Query::ACTION_FIND:
                /** @var FindQuery $query */
                return $this->compileFindQuery($query);
            case Query::ACTION_INSERT:
                /** @var InsertQuery $query */
                return $this->compileInsertQuery($query);
            case Query::ACTION_UPDATE:
                /** @var UpdateQuery $query */
                return $this->compileUpdateQuery($query);
            case Query::ACTION_DELETE:
                /** @var DeleteQuery $query */
                return $this->compileDeleteQuery($query);
            default:
                throw new QueryException("Invalid query action: {$query->getAction()}");
        }
    }
166672
protected function setJoin(Query $query = null)
    {
        $query = $query ?: $this->query;

        $foreignKey = $this->relatedMap->getTable().'.'.$this->secondKey;

        $query->join($this->parentMap->getTable(), $this->getQualifiedParentKeyName(), '=', $foreignKey);
    }
691169
protected function addCriteriaToPositionQuery($query)
    {
        $contents = ContentFolderQuery::create()
            ->filterByFolderId($this->getDefaultFolderId())
            ->filterByDefaultFolder(true)
            ->select('content_id')
            ->find();

        // Filtrer la requete sur ces produits
        if ($contents != null) {
            $query->filterById($contents, Criteria::IN);
        }
    }
795417
protected function _selectQueryTranslator($query)
    {
        $limit = $query->clause('limit');
        $offset = $query->clause('offset');

        if ($limit && $offset === null) {
            $query->modifier(['_auto_top_' => sprintf('TOP %d', $limit)]);
        }

        if ($offset !== null && !$query->clause('order')) {
            $query->order($query->newExpr()->add('(SELECT NULL)'));
        }

        if ($this->_version() < 11 && $offset !== null) {
            return $this->_pagingSubquery($query, $limit, $offset);
        }

        return $this->_transformDistinct($query);
    }
458
private static function _setWhere($where, QueryBuilder $query, string $primaryKey = "id") : QueryBuilder
    {
        if(!is_array($where)) {
            return $query->where([
                $primaryKey => $where
            ]);
        }

        $columns = $where;

        unset($columns["ORDER BY"]);
        unset($columns["LIMIT"]);
        unset($columns["OFFSET"]);

        if(!empty($columns)) {
            $query->where($columns);
        }

        if(isset($where["ORDER BY"])) {
            $order = $where["ORDER BY"];
            if(!is_array($order)) {
                $order = [$order];
            }

            $query->order(... $order);
        }
        if(isset($where["LIMIT"])) {
            $limit = $where["LIMIT"];
            if(!is_array($limit)) {
                $limit = [$limit];
            }

            $query->limit(... $limit);
        }
        if(isset($where["OFFSET"])) {
            $query->offset($where["OFFSET"]);
        }

        return $query;
    }
1047596
protected function getResults($query)
    {
         $searchFields = ($this->getSearchFields() ?: singleton($this->sourceObject)->stat('searchable_fields'));

        if(!$searchFields) {
            throw new Exception(
                sprintf('HasOneAutocompleteField: No searchable fields could be found for class "%s"',
                $this->sourceObject));
        }

        $params = [];
        $sort = [];
        
        foreach($searchFields as $searchField) {
            $name = (strpos($searchField, ':') !== FALSE) ? $searchField : "$searchField:PartialMatch:nocase";
            $params[$name] = $query;
            $sort[$searchField] = "ASC";
        }

        $results = DataList::create($this->sourceObject)
            ->filterAny($params)
            ->sort($sort)
            ->limit($this->getResultsLimit());

        return $results;
    }
981241
public function offset($offset)
    {
        if ($this->queryType !== self::QUERY_SELECT) {
            $this->exception = new QueryException("Offset can only be applied on SELECT mode!", 0, $this->exception);
            return $this;
        }
        if (! is_int($offset) || $offset < 0) {
            $this->exception = new QueryException("Offset value should be an positive integer!", 0, $this->exception);
            return $this;
        }
        $this->limitOffset = intval($offset);

        return $this;
    }
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());
    }
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());
    }
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;
    }
1285334
public function run($query = false, $exception = true)
    {

        if (true === $query) {
            return $this->resolveQuery($this->query);
        }

        list($prepare, $resolved) = $this->resolvePreparedStatement($this->query, $this->params);

        if (false === $resolved) {
            if (true === $exception) {
                $this->resolveQueryException();
            }
        }

        return $prepare;
    }
405843
public function formatFields(Query $query) {
        $joins = $query->getJoins();
        $type = $query->getType();

        switch ($type) {
            case Query::INSERT:
            case Query::MULTI_INSERT:
                $fields = $query->getData();

                if (empty($fields)) {
                    throw new InvalidQueryException('Missing field data for insert query');
                }

                if ($type === Query::MULTI_INSERT) {
                    $fields = $fields[0];
                }

                return '(' . $this->quoteList(array_keys($fields)) . ')';
            break;

            case Query::SELECT:
                $fields = $query->getFields();

                if ($joins) {
                    $columns = $this->formatSelectFields($fields, $query->getRepository()->getAlias());

                    foreach ($joins as $join) {
                        $fields = $join->getFields();

                        if (empty($fields)) {
                            throw new InvalidQueryException('Missing field data for join query');
                        }

                        $columns = array_merge($columns, $this->formatSelectFields($fields, $join->getAlias()));
                    }
                } else {
                    $columns = $this->formatSelectFields($fields);
                }

                return implode(', ', $columns);
            break;

            case Query::UPDATE:
                $fields = $query->getData();

                if (empty($fields)) {
                    throw new InvalidQueryException('Missing field data for update query');
                }

                if ($joins) {
                    $values = $this->formatUpdateFields($fields, $query->getRepository()->getAlias());

                    foreach ($joins as $join) {
                        $values = array_merge($values, $this->formatUpdateFields($join->getFields(), $join->getAlias()));
                    }
                } else {
                    $values = $this->formatUpdateFields($fields);
                }

                return implode(', ', $values);
            break;

            case Query::CREATE_INDEX:
                $fields = $query->getData();
                $columns = [];

                foreach ($fields as $column => $data) {
                    if (is_numeric($column)) {
                        $column = $data;
                        $data = [];
                    }

                    if (is_numeric($data)) {
                        $data = ['length' => $data, 'order' => '', 'collate' => ''];
                    } else if (is_string($data)) {
                        $data = ['length' => '', 'order' => $data, 'collate' => ''];
                    }

                    $column = $this->quote($column);

                    if (!empty($data['length'])) {
                        $column .= sprintf($this->getClause(self::GROUP), $data['length']);
                    }

                    if (!empty($data['collate'])) {
                        $column .= ' ' . sprintf($this->getClause(self::COLLATE), $data['collate']);
                    }

                    if (!empty($data['order'])) {
                        $column .= ' ' . $this->getKeyword($data['order']);
                    }

                    $columns[] = $column;
                }

                return implode(', ', $columns);
            break;
        }

        return '';
    }
1185106
public function doSearch($query = [])
    {
        if (!$this->index) {
            throw new \RuntimeException("You must set an index");
        }

        $this->prepare($query);

        // Only process query when there is a value, in order to avoid sending
        // an empty query string to ElasticSearch, its API is so weird that we
        // probably would end up with exceptions
        $value = $this->getQueryParam($query, $this->fulltextParameterName);
        if ($value) {
            $isQueryEmpty = false;

            $queryPart = [
                'query_string' => [
                    'query' => $this->fixSmartSearch((string)$value),
                    'fields' => $this->fulltextFields,
                 ],
            ];

            if ($this->fulltextAnalyzer) {
                $queryPart['query_string']['analyzer'] = $this->fulltextAnalyzer;
            }

        } else {
            $isQueryEmpty = true;
            $queryPart = [];
        }

        // This must be set before filter since filter query will be altered by
        // the applied aggregations
        $aggs = $this->buildAggQueryData($query);

        if (count($this->filterQuery)) {
            if ($isQueryEmpty) {
                $body = [
                    'query' => [
                        'constant_score' => [
                            'filter' => [
                                'fquery' => [
                                    'query' => [
                                        'query_string' => [
                                            'query' => (string)$this->filterQuery
                                        ],
                                    ],
                                    // @todo Without this ElasticSearch seems to
                                    // throw exceptions...
                                    '_cache' => true,
                                ],
                            ],
                        ],
                    ],
                ];
            } else {
                $body = [
                    'query' => [
                        'filtered' => [
                            'query'  => $queryPart,
                            'filter' => [
                                'fquery' => [
                                    'query' => [
                                        'query_string' => [
                                            'query' => (string)$this->filterQuery
                                        ],
                                    ],
                                    // @todo Without this ElasticSearch seems to
                                    // throw exceptions...
                                    '_cache' => true,
                                ],
                            ],
                        ],
                    ],
                ];
            }
        } else {
            if ($isQueryEmpty) {
                $body = [
                    'query' => [
                        'match_all' => []
                    ],
                ];
            } else {
                $body = [
                    'query' => $queryPart,
                ];
            }
        }

        if (count($this->postFilterQuery)) {
            $body['post_filter']['query_string']['query'] = (string)$this->postFilterQuery;
        }

        if ($aggs) {
            $body['aggs'] = $aggs;
        }
/*
        if ($this->fields) {
            $body['fields'] = $this->fields;
        }*/

        if (count($this->sortFields)) {
            foreach ($this->sortFields as $sort) {
                $body['sort'][] = $sort->getSortStructure();
            }
        }

        $data = [
            'index' => $this->index,
            'type'  => 'node',
            'body'  => $body,
        ];

        if (!empty($this->limit)) {
            $data['size'] = $this->limit;
            if (!empty($this->page)) {
                $data['from'] = max([0, $this->page - 1]) * $this->limit;
            }
        }

        return new Response($this, $this->client->search($data));
    }
961702
function executeNonQuery($query) {

        try {
            $connection = $this->getConnection();

            if (!mysql_query($query, $connection)) {
                mysql_close($connection);
                throw new \Exception("SQL Error: " . mysql_error());
            }

            mysql_close($connection);
        } catch (\Exception $pEx) {
            throw new \Exception("Fallo al ejecutar la query: " . $query . $pEx->getMessage());
        }
    }
408334
public function query($type = 'object')
    {
        $sql = 'select '.$this->columns.' from '.$this->getTables($this->tables).' '.$this->where.' '.$this->order.' '.$this->group;

        static::$sql = static::$register[] = $sql;
        //
        if ($data = Database::read($sql)) {
            return self::fetch($data, $type);
        } elseif (Database::execerr()) {
            throw new QueryException();
        }
    }
1135449
public function prepare(string $queryStatement): void
    {
        try {
            $this->stmt = $this->getPDO()->prepare($queryStatement);
        } catch (PDOException $e) {
            //$dashes = str_repeat('=', 50);
            //Log::notice("Can't prepare query statement ({$this->getConfigKey()}):\n{$dashes}\n{$queryStatement}\n{$dashes}");

            $exception = new QueryException($e->getMessage(), (int)$e->getCode(), $e);
            $exception->setSql($queryStatement);
            throw $exception;
        }
    }
501525
protected function getQueryLocation($database, $query, $limit = null, $fetchPlan = null, $language = BindingInterface::LANGUAGE_SQLPLUS)
    {
        $arguments = array($language, $query);

        if (isset($limit)) {
            $arguments[] = $limit;
        }

        if (isset($fetchPlan)) {
            $arguments[] = $fetchPlan;
        }

        return $this->getLocation('query', $database, $arguments);
    }