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