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