From 06f83d5c19ad0a98613830a2631a554009d256ba Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Wed, 12 Aug 2020 11:44:39 -0400 Subject: [PATCH] Early return during APIv4::get if table doesn't exist If there are pending upgrades, checks if table exists before attempting to read from it. --- CRM/Core/DAO.php | 17 +++++++++++++++++ Civi/Api4/Generic/DAOGetAction.php | 6 ++++++ tests/phpunit/CRM/Core/DAOTest.php | 13 +++++++++++++ 3 files changed, 36 insertions(+) diff --git a/CRM/Core/DAO.php b/CRM/Core/DAO.php index 7c17558d88..96da596f6b 100644 --- a/CRM/Core/DAO.php +++ b/CRM/Core/DAO.php @@ -1148,6 +1148,23 @@ class CRM_Core_DAO extends DB_DataObject { return $result; } + /** + * Checks if this DAO's table ought to exist. + * + * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version. + * + * @return bool + * @throws CRM_Core_Exception + */ + public static function tableHasBeenAdded() { + if (CRM_Utils_System::version() === CRM_Core_BAO_Domain::version()) { + return TRUE; + } + $daoExt = constant(static::class . '::EXT'); + $daoVersion = constant(static::class . '::TABLE_ADDED') ?? '1.0'; + return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain::version(), $daoVersion, '<')); + } + /** * Check if there is a given table in the database. * diff --git a/Civi/Api4/Generic/DAOGetAction.php b/Civi/Api4/Generic/DAOGetAction.php index 9ad1d54adc..cbdec8841e 100644 --- a/Civi/Api4/Generic/DAOGetAction.php +++ b/Civi/Api4/Generic/DAOGetAction.php @@ -85,6 +85,12 @@ class DAOGetAction extends AbstractGetAction { protected $having = []; public function _run(Result $result) { + // Early return if table doesn't exist yet due to pending upgrade + $baoName = $this->getBaoName(); + if (!$baoName::tableHasBeenAdded()) { + return; + } + $this->setDefaultWhereClause(); $this->expandSelectClauseWildcards(); $this->getObjects($result); diff --git a/tests/phpunit/CRM/Core/DAOTest.php b/tests/phpunit/CRM/Core/DAOTest.php index ed008287ed..0523aab7d5 100644 --- a/tests/phpunit/CRM/Core/DAOTest.php +++ b/tests/phpunit/CRM/Core/DAOTest.php @@ -542,4 +542,17 @@ class CRM_Core_DAOTest extends CiviUnitTestCase { $this->assertArrayNotHasKey('api_key', $permissionedContactFields); } + public function testTableHasBeenAdded() { + // Hack a different db version + CRM_Core_BAO_Domain::getDomain()->version = '5.28.0'; + + // Table was added in 5.29 + $this->assertFalse(CRM_Contact_DAO_RelationshipCache::tableHasBeenAdded()); + + // Remove domain version override: + CRM_Core_BAO_Domain::version(TRUE); + + $this->assertTrue(CRM_Contact_DAO_RelationshipCache::tableHasBeenAdded()); + } + } -- 2.25.1