Fixed mysqlisms in Database.php comments, abstracted getSearchEngine()
[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 function getType() {
11 return 'mysql';
12 }
13
14 /*private*/ function doQuery( $sql ) {
15 if( $this->bufferResults() ) {
16 $ret = mysql_query( $sql, $this->mConn );
17 } else {
18 $ret = mysql_unbuffered_query( $sql, $this->mConn );
19 }
20 return $ret;
21 }
22
23 function open( $server, $user, $password, $dbName ) {
24 global $wgAllDBsAreLocalhost;
25 wfProfileIn( __METHOD__ );
26
27 # Test for missing mysql.so
28 # First try to load it
29 wfDl( 'mysql' );
30
31 # Fail now
32 # Otherwise we get a suppressed fatal error, which is very hard to track down
33 if ( !function_exists( 'mysql_connect' ) ) {
34 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
35 }
36
37 # Debugging hack -- fake cluster
38 if ( $wgAllDBsAreLocalhost ) {
39 $realServer = 'localhost';
40 } else {
41 $realServer = $server;
42 }
43 $this->close();
44 $this->mServer = $server;
45 $this->mUser = $user;
46 $this->mPassword = $password;
47 $this->mDBname = $dbName;
48
49 $success = false;
50
51 wfProfileIn("dbconnect-$server");
52
53 # The kernel's default SYN retransmission period is far too slow for us,
54 # so we use a short timeout plus a manual retry. Retrying means that a small
55 # but finite rate of SYN packet loss won't cause user-visible errors.
56 $this->mConn = false;
57 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
58 $numAttempts = 2;
59 } else {
60 $numAttempts = 1;
61 }
62 $this->installErrorHandler();
63 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
64 if ( $i > 1 ) {
65 usleep( 1000 );
66 }
67 if ( $this->mFlags & DBO_PERSISTENT ) {
68 $this->mConn = mysql_pconnect( $realServer, $user, $password );
69 } else {
70 # Create a new connection...
71 $this->mConn = mysql_connect( $realServer, $user, $password, true );
72 }
73 if ($this->mConn === false) {
74 #$iplus = $i + 1;
75 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
76 }
77 }
78 $phpError = $this->restoreErrorHandler();
79 # Always log connection errors
80 if ( !$this->mConn ) {
81 $error = $this->lastError();
82 if ( !$error ) {
83 $error = $phpError;
84 }
85 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
86 wfDebug( "DB connection error\n" );
87 wfDebug( "Server: $server, User: $user, Password: " .
88 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
89 $success = false;
90 }
91
92 wfProfileOut("dbconnect-$server");
93
94 if ( $dbName != '' && $this->mConn !== false ) {
95 $success = @/**/mysql_select_db( $dbName, $this->mConn );
96 if ( !$success ) {
97 $error = "Error selecting database $dbName on server {$this->mServer} " .
98 "from client host " . wfHostname() . "\n";
99 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
100 wfDebug( $error );
101 }
102 } else {
103 # Delay USE query
104 $success = (bool)$this->mConn;
105 }
106
107 if ( $success ) {
108 $version = $this->getServerVersion();
109 if ( version_compare( $version, '4.1' ) >= 0 ) {
110 // Tell the server we're communicating with it in UTF-8.
111 // This may engage various charset conversions.
112 global $wgDBmysql5;
113 if( $wgDBmysql5 ) {
114 $this->query( 'SET NAMES utf8', __METHOD__ );
115 }
116 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
117 global $wgSQLMode;
118 if ( is_string( $wgSQLMode ) ) {
119 $mode = $this->addQuotes( $wgSQLMode );
120 $this->query( "SET sql_mode = $mode", __METHOD__ );
121 }
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", __METHOD__, true );
266 if ( !$res ) {
267 return false;
268 }
269 $n = mysql_num_fields( $res->result );
270 for( $i = 0; $i < $n; $i++ ) {
271 $meta = mysql_fetch_field( $res->result, $i );
272 if( $field == $meta->name ) {
273 return new MySQLField($meta);
274 }
275 }
276 return false;
277 }
278
279 function selectDB( $db ) {
280 $this->mDBname = $db;
281 return mysql_select_db( $db, $this->mConn );
282 }
283
284 function strencode( $s ) {
285 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
286
287 if($sQuoted === false) {
288 $this->ping();
289 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
290 }
291 return $sQuoted;
292 }
293
294 function ping() {
295 $ping = mysql_ping( $this->mConn );
296 if ( $ping ) {
297 return true;
298 }
299
300 mysql_close( $this->mConn );
301 $this->mOpened = false;
302 $this->mConn = false;
303 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
304 return true;
305 }
306
307 /**
308 * Returns slave lag.
309 * At the moment, this will only work if the DB user has the PROCESS privilege
310 * @result int
311 */
312 function getLag() {
313 if ( !is_null( $this->mFakeSlaveLag ) ) {
314 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
315 return $this->mFakeSlaveLag;
316 }
317 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
318 # Find slave SQL thread
319 while ( $row = $this->fetchObject( $res ) ) {
320 /* This should work for most situations - when default db
321 * for thread is not specified, it had no events executed,
322 * and therefore it doesn't know yet how lagged it is.
323 *
324 * Relay log I/O thread does not select databases.
325 */
326 if ( $row->User == 'system user' &&
327 $row->State != 'Waiting for master to send event' &&
328 $row->State != 'Connecting to master' &&
329 $row->State != 'Queueing master event to the relay log' &&
330 $row->State != 'Waiting for master update' &&
331 $row->State != 'Requesting binlog dump' &&
332 $row->State != 'Waiting to reconnect after a failed master event read' &&
333 $row->State != 'Reconnecting after a failed master event read' &&
334 $row->State != 'Registering slave on master'
335 ) {
336 # This is it, return the time (except -ve)
337 if ( $row->Time > 0x7fffffff ) {
338 return false;
339 } else {
340 return $row->Time;
341 }
342 }
343 }
344 return false;
345 }
346
347 function getServerVersion() {
348 return mysql_get_server_info( $this->mConn );
349 }
350
351 function useIndexClause( $index ) {
352 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
353 }
354
355 function lowPriorityOption() {
356 return 'LOW_PRIORITY';
357 }
358
359 function getSoftwareLink() {
360 return '[http://www.mysql.com/ MySQL]';
361 }
362
363 function standardSelectDistinct() {
364 return false;
365 }
366
367 public function setTimeout( $timeout ) {
368 $this->query( "SET net_read_timeout=$timeout" );
369 $this->query( "SET net_write_timeout=$timeout" );
370 }
371
372 public function lock( $lockName, $method, $timeout = 5 ) {
373 $lockName = $this->addQuotes( $lockName );
374 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
375 $row = $this->fetchObject( $result );
376 $this->freeResult( $result );
377
378 if( $row->lockstatus == 1 ) {
379 return true;
380 } else {
381 wfDebug( __METHOD__." failed to acquire lock\n" );
382 return false;
383 }
384 }
385
386 /**
387 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
388 */
389 public function unlock( $lockName, $method ) {
390 $lockName = $this->addQuotes( $lockName );
391 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
392 $row = $this->fetchObject( $result );
393 return $row->lockstatus;
394 }
395
396 public function lockTables( $read, $write, $method, $lowPriority = true ) {
397 $items = array();
398
399 foreach( $write as $table ) {
400 $tbl = $this->tableName( $table ) .
401 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
402 ' WRITE';
403 $items[] = $tbl;
404 }
405 foreach( $read as $table ) {
406 $items[] = $this->tableName( $table ) . ' READ';
407 }
408 $sql = "LOCK TABLES " . implode( ',', $items );
409 $this->query( $sql, $method );
410 }
411
412 public function unlockTables( $method ) {
413 $this->query( "UNLOCK TABLES", $method );
414 }
415
416 /**
417 * Get search engine class. All subclasses of this
418 * need to implement this if they wish to use searching.
419 *
420 * @return String
421 */
422 public function getSearchEngine() {
423 return 'SearchMySQL';
424 }
425
426 public function setBigSelects( $value = true ) {
427 if ( $value === 'default' ) {
428 if ( $this->mDefaultBigSelects === null ) {
429 # Function hasn't been called before so it must already be set to the default
430 return;
431 } else {
432 $value = $this->mDefaultBigSelects;
433 }
434 } elseif ( $this->mDefaultBigSelects === null ) {
435 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
436 }
437 $encValue = $value ? '1' : '0';
438 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
439 }
440
441
442 /**
443 * Determines if the last failure was due to a deadlock
444 */
445 function wasDeadlock() {
446 return $this->lastErrno() == 1213;
447 }
448
449 /**
450 * Determines if the last query error was something that should be dealt
451 * with by pinging the connection and reissuing the query
452 */
453 function wasErrorReissuable() {
454 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
455 }
456
457 /**
458 * Determines if the last failure was due to the database being read-only.
459 */
460 function wasReadOnlyError() {
461 return $this->lastErrno() == 1223 ||
462 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
463 }
464
465 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
466 $tmp = $temporary ? 'TEMPORARY ' : '';
467 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
468 # Hack for MySQL versions < 4.1, which don't support
469 # "CREATE TABLE ... LIKE". Note that
470 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
471 # would not create the indexes we need....
472 #
473 # Note that we don't bother changing around the prefixes here be-
474 # cause we know we're using MySQL anyway.
475
476 $res = $this->query( "SHOW CREATE TABLE $oldName" );
477 $row = $this->fetchRow( $res );
478 $oldQuery = $row[1];
479 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
480 "CREATE $tmp TABLE `$newName`", $oldQuery );
481 if ($oldQuery === $query) {
482 # Couldn't do replacement
483 throw new MWException( "could not create temporary table $newName" );
484 }
485 } else {
486 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
487 }
488 $this->query( $query, $fname );
489 }
490
491 }
492
493 /**
494 * Legacy support: Database == DatabaseMysql
495 */
496 class Database extends DatabaseMysql {}
497
498 class MySQLMasterPos {
499 var $file, $pos;
500
501 function __construct( $file, $pos ) {
502 $this->file = $file;
503 $this->pos = $pos;
504 }
505
506 function __toString() {
507 return "{$this->file}/{$this->pos}";
508 }
509 }