ravendb / ravendb-php-client

MIT License
6 stars 4 forks source link

Query doesn't return results if count() is called before #53

Closed plexcellmedia closed 1 year ago

plexcellmedia commented 1 year ago

After updating package version to latest, this issue started to occur.

If $query->count() is called, then toList() returns empty array

try {
    $query = $session->query(Site::class)->whereEquals("userId", $userId);

    if ($query->count() <= 0) {
        return [];
    }

    return $query->toList(); // returns []
} finally {
    $session->close();
}

But if the count call is taken away, then it works.

try {
    $query = $session->query(Site::class)->whereEquals("userId", $userId);

    return $query->toList(); // returns [{}, {}, {}, ...]
} finally {
    $session->close();
}
alxsabo commented 1 year ago

Those are two different queries, and you can't use them in the way you mentioned.

First query when translated to RQL, it will be:

$session->query(Site::class)
->whereEquals("userId", $userId)
->toList();
from "Sites" 
where userId == "UserID"

and if you create a query with count(), it will create RQL like:

$session->query(Site::class)
->whereEquals("userId", $userId)
->count();
from "Sites"
where userId == "UserID" limit 0, 0

The method count() will return just an integer value. PHP client will send this query to the server to get the number of documents, but it will not return any document from the server. More about count can be found in the documentation: https://ravendb.net/docs/article-page/5.4/csharp/client-api/session/querying/how-to-count-query-results

It would be best to leave out the count() part for the mentioned case because 'toList()' method will always return an array.

ayende commented 1 year ago

Another thing to consider is that RavenDB doesn't need a separate query. You can use the getQueryStatistics() to get the results in one remote call.

See: https://github.com/ravendb/ravendb-php-client/blob/00c504c11fc250f1d0304f2a70bca06d1601014e/tests/Test/Client/Spatial/_SpatialTest/SpatialTest.php#L39C4-L47

$statsRef = new QueryStatistics();
$query = $session->query(Site::class)->whereEquals("userId", $userId);
$results = $query->statistics($statsRef)->toList();
$totalResults = $statsRef->getTotalResults();
plexcellmedia commented 1 year ago

Thank you both of you! It just felt like an issue, because the call to $query->count() overrides the $query variable, which it before didn't do. But this resolves with using statistics or changing our approach a little bit.