Merge "Revert "Declare visibility for class properties in MySQLMasterPos""
[lhc/web/wiklou.git] / includes / db / DatabaseMysqlBase.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 * Defines methods independent on used MySQL extension.
27 *
28 * @ingroup Database
29 * @since 1.22
30 * @see Database
31 */
32 abstract class DatabaseMysqlBase extends DatabaseBase {
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35
36 /**
37 * @return string
38 */
39 function getType() {
40 return 'mysql';
41 }
42
43 /**
44 * @param $server string
45 * @param $user string
46 * @param $password string
47 * @param $dbName string
48 * @return bool
49 * @throws DBConnectionError
50 */
51 function open( $server, $user, $password, $dbName ) {
52 global $wgAllDBsAreLocalhost, $wgSQLMode;
53 wfProfileIn( __METHOD__ );
54
55 # Debugging hack -- fake cluster
56 if ( $wgAllDBsAreLocalhost ) {
57 $realServer = 'localhost';
58 } else {
59 $realServer = $server;
60 }
61 $this->close();
62 $this->mServer = $server;
63 $this->mUser = $user;
64 $this->mPassword = $password;
65 $this->mDBname = $dbName;
66
67 wfProfileIn( "dbconnect-$server" );
68
69 # The kernel's default SYN retransmission period is far too slow for us,
70 # so we use a short timeout plus a manual retry. Retrying means that a small
71 # but finite rate of SYN packet loss won't cause user-visible errors.
72 $this->mConn = false;
73 $this->installErrorHandler();
74 try {
75 $this->mConn = $this->mysqlConnect( $realServer );
76 } catch ( Exception $ex ) {
77 wfProfileOut( "dbconnect-$server" );
78 wfProfileOut( __METHOD__ );
79 $this->restoreErrorHandler();
80 throw $ex;
81 }
82 $error = $this->restoreErrorHandler();
83
84 wfProfileOut( "dbconnect-$server" );
85
86 # Always log connection errors
87 if ( !$this->mConn ) {
88 if ( !$error ) {
89 $error = $this->lastError();
90 }
91 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
92 wfDebug( "DB connection error\n" .
93 "Server: $server, User: $user, Password: " .
94 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
95
96 wfProfileOut( __METHOD__ );
97
98 $this->reportConnectionError( $error );
99 }
100
101 if ( $dbName != '' ) {
102 wfSuppressWarnings();
103 $success = $this->selectDB( $dbName );
104 wfRestoreWarnings();
105 if ( !$success ) {
106 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
107 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
108 "from client host " . wfHostname() . "\n" );
109
110 wfProfileOut( __METHOD__ );
111
112 $this->reportConnectionError( "Error selecting database $dbName" );
113 }
114 }
115
116 // Tell the server what we're communicating with
117 if ( !$this->connectInitCharset() ) {
118 $this->reportConnectionError( "Error setting character set" );
119 }
120
121 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
122 if ( is_string( $wgSQLMode ) ) {
123 $mode = $this->addQuotes( $wgSQLMode );
124 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
125 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__ );
126 if ( !$success ) {
127 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
128 wfProfileOut( __METHOD__ );
129 $this->reportConnectionError( "Error setting sql_mode to $mode" );
130 }
131 }
132
133 $this->mOpened = true;
134 wfProfileOut( __METHOD__ );
135
136 return true;
137 }
138
139 /**
140 * Set the character set information right after connection
141 * @return bool
142 */
143 protected function connectInitCharset() {
144 global $wgDBmysql5;
145
146 if ( $wgDBmysql5 ) {
147 // Tell the server we're communicating with it in UTF-8.
148 // This may engage various charset conversions.
149 return $this->mysqlSetCharset( 'utf8' );
150 } else {
151 return $this->mysqlSetCharset( 'binary' );
152 }
153 }
154
155 /**
156 * Open a connection to a MySQL server
157 *
158 * @param $realServer string
159 * @return mixed Raw connection
160 * @throws DBConnectionError
161 */
162 abstract protected function mysqlConnect( $realServer );
163
164 /**
165 * Set the character set of the MySQL link
166 *
167 * @param string $charset
168 * @return bool
169 */
170 abstract protected function mysqlSetCharset( $charset );
171
172 /**
173 * @param $res ResultWrapper
174 * @throws DBUnexpectedError
175 */
176 function freeResult( $res ) {
177 if ( $res instanceof ResultWrapper ) {
178 $res = $res->result;
179 }
180 wfSuppressWarnings();
181 $ok = $this->mysqlFreeResult( $res );
182 wfRestoreWarnings();
183 if ( !$ok ) {
184 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
185 }
186 }
187
188 /**
189 * Free result memory
190 *
191 * @param $res Raw result
192 * @return bool
193 */
194 abstract protected function mysqlFreeResult( $res );
195
196 /**
197 * @param $res ResultWrapper
198 * @return object|bool
199 * @throws DBUnexpectedError
200 */
201 function fetchObject( $res ) {
202 if ( $res instanceof ResultWrapper ) {
203 $res = $res->result;
204 }
205 wfSuppressWarnings();
206 $row = $this->mysqlFetchObject( $res );
207 wfRestoreWarnings();
208
209 $errno = $this->lastErrno();
210 // Unfortunately, mysql_fetch_object does not reset the last errno.
211 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
212 // these are the only errors mysql_fetch_object can cause.
213 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
214 if ( $errno == 2000 || $errno == 2013 ) {
215 throw new DBUnexpectedError(
216 $this,
217 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
218 );
219 }
220
221 return $row;
222 }
223
224 /**
225 * Fetch a result row as an object
226 *
227 * @param $res Raw result
228 * @return stdClass
229 */
230 abstract protected function mysqlFetchObject( $res );
231
232 /**
233 * @param $res ResultWrapper
234 * @return array|bool
235 * @throws DBUnexpectedError
236 */
237 function fetchRow( $res ) {
238 if ( $res instanceof ResultWrapper ) {
239 $res = $res->result;
240 }
241 wfSuppressWarnings();
242 $row = $this->mysqlFetchArray( $res );
243 wfRestoreWarnings();
244
245 $errno = $this->lastErrno();
246 // Unfortunately, mysql_fetch_array does not reset the last errno.
247 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
248 // these are the only errors mysql_fetch_array can cause.
249 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
250 if ( $errno == 2000 || $errno == 2013 ) {
251 throw new DBUnexpectedError(
252 $this,
253 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
254 );
255 }
256
257 return $row;
258 }
259
260 /**
261 * Fetch a result row as an associative and numeric array
262 *
263 * @param $res Raw result
264 * @return array
265 */
266 abstract protected function mysqlFetchArray( $res );
267
268 /**
269 * @throws DBUnexpectedError
270 * @param $res ResultWrapper
271 * @return int
272 */
273 function numRows( $res ) {
274 if ( $res instanceof ResultWrapper ) {
275 $res = $res->result;
276 }
277 wfSuppressWarnings();
278 $n = $this->mysqlNumRows( $res );
279 wfRestoreWarnings();
280
281 // Unfortunately, mysql_num_rows does not reset the last errno.
282 // We are not checking for any errors here, since
283 // these are no errors mysql_num_rows can cause.
284 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
285 // See https://bugzilla.wikimedia.org/42430
286 return $n;
287 }
288
289 /**
290 * Get number of rows in result
291 *
292 * @param $res Raw result
293 * @return int
294 */
295 abstract protected function mysqlNumRows( $res );
296
297 /**
298 * @param $res ResultWrapper
299 * @return int
300 */
301 function numFields( $res ) {
302 if ( $res instanceof ResultWrapper ) {
303 $res = $res->result;
304 }
305
306 return $this->mysqlNumFields( $res );
307 }
308
309 /**
310 * Get number of fields in result
311 *
312 * @param $res Raw result
313 * @return int
314 */
315 abstract protected function mysqlNumFields( $res );
316
317 /**
318 * @param $res ResultWrapper
319 * @param $n int
320 * @return string
321 */
322 function fieldName( $res, $n ) {
323 if ( $res instanceof ResultWrapper ) {
324 $res = $res->result;
325 }
326
327 return $this->mysqlFieldName( $res, $n );
328 }
329
330 /**
331 * Get the name of the specified field in a result
332 *
333 * @param $res Raw result
334 * @param $n int
335 * @return string
336 */
337 abstract protected function mysqlFieldName( $res, $n );
338
339 /**
340 * mysql_field_type() wrapper
341 * @param $res
342 * @param $n int
343 * @return string
344 */
345 public function fieldType( $res, $n ) {
346 if ( $res instanceof ResultWrapper ) {
347 $res = $res->result;
348 }
349
350 return $this->mysqlFieldType( $res, $n );
351 }
352
353 /**
354 * Get the type of the specified field in a result
355 *
356 * @param $res Raw result
357 * @param $n int
358 * @return string
359 */
360 abstract protected function mysqlFieldType( $res, $n );
361
362 /**
363 * @param $res ResultWrapper
364 * @param $row
365 * @return bool
366 */
367 function dataSeek( $res, $row ) {
368 if ( $res instanceof ResultWrapper ) {
369 $res = $res->result;
370 }
371
372 return $this->mysqlDataSeek( $res, $row );
373 }
374
375 /**
376 * Move internal result pointer
377 *
378 * @param $res Raw result
379 * @param $row int
380 * @return bool
381 */
382 abstract protected function mysqlDataSeek( $res, $row );
383
384 /**
385 * @return string
386 */
387 function lastError() {
388 if ( $this->mConn ) {
389 # Even if it's non-zero, it can still be invalid
390 wfSuppressWarnings();
391 $error = $this->mysqlError( $this->mConn );
392 if ( !$error ) {
393 $error = $this->mysqlError();
394 }
395 wfRestoreWarnings();
396 } else {
397 $error = $this->mysqlError();
398 }
399 if ( $error ) {
400 $error .= ' (' . $this->mServer . ')';
401 }
402
403 return $error;
404 }
405
406 /**
407 * Returns the text of the error message from previous MySQL operation
408 *
409 * @param $conn Raw connection
410 * @return string
411 */
412 abstract protected function mysqlError( $conn = null );
413
414 /**
415 * @param $table string
416 * @param $uniqueIndexes
417 * @param $rows array
418 * @param $fname string
419 * @return ResultWrapper
420 */
421 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
422 return $this->nativeReplace( $table, $rows, $fname );
423 }
424
425 /**
426 * Estimate rows in dataset
427 * Returns estimated count, based on EXPLAIN output
428 * Takes same arguments as Database::select()
429 *
430 * @param $table string|array
431 * @param $vars string|array
432 * @param $conds string|array
433 * @param $fname string
434 * @param $options string|array
435 * @return int
436 */
437 public function estimateRowCount( $table, $vars = '*', $conds = '',
438 $fname = __METHOD__, $options = array()
439 ) {
440 $options['EXPLAIN'] = true;
441 $res = $this->select( $table, $vars, $conds, $fname, $options );
442 if ( $res === false ) {
443 return false;
444 }
445 if ( !$this->numRows( $res ) ) {
446 return 0;
447 }
448
449 $rows = 1;
450 foreach ( $res as $plan ) {
451 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
452 }
453
454 return $rows;
455 }
456
457 /**
458 * @param $table string
459 * @param $field string
460 * @return bool|MySQLField
461 */
462 function fieldInfo( $table, $field ) {
463 $table = $this->tableName( $table );
464 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
465 if ( !$res ) {
466 return false;
467 }
468 $n = $this->mysqlNumFields( $res->result );
469 for ( $i = 0; $i < $n; $i++ ) {
470 $meta = $this->mysqlFetchField( $res->result, $i );
471 if ( $field == $meta->name ) {
472 return new MySQLField( $meta );
473 }
474 }
475
476 return false;
477 }
478
479 /**
480 * Get column information from a result
481 *
482 * @param $res Raw result
483 * @param $n int
484 * @return stdClass
485 */
486 abstract protected function mysqlFetchField( $res, $n );
487
488 /**
489 * Get information about an index into an object
490 * Returns false if the index does not exist
491 *
492 * @param $table string
493 * @param $index string
494 * @param $fname string
495 * @return bool|array|null False or null on failure
496 */
497 function indexInfo( $table, $index, $fname = __METHOD__ ) {
498 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
499 # SHOW INDEX should work for 3.x and up:
500 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
501 $table = $this->tableName( $table );
502 $index = $this->indexName( $index );
503
504 $sql = 'SHOW INDEX FROM ' . $table;
505 $res = $this->query( $sql, $fname );
506
507 if ( !$res ) {
508 return null;
509 }
510
511 $result = array();
512
513 foreach ( $res as $row ) {
514 if ( $row->Key_name == $index ) {
515 $result[] = $row;
516 }
517 }
518
519 return empty( $result ) ? false : $result;
520 }
521
522 /**
523 * @param $s string
524 *
525 * @return string
526 */
527 function strencode( $s ) {
528 $sQuoted = $this->mysqlRealEscapeString( $s );
529
530 if ( $sQuoted === false ) {
531 $this->ping();
532 $sQuoted = $this->mysqlRealEscapeString( $s );
533 }
534
535 return $sQuoted;
536 }
537
538 /**
539 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
540 *
541 * @param $s string
542 *
543 * @return string
544 */
545 public function addIdentifierQuotes( $s ) {
546 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
547 // Remove NUL bytes and escape backticks by doubling
548 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
549 }
550
551 /**
552 * @param $name string
553 * @return bool
554 */
555 public function isQuotedIdentifier( $name ) {
556 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
557 }
558
559 /**
560 * @return bool
561 */
562 function ping() {
563 $ping = $this->mysqlPing();
564 if ( $ping ) {
565 return true;
566 }
567
568 $this->closeConnection();
569 $this->mOpened = false;
570 $this->mConn = false;
571 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
572
573 return true;
574 }
575
576 /**
577 * Ping a server connection or reconnect if there is no connection
578 *
579 * @return bool
580 */
581 abstract protected function mysqlPing();
582
583 /**
584 * Returns slave lag.
585 *
586 * This will do a SHOW SLAVE STATUS
587 *
588 * @return int
589 */
590 function getLag() {
591 if ( !is_null( $this->mFakeSlaveLag ) ) {
592 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
593
594 return $this->mFakeSlaveLag;
595 }
596
597 return $this->getLagFromSlaveStatus();
598 }
599
600 /**
601 * @return bool|int
602 */
603 function getLagFromSlaveStatus() {
604 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
605 if ( !$res ) {
606 return false;
607 }
608 $row = $res->fetchObject();
609 if ( !$row ) {
610 return false;
611 }
612 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
613 return false;
614 } else {
615 return intval( $row->Seconds_Behind_Master );
616 }
617 }
618
619 /**
620 * @deprecated in 1.19, use getLagFromSlaveStatus
621 *
622 * @return bool|int
623 */
624 function getLagFromProcesslist() {
625 wfDeprecated( __METHOD__, '1.19' );
626 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
627 if ( !$res ) {
628 return false;
629 }
630 # Find slave SQL thread
631 foreach ( $res as $row ) {
632 /* This should work for most situations - when default db
633 * for thread is not specified, it had no events executed,
634 * and therefore it doesn't know yet how lagged it is.
635 *
636 * Relay log I/O thread does not select databases.
637 */
638 if ( $row->User == 'system user' &&
639 $row->State != 'Waiting for master to send event' &&
640 $row->State != 'Connecting to master' &&
641 $row->State != 'Queueing master event to the relay log' &&
642 $row->State != 'Waiting for master update' &&
643 $row->State != 'Requesting binlog dump' &&
644 $row->State != 'Waiting to reconnect after a failed master event read' &&
645 $row->State != 'Reconnecting after a failed master event read' &&
646 $row->State != 'Registering slave on master'
647 ) {
648 # This is it, return the time (except -ve)
649 if ( $row->Time > 0x7fffffff ) {
650 return false;
651 } else {
652 return $row->Time;
653 }
654 }
655 }
656
657 return false;
658 }
659
660 /**
661 * Wait for the slave to catch up to a given master position.
662 * @TODO: return values for this and base class are rubbish
663 *
664 * @param $pos DBMasterPos object
665 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
666 * @return bool|string
667 */
668 function masterPosWait( DBMasterPos $pos, $timeout ) {
669 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
670 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
671 }
672
673 wfProfileIn( __METHOD__ );
674 # Commit any open transactions
675 $this->commit( __METHOD__, 'flush' );
676
677 if ( !is_null( $this->mFakeSlaveLag ) ) {
678 $status = parent::masterPosWait( $pos, $timeout );
679 wfProfileOut( __METHOD__ );
680
681 return $status;
682 }
683
684 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
685 $encFile = $this->addQuotes( $pos->file );
686 $encPos = intval( $pos->pos );
687 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
688 $res = $this->doQuery( $sql );
689
690 $status = false;
691 if ( $res && $row = $this->fetchRow( $res ) ) {
692 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
693 if ( ctype_digit( $status ) ) { // success
694 $this->lastKnownSlavePos = $pos;
695 }
696 }
697
698 wfProfileOut( __METHOD__ );
699
700 return $status;
701 }
702
703 /**
704 * Get the position of the master from SHOW SLAVE STATUS
705 *
706 * @return MySQLMasterPos|bool
707 */
708 function getSlavePos() {
709 if ( !is_null( $this->mFakeSlaveLag ) ) {
710 return parent::getSlavePos();
711 }
712
713 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
714 $row = $this->fetchObject( $res );
715
716 if ( $row ) {
717 $pos = isset( $row->Exec_master_log_pos )
718 ? $row->Exec_master_log_pos
719 : $row->Exec_Master_Log_Pos;
720
721 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
722 } else {
723 return false;
724 }
725 }
726
727 /**
728 * Get the position of the master from SHOW MASTER STATUS
729 *
730 * @return MySQLMasterPos|bool
731 */
732 function getMasterPos() {
733 if ( $this->mFakeMaster ) {
734 return parent::getMasterPos();
735 }
736
737 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
738 $row = $this->fetchObject( $res );
739
740 if ( $row ) {
741 return new MySQLMasterPos( $row->File, $row->Position );
742 } else {
743 return false;
744 }
745 }
746
747 /**
748 * @param $index
749 * @return string
750 */
751 function useIndexClause( $index ) {
752 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
753 }
754
755 /**
756 * @return string
757 */
758 function lowPriorityOption() {
759 return 'LOW_PRIORITY';
760 }
761
762 /**
763 * @return string
764 */
765 public function getSoftwareLink() {
766 return '[http://www.mysql.com/ MySQL]';
767 }
768
769 /**
770 * @param $options array
771 */
772 public function setSessionOptions( array $options ) {
773 if ( isset( $options['connTimeout'] ) ) {
774 $timeout = (int)$options['connTimeout'];
775 $this->query( "SET net_read_timeout=$timeout" );
776 $this->query( "SET net_write_timeout=$timeout" );
777 }
778 }
779
780 public function streamStatementEnd( &$sql, &$newLine ) {
781 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
782 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
783 $this->delimiter = $m[1];
784 $newLine = '';
785 }
786
787 return parent::streamStatementEnd( $sql, $newLine );
788 }
789
790 /**
791 * Check to see if a named lock is available. This is non-blocking.
792 *
793 * @param string $lockName name of lock to poll
794 * @param string $method name of method calling us
795 * @return Boolean
796 * @since 1.20
797 */
798 public function lockIsFree( $lockName, $method ) {
799 $lockName = $this->addQuotes( $lockName );
800 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
801 $row = $this->fetchObject( $result );
802
803 return ( $row->lockstatus == 1 );
804 }
805
806 /**
807 * @param $lockName string
808 * @param $method string
809 * @param $timeout int
810 * @return bool
811 */
812 public function lock( $lockName, $method, $timeout = 5 ) {
813 $lockName = $this->addQuotes( $lockName );
814 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
815 $row = $this->fetchObject( $result );
816
817 if ( $row->lockstatus == 1 ) {
818 return true;
819 } else {
820 wfDebug( __METHOD__ . " failed to acquire lock\n" );
821
822 return false;
823 }
824 }
825
826 /**
827 * FROM MYSQL DOCS:
828 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
829 * @param $lockName string
830 * @param $method string
831 * @return bool
832 */
833 public function unlock( $lockName, $method ) {
834 $lockName = $this->addQuotes( $lockName );
835 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
836 $row = $this->fetchObject( $result );
837
838 return ( $row->lockstatus == 1 );
839 }
840
841 /**
842 * @param $read array
843 * @param $write array
844 * @param $method string
845 * @param $lowPriority bool
846 * @return bool
847 */
848 public function lockTables( $read, $write, $method, $lowPriority = true ) {
849 $items = array();
850
851 foreach ( $write as $table ) {
852 $tbl = $this->tableName( $table ) .
853 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
854 ' WRITE';
855 $items[] = $tbl;
856 }
857 foreach ( $read as $table ) {
858 $items[] = $this->tableName( $table ) . ' READ';
859 }
860 $sql = "LOCK TABLES " . implode( ',', $items );
861 $this->query( $sql, $method );
862
863 return true;
864 }
865
866 /**
867 * @param $method string
868 * @return bool
869 */
870 public function unlockTables( $method ) {
871 $this->query( "UNLOCK TABLES", $method );
872
873 return true;
874 }
875
876 /**
877 * Get search engine class. All subclasses of this
878 * need to implement this if they wish to use searching.
879 *
880 * @return String
881 */
882 public function getSearchEngine() {
883 return 'SearchMySQL';
884 }
885
886 /**
887 * @param bool $value
888 * @return mixed
889 */
890 public function setBigSelects( $value = true ) {
891 if ( $value === 'default' ) {
892 if ( $this->mDefaultBigSelects === null ) {
893 # Function hasn't been called before so it must already be set to the default
894 return;
895 } else {
896 $value = $this->mDefaultBigSelects;
897 }
898 } elseif ( $this->mDefaultBigSelects === null ) {
899 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
900 }
901 $encValue = $value ? '1' : '0';
902 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
903 }
904
905 /**
906 * DELETE where the condition is a join. MySql uses multi-table deletes.
907 * @param $delTable string
908 * @param $joinTable string
909 * @param $delVar string
910 * @param $joinVar string
911 * @param $conds array|string
912 * @param bool|string $fname bool
913 * @throws DBUnexpectedError
914 * @return bool|ResultWrapper
915 */
916 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
917 if ( !$conds ) {
918 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
919 }
920
921 $delTable = $this->tableName( $delTable );
922 $joinTable = $this->tableName( $joinTable );
923 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
924
925 if ( $conds != '*' ) {
926 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
927 }
928
929 return $this->query( $sql, $fname );
930 }
931
932 /**
933 * @param string $table
934 * @param array $rows
935 * @param array $uniqueIndexes
936 * @param array $set
937 * @param string $fname
938 * @param array $options
939 * @return bool
940 */
941 public function upsert(
942 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
943 ) {
944 if ( !count( $rows ) ) {
945 return true; // nothing to do
946 }
947 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
948
949 $table = $this->tableName( $table );
950 $columns = array_keys( $rows[0] );
951
952 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
953 $rowTuples = array();
954 foreach ( $rows as $row ) {
955 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
956 }
957 $sql .= implode( ',', $rowTuples );
958 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
959
960 return (bool)$this->query( $sql, $fname );
961 }
962
963 /**
964 * Determines how long the server has been up
965 *
966 * @return int
967 */
968 function getServerUptime() {
969 $vars = $this->getMysqlStatus( 'Uptime' );
970
971 return (int)$vars['Uptime'];
972 }
973
974 /**
975 * Determines if the last failure was due to a deadlock
976 *
977 * @return bool
978 */
979 function wasDeadlock() {
980 return $this->lastErrno() == 1213;
981 }
982
983 /**
984 * Determines if the last failure was due to a lock timeout
985 *
986 * @return bool
987 */
988 function wasLockTimeout() {
989 return $this->lastErrno() == 1205;
990 }
991
992 /**
993 * Determines if the last query error was something that should be dealt
994 * with by pinging the connection and reissuing the query
995 *
996 * @return bool
997 */
998 function wasErrorReissuable() {
999 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1000 }
1001
1002 /**
1003 * Determines if the last failure was due to the database being read-only.
1004 *
1005 * @return bool
1006 */
1007 function wasReadOnlyError() {
1008 return $this->lastErrno() == 1223 ||
1009 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1010 }
1011
1012 /**
1013 * @param $oldName
1014 * @param $newName
1015 * @param $temporary bool
1016 * @param $fname string
1017 */
1018 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1019 $tmp = $temporary ? 'TEMPORARY ' : '';
1020 $newName = $this->addIdentifierQuotes( $newName );
1021 $oldName = $this->addIdentifierQuotes( $oldName );
1022 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1023 $this->query( $query, $fname );
1024 }
1025
1026 /**
1027 * List all tables on the database
1028 *
1029 * @param string $prefix Only show tables with this prefix, e.g. mw_
1030 * @param string $fname calling function name
1031 * @return array
1032 */
1033 function listTables( $prefix = null, $fname = __METHOD__ ) {
1034 $result = $this->query( "SHOW TABLES", $fname );
1035
1036 $endArray = array();
1037
1038 foreach ( $result as $table ) {
1039 $vars = get_object_vars( $table );
1040 $table = array_pop( $vars );
1041
1042 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1043 $endArray[] = $table;
1044 }
1045 }
1046
1047 return $endArray;
1048 }
1049
1050 /**
1051 * @param $tableName
1052 * @param $fName string
1053 * @return bool|ResultWrapper
1054 */
1055 public function dropTable( $tableName, $fName = __METHOD__ ) {
1056 if ( !$this->tableExists( $tableName, $fName ) ) {
1057 return false;
1058 }
1059
1060 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1061 }
1062
1063 /**
1064 * @return array
1065 */
1066 protected function getDefaultSchemaVars() {
1067 $vars = parent::getDefaultSchemaVars();
1068 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1069 $vars['wgDBTableOptions'] = str_replace(
1070 'CHARSET=mysql4',
1071 'CHARSET=binary',
1072 $vars['wgDBTableOptions']
1073 );
1074
1075 return $vars;
1076 }
1077
1078 /**
1079 * Get status information from SHOW STATUS in an associative array
1080 *
1081 * @param $which string
1082 * @return array
1083 */
1084 function getMysqlStatus( $which = "%" ) {
1085 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1086 $status = array();
1087
1088 foreach ( $res as $row ) {
1089 $status[$row->Variable_name] = $row->Value;
1090 }
1091
1092 return $status;
1093 }
1094
1095 /**
1096 * Lists VIEWs in the database
1097 *
1098 * @param string $prefix Only show VIEWs with this prefix, eg.
1099 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1100 * @param string $fname Name of calling function
1101 * @return array
1102 * @since 1.22
1103 */
1104 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1105
1106 if ( !isset( $this->allViews ) ) {
1107
1108 // The name of the column containing the name of the VIEW
1109 $propertyName = 'Tables_in_' . $this->mDBname;
1110
1111 // Query for the VIEWS
1112 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1113 $this->allViews = array();
1114 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1115 array_push( $this->allViews, $row[$propertyName] );
1116 }
1117 }
1118
1119 if ( is_null( $prefix ) || $prefix === '' ) {
1120 return $this->allViews;
1121 }
1122
1123 $filteredViews = array();
1124 foreach ( $this->allViews as $viewName ) {
1125 // Does the name of this VIEW start with the table-prefix?
1126 if ( strpos( $viewName, $prefix ) === 0 ) {
1127 array_push( $filteredViews, $viewName );
1128 }
1129 }
1130
1131 return $filteredViews;
1132 }
1133
1134 /**
1135 * Differentiates between a TABLE and a VIEW.
1136 *
1137 * @param $name string: Name of the TABLE/VIEW to test
1138 * @return bool
1139 * @since 1.22
1140 */
1141 public function isView( $name, $prefix = null ) {
1142 return in_array( $name, $this->listViews( $prefix ) );
1143 }
1144 }
1145
1146 /**
1147 * Utility class.
1148 * @ingroup Database
1149 */
1150 class MySQLField implements Field {
1151 private $name, $tablename, $default, $max_length, $nullable,
1152 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1153
1154 function __construct( $info ) {
1155 $this->name = $info->name;
1156 $this->tablename = $info->table;
1157 $this->default = $info->def;
1158 $this->max_length = $info->max_length;
1159 $this->nullable = !$info->not_null;
1160 $this->is_pk = $info->primary_key;
1161 $this->is_unique = $info->unique_key;
1162 $this->is_multiple = $info->multiple_key;
1163 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1164 $this->type = $info->type;
1165 $this->binary = isset( $info->binary ) ? $info->binary : false;
1166 }
1167
1168 /**
1169 * @return string
1170 */
1171 function name() {
1172 return $this->name;
1173 }
1174
1175 /**
1176 * @return string
1177 */
1178 function tableName() {
1179 return $this->tableName;
1180 }
1181
1182 /**
1183 * @return string
1184 */
1185 function type() {
1186 return $this->type;
1187 }
1188
1189 /**
1190 * @return bool
1191 */
1192 function isNullable() {
1193 return $this->nullable;
1194 }
1195
1196 function defaultValue() {
1197 return $this->default;
1198 }
1199
1200 /**
1201 * @return bool
1202 */
1203 function isKey() {
1204 return $this->is_key;
1205 }
1206
1207 /**
1208 * @return bool
1209 */
1210 function isMultipleKey() {
1211 return $this->is_multiple;
1212 }
1213
1214 function isBinary() {
1215 return $this->binary;
1216 }
1217 }
1218
1219 class MySQLMasterPos implements DBMasterPos {
1220 var $file, $pos;
1221
1222 function __construct( $file, $pos ) {
1223 $this->file = $file;
1224 $this->pos = $pos;
1225 }
1226
1227 function __toString() {
1228 // e.g db1034-bin.000976/843431247
1229 return "{$this->file}/{$this->pos}";
1230 }
1231
1232 /**
1233 * @return array|false (int, int)
1234 */
1235 protected function getCoordinates() {
1236 $m = array();
1237 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1238 return array( (int)$m[1], (int)$m[2] );
1239 }
1240
1241 return false;
1242 }
1243
1244 function hasReached( MySQLMasterPos $pos ) {
1245 $thisPos = $this->getCoordinates();
1246 $thatPos = $pos->getCoordinates();
1247
1248 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1249 }
1250 }