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