Skip to content

Commit

Permalink
#8700 Added Builder macro to count records in a safe and performant way
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasraoni committed Mar 23, 2023
1 parent 1e9678c commit 01a32bb
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions classes/core/PKPApplication.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
define('WORKFLOW_TYPE_AUTHOR', 'author');

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Query\Builder;

interface iPKPApplicationInfoProvider {
/**
Expand Down Expand Up @@ -224,6 +225,17 @@ public function initializeDatabaseConnection() {
error_log("Database query\n$query->sql\n" . json_encode($query->bindings));//\n Bindings: " . print_r($query->bindings, true));
});

Builder::macro('safeCount', function (): int {
// Clone query to avoid side-effects
/** @var Builder */
$query = clone $this;
// Discard the SELECT and ORDER BY clauses
$query->select(Capsule::raw('0'))->reorder();
// Enclose in a sub-query to avoid Laravel issues with GROUP BY queries
return Capsule::table(Capsule::raw("({$query->toSql()}) AS query"))
->mergeBindings($query)
->count();
});

// Set up Laravel queue handling
$laravelContainer->bind('exception.handler', function () {
Expand Down

0 comments on commit 01a32bb

Please sign in to comment.