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',
184 "ExternalStoreDB::fetchBlob cache hit on $cacheID\n" );
185 return $externalBlobCache[$cacheID];
188 wfDebugLog( 'ExternalStoreDB-cache',
189 "ExternalStoreDB::fetchBlob cache miss on $cacheID\n" );
191 $dbr =& $this->getSlave( $cluster );
192 $ret = $dbr->selectField( $this->getTable( $dbr ),
193 'blob_text', array( 'blob_id' => $id ), __METHOD__
);
194 if ( $ret === false ) {
195 wfDebugLog( 'ExternalStoreDB',
196 "ExternalStoreDB::fetchBlob master fallback on $cacheID\n" );
198 $dbw =& $this->getMaster( $cluster );
199 $ret = $dbw->selectField( $this->getTable( $dbw ),
200 'blob_text', array( 'blob_id' => $id ), __METHOD__
);
201 if ( $ret === false ) {
202 wfDebugLog( 'ExternalStoreDB',
203 "ExternalStoreDB::fetchBlob master failed to find $cacheID\n" );
206 if ( $itemID !== false && $ret !== false ) {
207 // Unserialise object; caller extracts item
208 $ret = unserialize( $ret );
211 $externalBlobCache = array( $cacheID => &$ret );
216 * Fetch multiple blob items out of the database
218 * @param string $cluster A cluster name valid for use with LBFactory
219 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
220 * @return array A map from the blob_id's requested to their content. Unlocated ids are not represented
222 function batchFetchBlobs( $cluster, array $ids ) {
223 $dbr = $this->getSlave( $cluster );
224 $res = $dbr->select( $this->getTable( $dbr ),
225 array( 'blob_id', 'blob_text' ), array( 'blob_id' => array_keys( $ids ) ), __METHOD__
);
227 if ( $res !== false ) {
228 $this->mergeBatchResult( $ret, $ids, $res );
231 wfDebugLog( __CLASS__
, __METHOD__
.
232 " master fallback on '$cluster' for: " .
233 implode( ',', array_keys( $ids ) ) . "\n" );
235 $dbw = $this->getMaster( $cluster );
236 $res = $dbw->select( $this->getTable( $dbr ),
237 array( 'blob_id', 'blob_text' ),
238 array( 'blob_id' => array_keys( $ids ) ),
240 if ( $res === false ) {
241 wfDebugLog( __CLASS__
, __METHOD__
. " master failed on '$cluster'\n" );
243 $this->mergeBatchResult( $ret, $ids, $res );
247 wfDebugLog( __CLASS__
, __METHOD__
.
248 " master on '$cluster' failed locating items: " .
249 implode( ',', array_keys( $ids ) ) . "\n" );
255 * Helper function for self::batchFetchBlobs for merging master/slave results
256 * @param array &$ret Current self::batchFetchBlobs return value
257 * @param array &$ids Map from blob_id to requested itemIDs
258 * @param mixed $res DB result from DatabaseBase::select
260 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
261 foreach ( $res as $row ) {
263 $itemIDs = $ids[$id];
264 unset( $ids[$id] ); // to track if everything is found
265 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
266 // single result stored per blob
267 $ret[$id] = $row->blob_text
;
269 // multi result stored per blob
270 $ret[$id] = unserialize( $row->blob_text
);
275 protected function parseURL( $url ) {
276 $path = explode( '/', $url );
280 isset( $path[4] ) ?
$path[4] : false // itemID