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