Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions CRM/Logging/Differ.php
Original file line number Diff line number Diff line change
Expand Up @@ -461,10 +461,9 @@ public function getAllChangesForConnection($tables, $limit = 0, $offset = 0) {
* @param array $tables
* Array of tables to inspect.
*
* @return array
* @return int
*/
public function getCountOfAllContactChangesForConnection($tables) {
$count = 0;
$params = [1 => [$this->log_conn_id, 'String']];
foreach ($tables as $table) {
if (empty($sql)) {
Expand All @@ -475,8 +474,7 @@ public function getCountOfAllContactChangesForConnection($tables) {
}
}
$countSQL = " SELECT count(*) as countOfContacts FROM ({$sql}) count";
$count = CRM_Core_DAO::singleValueQuery($countSQL, $params);
return $count;
return (int) CRM_Core_DAO::singleValueQuery($countSQL, $params);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions CRM/Logging/ReportDetail.php
Original file line number Diff line number Diff line change
Expand Up @@ -381,11 +381,11 @@ public function getAllContactChangesForConnection() {
/**
* Get an count of contacts with changes.
*
* @return mixed
* @return int
*/
public function getCountOfAllContactChangesForConnection() {
if (empty($this->log_conn_id)) {
return [];
return 0;
}
$this->setDiffer();
try {
Expand Down
105 changes: 97 additions & 8 deletions CRM/Report/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,13 @@ class CRM_Report_Form extends CRM_Core_Form {
*/
public $optimisedForOnlyFullGroupBy = TRUE;

/**
* User variables assigned by the last buildRows() query, restored before it is counted.
*
* @var string[]
*/
private $rowsFoundVariables = [];

/**
* Determines which chart types are supported for this report
* @var string[]
Expand Down Expand Up @@ -3251,10 +3258,16 @@ public function buildRows($sql, &$rows) {
if (!$this->optimisedForOnlyFullGroupBy) {
CRM_Core_DAO::disableFullGroupByMode();
}
$dao = CRM_Core_DAO::executeQuery($sql);
if (stristr($this->_select, 'SQL_CALC_FOUND_ROWS')) {
$this->_rowsFound = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
// Report extensions may still build legacy SELECT SQL_CALC_FOUND_ROWS queries.
$sql = preg_replace('/\bSQL_CALC_FOUND_ROWS\b/i', '', $sql);
// Queries that number rows through user variables (e.g. a top-N filter on @rows)
// are counted again from the same start values.
preg_match_all('/@(\w+)\s*:=/', $sql, $variables);
$this->rowsFoundVariables = array_unique($variables[1]);
if ($this->rowsFoundVariables) {
CRM_Core_DAO::executeQuery('SET ' . implode(', ', array_map(fn($name) => "@civicrm_report_$name := @$name", $this->rowsFoundVariables)));
}
$dao = CRM_Core_DAO::executeQuery($sql);
CRM_Core_DAO::reenableFullGroupByMode();
if (!is_array($rows)) {
$rows = [];
Expand All @@ -3265,6 +3278,7 @@ public function buildRows($sql, &$rows) {

$unselectedSectionColumns = $this->unselectedSectionColumns();

$fetched = 0;
while ($dao->fetch()) {
$row = [];
foreach ($this->_columnHeaders as $key => $value) {
Expand All @@ -3281,6 +3295,82 @@ public function buildRows($sql, &$rows) {
}

$rows[] = $row;
$fetched++;
}
$this->setRowsFound($sql, $fetched);
}

/**
* Set the total number of rows a paged query matches, for the pager.
*
* A page that is not full already gives the total; otherwise the query is
* counted again without its trailing LIMIT clause.
*
* @param string $sql
* The query as executed.
* @param int $fetched
* Number of rows it returned.
*/
protected function setRowsFound(string $sql, int $fetched): void {
if (!preg_match('/\sLIMIT\s+(\d+)(?:\s*,\s*(\d+)|\s+OFFSET\s+(\d+))?\s*$/i', $sql, $limit)) {
$this->_rowsFound = $fetched;
return;
}
$hasComma = ($limit[2] ?? '') !== '';
$offset = (int) ($hasComma ? $limit[1] : ($limit[3] ?? 0));
$rowCount = (int) ($hasComma ? $limit[2] : $limit[1]);
if ($fetched < $rowCount && ($fetched > 0 || $offset === 0)) {
$this->_rowsFound = $offset + $fetched;
return;
}
if (!$this->addPaging) {
// No pager is rendered, so the total stays unknown.
$this->_rowsFound = NULL;
return;
}
$this->_rowsFound = $this->countRowsFound(substr($sql, 0, -strlen($limit[0])));
}
Comment thread
jfilter marked this conversation as resolved.
Resolved

/**
* Count the rows a query returns.
*
* @param string $sql
* Query without LIMIT clause.
*
* @return int
*/
protected function countRowsFound(string $sql): int {
if (!$this->optimisedForOnlyFullGroupBy) {
CRM_Core_DAO::disableFullGroupByMode();
}
// Report extensions may still pass legacy SELECT SQL_CALC_FOUND_ROWS queries.
$sql = preg_replace('/\bSQL_CALC_FOUND_ROWS\b/i', '', $sql);
try {
$this->restoreRowsFoundVariables();
$count = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM ($sql) civicrm_report_rows_found");
}
catch (\Civi\Core\Exception\DBQueryException $e) {
// A derived table rejects repeated column names (error 1060); a CTE column list renames them.
if ($e->getSQLErrorCode() !== 1060) {
throw $e;
}
$columnCount = CRM_Core_DAO::executeQuery("$sql LIMIT 0")->getDatabaseResult()->numCols();
$columns = implode(', ', array_map(fn($i) => "column_$i", range(1, $columnCount)));
$this->restoreRowsFoundVariables();
$count = (int) CRM_Core_DAO::singleValueQuery("WITH civicrm_report_rows_found ($columns) AS ($sql) SELECT COUNT(*) FROM civicrm_report_rows_found");
}
Comment thread
jfilter marked this conversation as resolved.
Resolved
finally {
CRM_Core_DAO::reenableFullGroupByMode();
}
return $count;
}
Comment thread
jfilter marked this conversation as resolved.
Resolved

/**
* Reset the user variables the report query assigns to their values before it ran.
*/
private function restoreRowsFoundVariables(): void {
if ($this->rowsFoundVariables) {
CRM_Core_DAO::executeQuery('SET ' . implode(', ', array_map(fn($name) => "@$name := @civicrm_report_$name", $this->rowsFoundVariables)));
}
}

Expand Down Expand Up @@ -3707,8 +3797,6 @@ public function limit($rowCount = NULL) {
$rowCount = $this->_dashBoardRowCount;
}
if ($this->addPaging) {
$this->_select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);

$pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');

// @todo all http vars should be extracted in the preProcess
Expand Down Expand Up @@ -3756,9 +3844,10 @@ public function setPager($rowCount = NULL) {
}

if ($this->_limit && ($this->_limit != '')) {
if (!$this->_rowsFound) {
$sql = "SELECT FOUND_ROWS();";
$this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
if ($this->_rowsFound === NULL && $this->addPaging) {
// Report extensions that run their own SELECT SQL_CALC_FOUND_ROWS query rely on this.
CRM_Core_Error::deprecatedWarning('Report pager totals from FOUND_ROWS() are deprecated: call setRowsFound() after running the report query.');
$this->_rowsFound = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
}
$params = [
'total' => $this->_rowsFound,
Expand Down
12 changes: 2 additions & 10 deletions CRM/Report/Form/Contribute/Detail.php
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ public function statistics(&$rows) {
public function buildQuery($applyLimit = FALSE) {
if ($this->isTempTableBuilt) {
$this->limit();
return "SELECT SQL_CALC_FOUND_ROWS * FROM {$this->temporaryTables['civireport_contribution_detail_temp3']['name']} $this->_orderBy $this->_limit";
return "SELECT * FROM {$this->temporaryTables['civireport_contribution_detail_temp3']['name']} $this->_orderBy $this->_limit";
}
return parent::buildQuery($applyLimit);
}
Expand Down Expand Up @@ -581,13 +581,6 @@ public function beginPostProcessCommon() {
$sql = "{$select} {$this->_from} {$this->_where} $this->_groupBy";
$this->createTemporaryTable('civireport_contribution_detail_temp2', $sql);

if (($this->_params['contribution_or_soft_value'] ?? NULL) ==
'soft_credits_only'
) {
// revise pager : prev, next based on soft-credits only
$this->setPager();
}

// copy _from for later use of stats calculation for soft credits, and reset $this->_from to main query
$this->_softFrom = $this->_from;

Expand Down Expand Up @@ -866,8 +859,7 @@ public function sectionTotals() {

if (!empty($this->_sections)) {
// build the query with no LIMIT clause
$select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
$sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
$sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";

// pull section aliases out of $this->_sections
$sectionAliases = array_keys($this->_sections);
Expand Down
7 changes: 2 additions & 5 deletions CRM/Report/Form/Contribute/History.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,17 +616,14 @@ public function buildRows($sql, &$rows) {
$this->limit();
$getContacts = "SELECT {$this->_aliases['civicrm_contact']}.id as cid, SUM({$this->_aliases['civicrm_contribution']}.total_amount) as civicrm_contribution_total_amount_sum {$this->_from} {$this->_where} {$addWhere} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_having}";

// Run it without limit/offset first to get the right number of rows for
// the pager.
CRM_Core_DAO::executeQuery($getContacts);
$this->setPager();

$getContacts .= ' ' . $this->_limit;
$dao = CRM_Core_DAO::executeQuery($getContacts);

while ($dao->fetch()) {
$contactIds[] = $dao->cid;
}
$this->setRowsFound($getContacts, count($contactIds));
$this->setPager();
Comment thread
jfilter marked this conversation as resolved.
Resolved

$relationshipRows = [];
if (empty($contactIds)) {
Expand Down
9 changes: 2 additions & 7 deletions CRM/Report/Form/Contribute/Lybunt.php
Original file line number Diff line number Diff line change
Expand Up @@ -543,14 +543,10 @@ public function beginPostProcessCommon() {
$this->resetFormSqlAndWhereHavingClauses();

$this->contactTempTable = $this->createTemporaryTable('rptlybunt', "
SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid {$this->_from}
SELECT {$this->_aliases['civicrm_contact']}.id as cid {$this->_from}
{$this->_where}
GROUP BY {$this->_aliases['civicrm_contact']}.id"
);
$this->limit();
if (empty($this->_params['charts'])) {
$this->setPager();
}

// Reset where clauses to be regenerated in postProcess.
$this->_whereClauses = [];
Expand Down Expand Up @@ -600,8 +596,7 @@ public function buildQuery($applyLimit = TRUE) {
foreach ($this->_orderByFields as $field) {
$this->_orderBy = str_replace($field['dbAlias'], $field['tplField'], $this->_orderBy);
}
$sql = str_replace('SQL_CALC_FOUND_ROWS', '', $sql);
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM ( $sql ) as inner_query {$this->_orderBy} $this->_limit";
$sql = "SELECT * FROM ( $sql ) as inner_query {$this->_orderBy} $this->_limit";
}

CRM_Utils_Hook::alterReportVar('sql', $this, $this);
Expand Down
1 change: 1 addition & 0 deletions CRM/Report/Form/Contribute/Repeat.php
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,7 @@ public function postProcess() {
}
$count++;
}
$this->setRowsFound($sql, $count);

// FIXME: calculate % using query
foreach ($rows as $uid => $row) {
Expand Down
3 changes: 2 additions & 1 deletion CRM/Report/Form/Contribute/Sybunt.php
Original file line number Diff line number Diff line change
Expand Up @@ -362,13 +362,14 @@ public function postProcess() {
$rows = $contactIds = [];
if (empty($this->_params['charts'])) {
$this->limit();
$getContacts = "SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid {$this->_from} {$this->_where} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_limit}";
$getContacts = "SELECT {$this->_aliases['civicrm_contact']}.id as cid {$this->_from} {$this->_where} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_limit}";

$dao = CRM_Core_DAO::executeQuery($getContacts);

while ($dao->fetch()) {
$contactIds[] = $dao->cid;
}
$this->setRowsFound($getContacts, count($contactIds));
$this->setPager();
}

Expand Down
45 changes: 12 additions & 33 deletions CRM/Report/Form/Contribute/TopDonor.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
*/
protected $_groupLimit = '';

/**
* Offset of the current page, so ranks continue across pages.
*
* @var int
*/
protected $rankOffset = 0;

/**
*/
public function __construct() {
Expand Down Expand Up @@ -346,40 +353,12 @@ public function add2group($groupID) {
}

/**
* @param int $rowCount
* @inheritDoc
*/
public function limit($rowCount = NULL) {
$rowCount ??= $this->getRowCount();
// lets do the pager if in html mode
$this->_limit = NULL;

// CRM-14115, over-ride row count if rowCount is specified in URL
if ($this->_dashBoardRowCount) {
$rowCount = $this->_dashBoardRowCount;
}
if ($this->_outputMode == 'html') {
// Replace only first occurrence of SELECT.
$this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
$pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');

if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
if (!isset($_POST['PagerBottomButton'])) {
unset($_POST['crmPID_B']);
}
else {
$pageId = max((int) @$_POST['crmPID_B'], 1);
}
}

$pageId = $pageId ?: 1;
$this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
$offset = ($pageId - 1) * $rowCount;

$offset = CRM_Utils_Type::escape($offset, 'Int');
$rowCount = CRM_Utils_Type::escape($rowCount, 'Int');

$this->_limit = " LIMIT $offset, " . $rowCount;
}
$page = parent::limit($rowCount);
$this->rankOffset = $page[0] ?? (int) $this->_offsetValue;
return $page;
}

/**
Expand All @@ -393,7 +372,7 @@ public function limit($rowCount = NULL) {
*/
public function alterDisplay(&$rows) {
$entryFound = FALSE;
$rank = 1;
$rank = $this->rankOffset + 1;
if (!empty($rows)) {
foreach ($rows as $rowNum => $row) {

Expand Down
5 changes: 2 additions & 3 deletions CRM/Report/Form/Event/IncomeCountSummary.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,6 @@ public function postProcess() {

$dao = CRM_Core_DAO::executeQuery($sql);

//set pager before execution of query in function participantInfo()
$this->setPager();

$rows = [];

while ($dao->fetch()) {
Expand Down Expand Up @@ -326,6 +323,8 @@ public function postProcess() {
}
$rows[] = $row;
}
$this->setRowsFound($sql, count($rows));
$this->setPager();

// do not call pager here
$this->formatDisplay($rows, FALSE);
Expand Down
5 changes: 2 additions & 3 deletions CRM/Report/Form/Event/Summary.php
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,6 @@ public function postProcess() {

$dao = CRM_Core_DAO::executeQuery($sql);

//set pager before exicution of query in function participantInfo()
$this->setPager();

$rows = $graphRows = [];
$count = 0;
while ($dao->fetch()) {
Expand All @@ -323,6 +320,8 @@ public function postProcess() {
}
$rows[] = $row;
}
$this->setRowsFound($sql, count($rows));
$this->setPager();
if (!empty($rows)) {
$participant_info = $this->participantInfo();
foreach ($rows as $key => $value) {
Expand Down
Loading