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