From 2918cca22cea596330650b9f50c2e22df23c5c70 Mon Sep 17 00:00:00 2001 From: Gary Pendergast Date: Tue, 2 Feb 2016 00:12:28 +0000 Subject: [PATCH] WPDB: Add a `close()` method to `wpdb`, for when the connection needs to be manually closed. In the event that it was closed prematurely, `wpdb::query()` will re-open the connection automatically. Fixes #34903. git-svn-id: https://develop.svn.wordpress.org/trunk@36433 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/wp-db.php | 26 ++++++++++++++++++++++++++ tests/phpunit/tests/db.php | 16 ++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/wp-includes/wp-db.php b/src/wp-includes/wp-db.php index 1356a76163..f0ed7d9d34 100644 --- a/src/wp-includes/wp-db.php +++ b/src/wp-includes/wp-db.php @@ -3093,6 +3093,32 @@ class wpdb { wp_die($message); } + + /** + * Closes the current database connection. + * + * @since 4.5.0 + * + * @return bool True if the connection was succesfully closed, false if it wasn't, or the connection doesn't exist. + */ + public function close() { + if ( ! $this->dbh ) { + return false; + } + + if ( $this->use_mysqli ) { + $closed = mysqli_close( $this->dbh ); + } else { + $closed = mysql_close( $this->dbh ); + } + + if ( $closed ) { + $this->dbh = null; + } + + return $closed; + } + /** * Whether MySQL database is at least the required minimum version. * diff --git a/tests/phpunit/tests/db.php b/tests/phpunit/tests/db.php index 74036a2027..e74ca308d2 100644 --- a/tests/phpunit/tests/db.php +++ b/tests/phpunit/tests/db.php @@ -941,4 +941,20 @@ class Tests_DB extends WP_UnitTestCase { $this->assertNull( $row ); } + + /** + * @ticket 34903 + */ + function test_close() { + global $wpdb; + + $this->assertTrue( $wpdb->close() ); + $this->assertFalse( $wpdb->close() ); + + $wpdb->check_connection(); + + $this->assertTrue( $wpdb->close() ); + + $wpdb->check_connection(); + } }