cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[2.1.x] Paginator Query Adapter can't handle subqueries as columns

Open michanismus opened this issue 10 years ago • 2 comments

Hi,

Paginator can't handle queries with subqueries defined as column.

Example:

 $queryBuilder
            ->columns(
                array(
                    'invoice.id', 'invoice.invoiceDate', 'invoice.number', 'invoice.dueDate',
                    'customer.company',
                    'contract.number AS contractNumber',
                    'ROUND(
                        (SELECT SUM(amount * price) FROM Fcz\DefaultBundle\Model\InvoicePosition WHERE invoiceId = invoice.id) * ((100 + invoice.tax) / 100),
                        2
                    ) as total',
                    'ROUND(
                        (SELECT SUM(amount) FROM Fcz\DefaultBundle\Model\InvoiceIncome WHERE invoiceId = invoice.id),
                        2
                    ) as paid',
                )
            )
            ->leftJoin('Fcz\DefaultBundle\Model\Customer', 'customer.id = invoice.customerId', 'customer')
            ->leftJoin('Fcz\DefaultBundle\Model\Booking', 'invoice.bookingId = booking.id', 'booking')
            ->leftJoin('Fcz\DefaultBundle\Model\Contract', 'contract.bookingId = booking.id', 'contract')
            ;

The query works until I try to add where condition for subquery field "total". The reason is this line: https://github.com/phalcon/cphalcon/blob/master/phalcon/paginator/adapter/querybuilder.zep#L163

All columns are replaced by "COUNT(*) [rowcount]" and now we fire the query without the subquery field what, of course, fails.

michanismus avatar Feb 04 '16 11:02 michanismus

Ok, my results so far. I modified the Paginator\Adapter\QueryBuilder and ended up like this:

        /**
         * Change the queried columns by a COUNT(*)
         */
        let totalColumns = totalBuilder->getColumns();

        if typeof totalColumns == "array" {
            let totalColumns[] = "COUNT(*) [rowcount]";
        } else {
            let totalColumns .= ", COUNT(*) [rowcount]";
        }

        totalBuilder->columns(totalColumns);

That works with subqueries as column but the rowcount is wrong with conditions on a subquery field.

I extended the QueryBuilder (php) and everything works fine now! Here is my final solution:

        /**
         * Remove the 'ORDER BY' clause, PostgreSQL requires this
         */
        $totalBuilder->orderBy(null);

        $dependencyInjector = $totalBuilder->getDi();
        $totalQuery         = $totalBuilder->getQuery();
        $intermediate       = $totalQuery->parse();
        $bindParams         = $totalQuery->getBindParams();
        $bindTypes          = $totalQuery->getBindTypes();
        $connectionTypes    = array();

        foreach ($intermediate["models"] as $modelName) {

            $model = $dependencyInjector['modelsManager']->load($modelName, true);

            // Get database connection
            if (method_exists($model, "selectReadConnection")) {
                // use selectReadConnection() if implemented in extended Model class
                $connection = $model->selectReadConnection($intermediate, $bindParams, $bindTypes);
                if (!is_object($connection)) {
                    throw new \Exception("'selectReadConnection' didn't return a valid connection");
                }
            } else {
                $connection = $model->getReadConnection();
            }

            // More than one type of connection is not allowed
            $connectionTypes[$connection->getType()] = true;
            if (count($connectionTypes) == 2) {
                throw new \Exception("Cannot use models of different database systems in the same query");
            }
        }

        /**
         * Obtain the SQL for the total query
         */
        $totalSql = $totalQuery->getSql();

        /**
         * Obtain the result of the total query
         */
        $result = $connection->fetchOne(
            'SELECT COUNT(*) AS rowcount FROM (' . $totalSql['sql'] . ') AS countTable',
            \Phalcon\Db::FETCH_ASSOC,
            $bindParams,
            $bindTypes
        );

        $rowcount   = $result['rowcount'];
        $totalPages = intval(ceil($rowcount / $limit));

I only remove the order by and put the query into a count query. It is possible to use conditions on subquery fields or calculated join fields like "SUM(.......) AS total".

Unfortunately PHQL does not support "FROM (SELECT ....) as tableAlias", so I had to use raw sql.

What do think? Should I create a pull request?

michanismus avatar Feb 05 '16 12:02 michanismus

Thank you for contributing to this issue. As it has been 90 days since the last activity, we are automatically closing the issue. This is often because the request was already solved in some way and it just wasn't updated or it's no longer applicable. If that's not the case, please feel free to either reopen this issue or open a new one. We will be more than happy to look at it again! You can read more here: https://blog.phalconphp.com/post/github-closing-old-issues

stale[bot] avatar Apr 17 '18 02:04 stale[bot]