Merge "Never prefix table names with $wgSharedDB when used in foreign DB"
[lhc/web/wiklou.git] / includes / db / LoadBalancer.php
index 1d27308..60c2833 100644 (file)
@@ -117,7 +117,7 @@ class LoadBalancer {
         * Given an array of non-normalised probabilities, this function will select
         * an element and return the appropriate key
         *
-        * @deprecated 1.21, use ArrayUtils::pickRandom()
+        * @deprecated since 1.21, use ArrayUtils::pickRandom()
         *
         * @param $weights array
         *
@@ -479,6 +479,7 @@ class LoadBalancer {
 
                # Operation-based index
                if ( $i == DB_SLAVE ) {
+                       $this->mLastError = 'Unknown error'; // reset error string
                        $i = $this->getReaderIndex( false, $wiki );
                        # Couldn't find a working server in getReaderIndex()?
                        if ( $i === false ) {
@@ -544,6 +545,22 @@ class LoadBalancer {
                }
        }
 
+       /**
+        * Get a database connection handle reference
+        *
+        * The handle's methods wrap simply wrap those of a DatabaseBase handle
+        *
+        * @see LoadBalancer::getConnection() for parameter information
+        *
+        * @param integer $db
+        * @param mixed $groups
+        * @param string $wiki
+        * @return DBConnRef
+        */
+       public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
+               return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
+       }
+
        /**
         * Open a connection to the server given by the specified index
         * Index must be an actual index into the array.
@@ -1068,3 +1085,33 @@ class LoadBalancer {
                $this->mLagTimes = null;
        }
 }
+
+/**
+ * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
+ *
+ * @ingroup Database
+ * @since 1.22
+ */
+class DBConnRef implements IDatabase {
+       /** @var LoadBalancer */
+       protected $lb;
+       /** @var DatabaseBase */
+       protected $conn;
+
+       /**
+        * @param $lb LoadBalancer
+        * @param $conn DatabaseBase
+        */
+       public function __construct( LoadBalancer $lb, DatabaseBase $conn ) {
+               $this->lb = $lb;
+               $this->conn = $conn;
+       }
+
+       public function __call( $name, $arguments ) {
+               return call_user_func_array( array( $this->conn, $name ), $arguments );
+       }
+
+       function __destruct() {
+               $this->lb->reuseConnection( $this->conn );
+       }
+}