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