Factored MySQL-specific munging out of Language::stripForSearch() to DatabaseMysql...
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
5 *
6 * @ingroup Database
7 * @see Database
8 */
9 class DatabaseMysql extends DatabaseBase {
10 static $mMinSearchLength;
11
12 function getType() {
13 return 'mysql';
14 }
15
16 /*private*/ function doQuery( $sql ) {
17 if( $this->bufferResults() ) {
18 $ret = mysql_query( $sql, $this->mConn );
19 } else {
20 $ret = mysql_unbuffered_query( $sql, $this->mConn );
21 }
22 return $ret;
23 }
24
25 function open( $server, $user, $password, $dbName ) {
26 global $wgAllDBsAreLocalhost;
27 wfProfileIn( __METHOD__ );
28
29 # Test for missing mysql.so
30 # First try to load it
31 if (!@extension_loaded('mysql')) {
32 @dl('mysql.so');
33 }
34
35 # Fail now
36 # Otherwise we get a suppressed fatal error, which is very hard to track down
37 if ( !function_exists( 'mysql_connect' ) ) {
38 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
39 }
40
41 # Debugging hack -- fake cluster
42 if ( $wgAllDBsAreLocalhost ) {
43 $realServer = 'localhost';
44 } else {
45 $realServer = $server;
46 }
47 $this->close();
48 $this->mServer = $server;
49 $this->mUser = $user;
50 $this->mPassword = $password;
51 $this->mDBname = $dbName;
52
53 $success = false;
54
55 wfProfileIn("dbconnect-$server");
56
57 # The kernel's default SYN retransmission period is far too slow for us,
58 # so we use a short timeout plus a manual retry. Retrying means that a small
59 # but finite rate of SYN packet loss won't cause user-visible errors.
60 $this->mConn = false;
61 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
62 $numAttempts = 2;
63 } else {
64 $numAttempts = 1;
65 }
66 $this->installErrorHandler();
67 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
68 if ( $i > 1 ) {
69 usleep( 1000 );
70 }
71 if ( $this->mFlags & DBO_PERSISTENT ) {
72 $this->mConn = mysql_pconnect( $realServer, $user, $password );
73 } else {
74 # Create a new connection...
75 $this->mConn = mysql_connect( $realServer, $user, $password, true );
76 }
77 if ($this->mConn === false) {
78 #$iplus = $i + 1;
79 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
80 }
81 }
82 $phpError = $this->restoreErrorHandler();
83 # Always log connection errors
84 if ( !$this->mConn ) {
85 $error = $this->lastError();
86 if ( !$error ) {
87 $error = $phpError;
88 }
89 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
90 wfDebug( "DB connection error\n" );
91 wfDebug( "Server: $server, User: $user, Password: " .
92 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
93 $success = false;
94 }
95
96 wfProfileOut("dbconnect-$server");
97
98 if ( $dbName != '' && $this->mConn !== false ) {
99 $success = @/**/mysql_select_db( $dbName, $this->mConn );
100 if ( !$success ) {
101 $error = "Error selecting database $dbName on server {$this->mServer} " .
102 "from client host " . wfHostname() . "\n";
103 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
104 wfDebug( $error );
105 }
106 } else {
107 # Delay USE query
108 $success = (bool)$this->mConn;
109 }
110
111 if ( $success ) {
112 $version = $this->getServerVersion();
113 if ( version_compare( $version, '4.1' ) >= 0 ) {
114 // Tell the server we're communicating with it in UTF-8.
115 // This may engage various charset conversions.
116 global $wgDBmysql5;
117 if( $wgDBmysql5 ) {
118 $this->query( 'SET NAMES utf8', __METHOD__ );
119 }
120 // Turn off strict mode
121 $this->query( "SET sql_mode = ''", __METHOD__ );
122 }
123
124 // Turn off strict mode if it is on
125 } else {
126 $this->reportConnectionError( $phpError );
127 }
128
129 $this->mOpened = $success;
130 wfProfileOut( __METHOD__ );
131 return $success;
132 }
133
134 function close() {
135 $this->mOpened = false;
136 if ( $this->mConn ) {
137 if ( $this->trxLevel() ) {
138 $this->commit();
139 }
140 return mysql_close( $this->mConn );
141 } else {
142 return true;
143 }
144 }
145
146 function freeResult( $res ) {
147 if ( $res instanceof ResultWrapper ) {
148 $res = $res->result;
149 }
150 if ( !@/**/mysql_free_result( $res ) ) {
151 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
152 }
153 }
154
155 function fetchObject( $res ) {
156 if ( $res instanceof ResultWrapper ) {
157 $res = $res->result;
158 }
159 @/**/$row = mysql_fetch_object( $res );
160 if( $this->lastErrno() ) {
161 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
162 }
163 return $row;
164 }
165
166 function fetchRow( $res ) {
167 if ( $res instanceof ResultWrapper ) {
168 $res = $res->result;
169 }
170 @/**/$row = mysql_fetch_array( $res );
171 if ( $this->lastErrno() ) {
172 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
173 }
174 return $row;
175 }
176
177 function numRows( $res ) {
178 if ( $res instanceof ResultWrapper ) {
179 $res = $res->result;
180 }
181 @/**/$n = mysql_num_rows( $res );
182 if( $this->lastErrno() ) {
183 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
184 }
185 return $n;
186 }
187
188 function numFields( $res ) {
189 if ( $res instanceof ResultWrapper ) {
190 $res = $res->result;
191 }
192 return mysql_num_fields( $res );
193 }
194
195 function fieldName( $res, $n ) {
196 if ( $res instanceof ResultWrapper ) {
197 $res = $res->result;
198 }
199 return mysql_field_name( $res, $n );
200 }
201
202 function insertId() { return mysql_insert_id( $this->mConn ); }
203
204 function dataSeek( $res, $row ) {
205 if ( $res instanceof ResultWrapper ) {
206 $res = $res->result;
207 }
208 return mysql_data_seek( $res, $row );
209 }
210
211 function lastErrno() {
212 if ( $this->mConn ) {
213 return mysql_errno( $this->mConn );
214 } else {
215 return mysql_errno();
216 }
217 }
218
219 function lastError() {
220 if ( $this->mConn ) {
221 # Even if it's non-zero, it can still be invalid
222 wfSuppressWarnings();
223 $error = mysql_error( $this->mConn );
224 if ( !$error ) {
225 $error = mysql_error();
226 }
227 wfRestoreWarnings();
228 } else {
229 $error = mysql_error();
230 }
231 if( $error ) {
232 $error .= ' (' . $this->mServer . ')';
233 }
234 return $error;
235 }
236
237 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
238
239 /**
240 * Estimate rows in dataset
241 * Returns estimated count, based on EXPLAIN output
242 * Takes same arguments as Database::select()
243 */
244 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
245 $options['EXPLAIN'] = true;
246 $res = $this->select( $table, $vars, $conds, $fname, $options );
247 if ( $res === false )
248 return false;
249 if ( !$this->numRows( $res ) ) {
250 $this->freeResult($res);
251 return 0;
252 }
253
254 $rows = 1;
255 while( $plan = $this->fetchObject( $res ) ) {
256 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
257 }
258
259 $this->freeResult($res);
260 return $rows;
261 }
262
263 function fieldInfo( $table, $field ) {
264 $table = $this->tableName( $table );
265 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
266 $n = mysql_num_fields( $res->result );
267 for( $i = 0; $i < $n; $i++ ) {
268 $meta = mysql_fetch_field( $res->result, $i );
269 if( $field == $meta->name ) {
270 return new MySQLField($meta);
271 }
272 }
273 return false;
274 }
275
276 function selectDB( $db ) {
277 $this->mDBname = $db;
278 return mysql_select_db( $db, $this->mConn );
279 }
280
281 function strencode( $s ) {
282 return mysql_real_escape_string( $s, $this->mConn );
283 }
284
285 function ping() {
286 if( !function_exists( 'mysql_ping' ) ) {
287 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
288 return true;
289 }
290 $ping = mysql_ping( $this->mConn );
291 if ( $ping ) {
292 return true;
293 }
294
295 // Need to reconnect manually in MySQL client 5.0.13+
296 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
297 mysql_close( $this->mConn );
298 $this->mOpened = false;
299 $this->mConn = false;
300 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
301 return true;
302 }
303 return false;
304 }
305
306 function getServerVersion() {
307 return mysql_get_server_info( $this->mConn );
308 }
309
310 function useIndexClause( $index ) {
311 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
312 }
313
314 function lowPriorityOption() {
315 return 'LOW_PRIORITY';
316 }
317
318 function getSoftwareLink() {
319 return '[http://www.mysql.com/ MySQL]';
320 }
321
322 function standardSelectDistinct() {
323 return false;
324 }
325
326 public function setTimeout( $timeout ) {
327 $this->query( "SET net_read_timeout=$timeout" );
328 $this->query( "SET net_write_timeout=$timeout" );
329 }
330
331 public function lock( $lockName, $method, $timeout = 5 ) {
332 $lockName = $this->addQuotes( $lockName );
333 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
334 $row = $this->fetchObject( $result );
335 $this->freeResult( $result );
336
337 if( $row->lockstatus == 1 ) {
338 return true;
339 } else {
340 wfDebug( __METHOD__." failed to acquire lock\n" );
341 return false;
342 }
343 }
344
345 public function unlock( $lockName, $method ) {
346 $lockName = $this->addQuotes( $lockName );
347 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
348 $row = $this->fetchObject( $result );
349 return $row->lockstatus;
350 }
351
352 public function lockTables( $read, $write, $method, $lowPriority = true ) {
353 $items = array();
354
355 foreach( $write as $table ) {
356 $tbl = $this->tableName( $table ) .
357 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
358 ' WRITE';
359 $items[] = $tbl;
360 }
361 foreach( $read as $table ) {
362 $items[] = $this->tableName( $table ) . ' READ';
363 }
364 $sql = "LOCK TABLES " . implode( ',', $items );
365 $this->query( $sql, $method );
366 }
367
368 public function unlockTables( $method ) {
369 $this->query( "UNLOCK TABLES", $method );
370 }
371
372 /**
373 * Converts some characters for MySQL's indexing to grok it correctly,
374 * and pads short words to overcome limitations.
375 */
376 function stripForSearch( $string ) {
377 global $wgContLang;
378
379 wfProfileIn( __METHOD__ );
380
381 // MySQL fulltext index doesn't grok utf-8, so we
382 // need to fold cases and convert to hex
383 $out = preg_replace_callback(
384 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
385 array( $this, 'stripForSearchCallback' ),
386 $wgContLang->lc( $string ) );
387
388 // And to add insult to injury, the default indexing
389 // ignores short words... Pad them so we can pass them
390 // through without reconfiguring the server...
391 $minLength = $this->minSearchLength();
392 if( $minLength > 1 ) {
393 $n = $minLength - 1;
394 $out = preg_replace(
395 "/\b(\w{1,$n})\b/",
396 "$1u800",
397 $out );
398 }
399
400 // Periods within things like hostnames and IP addresses
401 // are also important -- we want a search for "example.com"
402 // or "192.168.1.1" to work sanely.
403 //
404 // MySQL's search seems to ignore them, so you'd match on
405 // "example.wikipedia.com" and "192.168.83.1" as well.
406 $out = preg_replace(
407 "/(\w)\.(\w|\*)/u",
408 "$1u82e$2",
409 $out );
410
411 wfProfileOut( __METHOD__ );
412
413 return $out;
414 }
415
416 /**
417 * Armor a case-folded UTF-8 string to get through MySQL's
418 * fulltext search without being mucked up by funny charset
419 * settings or anything else of the sort.
420 */
421 protected function stripForSearchCallback( $matches ) {
422 return 'u8' . bin2hex( $matches[1] );
423 }
424
425 /**
426 * Check MySQL server's ft_min_word_len setting so we know
427 * if we need to pad short words...
428 *
429 * @return int
430 */
431 protected function minSearchLength() {
432 if( is_null( self::$mMinSearchLength ) ) {
433 $sql = "show global variables like 'ft\\_min\\_word\\_len'";
434
435 // Even though this query is pretty fast, let's not overload the master
436 $dbr = wfGetDB( DB_SLAVE );
437 $result = $dbr->query( $sql );
438 $row = $result->fetchObject();
439 $result->free();
440
441 if( $row && $row->Variable_name == 'ft_min_word_len' ) {
442 self::$mMinSearchLength = intval( $row->Value );
443 } else {
444 self::$mMinSearchLength = 0;
445 }
446 }
447 return self::$mMinSearchLength;
448 }
449
450 public function setBigSelects( $value = true ) {
451 if ( $value === 'default' ) {
452 if ( $this->mDefaultBigSelects === null ) {
453 # Function hasn't been called before so it must already be set to the default
454 return;
455 } else {
456 $value = $this->mDefaultBigSelects;
457 }
458 } elseif ( $this->mDefaultBigSelects === null ) {
459 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
460 }
461 $encValue = $value ? '1' : '0';
462 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
463 }
464
465
466 /**
467 * Determines if the last failure was due to a deadlock
468 */
469 function wasDeadlock() {
470 return $this->lastErrno() == 1213;
471 }
472
473 /**
474 * Determines if the last query error was something that should be dealt
475 * with by pinging the connection and reissuing the query
476 */
477 function wasErrorReissuable() {
478 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
479 }
480
481 /**
482 * Determines if the last failure was due to the database being read-only.
483 */
484 function wasReadOnlyError() {
485 return $this->lastErrno() == 1223 ||
486 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
487 }
488
489 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
490 $tmp = $temporary ? 'TEMPORARY ' : '';
491 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
492 # Hack for MySQL versions < 4.1, which don't support
493 # "CREATE TABLE ... LIKE". Note that
494 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
495 # would not create the indexes we need....
496 #
497 # Note that we don't bother changing around the prefixes here be-
498 # cause we know we're using MySQL anyway.
499
500 $res = $this->query( "SHOW CREATE TABLE $oldName" );
501 $row = $this->fetchRow( $res );
502 $oldQuery = $row[1];
503 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
504 "CREATE $tmp TABLE `$newName`", $oldQuery );
505 if ($oldQuery === $query) {
506 # Couldn't do replacement
507 throw new MWException( "could not create temporary table $newName" );
508 }
509 } else {
510 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
511 }
512 $this->query( $query, $fname );
513 }
514
515 }
516
517 /**
518 * Legacy support: Database == DatabaseMysql
519 */
520 class Database extends DatabaseMysql {}
521
522 class MySQLMasterPos {
523 var $file, $pos;
524
525 function __construct( $file, $pos ) {
526 $this->file = $file;
527 $this->pos = $pos;
528 }
529
530 function __toString() {
531 return "{$this->file}/{$this->pos}";
532 }
533 }