3 * External storage in SQL database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * DB accessable external objects.
26 * In this system, each store "location" maps to a database "cluster".
27 * The clusters must be defined in the normal LBFactory configuration.
29 * @ingroup ExternalStorage
31 class ExternalStoreDB
extends ExternalStoreMedium
{
33 * The provided URL is in the form of DB://cluster/id
34 * or DB://cluster/id/itemid for concatened storage.
36 * @see ExternalStoreMedium::fetchFromURL()
38 public function fetchFromURL( $url ) {
39 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
40 $ret =& $this->fetchBlob( $cluster, $id, $itemID );
42 if ( $itemID !== false && $ret !== false ) {
43 return $ret->getItem( $itemID );
49 * Fetch data from given external store URLs.
50 * The provided URLs are in the form of DB://cluster/id
51 * or DB://cluster/id/itemid for concatened storage.
53 * @param array $urls An array of external store URLs
54 * @return array A map from url to stored content. Failed results
55 * are not represented.
57 public function batchFetchFromURLs( array $urls ) {
58 $batched = $inverseUrlMap = array();
59 foreach ( $urls as $url ) {
60 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
61 $batched[$cluster][$id][] = $itemID;
62 // false $itemID gets cast to int, but should be ok
63 // since we do === from the $itemID in $batched
64 $inverseUrlMap[$cluster][$id][$itemID] = $url;
67 foreach ( $batched as $cluster => $batchByCluster ) {
68 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
69 foreach ( $res as $id => $blob ) {
70 foreach ( $batchByCluster[$id] as $itemID ) {
71 $url = $inverseUrlMap[$cluster][$id][$itemID];
72 if ( $itemID === false ) {
75 $ret[$url] = $blob->getItem( $itemID );
84 * @see ExternalStoreMedium::store()
86 public function store( $cluster, $data ) {
87 $dbw = $this->getMaster( $cluster );
88 $id = $dbw->nextSequenceValue( 'blob_blob_id_seq' );
89 $dbw->insert( $this->getTable( $dbw ),
90 array( 'blob_id' => $id, 'blob_text' => $data ),
92 $id = $dbw->insertId();
94 throw new MWException( __METHOD__
. ': no insert ID' );
96 if ( $dbw->getFlag( DBO_TRX
) ) {
97 $dbw->commit( __METHOD__
);
99 return "DB://$cluster/$id";
103 * Get a LoadBalancer for the specified cluster
105 * @param string $cluster cluster name
106 * @return LoadBalancer object
108 function &getLoadBalancer( $cluster ) {
109 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
111 return wfGetLBFactory()->getExternalLB( $cluster, $wiki );
115 * Get a slave database connection for the specified cluster
117 * @param string $cluster cluster name
118 * @return DatabaseBase object
120 function &getSlave( $cluster ) {
121 global $wgDefaultExternalStore;
123 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
124 $lb =& $this->getLoadBalancer( $cluster );
126 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
127 wfDebug( "read only external store" );
128 $lb->allowLagged( true );
130 wfDebug( "writable external store" );
133 return $lb->getConnection( DB_SLAVE
, array(), $wiki );
137 * Get a master database connection for the specified cluster
139 * @param string $cluster cluster name
140 * @return DatabaseBase object
142 function &getMaster( $cluster ) {
143 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
144 $lb =& $this->getLoadBalancer( $cluster );
145 return $lb->getConnection( DB_MASTER
, array(), $wiki );
149 * Get the 'blobs' table name for this database
151 * @param $db DatabaseBase
152 * @return String: table name ('blobs' by default)
154 function getTable( &$db ) {
155 $table = $db->getLBInfo( 'blobs table' );
156 if ( is_null( $table ) ) {
163 * Fetch a blob item out of the database; a cache of the last-loaded
164 * blob will be kept so that multiple loads out of a multi-item blob
165 * can avoid redundant database access and decompression.
172 function &fetchBlob( $cluster, $id, $itemID ) {
174 * One-step cache variable to hold base blobs; operations that
175 * pull multiple revisions may often pull multiple times from
176 * the same blob. By keeping the last-used one open, we avoid
177 * redundant unserialization and decompression overhead.
179 static $externalBlobCache = array();
181 $cacheID = ( $itemID === false ) ?
"$cluster/$id" : "$cluster/$id/";
182 if ( isset( $externalBlobCache[$cacheID] ) ) {
183 wfDebugLog( 'ExternalStoreDB-cache', "ExternalStoreDB::fetchBlob cache hit on $cacheID\n" );
184 return $externalBlobCache[$cacheID];
187 wfDebugLog( 'ExternalStoreDB-cache', "ExternalStoreDB::fetchBlob cache miss on $cacheID\n" );
189 $dbr =& $this->getSlave( $cluster );
190 $ret = $dbr->selectField( $this->getTable( $dbr ), 'blob_text', array( 'blob_id' => $id ), __METHOD__
);
191 if ( $ret === false ) {
192 wfDebugLog( 'ExternalStoreDB', "ExternalStoreDB::fetchBlob master fallback on $cacheID\n" );
194 $dbw =& $this->getMaster( $cluster );
195 $ret = $dbw->selectField( $this->getTable( $dbw ), 'blob_text', array( 'blob_id' => $id ), __METHOD__
);
196 if ( $ret === false ) {
197 wfDebugLog( 'ExternalStoreDB', "ExternalStoreDB::fetchBlob master failed to find $cacheID\n" );
200 if ( $itemID !== false && $ret !== false ) {
201 // Unserialise object; caller extracts item
202 $ret = unserialize( $ret );
205 $externalBlobCache = array( $cacheID => &$ret );
210 * Fetch multiple blob items out of the database
212 * @param string $cluster A cluster name valid for use with LBFactory
213 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
214 * @return array A map from the blob_id's requested to their content. Unlocated ids are not represented
216 function batchFetchBlobs( $cluster, array $ids ) {
217 $dbr = $this->getSlave( $cluster );
218 $res = $dbr->select( $this->getTable( $dbr ), array( 'blob_id', 'blob_text' ), array( 'blob_id' => array_keys( $ids ) ), __METHOD__
);
220 if ( $res !== false ) {
221 $this->mergeBatchResult( $ret, $ids, $res );
224 wfDebugLog( __CLASS__
, __METHOD__
. " master fallback on '$cluster' for: " . implode( ',', array_keys( $ids ) ) . "\n" );
226 $dbw = $this->getMaster( $cluster );
227 $res = $dbw->select( $this->getTable( $dbr ), array( 'blob_id', 'blob_text' ), array( 'blob_id' => array_keys( $ids ) ), __METHOD__
);
228 if ( $res === false ) {
229 wfDebugLog( __CLASS__
, __METHOD__
. " master failed on '$cluster'\n" );
231 $this->mergeBatchResult( $ret, $ids, $res );
235 wfDebugLog( __CLASS__
, __METHOD__
. " master on '$cluster' failed locating items: " . implode( ',', array_keys( $ids ) ) . "\n" );
241 * Helper function for self::batchFetchBlobs for merging master/slave results
242 * @param array &$ret Current self::batchFetchBlobs return value
243 * @param array &$ids Map from blob_id to requested itemIDs
244 * @param mixed $res DB result from DatabaseBase::select
246 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
247 foreach ( $res as $row ) {
249 $itemIDs = $ids[$id];
250 unset( $ids[$id] ); // to track if everything is found
251 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
252 // single result stored per blob
253 $ret[$id] = $row->blob_text
;
255 // multi result stored per blob
256 $ret[$id] = unserialize( $row->blob_text
);
261 protected function parseURL( $url ) {
262 $path = explode( '/', $url );
266 isset( $path[4] ) ?
$path[4] : false // itemID