Merge "Localisation updates from https://translatewiki.net."
[mediawiki.git] / includes / externalstore / ExternalStoreDB.php
blob5774a24c783f2e33f77f4bba10e61125e69b74af
1 <?php
2 /**
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
20 * @file
23 /**
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 {
32 /**
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 );
46 return $ret;
49 /**
50 * Fetch data from given external store URLs.
51 * The provided URLs are in the form of DB://cluster/id
52 * or DB://cluster/id/itemid for concatened storage.
54 * @param array $urls An array of external store URLs
55 * @return array A map from url to stored content. Failed results
56 * are not represented.
58 public function batchFetchFromURLs( array $urls ) {
59 $batched = $inverseUrlMap = array();
60 foreach ( $urls as $url ) {
61 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
62 $batched[$cluster][$id][] = $itemID;
63 // false $itemID gets cast to int, but should be ok
64 // since we do === from the $itemID in $batched
65 $inverseUrlMap[$cluster][$id][$itemID] = $url;
67 $ret = array();
68 foreach ( $batched as $cluster => $batchByCluster ) {
69 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
70 /** @var HistoryBlob $blob */
71 foreach ( $res as $id => $blob ) {
72 foreach ( $batchByCluster[$id] as $itemID ) {
73 $url = $inverseUrlMap[$cluster][$id][$itemID];
74 if ( $itemID === false ) {
75 $ret[$url] = $blob;
76 } else {
77 $ret[$url] = $blob->getItem( $itemID );
83 return $ret;
86 /**
87 * @see ExternalStoreMedium::store()
89 public function store( $cluster, $data ) {
90 $dbw = $this->getMaster( $cluster );
91 $id = $dbw->nextSequenceValue( 'blob_blob_id_seq' );
92 $dbw->insert( $this->getTable( $dbw ),
93 array( 'blob_id' => $id, 'blob_text' => $data ),
94 __METHOD__ );
95 $id = $dbw->insertId();
96 if ( !$id ) {
97 throw new MWException( __METHOD__ . ': no insert ID' );
99 if ( $dbw->getFlag( DBO_TRX ) ) {
100 $dbw->commit( __METHOD__ );
103 return "DB://$cluster/$id";
107 * Get a LoadBalancer for the specified cluster
109 * @param string $cluster Cluster name
110 * @return LoadBalancer
112 function getLoadBalancer( $cluster ) {
113 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
115 return wfGetLBFactory()->getExternalLB( $cluster, $wiki );
119 * Get a slave database connection for the specified cluster
121 * @param string $cluster Cluster name
122 * @return DatabaseBase
124 function getSlave( $cluster ) {
125 global $wgDefaultExternalStore;
127 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
128 $lb = $this->getLoadBalancer( $cluster );
130 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
131 wfDebug( "read only external store\n" );
132 $lb->allowLagged( true );
133 } else {
134 wfDebug( "writable external store\n" );
137 return $lb->getConnection( DB_SLAVE, array(), $wiki );
141 * Get a master database connection for the specified cluster
143 * @param string $cluster Cluster name
144 * @return DatabaseBase
146 function getMaster( $cluster ) {
147 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
148 $lb = $this->getLoadBalancer( $cluster );
150 return $lb->getConnection( DB_MASTER, array(), $wiki );
154 * Get the 'blobs' table name for this database
156 * @param DatabaseBase $db
157 * @return string Table name ('blobs' by default)
159 function getTable( $db ) {
160 $table = $db->getLBInfo( 'blobs table' );
161 if ( is_null( $table ) ) {
162 $table = 'blobs';
165 return $table;
169 * Fetch a blob item out of the database; a cache of the last-loaded
170 * blob will be kept so that multiple loads out of a multi-item blob
171 * can avoid redundant database access and decompression.
172 * @param string $cluster
173 * @param string $id
174 * @param string $itemID
175 * @return mixed
176 * @private
178 function fetchBlob( $cluster, $id, $itemID ) {
180 * One-step cache variable to hold base blobs; operations that
181 * pull multiple revisions may often pull multiple times from
182 * the same blob. By keeping the last-used one open, we avoid
183 * redundant unserialization and decompression overhead.
185 static $externalBlobCache = array();
187 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
188 if ( isset( $externalBlobCache[$cacheID] ) ) {
189 wfDebugLog( 'ExternalStoreDB-cache',
190 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
192 return $externalBlobCache[$cacheID];
195 wfDebugLog( 'ExternalStoreDB-cache',
196 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
198 $dbr = $this->getSlave( $cluster );
199 $ret = $dbr->selectField( $this->getTable( $dbr ),
200 'blob_text', array( 'blob_id' => $id ), __METHOD__ );
201 if ( $ret === false ) {
202 wfDebugLog( 'ExternalStoreDB',
203 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
204 // Try the master
205 $dbw = $this->getMaster( $cluster );
206 $ret = $dbw->selectField( $this->getTable( $dbw ),
207 'blob_text', array( 'blob_id' => $id ), __METHOD__ );
208 if ( $ret === false ) {
209 wfDebugLog( 'ExternalStoreDB',
210 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
213 if ( $itemID !== false && $ret !== false ) {
214 // Unserialise object; caller extracts item
215 $ret = unserialize( $ret );
218 $externalBlobCache = array( $cacheID => $ret );
220 return $ret;
224 * Fetch multiple blob items out of the database
226 * @param string $cluster A cluster name valid for use with LBFactory
227 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
228 * @return array A map from the blob_id's requested to their content.
229 * Unlocated ids are not represented
231 function batchFetchBlobs( $cluster, array $ids ) {
232 $dbr = $this->getSlave( $cluster );
233 $res = $dbr->select( $this->getTable( $dbr ),
234 array( 'blob_id', 'blob_text' ), array( 'blob_id' => array_keys( $ids ) ), __METHOD__ );
235 $ret = array();
236 if ( $res !== false ) {
237 $this->mergeBatchResult( $ret, $ids, $res );
239 if ( $ids ) {
240 wfDebugLog( __CLASS__, __METHOD__ .
241 " master fallback on '$cluster' for: " .
242 implode( ',', array_keys( $ids ) ) );
243 // Try the master
244 $dbw = $this->getMaster( $cluster );
245 $res = $dbw->select( $this->getTable( $dbr ),
246 array( 'blob_id', 'blob_text' ),
247 array( 'blob_id' => array_keys( $ids ) ),
248 __METHOD__ );
249 if ( $res === false ) {
250 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
251 } else {
252 $this->mergeBatchResult( $ret, $ids, $res );
255 if ( $ids ) {
256 wfDebugLog( __CLASS__, __METHOD__ .
257 " master on '$cluster' failed locating items: " .
258 implode( ',', array_keys( $ids ) ) );
261 return $ret;
265 * Helper function for self::batchFetchBlobs for merging master/slave results
266 * @param array &$ret Current self::batchFetchBlobs return value
267 * @param array &$ids Map from blob_id to requested itemIDs
268 * @param mixed $res DB result from DatabaseBase::select
270 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
271 foreach ( $res as $row ) {
272 $id = $row->blob_id;
273 $itemIDs = $ids[$id];
274 unset( $ids[$id] ); // to track if everything is found
275 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
276 // single result stored per blob
277 $ret[$id] = $row->blob_text;
278 } else {
279 // multi result stored per blob
280 $ret[$id] = unserialize( $row->blob_text );
285 protected function parseURL( $url ) {
286 $path = explode( '/', $url );
288 return array(
289 $path[2], // cluster
290 $path[3], // id
291 isset( $path[4] ) ? $path[4] : false // itemID