Removed remaining profile calls
[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
75 # The kernel's default SYN retransmission period is far too slow for us,
76 # so we use a short timeout plus a manual retry. Retrying means that a small
77 # but finite rate of SYN packet loss won't cause user-visible errors.
78 $this->mConn = false;
79 $this->installErrorHandler();
80 try {
81 $this->mConn = $this->mysqlConnect( $realServer );
82 } catch ( Exception $ex ) {
83 $this->restoreErrorHandler();
84 throw $ex;
85 }
86 $error = $this->restoreErrorHandler();
87
88
89 # Always log connection errors
90 if ( !$this->mConn ) {
91 if ( !$error ) {
92 $error = $this->lastError();
93 }
94 wfLogDBError(
95 "Error connecting to {db_server}: {error}",
96 $this->getLogContext( array(
97 'method' => __METHOD__,
98 'error' => $error,
99 ) )
100 );
101 wfDebug( "DB connection error\n" .
102 "Server: $server, User: $user, Password: " .
103 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
104
105
106 $this->reportConnectionError( $error );
107 }
108
109 if ( $dbName != '' ) {
110 wfSuppressWarnings();
111 $success = $this->selectDB( $dbName );
112 wfRestoreWarnings();
113 if ( !$success ) {
114 wfLogDBError(
115 "Error selecting database {db_name} on server {db_server}",
116 $this->getLogContext( array(
117 'method' => __METHOD__,
118 ) )
119 );
120 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
121 "from client host " . wfHostname() . "\n" );
122
123
124 $this->reportConnectionError( "Error selecting database $dbName" );
125 }
126 }
127
128 // Tell the server what we're communicating with
129 if ( !$this->connectInitCharset() ) {
130 $this->reportConnectionError( "Error setting character set" );
131 }
132
133 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
134 if ( is_string( $wgSQLMode ) ) {
135 $mode = $this->addQuotes( $wgSQLMode );
136 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
137 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__ );
138 if ( !$success ) {
139 wfLogDBError(
140 "Error setting sql_mode to $mode on server {db_server}",
141 $this->getLogContext( array(
142 'method' => __METHOD__,
143 ) )
144 );
145 $this->reportConnectionError( "Error setting sql_mode to $mode" );
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 wfSuppressWarnings();
196 $ok = $this->mysqlFreeResult( $res );
197 wfRestoreWarnings();
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 wfSuppressWarnings();
221 $row = $this->mysqlFetchObject( $res );
222 wfRestoreWarnings();
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 wfSuppressWarnings();
257 $row = $this->mysqlFetchArray( $res );
258 wfRestoreWarnings();
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 wfSuppressWarnings();
293 $n = $this->mysqlNumRows( $res );
294 wfRestoreWarnings();
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://bugzilla.wikimedia.org/42430
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 wfSuppressWarnings();
406 $error = $this->mysqlError( $this->mConn );
407 if ( !$error ) {
408 $error = $this->mysqlError();
409 }
410 wfRestoreWarnings();
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 $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 return true;
579 }
580
581 $this->closeConnection();
582 $this->mOpened = false;
583 $this->mConn = false;
584 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
585
586 return true;
587 }
588
589 /**
590 * Ping a server connection or reconnect if there is no connection
591 *
592 * @return bool
593 */
594 abstract protected function mysqlPing();
595
596 /**
597 * Set lag time in seconds for a fake slave
598 *
599 * @param int $lag
600 */
601 public function setFakeSlaveLag( $lag ) {
602 $this->mFakeSlaveLag = $lag;
603 }
604
605 /**
606 * Make this connection a fake master
607 *
608 * @param bool $enabled
609 */
610 public function setFakeMaster( $enabled = true ) {
611 $this->mFakeMaster = $enabled;
612 }
613
614 /**
615 * Returns slave lag.
616 *
617 * This will do a SHOW SLAVE STATUS
618 *
619 * @return int
620 */
621 function getLag() {
622 if ( !is_null( $this->mFakeSlaveLag ) ) {
623 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
624
625 return $this->mFakeSlaveLag;
626 }
627
628 return $this->getLagFromSlaveStatus();
629 }
630
631 /**
632 * @return bool|int
633 */
634 function getLagFromSlaveStatus() {
635 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
636 if ( !$res ) {
637 return false;
638 }
639 $row = $res->fetchObject();
640 if ( !$row ) {
641 return false;
642 }
643 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
644 return false;
645 } else {
646 return intval( $row->Seconds_Behind_Master );
647 }
648 }
649
650 /**
651 * Wait for the slave to catch up to a given master position.
652 * @todo Return values for this and base class are rubbish
653 *
654 * @param DBMasterPos|MySQLMasterPos $pos
655 * @param int $timeout The maximum number of seconds to wait for synchronisation
656 * @return int Zero if the slave was past that position already,
657 * greater than zero if we waited for some period of time, less than
658 * zero if we timed out.
659 */
660 function masterPosWait( DBMasterPos $pos, $timeout ) {
661 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
662 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
663 }
664
665 # Commit any open transactions
666 $this->commit( __METHOD__, 'flush' );
667
668 if ( !is_null( $this->mFakeSlaveLag ) ) {
669 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
670
671 if ( $wait > $timeout * 1e6 ) {
672 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
673
674 return -1;
675 } elseif ( $wait > 0 ) {
676 wfDebug( "Fake slave waiting $wait us\n" );
677 usleep( $wait );
678
679 return 1;
680 } else {
681 wfDebug( "Fake slave up to date ($wait us)\n" );
682
683 return 0;
684 }
685 }
686
687 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
688 $encFile = $this->addQuotes( $pos->file );
689 $encPos = intval( $pos->pos );
690 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
691 $res = $this->doQuery( $sql );
692
693 $status = false;
694 if ( $res && $row = $this->fetchRow( $res ) ) {
695 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
696 if ( ctype_digit( $status ) ) { // success
697 $this->lastKnownSlavePos = $pos;
698 }
699 }
700
701
702 return $status;
703 }
704
705 /**
706 * Get the position of the master from SHOW SLAVE STATUS
707 *
708 * @return MySQLMasterPos|bool
709 */
710 function getSlavePos() {
711 if ( !is_null( $this->mFakeSlaveLag ) ) {
712 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
713 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
714
715 return $pos;
716 }
717
718 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
719 $row = $this->fetchObject( $res );
720
721 if ( $row ) {
722 $pos = isset( $row->Exec_master_log_pos )
723 ? $row->Exec_master_log_pos
724 : $row->Exec_Master_Log_Pos;
725
726 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
727 } else {
728 return false;
729 }
730 }
731
732 /**
733 * Get the position of the master from SHOW MASTER STATUS
734 *
735 * @return MySQLMasterPos|bool
736 */
737 function getMasterPos() {
738 if ( $this->mFakeMaster ) {
739 return new MySQLMasterPos( 'fake', microtime( true ) );
740 }
741
742 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
743 $row = $this->fetchObject( $res );
744
745 if ( $row ) {
746 return new MySQLMasterPos( $row->File, $row->Position );
747 } else {
748 return false;
749 }
750 }
751
752 /**
753 * @param string $index
754 * @return string
755 */
756 function useIndexClause( $index ) {
757 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
758 }
759
760 /**
761 * @return string
762 */
763 function lowPriorityOption() {
764 return 'LOW_PRIORITY';
765 }
766
767 /**
768 * @return string
769 */
770 public function getSoftwareLink() {
771 // MariaDB includes its name in its version string; this is how MariaDB's version of
772 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
773 // in libmysql/libmysql.c).
774 $version = $this->getServerVersion();
775 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
776 return '[{{int:version-db-mariadb-url}} MariaDB]';
777 }
778
779 // Percona Server's version suffix is not very distinctive, and @@version_comment
780 // doesn't give the necessary info for source builds, so assume the server is MySQL.
781 // (Even Percona's version of mysql doesn't try to make the distinction.)
782 return '[{{int:version-db-mysql-url}} MySQL]';
783 }
784
785 /**
786 * @return string
787 */
788 public function getServerVersion() {
789 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
790 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
791 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
792 if ( $this->serverVersion === null ) {
793 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
794 }
795 return $this->serverVersion;
796 }
797
798 /**
799 * @param array $options
800 */
801 public function setSessionOptions( array $options ) {
802 if ( isset( $options['connTimeout'] ) ) {
803 $timeout = (int)$options['connTimeout'];
804 $this->query( "SET net_read_timeout=$timeout" );
805 $this->query( "SET net_write_timeout=$timeout" );
806 }
807 }
808
809 /**
810 * @param string $sql
811 * @param string $newLine
812 * @return bool
813 */
814 public function streamStatementEnd( &$sql, &$newLine ) {
815 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
816 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
817 $this->delimiter = $m[1];
818 $newLine = '';
819 }
820
821 return parent::streamStatementEnd( $sql, $newLine );
822 }
823
824 /**
825 * Check to see if a named lock is available. This is non-blocking.
826 *
827 * @param string $lockName Name of lock to poll
828 * @param string $method Name of method calling us
829 * @return bool
830 * @since 1.20
831 */
832 public function lockIsFree( $lockName, $method ) {
833 $lockName = $this->addQuotes( $lockName );
834 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
835 $row = $this->fetchObject( $result );
836
837 return ( $row->lockstatus == 1 );
838 }
839
840 /**
841 * @param string $lockName
842 * @param string $method
843 * @param int $timeout
844 * @return bool
845 */
846 public function lock( $lockName, $method, $timeout = 5 ) {
847 $lockName = $this->addQuotes( $lockName );
848 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
849 $row = $this->fetchObject( $result );
850
851 if ( $row->lockstatus == 1 ) {
852 return true;
853 } else {
854 wfDebug( __METHOD__ . " failed to acquire lock\n" );
855
856 return false;
857 }
858 }
859
860 /**
861 * FROM MYSQL DOCS:
862 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
863 * @param string $lockName
864 * @param string $method
865 * @return bool
866 */
867 public function unlock( $lockName, $method ) {
868 $lockName = $this->addQuotes( $lockName );
869 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
870 $row = $this->fetchObject( $result );
871
872 return ( $row->lockstatus == 1 );
873 }
874
875 /**
876 * @param array $read
877 * @param array $write
878 * @param string $method
879 * @param bool $lowPriority
880 * @return bool
881 */
882 public function lockTables( $read, $write, $method, $lowPriority = true ) {
883 $items = array();
884
885 foreach ( $write as $table ) {
886 $tbl = $this->tableName( $table ) .
887 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
888 ' WRITE';
889 $items[] = $tbl;
890 }
891 foreach ( $read as $table ) {
892 $items[] = $this->tableName( $table ) . ' READ';
893 }
894 $sql = "LOCK TABLES " . implode( ',', $items );
895 $this->query( $sql, $method );
896
897 return true;
898 }
899
900 /**
901 * @param string $method
902 * @return bool
903 */
904 public function unlockTables( $method ) {
905 $this->query( "UNLOCK TABLES", $method );
906
907 return true;
908 }
909
910 /**
911 * Get search engine class. All subclasses of this
912 * need to implement this if they wish to use searching.
913 *
914 * @return string
915 */
916 public function getSearchEngine() {
917 return 'SearchMySQL';
918 }
919
920 /**
921 * @param bool $value
922 */
923 public function setBigSelects( $value = true ) {
924 if ( $value === 'default' ) {
925 if ( $this->mDefaultBigSelects === null ) {
926 # Function hasn't been called before so it must already be set to the default
927 return;
928 } else {
929 $value = $this->mDefaultBigSelects;
930 }
931 } elseif ( $this->mDefaultBigSelects === null ) {
932 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
933 }
934 $encValue = $value ? '1' : '0';
935 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
936 }
937
938 /**
939 * DELETE where the condition is a join. MySql uses multi-table deletes.
940 * @param string $delTable
941 * @param string $joinTable
942 * @param string $delVar
943 * @param string $joinVar
944 * @param array|string $conds
945 * @param bool|string $fname
946 * @throws DBUnexpectedError
947 * @return bool|ResultWrapper
948 */
949 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
950 if ( !$conds ) {
951 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
952 }
953
954 $delTable = $this->tableName( $delTable );
955 $joinTable = $this->tableName( $joinTable );
956 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
957
958 if ( $conds != '*' ) {
959 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
960 }
961
962 return $this->query( $sql, $fname );
963 }
964
965 /**
966 * @param string $table
967 * @param array $rows
968 * @param array $uniqueIndexes
969 * @param array $set
970 * @param string $fname
971 * @return bool
972 */
973 public function upsert( $table, array $rows, array $uniqueIndexes,
974 array $set, $fname = __METHOD__
975 ) {
976 if ( !count( $rows ) ) {
977 return true; // nothing to do
978 }
979
980 if ( !is_array( reset( $rows ) ) ) {
981 $rows = array( $rows );
982 }
983
984 $table = $this->tableName( $table );
985 $columns = array_keys( $rows[0] );
986
987 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
988 $rowTuples = array();
989 foreach ( $rows as $row ) {
990 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
991 }
992 $sql .= implode( ',', $rowTuples );
993 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
994
995 return (bool)$this->query( $sql, $fname );
996 }
997
998 /**
999 * Determines how long the server has been up
1000 *
1001 * @return int
1002 */
1003 function getServerUptime() {
1004 $vars = $this->getMysqlStatus( 'Uptime' );
1005
1006 return (int)$vars['Uptime'];
1007 }
1008
1009 /**
1010 * Determines if the last failure was due to a deadlock
1011 *
1012 * @return bool
1013 */
1014 function wasDeadlock() {
1015 return $this->lastErrno() == 1213;
1016 }
1017
1018 /**
1019 * Determines if the last failure was due to a lock timeout
1020 *
1021 * @return bool
1022 */
1023 function wasLockTimeout() {
1024 return $this->lastErrno() == 1205;
1025 }
1026
1027 /**
1028 * Determines if the last query error was something that should be dealt
1029 * with by pinging the connection and reissuing the query
1030 *
1031 * @return bool
1032 */
1033 function wasErrorReissuable() {
1034 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1035 }
1036
1037 /**
1038 * Determines if the last failure was due to the database being read-only.
1039 *
1040 * @return bool
1041 */
1042 function wasReadOnlyError() {
1043 return $this->lastErrno() == 1223 ||
1044 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1045 }
1046
1047 /**
1048 * @param string $oldName
1049 * @param string $newName
1050 * @param bool $temporary
1051 * @param string $fname
1052 * @return bool
1053 */
1054 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1055 $tmp = $temporary ? 'TEMPORARY ' : '';
1056 $newName = $this->addIdentifierQuotes( $newName );
1057 $oldName = $this->addIdentifierQuotes( $oldName );
1058 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1059
1060 return $this->query( $query, $fname );
1061 }
1062
1063 /**
1064 * List all tables on the database
1065 *
1066 * @param string $prefix Only show tables with this prefix, e.g. mw_
1067 * @param string $fname Calling function name
1068 * @return array
1069 */
1070 function listTables( $prefix = null, $fname = __METHOD__ ) {
1071 $result = $this->query( "SHOW TABLES", $fname );
1072
1073 $endArray = array();
1074
1075 foreach ( $result as $table ) {
1076 $vars = get_object_vars( $table );
1077 $table = array_pop( $vars );
1078
1079 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1080 $endArray[] = $table;
1081 }
1082 }
1083
1084 return $endArray;
1085 }
1086
1087 /**
1088 * @param string $tableName
1089 * @param string $fName
1090 * @return bool|ResultWrapper
1091 */
1092 public function dropTable( $tableName, $fName = __METHOD__ ) {
1093 if ( !$this->tableExists( $tableName, $fName ) ) {
1094 return false;
1095 }
1096
1097 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1098 }
1099
1100 /**
1101 * @return array
1102 */
1103 protected function getDefaultSchemaVars() {
1104 $vars = parent::getDefaultSchemaVars();
1105 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1106 $vars['wgDBTableOptions'] = str_replace(
1107 'CHARSET=mysql4',
1108 'CHARSET=binary',
1109 $vars['wgDBTableOptions']
1110 );
1111
1112 return $vars;
1113 }
1114
1115 /**
1116 * Get status information from SHOW STATUS in an associative array
1117 *
1118 * @param string $which
1119 * @return array
1120 */
1121 function getMysqlStatus( $which = "%" ) {
1122 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1123 $status = array();
1124
1125 foreach ( $res as $row ) {
1126 $status[$row->Variable_name] = $row->Value;
1127 }
1128
1129 return $status;
1130 }
1131
1132 /**
1133 * Lists VIEWs in the database
1134 *
1135 * @param string $prefix Only show VIEWs with this prefix, eg.
1136 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1137 * @param string $fname Name of calling function
1138 * @return array
1139 * @since 1.22
1140 */
1141 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1142
1143 if ( !isset( $this->allViews ) ) {
1144
1145 // The name of the column containing the name of the VIEW
1146 $propertyName = 'Tables_in_' . $this->mDBname;
1147
1148 // Query for the VIEWS
1149 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1150 $this->allViews = array();
1151 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1152 array_push( $this->allViews, $row[$propertyName] );
1153 }
1154 }
1155
1156 if ( is_null( $prefix ) || $prefix === '' ) {
1157 return $this->allViews;
1158 }
1159
1160 $filteredViews = array();
1161 foreach ( $this->allViews as $viewName ) {
1162 // Does the name of this VIEW start with the table-prefix?
1163 if ( strpos( $viewName, $prefix ) === 0 ) {
1164 array_push( $filteredViews, $viewName );
1165 }
1166 }
1167
1168 return $filteredViews;
1169 }
1170
1171 /**
1172 * Differentiates between a TABLE and a VIEW.
1173 *
1174 * @param string $name Name of the TABLE/VIEW to test
1175 * @param string $prefix
1176 * @return bool
1177 * @since 1.22
1178 */
1179 public function isView( $name, $prefix = null ) {
1180 return in_array( $name, $this->listViews( $prefix ) );
1181 }
1182 }
1183
1184 /**
1185 * Utility class.
1186 * @ingroup Database
1187 */
1188 class MySQLField implements Field {
1189 private $name, $tablename, $default, $max_length, $nullable,
1190 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1191
1192 function __construct( $info ) {
1193 $this->name = $info->name;
1194 $this->tablename = $info->table;
1195 $this->default = $info->def;
1196 $this->max_length = $info->max_length;
1197 $this->nullable = !$info->not_null;
1198 $this->is_pk = $info->primary_key;
1199 $this->is_unique = $info->unique_key;
1200 $this->is_multiple = $info->multiple_key;
1201 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1202 $this->type = $info->type;
1203 $this->binary = isset( $info->binary ) ? $info->binary : false;
1204 }
1205
1206 /**
1207 * @return string
1208 */
1209 function name() {
1210 return $this->name;
1211 }
1212
1213 /**
1214 * @return string
1215 */
1216 function tableName() {
1217 return $this->tableName;
1218 }
1219
1220 /**
1221 * @return string
1222 */
1223 function type() {
1224 return $this->type;
1225 }
1226
1227 /**
1228 * @return bool
1229 */
1230 function isNullable() {
1231 return $this->nullable;
1232 }
1233
1234 function defaultValue() {
1235 return $this->default;
1236 }
1237
1238 /**
1239 * @return bool
1240 */
1241 function isKey() {
1242 return $this->is_key;
1243 }
1244
1245 /**
1246 * @return bool
1247 */
1248 function isMultipleKey() {
1249 return $this->is_multiple;
1250 }
1251
1252 function isBinary() {
1253 return $this->binary;
1254 }
1255 }
1256
1257 class MySQLMasterPos implements DBMasterPos {
1258 /** @var string */
1259 public $file;
1260 /** @var int Position */
1261 public $pos;
1262 /** @var float UNIX timestamp */
1263 public $asOfTime = 0.0;
1264
1265 function __construct( $file, $pos ) {
1266 $this->file = $file;
1267 $this->pos = $pos;
1268 $this->asOfTime = microtime( true );
1269 }
1270
1271 function __toString() {
1272 // e.g db1034-bin.000976/843431247
1273 return "{$this->file}/{$this->pos}";
1274 }
1275
1276 /**
1277 * @return array|bool (int, int)
1278 */
1279 protected function getCoordinates() {
1280 $m = array();
1281 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1282 return array( (int)$m[1], (int)$m[2] );
1283 }
1284
1285 return false;
1286 }
1287
1288 function hasReached( MySQLMasterPos $pos ) {
1289 $thisPos = $this->getCoordinates();
1290 $thatPos = $pos->getCoordinates();
1291
1292 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1293 }
1294
1295 function asOfTime() {
1296 return $this->asOfTime;
1297 }
1298 }