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