From 402a9f931ed5c106fa8f67338827b54b71b0ecd6 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Thu, 3 Oct 2024 17:12:35 +1300 Subject: [PATCH] FIX Ensure primary connection is updated with temporary database --- _config.php | 2 +- src/TestSessionEnvironment.php | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/_config.php b/_config.php index a372c88..ec27655 100644 --- a/_config.php +++ b/_config.php @@ -12,7 +12,7 @@ TestSessionEnvironment::singleton()->loadFromFile(); */ if (class_exists('Resque_Event') && class_exists('SSResqueRun')) { Resque_Event::listen('beforeFork', function ($data) { - $databaseConfig = DB::getConfig(); + $databaseConfig = DB::getConfig(DB::CONN_PRIMARY); // Reconnect to the database - this may connect to the old DB first, but is required because these processes // are long-lived, and MySQL connections often get closed in between worker runs. We need to connect before diff --git a/src/TestSessionEnvironment.php b/src/TestSessionEnvironment.php index 7a067bd..c5fdedd 100644 --- a/src/TestSessionEnvironment.php +++ b/src/TestSessionEnvironment.php @@ -272,7 +272,7 @@ class TestSessionEnvironment $this->extend('onBeforeApplyState', $state); // back up source - $databaseConfig = DB::getConfig(); + $databaseConfig = DB::getConfig(DB::CONN_PRIMARY); $this->oldDatabaseName = $databaseConfig['database']; // Load existing state from $this->state into $state, if there is any @@ -523,9 +523,9 @@ class TestSessionEnvironment public function resetDatabaseName() { if ($this->oldDatabaseName) { - $databaseConfig = DB::getConfig(); + $databaseConfig = DB::getConfig(DB::CONN_PRIMARY); $databaseConfig['database'] = $this->oldDatabaseName; - DB::setConfig($databaseConfig); + DB::setConfig($databaseConfig, DB::CONN_PRIMARY); $conn = DB::get_conn(); @@ -568,7 +568,7 @@ class TestSessionEnvironment $state = $this->getState(); } - $databaseConfig = DB::getConfig(); + $databaseConfig = DB::getConfig(DB::CONN_PRIMARY); if (isset($state->database) && $state->database) { if (!DB::get_conn()) { @@ -579,14 +579,14 @@ class TestSessionEnvironment } // Connect to database - DB::connect($databaseConfig); + $this->connectToDB($databaseConfig); } else { // We've already connected to the database, do a fast check to see what database we're currently using $db = DB::get_conn()->getSelectedDatabase(); if (isset($state->database) && $db != $state->database) { $this->oldDatabaseName = $databaseConfig['database']; $databaseConfig['database'] = $state->database; - DB::connect($databaseConfig); + $this->connectToDB($databaseConfig); } } } @@ -622,4 +622,12 @@ class TestSessionEnvironment return true; } + + private function connectToDB(array $databaseConfig): void + { + // Ensure we connect the primary connection and not a replica + // which can happen if we use the default value of DB::CONN_DYNAMIC + // and there is a replica database configured + DB::connect($databaseConfig, DB::CONN_PRIMARY); + } }