Merge "Move subclasses of LogFormatter to their own file"
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database abstraction object for mySQL
26 * Inherit all methods and properties of Database::Database()
27 *
28 * @ingroup Database
29 * @see Database
30 */
31 class DatabaseMysql extends DatabaseBase {
32
33 /**
34 * @return string
35 */
36 function getType() {
37 return 'mysql';
38 }
39
40 /**
41 * @param $sql string
42 * @return resource
43 */
44 protected function doQuery( $sql ) {
45 if( $this->bufferResults() ) {
46 $ret = mysql_query( $sql, $this->mConn );
47 } else {
48 $ret = mysql_unbuffered_query( $sql, $this->mConn );
49 }
50 return $ret;
51 }
52
53 /**
54 * @param $server string
55 * @param $user string
56 * @param $password string
57 * @param $dbName string
58 * @return bool
59 * @throws DBConnectionError
60 */
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
63 wfProfileIn( __METHOD__ );
64
65 # Load mysql.so if we don't have it
66 wfDl( 'mysql' );
67
68 # Fail now
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if ( !function_exists( 'mysql_connect' ) ) {
71 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
72 }
73
74 # Debugging hack -- fake cluster
75 if ( $wgAllDBsAreLocalhost ) {
76 $realServer = 'localhost';
77 } else {
78 $realServer = $server;
79 }
80 $this->close();
81 $this->mServer = $server;
82 $this->mUser = $user;
83 $this->mPassword = $password;
84 $this->mDBname = $dbName;
85
86 $connFlags = 0;
87 if ( $this->mFlags & DBO_SSL ) {
88 $connFlags |= MYSQL_CLIENT_SSL;
89 }
90 if ( $this->mFlags & DBO_COMPRESS ) {
91 $connFlags |= MYSQL_CLIENT_COMPRESS;
92 }
93
94 wfProfileIn( "dbconnect-$server" );
95
96 # The kernel's default SYN retransmission period is far too slow for us,
97 # so we use a short timeout plus a manual retry. Retrying means that a small
98 # but finite rate of SYN packet loss won't cause user-visible errors.
99 $this->mConn = false;
100 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
101 $numAttempts = 2;
102 } else {
103 $numAttempts = 1;
104 }
105 $this->installErrorHandler();
106 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
107 if ( $i > 1 ) {
108 usleep( 1000 );
109 }
110 if ( $this->mFlags & DBO_PERSISTENT ) {
111 $this->mConn = mysql_pconnect( $realServer, $user, $password, $connFlags );
112 } else {
113 # Create a new connection...
114 $this->mConn = mysql_connect( $realServer, $user, $password, true, $connFlags );
115 }
116 #if ( $this->mConn === false ) {
117 #$iplus = $i + 1;
118 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
119 #}
120 }
121 $error = $this->restoreErrorHandler();
122
123 wfProfileOut( "dbconnect-$server" );
124
125 # Always log connection errors
126 if ( !$this->mConn ) {
127 if ( !$error ) {
128 $error = $this->lastError();
129 }
130 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
131 wfDebug( "DB connection error\n" .
132 "Server: $server, User: $user, Password: " .
133 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
134
135 wfProfileOut( __METHOD__ );
136 return $this->reportConnectionError( $error );
137 }
138
139 if ( $dbName != '' ) {
140 wfSuppressWarnings();
141 $success = mysql_select_db( $dbName, $this->mConn );
142 wfRestoreWarnings();
143 if ( !$success ) {
144 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
145 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
146 "from client host " . wfHostname() . "\n" );
147
148 wfProfileOut( __METHOD__ );
149 return $this->reportConnectionError( "Error selecting database $dbName" );
150 }
151 }
152
153 // Tell the server we're communicating with it in UTF-8.
154 // This may engage various charset conversions.
155 if( $wgDBmysql5 ) {
156 $this->query( 'SET NAMES utf8', __METHOD__ );
157 } else {
158 $this->query( 'SET NAMES binary', __METHOD__ );
159 }
160 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
161 if ( is_string( $wgSQLMode ) ) {
162 $mode = $this->addQuotes( $wgSQLMode );
163 $this->query( "SET sql_mode = $mode", __METHOD__ );
164 }
165
166 $this->mOpened = true;
167 wfProfileOut( __METHOD__ );
168 return true;
169 }
170
171 /**
172 * @return bool
173 */
174 protected function closeConnection() {
175 return mysql_close( $this->mConn );
176 }
177
178 /**
179 * @param $res ResultWrapper
180 * @throws DBUnexpectedError
181 */
182 function freeResult( $res ) {
183 if ( $res instanceof ResultWrapper ) {
184 $res = $res->result;
185 }
186 wfSuppressWarnings();
187 $ok = mysql_free_result( $res );
188 wfRestoreWarnings();
189 if ( !$ok ) {
190 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
191 }
192 }
193
194 /**
195 * @param $res ResultWrapper
196 * @return object|bool
197 * @throws DBUnexpectedError
198 */
199 function fetchObject( $res ) {
200 if ( $res instanceof ResultWrapper ) {
201 $res = $res->result;
202 }
203 wfSuppressWarnings();
204 $row = mysql_fetch_object( $res );
205 wfRestoreWarnings();
206
207 $errno = $this->lastErrno();
208 // Unfortunately, mysql_fetch_object does not reset the last errno.
209 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
210 // these are the only errors mysql_fetch_object can cause.
211 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
212 if( $errno == 2000 || $errno == 2013 ) {
213 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
214 }
215 return $row;
216 }
217
218 /**
219 * @param $res ResultWrapper
220 * @return array|bool
221 * @throws DBUnexpectedError
222 */
223 function fetchRow( $res ) {
224 if ( $res instanceof ResultWrapper ) {
225 $res = $res->result;
226 }
227 wfSuppressWarnings();
228 $row = mysql_fetch_array( $res );
229 wfRestoreWarnings();
230
231 $errno = $this->lastErrno();
232 // Unfortunately, mysql_fetch_array does not reset the last errno.
233 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
234 // these are the only errors mysql_fetch_object can cause.
235 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
236 if( $errno == 2000 || $errno == 2013 ) {
237 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
238 }
239 return $row;
240 }
241
242 /**
243 * @throws DBUnexpectedError
244 * @param $res ResultWrapper
245 * @return int
246 */
247 function numRows( $res ) {
248 if ( $res instanceof ResultWrapper ) {
249 $res = $res->result;
250 }
251 wfSuppressWarnings();
252 $n = mysql_num_rows( $res );
253 wfRestoreWarnings();
254 // Unfortunately, mysql_num_rows does not reset the last errno.
255 // We are not checking for any errors here, since
256 // these are no errors mysql_num_rows can cause.
257 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
258 // See https://bugzilla.wikimedia.org/42430
259 return $n;
260 }
261
262 /**
263 * @param $res ResultWrapper
264 * @return int
265 */
266 function numFields( $res ) {
267 if ( $res instanceof ResultWrapper ) {
268 $res = $res->result;
269 }
270 return mysql_num_fields( $res );
271 }
272
273 /**
274 * @param $res ResultWrapper
275 * @param $n string
276 * @return string
277 */
278 function fieldName( $res, $n ) {
279 if ( $res instanceof ResultWrapper ) {
280 $res = $res->result;
281 }
282 return mysql_field_name( $res, $n );
283 }
284
285 /**
286 * @return int
287 */
288 function insertId() {
289 return mysql_insert_id( $this->mConn );
290 }
291
292 /**
293 * @param $res ResultWrapper
294 * @param $row
295 * @return bool
296 */
297 function dataSeek( $res, $row ) {
298 if ( $res instanceof ResultWrapper ) {
299 $res = $res->result;
300 }
301 return mysql_data_seek( $res, $row );
302 }
303
304 /**
305 * @return int
306 */
307 function lastErrno() {
308 if ( $this->mConn ) {
309 return mysql_errno( $this->mConn );
310 } else {
311 return mysql_errno();
312 }
313 }
314
315 /**
316 * @return string
317 */
318 function lastError() {
319 if ( $this->mConn ) {
320 # Even if it's non-zero, it can still be invalid
321 wfSuppressWarnings();
322 $error = mysql_error( $this->mConn );
323 if ( !$error ) {
324 $error = mysql_error();
325 }
326 wfRestoreWarnings();
327 } else {
328 $error = mysql_error();
329 }
330 if( $error ) {
331 $error .= ' (' . $this->mServer . ')';
332 }
333 return $error;
334 }
335
336 /**
337 * @return int
338 */
339 function affectedRows() {
340 return mysql_affected_rows( $this->mConn );
341 }
342
343 /**
344 * @param $table string
345 * @param $uniqueIndexes
346 * @param $rows array
347 * @param $fname string
348 * @return ResultWrapper
349 */
350 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
351 return $this->nativeReplace( $table, $rows, $fname );
352 }
353
354 /**
355 * Estimate rows in dataset
356 * Returns estimated count, based on EXPLAIN output
357 * Takes same arguments as Database::select()
358 *
359 * @param $table string|array
360 * @param $vars string|array
361 * @param $conds string|array
362 * @param $fname string
363 * @param $options string|array
364 * @return int
365 */
366 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
367 $options['EXPLAIN'] = true;
368 $res = $this->select( $table, $vars, $conds, $fname, $options );
369 if ( $res === false ) {
370 return false;
371 }
372 if ( !$this->numRows( $res ) ) {
373 return 0;
374 }
375
376 $rows = 1;
377 foreach ( $res as $plan ) {
378 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
379 }
380 return $rows;
381 }
382
383 /**
384 * @param $table string
385 * @param $field string
386 * @return bool|MySQLField
387 */
388 function fieldInfo( $table, $field ) {
389 $table = $this->tableName( $table );
390 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
391 if ( !$res ) {
392 return false;
393 }
394 $n = mysql_num_fields( $res->result );
395 for( $i = 0; $i < $n; $i++ ) {
396 $meta = mysql_fetch_field( $res->result, $i );
397 if( $field == $meta->name ) {
398 return new MySQLField( $meta );
399 }
400 }
401 return false;
402 }
403
404 /**
405 * Get information about an index into an object
406 * Returns false if the index does not exist
407 *
408 * @param $table string
409 * @param $index string
410 * @param $fname string
411 * @return bool|array|null False or null on failure
412 */
413 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
414 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
415 # SHOW INDEX should work for 3.x and up:
416 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
417 $table = $this->tableName( $table );
418 $index = $this->indexName( $index );
419
420 $sql = 'SHOW INDEX FROM ' . $table;
421 $res = $this->query( $sql, $fname );
422
423 if ( !$res ) {
424 return null;
425 }
426
427 $result = array();
428
429 foreach ( $res as $row ) {
430 if ( $row->Key_name == $index ) {
431 $result[] = $row;
432 }
433 }
434 return empty( $result ) ? false : $result;
435 }
436
437 /**
438 * @param $db
439 * @return bool
440 */
441 function selectDB( $db ) {
442 $this->mDBname = $db;
443 return mysql_select_db( $db, $this->mConn );
444 }
445
446 /**
447 * @param $s string
448 *
449 * @return string
450 */
451 function strencode( $s ) {
452 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
453
454 if( $sQuoted === false ) {
455 $this->ping();
456 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
457 }
458 return $sQuoted;
459 }
460
461 /**
462 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
463 *
464 * @param $s string
465 *
466 * @return string
467 */
468 public function addIdentifierQuotes( $s ) {
469 return "`" . $this->strencode( $s ) . "`";
470 }
471
472 /**
473 * @param $name string
474 * @return bool
475 */
476 public function isQuotedIdentifier( $name ) {
477 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
478 }
479
480 /**
481 * @return bool
482 */
483 function ping() {
484 $ping = mysql_ping( $this->mConn );
485 if ( $ping ) {
486 return true;
487 }
488
489 mysql_close( $this->mConn );
490 $this->mOpened = false;
491 $this->mConn = false;
492 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
493 return true;
494 }
495
496 /**
497 * Returns slave lag.
498 *
499 * This will do a SHOW SLAVE STATUS
500 *
501 * @return int
502 */
503 function getLag() {
504 if ( !is_null( $this->mFakeSlaveLag ) ) {
505 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
506 return $this->mFakeSlaveLag;
507 }
508
509 return $this->getLagFromSlaveStatus();
510 }
511
512 /**
513 * @return bool|int
514 */
515 function getLagFromSlaveStatus() {
516 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
517 if ( !$res ) {
518 return false;
519 }
520 $row = $res->fetchObject();
521 if ( !$row ) {
522 return false;
523 }
524 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
525 return false;
526 } else {
527 return intval( $row->Seconds_Behind_Master );
528 }
529 }
530
531 /**
532 * @deprecated in 1.19, use getLagFromSlaveStatus
533 *
534 * @return bool|int
535 */
536 function getLagFromProcesslist() {
537 wfDeprecated( __METHOD__, '1.19' );
538 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
539 if( !$res ) {
540 return false;
541 }
542 # Find slave SQL thread
543 foreach( $res as $row ) {
544 /* This should work for most situations - when default db
545 * for thread is not specified, it had no events executed,
546 * and therefore it doesn't know yet how lagged it is.
547 *
548 * Relay log I/O thread does not select databases.
549 */
550 if ( $row->User == 'system user' &&
551 $row->State != 'Waiting for master to send event' &&
552 $row->State != 'Connecting to master' &&
553 $row->State != 'Queueing master event to the relay log' &&
554 $row->State != 'Waiting for master update' &&
555 $row->State != 'Requesting binlog dump' &&
556 $row->State != 'Waiting to reconnect after a failed master event read' &&
557 $row->State != 'Reconnecting after a failed master event read' &&
558 $row->State != 'Registering slave on master'
559 ) {
560 # This is it, return the time (except -ve)
561 if ( $row->Time > 0x7fffffff ) {
562 return false;
563 } else {
564 return $row->Time;
565 }
566 }
567 }
568 return false;
569 }
570
571 /**
572 * Wait for the slave to catch up to a given master position.
573 *
574 * @param $pos DBMasterPos object
575 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
576 * @return bool|string
577 */
578 function masterPosWait( DBMasterPos $pos, $timeout ) {
579 $fname = 'DatabaseBase::masterPosWait';
580 wfProfileIn( $fname );
581
582 # Commit any open transactions
583 if ( $this->mTrxLevel ) {
584 $this->commit( __METHOD__ );
585 }
586
587 if ( !is_null( $this->mFakeSlaveLag ) ) {
588 $status = parent::masterPosWait( $pos, $timeout );
589 wfProfileOut( $fname );
590 return $status;
591 }
592
593 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
594 $encFile = $this->addQuotes( $pos->file );
595 $encPos = intval( $pos->pos );
596 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
597 $res = $this->doQuery( $sql );
598
599 if ( $res && $row = $this->fetchRow( $res ) ) {
600 wfProfileOut( $fname );
601 return $row[0];
602 }
603 wfProfileOut( $fname );
604 return false;
605 }
606
607 /**
608 * Get the position of the master from SHOW SLAVE STATUS
609 *
610 * @return MySQLMasterPos|bool
611 */
612 function getSlavePos() {
613 if ( !is_null( $this->mFakeSlaveLag ) ) {
614 return parent::getSlavePos();
615 }
616
617 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
618 $row = $this->fetchObject( $res );
619
620 if ( $row ) {
621 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
622 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
623 } else {
624 return false;
625 }
626 }
627
628 /**
629 * Get the position of the master from SHOW MASTER STATUS
630 *
631 * @return MySQLMasterPos|bool
632 */
633 function getMasterPos() {
634 if ( $this->mFakeMaster ) {
635 return parent::getMasterPos();
636 }
637
638 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
639 $row = $this->fetchObject( $res );
640
641 if ( $row ) {
642 return new MySQLMasterPos( $row->File, $row->Position );
643 } else {
644 return false;
645 }
646 }
647
648 /**
649 * @return string
650 */
651 function getServerVersion() {
652 return mysql_get_server_info( $this->mConn );
653 }
654
655 /**
656 * @param $index
657 * @return string
658 */
659 function useIndexClause( $index ) {
660 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
661 }
662
663 /**
664 * @return string
665 */
666 function lowPriorityOption() {
667 return 'LOW_PRIORITY';
668 }
669
670 /**
671 * @return string
672 */
673 public static function getSoftwareLink() {
674 return '[http://www.mysql.com/ MySQL]';
675 }
676
677 /**
678 * @param $options array
679 */
680 public function setSessionOptions( array $options ) {
681 if ( isset( $options['connTimeout'] ) ) {
682 $timeout = (int)$options['connTimeout'];
683 $this->query( "SET net_read_timeout=$timeout" );
684 $this->query( "SET net_write_timeout=$timeout" );
685 }
686 }
687
688 public function streamStatementEnd( &$sql, &$newLine ) {
689 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
690 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
691 $this->delimiter = $m[1];
692 $newLine = '';
693 }
694 return parent::streamStatementEnd( $sql, $newLine );
695 }
696
697 /**
698 * Check to see if a named lock is available. This is non-blocking.
699 *
700 * @param string $lockName name of lock to poll
701 * @param string $method name of method calling us
702 * @return Boolean
703 * @since 1.20
704 */
705 public function lockIsFree( $lockName, $method ) {
706 $lockName = $this->addQuotes( $lockName );
707 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
708 $row = $this->fetchObject( $result );
709 return ( $row->lockstatus == 1 );
710 }
711
712 /**
713 * @param $lockName string
714 * @param $method string
715 * @param $timeout int
716 * @return bool
717 */
718 public function lock( $lockName, $method, $timeout = 5 ) {
719 $lockName = $this->addQuotes( $lockName );
720 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
721 $row = $this->fetchObject( $result );
722
723 if( $row->lockstatus == 1 ) {
724 return true;
725 } else {
726 wfDebug( __METHOD__ . " failed to acquire lock\n" );
727 return false;
728 }
729 }
730
731 /**
732 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
733 * @param $lockName string
734 * @param $method string
735 * @return bool
736 */
737 public function unlock( $lockName, $method ) {
738 $lockName = $this->addQuotes( $lockName );
739 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
740 $row = $this->fetchObject( $result );
741 return ( $row->lockstatus == 1 );
742 }
743
744 /**
745 * @param $read array
746 * @param $write array
747 * @param $method string
748 * @param $lowPriority bool
749 * @return bool
750 */
751 public function lockTables( $read, $write, $method, $lowPriority = true ) {
752 $items = array();
753
754 foreach( $write as $table ) {
755 $tbl = $this->tableName( $table ) .
756 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
757 ' WRITE';
758 $items[] = $tbl;
759 }
760 foreach( $read as $table ) {
761 $items[] = $this->tableName( $table ) . ' READ';
762 }
763 $sql = "LOCK TABLES " . implode( ',', $items );
764 $this->query( $sql, $method );
765 return true;
766 }
767
768 /**
769 * @param $method string
770 * @return bool
771 */
772 public function unlockTables( $method ) {
773 $this->query( "UNLOCK TABLES", $method );
774 return true;
775 }
776
777 /**
778 * Get search engine class. All subclasses of this
779 * need to implement this if they wish to use searching.
780 *
781 * @return String
782 */
783 public function getSearchEngine() {
784 return 'SearchMySQL';
785 }
786
787 /**
788 * @param bool $value
789 * @return mixed
790 */
791 public function setBigSelects( $value = true ) {
792 if ( $value === 'default' ) {
793 if ( $this->mDefaultBigSelects === null ) {
794 # Function hasn't been called before so it must already be set to the default
795 return;
796 } else {
797 $value = $this->mDefaultBigSelects;
798 }
799 } elseif ( $this->mDefaultBigSelects === null ) {
800 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
801 }
802 $encValue = $value ? '1' : '0';
803 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
804 }
805
806 /**
807 * DELETE where the condition is a join. MySql uses multi-table deletes.
808 * @param $delTable string
809 * @param $joinTable string
810 * @param $delVar string
811 * @param $joinVar string
812 * @param $conds array|string
813 * @param bool|string $fname bool
814 * @throws DBUnexpectedError
815 * @return bool|ResultWrapper
816 */
817 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
818 if ( !$conds ) {
819 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
820 }
821
822 $delTable = $this->tableName( $delTable );
823 $joinTable = $this->tableName( $joinTable );
824 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
825
826 if ( $conds != '*' ) {
827 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
828 }
829
830 return $this->query( $sql, $fname );
831 }
832
833 /**
834 * Determines how long the server has been up
835 *
836 * @return int
837 */
838 function getServerUptime() {
839 $vars = $this->getMysqlStatus( 'Uptime' );
840 return (int)$vars['Uptime'];
841 }
842
843 /**
844 * Determines if the last failure was due to a deadlock
845 *
846 * @return bool
847 */
848 function wasDeadlock() {
849 return $this->lastErrno() == 1213;
850 }
851
852 /**
853 * Determines if the last failure was due to a lock timeout
854 *
855 * @return bool
856 */
857 function wasLockTimeout() {
858 return $this->lastErrno() == 1205;
859 }
860
861 /**
862 * Determines if the last query error was something that should be dealt
863 * with by pinging the connection and reissuing the query
864 *
865 * @return bool
866 */
867 function wasErrorReissuable() {
868 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
869 }
870
871 /**
872 * Determines if the last failure was due to the database being read-only.
873 *
874 * @return bool
875 */
876 function wasReadOnlyError() {
877 return $this->lastErrno() == 1223 ||
878 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
879 }
880
881 /**
882 * @param $oldName
883 * @param $newName
884 * @param $temporary bool
885 * @param $fname string
886 */
887 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
888 $tmp = $temporary ? 'TEMPORARY ' : '';
889 $newName = $this->addIdentifierQuotes( $newName );
890 $oldName = $this->addIdentifierQuotes( $oldName );
891 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
892 $this->query( $query, $fname );
893 }
894
895 /**
896 * List all tables on the database
897 *
898 * @param string $prefix Only show tables with this prefix, e.g. mw_
899 * @param string $fname calling function name
900 * @return array
901 */
902 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
903 $result = $this->query( "SHOW TABLES", $fname);
904
905 $endArray = array();
906
907 foreach( $result as $table ) {
908 $vars = get_object_vars( $table );
909 $table = array_pop( $vars );
910
911 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
912 $endArray[] = $table;
913 }
914 }
915
916 return $endArray;
917 }
918
919 /**
920 * @param $tableName
921 * @param $fName string
922 * @return bool|ResultWrapper
923 */
924 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
925 if( !$this->tableExists( $tableName, $fName ) ) {
926 return false;
927 }
928 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
929 }
930
931 /**
932 * @return array
933 */
934 protected function getDefaultSchemaVars() {
935 $vars = parent::getDefaultSchemaVars();
936 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
937 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
938 return $vars;
939 }
940
941 /**
942 * Get status information from SHOW STATUS in an associative array
943 *
944 * @param $which string
945 * @return array
946 */
947 function getMysqlStatus( $which = "%" ) {
948 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
949 $status = array();
950
951 foreach ( $res as $row ) {
952 $status[$row->Variable_name] = $row->Value;
953 }
954
955 return $status;
956 }
957
958 }
959
960 /**
961 * Utility class.
962 * @ingroup Database
963 */
964 class MySQLField implements Field {
965 private $name, $tablename, $default, $max_length, $nullable,
966 $is_pk, $is_unique, $is_multiple, $is_key, $type;
967
968 function __construct( $info ) {
969 $this->name = $info->name;
970 $this->tablename = $info->table;
971 $this->default = $info->def;
972 $this->max_length = $info->max_length;
973 $this->nullable = !$info->not_null;
974 $this->is_pk = $info->primary_key;
975 $this->is_unique = $info->unique_key;
976 $this->is_multiple = $info->multiple_key;
977 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
978 $this->type = $info->type;
979 }
980
981 /**
982 * @return string
983 */
984 function name() {
985 return $this->name;
986 }
987
988 /**
989 * @return string
990 */
991 function tableName() {
992 return $this->tableName;
993 }
994
995 /**
996 * @return string
997 */
998 function type() {
999 return $this->type;
1000 }
1001
1002 /**
1003 * @return bool
1004 */
1005 function isNullable() {
1006 return $this->nullable;
1007 }
1008
1009 function defaultValue() {
1010 return $this->default;
1011 }
1012
1013 /**
1014 * @return bool
1015 */
1016 function isKey() {
1017 return $this->is_key;
1018 }
1019
1020 /**
1021 * @return bool
1022 */
1023 function isMultipleKey() {
1024 return $this->is_multiple;
1025 }
1026 }
1027
1028 class MySQLMasterPos implements DBMasterPos {
1029 var $file, $pos;
1030
1031 function __construct( $file, $pos ) {
1032 $this->file = $file;
1033 $this->pos = $pos;
1034 }
1035
1036 function __toString() {
1037 return "{$this->file}/{$this->pos}";
1038 }
1039 }