Merge "mediawiki.searchSuggest: Blacklist Konqueror < 4.11"
[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 string $server
45 * @param string $user
46 * @param string $password
47 * @param string $dbName
48 * @throws Exception|DBConnectionError
49 * @return bool
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 string $realServer
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 ResultWrapper|resource $res
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 resource $res Raw result
192 * @return bool
193 */
194 abstract protected function mysqlFreeResult( $res );
195
196 /**
197 * @param ResultWrapper|resource $res
198 * @return stdClass|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 resource $res Raw result
228 * @return stdClass
229 */
230 abstract protected function mysqlFetchObject( $res );
231
232 /**
233 * @param ResultWrapper|resource $res
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 resource $res Raw result
264 * @return array
265 */
266 abstract protected function mysqlFetchArray( $res );
267
268 /**
269 * @throws DBUnexpectedError
270 * @param ResultWrapper|resource $res
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 resource $res Raw result
293 * @return int
294 */
295 abstract protected function mysqlNumRows( $res );
296
297 /**
298 * @param ResultWrapper|resource $res
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 resource $res Raw result
313 * @return int
314 */
315 abstract protected function mysqlNumFields( $res );
316
317 /**
318 * @param ResultWrapper|resource $res
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 ResultWrapper|resource $res
334 * @param $n int
335 * @return string
336 */
337 abstract protected function mysqlFieldName( $res, $n );
338
339 /**
340 * mysql_field_type() wrapper
341 * @param ResultWrapper|resource $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 ResultWrapper|resource $res
357 * @param int $n
358 * @return string
359 */
360 abstract protected function mysqlFieldType( $res, $n );
361
362 /**
363 * @param ResultWrapper|resource $res
364 * @param int $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 ResultWrapper|resource $res
379 * @param int $row
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 resource $conn Raw connection
410 * @return string
411 */
412 abstract protected function mysqlError( $conn = null );
413
414 /**
415 * @param string $table
416 * @param array $uniqueIndexes
417 * @param array $rows
418 * @param string $fname
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 string|array $table
431 * @param string|array $vars
432 * @param string|array $conds
433 * @param string $fname
434 * @param string|array $options
435 * @return bool|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 string $table
459 * @param string $field
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 resource $res Raw result
483 * @param int $n
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 string $table
493 * @param string $index
494 * @param string $fname
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 string $s
524 * @return string
525 */
526 function strencode( $s ) {
527 $sQuoted = $this->mysqlRealEscapeString( $s );
528
529 if ( $sQuoted === false ) {
530 $this->ping();
531 $sQuoted = $this->mysqlRealEscapeString( $s );
532 }
533
534 return $sQuoted;
535 }
536
537 /**
538 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
539 *
540 * @param string $s
541 * @return string
542 */
543 public function addIdentifierQuotes( $s ) {
544 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
545 // Remove NUL bytes and escape backticks by doubling
546 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
547 }
548
549 /**
550 * @param string $name
551 * @return bool
552 */
553 public function isQuotedIdentifier( $name ) {
554 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
555 }
556
557 /**
558 * @return bool
559 */
560 function ping() {
561 $ping = $this->mysqlPing();
562 if ( $ping ) {
563 return true;
564 }
565
566 $this->closeConnection();
567 $this->mOpened = false;
568 $this->mConn = false;
569 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
570
571 return true;
572 }
573
574 /**
575 * Ping a server connection or reconnect if there is no connection
576 *
577 * @return bool
578 */
579 abstract protected function mysqlPing();
580
581 /**
582 * Returns slave lag.
583 *
584 * This will do a SHOW SLAVE STATUS
585 *
586 * @return int
587 */
588 function getLag() {
589 if ( !is_null( $this->mFakeSlaveLag ) ) {
590 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
591
592 return $this->mFakeSlaveLag;
593 }
594
595 return $this->getLagFromSlaveStatus();
596 }
597
598 /**
599 * @return bool|int
600 */
601 function getLagFromSlaveStatus() {
602 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
603 if ( !$res ) {
604 return false;
605 }
606 $row = $res->fetchObject();
607 if ( !$row ) {
608 return false;
609 }
610 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
611 return false;
612 } else {
613 return intval( $row->Seconds_Behind_Master );
614 }
615 }
616
617 /**
618 * @deprecated in 1.19, use getLagFromSlaveStatus
619 *
620 * @return bool|int
621 */
622 function getLagFromProcesslist() {
623 wfDeprecated( __METHOD__, '1.19' );
624 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
625 if ( !$res ) {
626 return false;
627 }
628 # Find slave SQL thread
629 foreach ( $res as $row ) {
630 /* This should work for most situations - when default db
631 * for thread is not specified, it had no events executed,
632 * and therefore it doesn't know yet how lagged it is.
633 *
634 * Relay log I/O thread does not select databases.
635 */
636 if ( $row->User == 'system user' &&
637 $row->State != 'Waiting for master to send event' &&
638 $row->State != 'Connecting to master' &&
639 $row->State != 'Queueing master event to the relay log' &&
640 $row->State != 'Waiting for master update' &&
641 $row->State != 'Requesting binlog dump' &&
642 $row->State != 'Waiting to reconnect after a failed master event read' &&
643 $row->State != 'Reconnecting after a failed master event read' &&
644 $row->State != 'Registering slave on master'
645 ) {
646 # This is it, return the time (except -ve)
647 if ( $row->Time > 0x7fffffff ) {
648 return false;
649 } else {
650 return $row->Time;
651 }
652 }
653 }
654
655 return false;
656 }
657
658 /**
659 * Wait for the slave to catch up to a given master position.
660 * @todo Return values for this and base class are rubbish
661 *
662 * @param DBMasterPos|MySQLMasterPos $pos
663 * @param int $timeout The maximum number of seconds to wait for synchronisation
664 * @return bool|string
665 */
666 function masterPosWait( DBMasterPos $pos, $timeout ) {
667 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
668 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
669 }
670
671 wfProfileIn( __METHOD__ );
672 # Commit any open transactions
673 $this->commit( __METHOD__, 'flush' );
674
675 if ( !is_null( $this->mFakeSlaveLag ) ) {
676 $status = parent::masterPosWait( $pos, $timeout );
677 wfProfileOut( __METHOD__ );
678
679 return $status;
680 }
681
682 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
683 $encFile = $this->addQuotes( $pos->file );
684 $encPos = intval( $pos->getMasterPos() );
685 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
686 $res = $this->doQuery( $sql );
687
688 $status = false;
689 if ( $res && $row = $this->fetchRow( $res ) ) {
690 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
691 if ( ctype_digit( $status ) ) { // success
692 $this->lastKnownSlavePos = $pos;
693 }
694 }
695
696 wfProfileOut( __METHOD__ );
697
698 return $status;
699 }
700
701 /**
702 * Get the position of the master from SHOW SLAVE STATUS
703 *
704 * @return MySQLMasterPos|bool
705 */
706 function getSlavePos() {
707 if ( !is_null( $this->mFakeSlaveLag ) ) {
708 return parent::getSlavePos();
709 }
710
711 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
712 $row = $this->fetchObject( $res );
713
714 if ( $row ) {
715 $pos = isset( $row->Exec_master_log_pos )
716 ? $row->Exec_master_log_pos
717 : $row->Exec_Master_Log_Pos;
718
719 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
720 } else {
721 return false;
722 }
723 }
724
725 /**
726 * Get the position of the master from SHOW MASTER STATUS
727 *
728 * @return MySQLMasterPos|bool
729 */
730 function getMasterPos() {
731 if ( $this->mFakeMaster ) {
732 return parent::getMasterPos();
733 }
734
735 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
736 $row = $this->fetchObject( $res );
737
738 if ( $row ) {
739 return new MySQLMasterPos( $row->File, $row->Position );
740 } else {
741 return false;
742 }
743 }
744
745 /**
746 * @param string $index
747 * @return string
748 */
749 function useIndexClause( $index ) {
750 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
751 }
752
753 /**
754 * @return string
755 */
756 function lowPriorityOption() {
757 return 'LOW_PRIORITY';
758 }
759
760 /**
761 * @return string
762 */
763 public function getSoftwareLink() {
764 $version = $this->getServerVersion();
765 if ( strpos( $version, 'MariaDB' ) !== false ) {
766 return '[{{int:version-db-mariadb-url}} MariaDB]';
767 } elseif ( strpos( $version, 'percona' ) !== false ) {
768 return '[{{int:version-db-percona-url}} Percona Server]';
769 } else {
770 return '[{{int:version-db-mysql-url}} MySQL]';
771 }
772 }
773
774 /**
775 * @param array $options
776 */
777 public function setSessionOptions( array $options ) {
778 if ( isset( $options['connTimeout'] ) ) {
779 $timeout = (int)$options['connTimeout'];
780 $this->query( "SET net_read_timeout=$timeout" );
781 $this->query( "SET net_write_timeout=$timeout" );
782 }
783 }
784
785 /**
786 * @param string $sql
787 * @param string $newLine
788 * @return bool
789 */
790 public function streamStatementEnd( &$sql, &$newLine ) {
791 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
792 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
793 $this->delimiter = $m[1];
794 $newLine = '';
795 }
796
797 return parent::streamStatementEnd( $sql, $newLine );
798 }
799
800 /**
801 * Check to see if a named lock is available. This is non-blocking.
802 *
803 * @param string $lockName name of lock to poll
804 * @param string $method name of method calling us
805 * @return bool
806 * @since 1.20
807 */
808 public function lockIsFree( $lockName, $method ) {
809 $lockName = $this->addQuotes( $lockName );
810 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
811 $row = $this->fetchObject( $result );
812
813 return ( $row->lockstatus == 1 );
814 }
815
816 /**
817 * @param string $lockName
818 * @param string $method
819 * @param int $timeout
820 * @return bool
821 */
822 public function lock( $lockName, $method, $timeout = 5 ) {
823 $lockName = $this->addQuotes( $lockName );
824 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
825 $row = $this->fetchObject( $result );
826
827 if ( $row->lockstatus == 1 ) {
828 return true;
829 } else {
830 wfDebug( __METHOD__ . " failed to acquire lock\n" );
831
832 return false;
833 }
834 }
835
836 /**
837 * FROM MYSQL DOCS:
838 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
839 * @param string $lockName
840 * @param string $method
841 * @return bool
842 */
843 public function unlock( $lockName, $method ) {
844 $lockName = $this->addQuotes( $lockName );
845 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
846 $row = $this->fetchObject( $result );
847
848 return ( $row->lockstatus == 1 );
849 }
850
851 /**
852 * @param array $read
853 * @param array $write
854 * @param string $method
855 * @param bool $lowPriority
856 * @return bool
857 */
858 public function lockTables( $read, $write, $method, $lowPriority = true ) {
859 $items = array();
860
861 foreach ( $write as $table ) {
862 $tbl = $this->tableName( $table ) .
863 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
864 ' WRITE';
865 $items[] = $tbl;
866 }
867 foreach ( $read as $table ) {
868 $items[] = $this->tableName( $table ) . ' READ';
869 }
870 $sql = "LOCK TABLES " . implode( ',', $items );
871 $this->query( $sql, $method );
872
873 return true;
874 }
875
876 /**
877 * @param string $method
878 * @return bool
879 */
880 public function unlockTables( $method ) {
881 $this->query( "UNLOCK TABLES", $method );
882
883 return true;
884 }
885
886 /**
887 * Get search engine class. All subclasses of this
888 * need to implement this if they wish to use searching.
889 *
890 * @return string
891 */
892 public function getSearchEngine() {
893 return 'SearchMySQL';
894 }
895
896 /**
897 * @param bool $value
898 * @return mixed null|bool|ResultWrapper
899 */
900 public function setBigSelects( $value = true ) {
901 if ( $value === 'default' ) {
902 if ( $this->mDefaultBigSelects === null ) {
903 # Function hasn't been called before so it must already be set to the default
904 return;
905 } else {
906 $value = $this->mDefaultBigSelects;
907 }
908 } elseif ( $this->mDefaultBigSelects === null ) {
909 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
910 }
911 $encValue = $value ? '1' : '0';
912 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
913 }
914
915 /**
916 * DELETE where the condition is a join. MySql uses multi-table deletes.
917 * @param $delTable string
918 * @param $joinTable string
919 * @param $delVar string
920 * @param $joinVar string
921 * @param $conds array|string
922 * @param bool|string $fname bool
923 * @throws DBUnexpectedError
924 * @return bool|ResultWrapper
925 */
926 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
927 if ( !$conds ) {
928 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
929 }
930
931 $delTable = $this->tableName( $delTable );
932 $joinTable = $this->tableName( $joinTable );
933 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
934
935 if ( $conds != '*' ) {
936 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
937 }
938
939 return $this->query( $sql, $fname );
940 }
941
942 /**
943 * @param string $table
944 * @param array $rows
945 * @param array $uniqueIndexes
946 * @param array $set
947 * @param string $fname
948 * @return bool
949 */
950 public function upsert( $table, array $rows, array $uniqueIndexes,
951 array $set, $fname = __METHOD__
952 ) {
953 if ( !count( $rows ) ) {
954 return true; // nothing to do
955 }
956 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
957
958 $table = $this->tableName( $table );
959 $columns = array_keys( $rows[0] );
960
961 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
962 $rowTuples = array();
963 foreach ( $rows as $row ) {
964 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
965 }
966 $sql .= implode( ',', $rowTuples );
967 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
968
969 return (bool)$this->query( $sql, $fname );
970 }
971
972 /**
973 * Determines how long the server has been up
974 *
975 * @return int
976 */
977 function getServerUptime() {
978 $vars = $this->getMysqlStatus( 'Uptime' );
979
980 return (int)$vars['Uptime'];
981 }
982
983 /**
984 * Determines if the last failure was due to a deadlock
985 *
986 * @return bool
987 */
988 function wasDeadlock() {
989 return $this->lastErrno() == 1213;
990 }
991
992 /**
993 * Determines if the last failure was due to a lock timeout
994 *
995 * @return bool
996 */
997 function wasLockTimeout() {
998 return $this->lastErrno() == 1205;
999 }
1000
1001 /**
1002 * Determines if the last query error was something that should be dealt
1003 * with by pinging the connection and reissuing the query
1004 *
1005 * @return bool
1006 */
1007 function wasErrorReissuable() {
1008 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1009 }
1010
1011 /**
1012 * Determines if the last failure was due to the database being read-only.
1013 *
1014 * @return bool
1015 */
1016 function wasReadOnlyError() {
1017 return $this->lastErrno() == 1223 ||
1018 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1019 }
1020
1021 /**
1022 * @param string $oldName
1023 * @param string $newName
1024 * @param bool $temporary
1025 * @param string $fname
1026 * @return bool
1027 */
1028 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1029 $tmp = $temporary ? 'TEMPORARY ' : '';
1030 $newName = $this->addIdentifierQuotes( $newName );
1031 $oldName = $this->addIdentifierQuotes( $oldName );
1032 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1033
1034 return $this->query( $query, $fname );
1035 }
1036
1037 /**
1038 * List all tables on the database
1039 *
1040 * @param string $prefix Only show tables with this prefix, e.g. mw_
1041 * @param string $fname Calling function name
1042 * @return array
1043 */
1044 function listTables( $prefix = null, $fname = __METHOD__ ) {
1045 $result = $this->query( "SHOW TABLES", $fname );
1046
1047 $endArray = array();
1048
1049 foreach ( $result as $table ) {
1050 $vars = get_object_vars( $table );
1051 $table = array_pop( $vars );
1052
1053 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1054 $endArray[] = $table;
1055 }
1056 }
1057
1058 return $endArray;
1059 }
1060
1061 /**
1062 * @param $tableName
1063 * @param $fName string
1064 * @return bool|ResultWrapper
1065 */
1066 public function dropTable( $tableName, $fName = __METHOD__ ) {
1067 if ( !$this->tableExists( $tableName, $fName ) ) {
1068 return false;
1069 }
1070
1071 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1072 }
1073
1074 /**
1075 * @return array
1076 */
1077 protected function getDefaultSchemaVars() {
1078 $vars = parent::getDefaultSchemaVars();
1079 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1080 $vars['wgDBTableOptions'] = str_replace(
1081 'CHARSET=mysql4',
1082 'CHARSET=binary',
1083 $vars['wgDBTableOptions']
1084 );
1085
1086 return $vars;
1087 }
1088
1089 /**
1090 * Get status information from SHOW STATUS in an associative array
1091 *
1092 * @param string $which
1093 * @return array
1094 */
1095 function getMysqlStatus( $which = "%" ) {
1096 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1097 $status = array();
1098
1099 foreach ( $res as $row ) {
1100 $status[$row->Variable_name] = $row->Value;
1101 }
1102
1103 return $status;
1104 }
1105
1106 /**
1107 * Lists VIEWs in the database
1108 *
1109 * @param string $prefix Only show VIEWs with this prefix, eg.
1110 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1111 * @param string $fname Name of calling function
1112 * @return array
1113 * @since 1.22
1114 */
1115 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1116
1117 if ( !isset( $this->allViews ) ) {
1118
1119 // The name of the column containing the name of the VIEW
1120 $propertyName = 'Tables_in_' . $this->mDBname;
1121
1122 // Query for the VIEWS
1123 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1124 $this->allViews = array();
1125 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1126 array_push( $this->allViews, $row[$propertyName] );
1127 }
1128 }
1129
1130 if ( is_null( $prefix ) || $prefix === '' ) {
1131 return $this->allViews;
1132 }
1133
1134 $filteredViews = array();
1135 foreach ( $this->allViews as $viewName ) {
1136 // Does the name of this VIEW start with the table-prefix?
1137 if ( strpos( $viewName, $prefix ) === 0 ) {
1138 array_push( $filteredViews, $viewName );
1139 }
1140 }
1141
1142 return $filteredViews;
1143 }
1144
1145 /**
1146 * Differentiates between a TABLE and a VIEW.
1147 *
1148 * @param string $name Name of the TABLE/VIEW to test
1149 * @param string $prefix
1150 * @return bool
1151 * @since 1.22
1152 */
1153 public function isView( $name, $prefix = null ) {
1154 return in_array( $name, $this->listViews( $prefix ) );
1155 }
1156 }
1157
1158 /**
1159 * Utility class.
1160 * @ingroup Database
1161 */
1162 class MySQLField implements Field {
1163 private $name, $tablename, $default, $max_length, $nullable,
1164 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1165
1166 function __construct( $info ) {
1167 $this->name = $info->name;
1168 $this->tablename = $info->table;
1169 $this->default = $info->def;
1170 $this->max_length = $info->max_length;
1171 $this->nullable = !$info->not_null;
1172 $this->is_pk = $info->primary_key;
1173 $this->is_unique = $info->unique_key;
1174 $this->is_multiple = $info->multiple_key;
1175 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1176 $this->type = $info->type;
1177 $this->binary = isset( $info->binary ) ? $info->binary : false;
1178 }
1179
1180 /**
1181 * @return string
1182 */
1183 function name() {
1184 return $this->name;
1185 }
1186
1187 /**
1188 * @return string
1189 */
1190 function tableName() {
1191 return $this->tableName;
1192 }
1193
1194 /**
1195 * @return string
1196 */
1197 function type() {
1198 return $this->type;
1199 }
1200
1201 /**
1202 * @return bool
1203 */
1204 function isNullable() {
1205 return $this->nullable;
1206 }
1207
1208 function defaultValue() {
1209 return $this->default;
1210 }
1211
1212 /**
1213 * @return bool
1214 */
1215 function isKey() {
1216 return $this->is_key;
1217 }
1218
1219 /**
1220 * @return bool
1221 */
1222 function isMultipleKey() {
1223 return $this->is_multiple;
1224 }
1225
1226 function isBinary() {
1227 return $this->binary;
1228 }
1229 }
1230
1231 class MySQLMasterPos implements DBMasterPos {
1232 /** @var string */
1233 public $file;
1234
1235 /** @var int */
1236 private $pos;
1237
1238 function __construct( $file, $pos ) {
1239 $this->file = $file;
1240 $this->pos = $pos;
1241 }
1242
1243 function __toString() {
1244 // e.g db1034-bin.000976/843431247
1245 return "{$this->file}/{$this->pos}";
1246 }
1247
1248 /**
1249 * @return array|false (int, int)
1250 */
1251 protected function getCoordinates() {
1252 $m = array();
1253 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1254 return array( (int)$m[1], (int)$m[2] );
1255 }
1256
1257 return false;
1258 }
1259
1260 function hasReached( MySQLMasterPos $pos ) {
1261 $thisPos = $this->getCoordinates();
1262 $thatPos = $pos->getCoordinates();
1263
1264 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1265 }
1266
1267 /**
1268 * @return int
1269 */
1270 public function getMasterPos() {
1271 return $this->pos;
1272 }
1273 }