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