Add PV to original query.

@param $query
@throws \Zend_Db_Select_Exception
431472
private function queryAddPv($query)
    {
        $asSales = $this->getAliasForMainTable($query);
        if ($asSales) {
            /* there is 'sales_order' table - we can JOIN our tables to get PV */
            $tbl = $this->resource->getTableName(EPvSaleItem::ENTITY_NAME);
            $as = self::AS_PV_SALE_ITEM;
            $cols = [
                DPvSaleItem::A_PV_SUBTOTAL => EPvSaleItem::A_SUBTOTAL,
                DPvSaleItem::A_PV_DISCOUNT => EPvSaleItem::A_DISCOUNT,
                DPvSaleItem::A_PV_GRAND => EPvSaleItem::A_TOTAL,
            ];
            $cond = "$as." . EPvSaleItem::A_ITEM_REF . "=$asSales." . Cfg::E_SALE_ORDER_ITEM_A_ITEM_ID;
            $query->joinLeft([$as => $tbl], $cond, $cols);
        }
    }
702090
protected function pdoException(string $query, array $params) : void
    {
        $this->createException($this->pdo->errorInfo()[2], $query, $params);
    }
1128657
public function ExecuteMultiQuery($query)
    {
        $result = $this->db->multi_query($query);
        if ($result)
        {
            while ($this->db->next_result()) {;} //overgo the results!
        }
        if (!$result)
        {
            throw new DBExceptions\DatabaseException('Error in multi query', 101, $query);
        }
    }
1050238
public function select($query)
    {
        $clause = 'SELECT @DISTINCT';

        if ($query->operation['type'] & AnDomainQuery::QUERY_SELECT_DEFAULT) {
            $description = $query->getRepository()->getDescription();
            $columns = AnDomainQueryHelper::parseColumns($query, $query->columns);
            foreach ($description->getProperty() as $name => $property) {
                if (isset($columns[$name])) {
                    $result = AnDomainQueryHelper::parseColumn($query, $name);
                    if ($result['columns'] instanceof AnDomainResourceColumn) {
                        $columns[] = $columns[$name].' AS '.$this->_store->quoteValue($result['columns']->key());
                        unset($columns[$name]);
                    }
                } elseif ($property->isAttribute()) {
                    $columns[] = $property->getColumn();
                } elseif ($property->isRelationship() && $property->isManyToOne()) {
                    $columns = array_merge($columns, array_values(AnConfig::unbox($property->getColumns())));
                }
            }

            if ($description->getInheritanceColumn()) {
                $columns[] = $description->getInheritanceColumn();
            }

            foreach ($columns as $key => $column) {
                if ($column instanceof AnDomainResourceColumn) {
                    if ($column->resource->getLink()) {
                        $columns[$key] = $column.' AS '.$this->_store->quoteValue((string) $column);
                        continue;
                    } else {
                        $columns[$key] = (string) $column;
                    }
                }
                if (!is_numeric($key)) {
                    $columns[$key] = $column.' AS '.$this->_store->quoteValue($key);
                }
            }
            $clause .= ' '.implode(' , ', $columns);
        } else {
            $columns = (array) $query->operation['value'];
            $columns = AnDomainQueryHelper::parseColumns($query, $columns);
            $clause .= ' '.implode(' , ', $columns);
        }

        return $clause;
    }
1232451
protected function _quoteUpdate($query)
    {
        $table = $query->clause('update')[0];

        if (is_string($table)) {
            $query->update($this->_driver->quoteIdentifier($table));
        }
    }
1172785
public static function query($query)
    {
        //
        static::applySchema();

        //
        $table = self::getTable();
        $whereArray = [];

        //
        if (isset($query['where'])) {
            $whereArray[] = '('.$query['where'].')';
            unset($query['where']);
        }

        //
        foreach ($query as $field => $value) {
            if (in_array($field, ['order', 'limit'])) {
                continue;
            }
            $whereArray[] = "{$field} = '{$value}'";
        }

        //
        $where = count($whereArray) > 0 ? 'WHERE '.implode(' AND ', $whereArray) : '';
        $order = isset($query['order']) ? 'ORDER BY '.$query['order'] : '';
        $limit = isset($query['limit']) ? 'LIMIT '.$query['limit'] : '';
        $sql = "SELECT * FROM {$table} {$where} {$order} {$limit}";
        $results = static::getDatabase()->getResults($sql);

        //
        foreach ($results as &$record) {
            $record = static::create($record);
        }

        return $results;
    }
982417
protected function initSelectQuery(SelectQuery $query)
    {
        /** @var \eZ\Publish\Core\Persistence\Database\DatabaseHandler $databaseHandler */
        $databaseHandler = $this->getContainer()->get('ezpublish.connection');

        $query
            ->select(
                $databaseHandler->quoteColumn('id', 'ezcontentobject'),
                $databaseHandler->quoteColumn('current_version', 'ezcontentobject'),
                $databaseHandler->quoteColumn('initial_language_id', 'ezcontentobject'),
                $query->expr->count('distinct ezcontentobject_attribute.language_code')
            )
            ->from('ezcontentobject')
            ->innerJoin(
                $databaseHandler->quoteTable('ezcontentobject_attribute'),
                $query->expr->lAnd(
                    $query->expr->eq(
                        $databaseHandler->quoteColumn('id', 'ezcontentobject'),
                        $databaseHandler->quoteColumn(
                            'contentobject_id',
                            'ezcontentobject_attribute'
                        )
                    ),
                    $query->expr->eq(
                        $databaseHandler->quoteColumn('current_version', 'ezcontentobject'),
                        $databaseHandler->quoteColumn('version', 'ezcontentobject_attribute')
                    ),
                    // Join only with fields marked as always available
                    $query->expr->gt(
                        $query->expr->bitAnd(
                            $databaseHandler->quoteColumn(
                                'language_id',
                                'ezcontentobject_attribute'
                            ),
                            $query->bindValue(1, null, PDO::PARAM_INT)
                        ),
                        $query->bindValue(0, null, PDO::PARAM_INT)
                    )
                )
            )
            ->where(
                $query->expr->lAnd(
                    // Content is always available
                    $query->expr->gt(
                        $query->expr->bitAnd(
                            $databaseHandler->quoteColumn('language_mask', 'ezcontentobject'),
                            $query->bindValue(1, null, PDO::PARAM_INT)
                        ),
                        $query->bindValue(0, null, PDO::PARAM_INT)
                    ),
                    // Content exists in more than one language
                    $query->expr->neq(
                        $query->expr->bitAnd(
                            $query->expr->bitAnd(
                                $databaseHandler->quoteColumn('language_mask', 'ezcontentobject'),
                                $query->bindValue(-2, null, PDO::PARAM_INT)
                            ),
                            $query->expr->sub(
                                $query->expr->bitAnd(
                                    $databaseHandler->quoteColumn(
                                        'language_mask',
                                        'ezcontentobject'
                                    ),
                                    $query->bindValue(-2, null, PDO::PARAM_INT)
                                ),
                                $query->bindValue(1, null, PDO::PARAM_INT)
                            )
                        ),
                        $query->bindValue(0, null, PDO::PARAM_INT)
                    )
                )
            )
            ->groupBy($databaseHandler->quoteColumn('id', 'ezcontentobject'))
            // Remove Content with fields marked as always available in only one language
            ->having(
                $query->expr->gt(
                    $query->expr->count('distinct ezcontentobject_attribute.language_code'),
                    $query->bindValue(1, null, PDO::PARAM_INT)
                )
            );
    }
5277
protected function executeQuery($query)
        {
            $res = @odbc_exec($this->_lnk, $query);
            if(!$res) {
                $error = odbc_errormsg($this->_lnk);
                $this->log('Query failed: '.$error);
                throw new Exception('Executing query failed ' . $error, self::QUERY_FAILED);
            }
            return $res;
        }
443198
function setQuery($query)
    {
        if ($query !== null) {
            $q = $this->getQuery();
            $q->with($q::parseWith($query));
        }

        return $this;
    }
1366413
protected function addCriteriaToPositionQuery($query)
    {
        // Find products in the same category
        $products = ProductCategoryQuery::create()
            ->filterByCategoryId($this->getDefaultCategoryId())
            ->filterByDefaultCategory(true)
            ->select('product_id')
            ->find();

        if ($products != null) {
            $query->filterById($products, Criteria::IN);
        }
    }
178205
public function execQuery(Query $query)
    {
        $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $query->isSingle());
        $resultDataType = $query->getResultDataType();

        foreach ($query as $sql) {
            $sqlResult = $sql->getResult();
            if ($resultDataType instanceof DataInterface) {
                $sqlResult->setDataType($resultDataType);
            }

            try {
                if ($this->error->hasError()) {
                    throw new \PDOException($this->error->getMessage());
                    break;
                }
                $sqlQuery = $sql->toString();
                $totalRows = 0;
                if ($sql->getCommand() == 'SELECT' && !$query->isSingle()) {
                    $template = '{SQL}';
                    $templateCounter = 'SELECT COUNT(*) totalRows FROM (%s) fakeTable';
                    $templateParams = array(
                        'SQL' => $sqlQuery,
                        'LIMIT' => $query->getLimit(),
                        'OFFSET' => $query->getOffset(),
                    );
                    if ($query->getLimit()) {
                        switch ($this->config->getType()) {
                            case 'firebird':
                                $template = 'SELECT FIRST {LIMIT} SKIP {OFFSET} * FROM ({SQL}) fakeTable';
                            break;
                            case 'oci':
                                $templateCounter = 'SELECT COUNT(*) "totalRows" FROM (%s) "fakeTable"';
                                $template = 'SELECT a.* FROM (SELECT b.*, rownum "[]" FROM '.
                                            '({SQL}) b WHERE rownum <= {LIMIT}) a WHERE "[]" > {OFFSET}';
                            break;
                            default:
                                $template = 'SELECT * FROM ({SQL}) fakeTable LIMIT {LIMIT} OFFSET {OFFSET}';
                            break;
                        }
                    }

                    $resultCounter = $this->connection->prepare(sprintf($templateCounter, $sqlQuery));
                    $resultCounter->execute();
                    $totalRows = $resultCounter->fetch();

                    $sqlResult->setTotalRows((int) @$totalRows['totalRows']);
                    foreach ($templateParams as $key => $val) {
                        $template = str_replace('{'.$key.'}', $val, $template);
                    }
                    $sqlQuery = $template;
                }

                $result = $this->connection->prepare($sqlQuery);
                $stmt = $result->execute();
                $sql->execute();

                if ($sql->isRead()) {
                    $columns = $this->_define_column_types($result);

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected(0);
                    $sqlResult->setStartRow($query->getOffset());
                    if (!$sqlResult->getTotalRows()) {
                        $sqlResult->setTotalRows($result->rowCount());
                    }

                    $rows = $result->fetchAll(\PDO::FETCH_ASSOC);

                    foreach ($rows as $row) {
                        $data = $this->_merge_values($sql->getResult()->getDataType(), $row, $columns);
                        $sqlResult->add($data);
                    }

                    $sqlResult->setTotalShows($sqlResult->length());
                    $sqlResult->setEnd(microtime(true));
                } elseif ($sql->isWrite() || $sql->isDDL()) {
                    $insertId = $this->connection->lastInsertId();
                    $affected = $result->rowCount();
                    $endTime = microtime(true);
                    $sqlResult->setEnd($endTime);

                    $columns = array(
                        'affected' => 'integer',
                        'seconds' => 'double',
                    );

                    $row = array(
                        'affected' => $affected,
                        'seconds' => $sqlResult->getSeconds(),
                    );

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected($affected);

                    $data = new Data();
                    $this->_merge_values($data, $row, $columns);
                    $sqlResult->add($data);
                    $sqlResult->setInsertId($insertId);
                }
            } catch (\PDOException $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            } catch (\Exception $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            }
        }
    }
903932
private function runQuery($query)
    {
        $resultSetMapping = (new ResultSetMapping())
                ->addScalarResult('id', 'id')
                ->addScalarResult('type', 'type')
                ->addScalarResult('date', 'date');
        
        return $this->em->createNativeQuery($query, $resultSetMapping)
                ->getArrayResult();
    }
95248
public function initSelectQuery($model, $query)
    {
        // if ON is set, we don't have to worry about anything
        if ($this->on) {
            $query->join(
                $this->foreign_table.' '.$this->foreign_alias,
                $this->on instanceof \atk4\dsql\Expression ? $this->on : $model->expr($this->on),
                $this->kind
            );

            return;
        }

        $query->join(
            $this->foreign_table.(isset($this->foreign_alias) ? (' '.$this->foreign_alias) : ''),
            $model->expr('{}.{} = {}', [
                (isset($this->foreign_alias) ? $this->foreign_alias : $this->foreign_table),
                $this->foreign_field,
                $this->owner->getField($this->master_field),
            ]),
            $this->kind
        );

        /*
        if ($this->reverse) {
            $query->field([$this->short_name => ($this->join ?:
                (
                    (isset($this->owner->table_alias) ? $this->owner->table_alias : $this->owner->table)
                    .'.'.$this->master_field)
            )]);
        } else {
            $query->field([$this->short_name => $this->foreign_alias.'.'.$this->foreign_field]);
        }
         */
    }
750161
public function augmentSQL(SQLQuery &$query) {

		$base = ClassInfo::baseDataClass($this->owner);

		$simple = DB::getConn() instanceof SQLite3Database ? true : false;

		if ($simple) {
			$bound = "(($base.Up / $base.Down) / ($base.Up + $base.Down))";
		} else {
			$bound = "(($base.Up + 1.9208) / ($base.Up + $base.Down) - " .
                   "1.96 * SQRT(($base.Up * $base.Down) / ($base.Up + $base.Down) + 0.9604) / " .
                   "($base.Up + $base.Down)) / (1 + 3.8416 / ($base.Up + $base.Down))  / SQRT(HOUR(TIMEDIFF(NOW(), $base.Created)) + 1)";
		}

		$query->selectField($bound, 'WilsonRating');

		$query->selectField("($base.Up + $base.Down)", 'ActiveRating');

		$query->selectField("($base.Up - $base.Down)", "PositiveRating");

	}
942322
public function copyTo(Select $query)
    {
        $query->fields = $this->fields;
        $query->distinct = $this->distinct;
        $query->orders = $this->orders;
        $query->groups = $this->groups;
        $query->joins = $this->joins;
        $query->groupResults = $this->groupResults;
        $query->forwardKey = $this->forwardKey;
    }
616830
public function run($query)
    {
        $options = $this->options;
        $count = $query->getCountForPagination();

        if (!$options['limit']) {
            $options['page'] = 1;
        } elseif ($options['page'] < 1 || $options['page'] > ceil($count / $options['limit'])) {
            $options['page'] = 1;
        }

        $order = false;
        $direction = false;
        if (!empty($options['order'])) {
            if (is_array($options['order'])) {
                foreach ($options['order'] as $order_column) {
                    if (!empty($options['sort'][$order_column])) {
                        $order = $order_column;
                        if (isset($options['direction']) && strtolower($options['direction']) == 'desc') {
                            $direction = 'desc';
                            $query->orderBy($options['sort'][$order_column], 'DESC', true);
                        } else {
                            $direction = 'asc';
                            $query->orderBy($options['sort'][$order_column], 'ASC', true);
                        }
                    }
                }
            } else {
                if (!empty($options['sort'][$options['order']])) {
                    $order = $options['order'];
                    if (isset($options['direction']) && strtolower($options['direction']) == 'desc') {
                        $direction = 'desc';
                        $query->orderBy($options['sort'][$options['order']], 'DESC', true);
                    } else {
                        $direction = 'asc';
                        $query->orderBy($options['sort'][$options['order']], 'ASC', true);
                    }
                }
            }
        }
        // Add order by unique key
        if ($query instanceof \Globalis\PuppetSkilled\Database\Magic\Builder) {
            $isOrdering = !empty($query->getQuery()->orders);
        } else {
            $isOrdering = !empty($query->orders);
        }

        if ($isOrdering) {
            $query->orderBy($options['unique_order_key']);
        }

        if (!empty($options['limit_choices']) && !in_array($options['limit'], $options['limit_choices'])) {
            $options['limit'] = current($options['limit_choices']);
        }
        if (!empty($options['limit'])) {
            $query->limit($options['limit']);
            $query->offset(($options['page']-1) * $options['limit']);
        }

        $page = $options['page'];
        $limit = $options['limit'];

        if (!$options['limit']) {
            $pageCount = 1;
        } else {
            $pageCount = (int)ceil($count / $limit);
        }
        $this->result =  [
            'result'        => $query->get(),
            'page'          => $page,
            'total'         => $count,
            'perPage'       => $limit,
            'prevPage'      => ($page > 1),
            'nextPage'      => ($count > ($page * $limit)),
            'pageCount'     => $pageCount,
            'sort'          => $order,
            'direction'     => $direction,
            'limit'         => $limit,
            'limit_choices' => $options['limit_choices'],
        ];
        return $this->result;
    }
1044041
protected function sendQuery(string $query)
    {
        if (self::$monitorQueries) {
            self::$queriesCount++;
        }
        $result = $this->link->query($query);
        if ($result === false) {
            throw new SqlException(
                'SQL-error [' . $this->link->errno . ']: ' . $this->link->error . "\nSQL-query: $query",
                $this->link->errno
            );
        }

        return $result === true ? $result : new Query\Result($result);
    }