diff --git a/CRM/Logging/Differ.php b/CRM/Logging/Differ.php index fa4eff25ffa..425e8ffe6f7 100644 --- a/CRM/Logging/Differ.php +++ b/CRM/Logging/Differ.php @@ -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)) { @@ -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); } /** diff --git a/CRM/Logging/ReportDetail.php b/CRM/Logging/ReportDetail.php index a8ac75bd363..94642ff7873 100644 --- a/CRM/Logging/ReportDetail.php +++ b/CRM/Logging/ReportDetail.php @@ -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 { diff --git a/CRM/Report/Form.php b/CRM/Report/Form.php index 47526df328b..c8a4fe37097 100644 --- a/CRM/Report/Form.php +++ b/CRM/Report/Form.php @@ -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[] @@ -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 = []; @@ -3265,6 +3278,7 @@ public function buildRows($sql, &$rows) { $unselectedSectionColumns = $this->unselectedSectionColumns(); + $fetched = 0; while ($dao->fetch()) { $row = []; foreach ($this->_columnHeaders as $key => $value) { @@ -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]))); + } + + /** + * 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), so such a query is streamed and its rows counted. + // @todo From CiviCRM 6.23, which requires MySQL 8.0, count it on the server through a CTE with a column list. + if ($e->getSQLErrorCode() !== 1060) { + throw $e; + } + $this->restoreRowsFoundVariables(); + $dao = CRM_Core_DAO::executeUnbufferedQuery($sql); + for ($count = 0; $dao->fetch(); $count++); + } + finally { + CRM_Core_DAO::reenableFullGroupByMode(); + } + return $count; + } + + /** + * 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))); } } @@ -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 @@ -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, diff --git a/CRM/Report/Form/Contribute/Detail.php b/CRM/Report/Form/Contribute/Detail.php index 1920888a6f3..bb7e013c127 100644 --- a/CRM/Report/Form/Contribute/Detail.php +++ b/CRM/Report/Form/Contribute/Detail.php @@ -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); } @@ -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; @@ -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); diff --git a/CRM/Report/Form/Contribute/History.php b/CRM/Report/Form/Contribute/History.php index 661ecef6081..2ad919e5baf 100644 --- a/CRM/Report/Form/Contribute/History.php +++ b/CRM/Report/Form/Contribute/History.php @@ -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(); $relationshipRows = []; if (empty($contactIds)) { diff --git a/CRM/Report/Form/Contribute/Lybunt.php b/CRM/Report/Form/Contribute/Lybunt.php index a11b8076a15..6c5555f1986 100644 --- a/CRM/Report/Form/Contribute/Lybunt.php +++ b/CRM/Report/Form/Contribute/Lybunt.php @@ -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 = []; @@ -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); diff --git a/CRM/Report/Form/Contribute/Repeat.php b/CRM/Report/Form/Contribute/Repeat.php index 09727f4f33c..3dd6a403812 100644 --- a/CRM/Report/Form/Contribute/Repeat.php +++ b/CRM/Report/Form/Contribute/Repeat.php @@ -845,6 +845,7 @@ public function postProcess() { } $count++; } + $this->setRowsFound($sql, $count); // FIXME: calculate % using query foreach ($rows as $uid => $row) { diff --git a/CRM/Report/Form/Contribute/Sybunt.php b/CRM/Report/Form/Contribute/Sybunt.php index f9c11685bbe..2d4d5a1b197 100644 --- a/CRM/Report/Form/Contribute/Sybunt.php +++ b/CRM/Report/Form/Contribute/Sybunt.php @@ -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(); } diff --git a/CRM/Report/Form/Contribute/TopDonor.php b/CRM/Report/Form/Contribute/TopDonor.php index 55438cd19d3..02811041afa 100644 --- a/CRM/Report/Form/Contribute/TopDonor.php +++ b/CRM/Report/Form/Contribute/TopDonor.php @@ -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() { @@ -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; } /** @@ -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) { diff --git a/CRM/Report/Form/Event/IncomeCountSummary.php b/CRM/Report/Form/Event/IncomeCountSummary.php index d0865aa4eae..a7f17a7064c 100644 --- a/CRM/Report/Form/Event/IncomeCountSummary.php +++ b/CRM/Report/Form/Event/IncomeCountSummary.php @@ -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()) { @@ -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); diff --git a/CRM/Report/Form/Event/Summary.php b/CRM/Report/Form/Event/Summary.php index 2a2d612fc2e..b74c584ea92 100644 --- a/CRM/Report/Form/Event/Summary.php +++ b/CRM/Report/Form/Event/Summary.php @@ -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()) { @@ -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) { diff --git a/CRM/Report/Form/Member/Lapse.php b/CRM/Report/Form/Member/Lapse.php index d2443dd7e3b..046ddb374d6 100644 --- a/CRM/Report/Form/Member/Lapse.php +++ b/CRM/Report/Form/Member/Lapse.php @@ -286,6 +286,7 @@ public function postProcess() { $rows[] = $row; } + $this->setRowsFound($sql, count($rows)); $this->formatDisplay($rows); // assign variables to templates diff --git a/CRM/Report/Form/Pledge/Detail.php b/CRM/Report/Form/Pledge/Detail.php index 8aa0c5f4987..21b6b71eafc 100644 --- a/CRM/Report/Form/Pledge/Detail.php +++ b/CRM/Report/Form/Pledge/Detail.php @@ -380,12 +380,11 @@ public function postProcess() { $rows = $payment = []; $dao = CRM_Core_DAO::executeQuery($sql); - - // Set pager for the Main Query only which displays basic information - $this->setPager(); $this->assign('columnHeaders', $this->_columnHeaders); + $fetched = 0; while ($dao->fetch()) { + $fetched++; $pledgeID = $dao->civicrm_pledge_id; foreach ($this->_columnHeaders as $columnHeadersKey => $columnHeadersValue) { $row = []; @@ -395,6 +394,8 @@ public function postProcess() { } $pledgeIDArray[] = $pledgeID; } + $this->setRowsFound($sql, $fetched); + $this->setPager(); // Add Special headers $this->_columnHeaders['scheduled_date'] = [ diff --git a/tests/phpunit/CRM/Report/Form/LegacyFoundRowsForm.php b/tests/phpunit/CRM/Report/Form/LegacyFoundRowsForm.php new file mode 100644 index 00000000000..ed95126099e --- /dev/null +++ b/tests/phpunit/CRM/Report/Form/LegacyFoundRowsForm.php @@ -0,0 +1,24 @@ +isTempTableBuilt) { + $sql = preg_replace('/^SELECT SQL_CALC_FOUND_ROWS \*/', 'SELECT SQL_CALC_FOUND_ROWS *, 1 AS legacy_column, 1 AS legacy_column', $sql, 1, $replaced); + if ($replaced !== 1) { + throw new RuntimeException('Displayed query has an unexpected form.'); + } + } + return $sql; + } + +} diff --git a/tests/phpunit/CRM/Report/Form/LegacyOwnQueryForm.php b/tests/phpunit/CRM/Report/Form/LegacyOwnQueryForm.php new file mode 100644 index 00000000000..14d873b5d02 --- /dev/null +++ b/tests/phpunit/CRM/Report/Form/LegacyOwnQueryForm.php @@ -0,0 +1,29 @@ +beginPostProcess(); + $this->buildACLClause($this->_aliases['civicrm_contact']); + $sql = preg_replace('/^\s*SELECT\b/i', 'SELECT SQL_CALC_FOUND_ROWS', $this->buildQuery(TRUE)); + $dao = CRM_Core_DAO::executeQuery($sql); + $rows = []; + while ($dao->fetch()) { + $row = []; + foreach ($this->_columnHeaders as $key => $value) { + $row[$key] = $dao->$key; + } + $rows[] = $row; + } + $this->formatDisplay($rows); + $this->doTemplateAssignment($rows); + $this->endPostProcess($rows); + } + +} diff --git a/tests/phpunit/CRM/Report/Form/LegacyTopRowsForm.php b/tests/phpunit/CRM/Report/Form/LegacyTopRowsForm.php new file mode 100644 index 00000000000..dacddab90a6 --- /dev/null +++ b/tests/phpunit/CRM/Report/Form/LegacyTopRowsForm.php @@ -0,0 +1,20 @@ +_limit; + $query = $limit === '' ? $sql : substr($sql, 0, strrpos($sql, $limit)); + parent::buildRows('SELECT * FROM (' . $query . ') top_rows WHERE (@legacy_rows := @legacy_rows + 1) <= ' . self::TOP_ROWS . " $limit", $rows); + } + +} diff --git a/tests/phpunit/CRM/Report/Form/PagerTest.php b/tests/phpunit/CRM/Report/Form/PagerTest.php new file mode 100644 index 00000000000..40045c7a9d2 --- /dev/null +++ b/tests/phpunit/CRM/Report/Form/PagerTest.php @@ -0,0 +1,228 @@ +push(['_REQUEST' => ['rowCount' => 2, 'crmPID' => $page]]); + try { + $report = $this->getReportObject($reportClass, $inputParams); + } + finally { + CRM_Utils_GlobalStack::singleton()->pop(); + } + return [$report, $report::getTemplate()->getTemplateVars('pager')]; + } + + /** + * Create three donors with one contribution each this year and last year. + * + * @return int[] + * Contact IDs, largest donor first. + */ + private function createDonors(): array { + $contactIDs = []; + foreach ([300, 200, 100] as $amount) { + $contactID = $this->individualCreate([], count($contactIDs)); + $this->contributionCreate(['contact_id' => $contactID, 'total_amount' => $amount, 'receive_date' => date('Y') . '-01-01']); + $this->contributionCreate(['contact_id' => $contactID, 'total_amount' => $amount, 'receive_date' => (date('Y') - 1) . '-01-01']); + $contactIDs[] = $contactID; + } + return $contactIDs; + } + + /** + * @param int[] $contactIDs + */ + private function deleteContributionsThisYear(array $contactIDs): void { + Contribution::delete(FALSE) + ->addWhere('contact_id', 'IN', $contactIDs) + ->addWhere('receive_date', '>=', date('Y') . '-01-01') + ->execute(); + } + + /** + * Create three expired memberships. + */ + private function createLapsedMemberships(): void { + $membershipTypeID = $this->membershipTypeCreate(); + foreach ($this->createDonors() as $contactID) { + $this->createTestEntity('Membership', [ + 'contact_id' => $contactID, + 'membership_type_id' => $membershipTypeID, + 'join_date' => '2020-01-01', + 'start_date' => '2020-01-01', + 'end_date' => '2020-12-31', + 'status_id:name' => 'Expired', + 'is_override' => TRUE, + ], 'lapsed_' . $contactID); + } + } + + public function testEmptyReportTotalIsZero(): void { + [, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Detail'); + $this->assertSame(0, (int) $pager->_totalItems); + } + + public function testDetailTotalCountsAllPages(): void { + $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Detail'); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(6, (int) $pager->_totalItems); + } + + public function testDetailTotalOnLastPage(): void { + $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Detail', 3); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(6, (int) $pager->_totalItems); + } + + public function testLegacyFoundRowsQueryTotalCountsAllPages(): void { + $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_LegacyFoundRowsForm'); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(6, (int) $pager->_totalItems); + } + + public function testLegacyTopRowsQueryTotalCountsFromSameStart(): void { + $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_LegacyTopRowsForm'); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(CRM_Report_Form_LegacyTopRowsForm::TOP_ROWS, (int) $pager->_totalItems); + } + + public function testRepeatTotalCountsAllContacts(): void { + $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Repeat'); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(3, (int) $pager->_totalItems); + } + + public function testLybuntTotalCountsAllContacts(): void { + $this->deleteContributionsThisYear($this->createDonors()); + [, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Lybunt'); + // Three donors plus the grand total row. + $this->assertSame(4, (int) $pager->_totalItems); + } + + public function testSybuntTotalCountsAllContacts(): void { + $contactIDs = $this->createDonors(); + $this->deleteContributionsThisYear($contactIDs); + [, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_Sybunt'); + $this->assertSame(3, (int) $pager->_totalItems); + } + + public function testEventSummaryTotalCountsAllEvents(): void { + $eventIDs = []; + foreach (['a', 'b', 'c'] as $identifier) { + $eventIDs[] = $this->eventCreateUnpaid([], $identifier)['id']; + } + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Event_Summary', 1, ['filters' => ['id_op' => 'in', 'id_value' => implode(',', $eventIDs)]]); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(3, (int) $pager->_totalItems); + } + + public function testEventIncomeCountSummaryTotalCountsAllEvents(): void { + foreach (['a', 'b', 'c'] as $identifier) { + $this->eventCreateUnpaid([], $identifier); + } + [, $pager] = $this->runPagedReport('CRM_Report_Form_Event_IncomeCountSummary'); + // Three events plus the grand total row. + $this->assertSame(4, (int) $pager->_totalItems); + } + + public function testPledgeDetailTotalCountsAllPledges(): void { + foreach ($this->createDonors() as $contactID) { + $this->pledgeCreate(['contact_id' => $contactID]); + } + [, $pager] = $this->runPagedReport('CRM_Report_Form_Pledge_Detail'); + $this->assertSame(3, (int) $pager->_totalItems); + } + + public function testMemberLapseTotalCountsAllMemberships(): void { + $this->createLapsedMemberships(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Member_Lapse'); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(3, (int) $pager->_totalItems); + } + + public function testLegacyOwnFoundRowsQueryTotalCountsAllPages(): void { + $this->createLapsedMemberships(); + $deprecations = self::captureErrors(E_USER_DEPRECATED, function () use (&$report, &$pager) { + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_LegacyOwnQueryForm'); + }); + $this->assertCount(2, $report->getResultSet()); + $this->assertSame(3, (int) $pager->_totalItems); + $this->assertCount(1, $deprecations); + $this->assertStringContainsString('call setRowsFound()', $deprecations[0]); + } + + public function testRowsFoundAcceptsLimitSyntaxes(): void { + $this->createDonors(); + $report = new CRM_Report_Form_Contribute_Detail(); + $rowsFound = fn(string $sql, int $fetched) => (function () use ($sql, $fetched) { + $this->setRowsFound($sql, $fetched); + return $this->_rowsFound; + })->call($report); + $sql = 'SELECT id FROM civicrm_contribution'; + $this->assertSame(6, $rowsFound("$sql LIMIT 2", 2)); + $this->assertSame(6, $rowsFound("$sql LIMIT 2, 2", 2)); + $this->assertSame(6, $rowsFound("$sql LIMIT 2 OFFSET 2", 2)); + $this->assertSame(6, $rowsFound("$sql LIMIT 4 OFFSET 4", 2)); + $this->assertSame(6, $rowsFound($sql, 6)); + } + + public function testRowsFoundWithoutPagingRunsNoCount(): void { + $this->createDonors(); + $report = new CRM_Report_Form_Contribute_Detail(); + $report->setAddPaging(FALSE); + Invasive::call([$report, 'setRowsFound'], ['SELECT id FROM civicrm_contribution LIMIT 2', 2]); + $this->assertNull(Invasive::get([$report, '_rowsFound'])); + } + + public function testHistoryTotalCountsAllContacts(): void { + $this->createDonors(); + foreach ([1, 2] as $page) { + [, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_History', $page); + $this->assertSame(3, (int) $pager->_totalItems, "page $page"); + } + } + + public function testTopDonorPagesAndContinuesRanks(): void { + $contactIDs = $this->createDonors(); + [$report, $pager] = $this->runPagedReport('CRM_Report_Form_Contribute_TopDonor', 2); + $rows = $report->getResultSet(); + $this->assertSame(3, (int) $pager->_totalItems); + $this->assertCount(1, $rows); + $this->assertSame((string) $contactIDs[2], (string) $rows[0]['civicrm_contact_id']); + $this->assertSame(3, $rows[0]['civicrm_donor_rank']); + } + +} diff --git a/tests/phpunit/api/v3/ReportTemplateTest.php b/tests/phpunit/api/v3/ReportTemplateTest.php index 92e12c63ff9..e094e15e7e3 100644 --- a/tests/phpunit/api/v3/ReportTemplateTest.php +++ b/tests/phpunit/api/v3/ReportTemplateTest.php @@ -482,7 +482,7 @@ public function testLybuntReportWithFYData(): void { $this->assertSame(2, $rows['count'], 'Report failed - the sql used to generate the results was ' . print_r($rows['metadata']['sql'], TRUE)); $inUseCollation = CRM_Core_BAO_SchemaHandler::getInUseCollation(); $expected = preg_replace('/\s+/', ' ', 'COLLATE ' . $inUseCollation . ' AS - SELECT SQL_CALC_FOUND_ROWS contact_civireport.id as cid FROM civicrm_contact contact_civireport INNER JOIN civicrm_contribution contribution_civireport USE index (received_date) ON contribution_civireport.contact_id = contact_civireport.id + SELECT contact_civireport.id as cid FROM civicrm_contact contact_civireport INNER JOIN civicrm_contribution contribution_civireport USE index (received_date) ON contribution_civireport.contact_id = contact_civireport.id AND contribution_civireport.is_test = 0 AND contribution_civireport.is_template = 0 AND contribution_civireport.receive_date BETWEEN \'20140701000000\' AND \'20150630235959\'