Move up devunt's name to Developers
[lhc/web/wiklou.git] / includes / db / DatabaseMysqlBase.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
27 *
28 * @ingroup Database
29 * @since 1.22
30 * @see Database
31 */
32 abstract class DatabaseMysqlBase extends DatabaseBase {
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35
36 /** @var null|int */
37 protected $mFakeSlaveLag = null;
38
39 protected $mFakeMaster = false;
40
41 /** @var string|null */
42 private $serverVersion = null;
43
44 /**
45 * @return string
46 */
47 function getType() {
48 return 'mysql';
49 }
50
51 /**
52 * @param string $server
53 * @param string $user
54 * @param string $password
55 * @param string $dbName
56 * @throws Exception|DBConnectionError
57 * @return bool
58 */
59 function open( $server, $user, $password, $dbName ) {
60 global $wgAllDBsAreLocalhost, $wgSQLMode;
61
62 # Debugging hack -- fake cluster
63 if ( $wgAllDBsAreLocalhost ) {
64 $realServer = 'localhost';
65 } else {
66 $realServer = $server;
67 }
68 $this->close();
69 $this->mServer = $server;
70 $this->mUser = $user;
71 $this->mPassword = $password;
72 $this->mDBname = $dbName;
73
74 # The kernel's default SYN retransmission period is far too slow for us,
75 # so we use a short timeout plus a manual retry. Retrying means that a small
76 # but finite rate of SYN packet loss won't cause user-visible errors.
77 $this->mConn = false;
78 $this->installErrorHandler();
79 try {
80 $this->mConn = $this->mysqlConnect( $realServer );
81 } catch ( Exception $ex ) {
82 $this->restoreErrorHandler();
83 throw $ex;
84 }
85 $error = $this->restoreErrorHandler();
86
87 # Always log connection errors
88 if ( !$this->mConn ) {
89 if ( !$error ) {
90 $error = $this->lastError();
91 }
92 wfLogDBError(
93 "Error connecting to {db_server}: {error}",
94 $this->getLogContext( array(
95 'method' => __METHOD__,
96 'error' => $error,
97 ) )
98 );
99 wfDebug( "DB connection error\n" .
100 "Server: $server, User: $user, Password: " .
101 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
102
103 $this->reportConnectionError( $error );
104 }
105
106 if ( $dbName != '' ) {
107 wfSuppressWarnings();
108 $success = $this->selectDB( $dbName );
109 wfRestoreWarnings();
110 if ( !$success ) {
111 wfLogDBError(
112 "Error selecting database {db_name} on server {db_server}",
113 $this->getLogContext( array(
114 'method' => __METHOD__,
115 ) )
116 );
117 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
118 "from client host " . wfHostname() . "\n" );
119
120 $this->reportConnectionError( "Error selecting database $dbName" );
121 }
122 }
123
124 // Tell the server what we're communicating with
125 if ( !$this->connectInitCharset() ) {
126 $this->reportConnectionError( "Error setting character set" );
127 }
128
129 // Abstract over any insane MySQL defaults
130 $set = array( 'group_concat_max_len = 262144' );
131 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
132 if ( is_string( $wgSQLMode ) ) {
133 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
134 }
135 // Set any custom settings defined by site config
136 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
137 foreach ( $this->mSessionVars as $var => $val ) {
138 // Escape strings but not numbers to avoid MySQL complaining
139 if ( !is_int( $val ) && !is_float( $val ) ) {
140 $val = $this->addQuotes( $val );
141 }
142 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
143 }
144
145 if ( $set ) {
146 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
147 $success = $this->doQuery( 'SET ' . implode( ', ', $set ), __METHOD__ );
148 if ( !$success ) {
149 wfLogDBError(
150 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
151 $this->getLogContext( array(
152 'method' => __METHOD__,
153 ) )
154 );
155 $this->reportConnectionError(
156 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
157 }
158 }
159
160 $this->mOpened = true;
161
162 return true;
163 }
164
165 /**
166 * Set the character set information right after connection
167 * @return bool
168 */
169 protected function connectInitCharset() {
170 global $wgDBmysql5;
171
172 if ( $wgDBmysql5 ) {
173 // Tell the server we're communicating with it in UTF-8.
174 // This may engage various charset conversions.
175 return $this->mysqlSetCharset( 'utf8' );
176 } else {
177 return $this->mysqlSetCharset( 'binary' );
178 }
179 }
180
181 /**
182 * Open a connection to a MySQL server
183 *
184 * @param string $realServer
185 * @return mixed Raw connection
186 * @throws DBConnectionError
187 */
188 abstract protected function mysqlConnect( $realServer );
189
190 /**
191 * Set the character set of the MySQL link
192 *
193 * @param string $charset
194 * @return bool
195 */
196 abstract protected function mysqlSetCharset( $charset );
197
198 /**
199 * @param ResultWrapper|resource $res
200 * @throws DBUnexpectedError
201 */
202 function freeResult( $res ) {
203 if ( $res instanceof ResultWrapper ) {
204 $res = $res->result;
205 }
206 wfSuppressWarnings();
207 $ok = $this->mysqlFreeResult( $res );
208 wfRestoreWarnings();
209 if ( !$ok ) {
210 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
211 }
212 }
213
214 /**
215 * Free result memory
216 *
217 * @param resource $res Raw result
218 * @return bool
219 */
220 abstract protected function mysqlFreeResult( $res );
221
222 /**
223 * @param ResultWrapper|resource $res
224 * @return stdClass|bool
225 * @throws DBUnexpectedError
226 */
227 function fetchObject( $res ) {
228 if ( $res instanceof ResultWrapper ) {
229 $res = $res->result;
230 }
231 wfSuppressWarnings();
232 $row = $this->mysqlFetchObject( $res );
233 wfRestoreWarnings();
234
235 $errno = $this->lastErrno();
236 // Unfortunately, mysql_fetch_object does not reset the last errno.
237 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
238 // these are the only errors mysql_fetch_object can cause.
239 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
240 if ( $errno == 2000 || $errno == 2013 ) {
241 throw new DBUnexpectedError(
242 $this,
243 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
244 );
245 }
246
247 return $row;
248 }
249
250 /**
251 * Fetch a result row as an object
252 *
253 * @param resource $res Raw result
254 * @return stdClass
255 */
256 abstract protected function mysqlFetchObject( $res );
257
258 /**
259 * @param ResultWrapper|resource $res
260 * @return array|bool
261 * @throws DBUnexpectedError
262 */
263 function fetchRow( $res ) {
264 if ( $res instanceof ResultWrapper ) {
265 $res = $res->result;
266 }
267 wfSuppressWarnings();
268 $row = $this->mysqlFetchArray( $res );
269 wfRestoreWarnings();
270
271 $errno = $this->lastErrno();
272 // Unfortunately, mysql_fetch_array does not reset the last errno.
273 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
274 // these are the only errors mysql_fetch_array can cause.
275 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
276 if ( $errno == 2000 || $errno == 2013 ) {
277 throw new DBUnexpectedError(
278 $this,
279 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
280 );
281 }
282
283 return $row;
284 }
285
286 /**
287 * Fetch a result row as an associative and numeric array
288 *
289 * @param resource $res Raw result
290 * @return array
291 */
292 abstract protected function mysqlFetchArray( $res );
293
294 /**
295 * @throws DBUnexpectedError
296 * @param ResultWrapper|resource $res
297 * @return int
298 */
299 function numRows( $res ) {
300 if ( $res instanceof ResultWrapper ) {
301 $res = $res->result;
302 }
303 wfSuppressWarnings();
304 $n = $this->mysqlNumRows( $res );
305 wfRestoreWarnings();
306
307 // Unfortunately, mysql_num_rows does not reset the last errno.
308 // We are not checking for any errors here, since
309 // these are no errors mysql_num_rows can cause.
310 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
311 // See https://bugzilla.wikimedia.org/42430
312 return $n;
313 }
314
315 /**
316 * Get number of rows in result
317 *
318 * @param resource $res Raw result
319 * @return int
320 */
321 abstract protected function mysqlNumRows( $res );
322
323 /**
324 * @param ResultWrapper|resource $res
325 * @return int
326 */
327 function numFields( $res ) {
328 if ( $res instanceof ResultWrapper ) {
329 $res = $res->result;
330 }
331
332 return $this->mysqlNumFields( $res );
333 }
334
335 /**
336 * Get number of fields in result
337 *
338 * @param resource $res Raw result
339 * @return int
340 */
341 abstract protected function mysqlNumFields( $res );
342
343 /**
344 * @param ResultWrapper|resource $res
345 * @param int $n
346 * @return string
347 */
348 function fieldName( $res, $n ) {
349 if ( $res instanceof ResultWrapper ) {
350 $res = $res->result;
351 }
352
353 return $this->mysqlFieldName( $res, $n );
354 }
355
356 /**
357 * Get the name of the specified field in a result
358 *
359 * @param ResultWrapper|resource $res
360 * @param int $n
361 * @return string
362 */
363 abstract protected function mysqlFieldName( $res, $n );
364
365 /**
366 * mysql_field_type() wrapper
367 * @param ResultWrapper|resource $res
368 * @param int $n
369 * @return string
370 */
371 public function fieldType( $res, $n ) {
372 if ( $res instanceof ResultWrapper ) {
373 $res = $res->result;
374 }
375
376 return $this->mysqlFieldType( $res, $n );
377 }
378
379 /**
380 * Get the type of the specified field in a result
381 *
382 * @param ResultWrapper|resource $res
383 * @param int $n
384 * @return string
385 */
386 abstract protected function mysqlFieldType( $res, $n );
387
388 /**
389 * @param ResultWrapper|resource $res
390 * @param int $row
391 * @return bool
392 */
393 function dataSeek( $res, $row ) {
394 if ( $res instanceof ResultWrapper ) {
395 $res = $res->result;
396 }
397
398 return $this->mysqlDataSeek( $res, $row );
399 }
400
401 /**
402 * Move internal result pointer
403 *
404 * @param ResultWrapper|resource $res
405 * @param int $row
406 * @return bool
407 */
408 abstract protected function mysqlDataSeek( $res, $row );
409
410 /**
411 * @return string
412 */
413 function lastError() {
414 if ( $this->mConn ) {
415 # Even if it's non-zero, it can still be invalid
416 wfSuppressWarnings();
417 $error = $this->mysqlError( $this->mConn );
418 if ( !$error ) {
419 $error = $this->mysqlError();
420 }
421 wfRestoreWarnings();
422 } else {
423 $error = $this->mysqlError();
424 }
425 if ( $error ) {
426 $error .= ' (' . $this->mServer . ')';
427 }
428
429 return $error;
430 }
431
432 /**
433 * Returns the text of the error message from previous MySQL operation
434 *
435 * @param resource $conn Raw connection
436 * @return string
437 */
438 abstract protected function mysqlError( $conn = null );
439
440 /**
441 * @param string $table
442 * @param array $uniqueIndexes
443 * @param array $rows
444 * @param string $fname
445 * @return ResultWrapper
446 */
447 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
448 return $this->nativeReplace( $table, $rows, $fname );
449 }
450
451 /**
452 * Estimate rows in dataset
453 * Returns estimated count, based on EXPLAIN output
454 * Takes same arguments as Database::select()
455 *
456 * @param string|array $table
457 * @param string|array $vars
458 * @param string|array $conds
459 * @param string $fname
460 * @param string|array $options
461 * @return bool|int
462 */
463 public function estimateRowCount( $table, $vars = '*', $conds = '',
464 $fname = __METHOD__, $options = array()
465 ) {
466 $options['EXPLAIN'] = true;
467 $res = $this->select( $table, $vars, $conds, $fname, $options );
468 if ( $res === false ) {
469 return false;
470 }
471 if ( !$this->numRows( $res ) ) {
472 return 0;
473 }
474
475 $rows = 1;
476 foreach ( $res as $plan ) {
477 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
478 }
479
480 return (int)$rows;
481 }
482
483 /**
484 * @param string $table
485 * @param string $field
486 * @return bool|MySQLField
487 */
488 function fieldInfo( $table, $field ) {
489 $table = $this->tableName( $table );
490 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
491 if ( !$res ) {
492 return false;
493 }
494 $n = $this->mysqlNumFields( $res->result );
495 for ( $i = 0; $i < $n; $i++ ) {
496 $meta = $this->mysqlFetchField( $res->result, $i );
497 if ( $field == $meta->name ) {
498 return new MySQLField( $meta );
499 }
500 }
501
502 return false;
503 }
504
505 /**
506 * Get column information from a result
507 *
508 * @param resource $res Raw result
509 * @param int $n
510 * @return stdClass
511 */
512 abstract protected function mysqlFetchField( $res, $n );
513
514 /**
515 * Get information about an index into an object
516 * Returns false if the index does not exist
517 *
518 * @param string $table
519 * @param string $index
520 * @param string $fname
521 * @return bool|array|null False or null on failure
522 */
523 function indexInfo( $table, $index, $fname = __METHOD__ ) {
524 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
525 # SHOW INDEX should work for 3.x and up:
526 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
527 $table = $this->tableName( $table );
528 $index = $this->indexName( $index );
529
530 $sql = 'SHOW INDEX FROM ' . $table;
531 $res = $this->query( $sql, $fname );
532
533 if ( !$res ) {
534 return null;
535 }
536
537 $result = array();
538
539 foreach ( $res as $row ) {
540 if ( $row->Key_name == $index ) {
541 $result[] = $row;
542 }
543 }
544
545 return empty( $result ) ? false : $result;
546 }
547
548 /**
549 * @param string $s
550 * @return string
551 */
552 function strencode( $s ) {
553 $sQuoted = $this->mysqlRealEscapeString( $s );
554
555 if ( $sQuoted === false ) {
556 $this->ping();
557 $sQuoted = $this->mysqlRealEscapeString( $s );
558 }
559
560 return $sQuoted;
561 }
562
563 /**
564 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
565 *
566 * @param string $s
567 * @return string
568 */
569 public function addIdentifierQuotes( $s ) {
570 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
571 // Remove NUL bytes and escape backticks by doubling
572 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
573 }
574
575 /**
576 * @param string $name
577 * @return bool
578 */
579 public function isQuotedIdentifier( $name ) {
580 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
581 }
582
583 /**
584 * @return bool
585 */
586 function ping() {
587 $ping = $this->mysqlPing();
588 if ( $ping ) {
589 return true;
590 }
591
592 $this->closeConnection();
593 $this->mOpened = false;
594 $this->mConn = false;
595 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
596
597 return true;
598 }
599
600 /**
601 * Ping a server connection or reconnect if there is no connection
602 *
603 * @return bool
604 */
605 abstract protected function mysqlPing();
606
607 /**
608 * Set lag time in seconds for a fake slave
609 *
610 * @param int $lag
611 */
612 public function setFakeSlaveLag( $lag ) {
613 $this->mFakeSlaveLag = $lag;
614 }
615
616 /**
617 * Make this connection a fake master
618 *
619 * @param bool $enabled
620 */
621 public function setFakeMaster( $enabled = true ) {
622 $this->mFakeMaster = $enabled;
623 }
624
625 /**
626 * Returns slave lag.
627 *
628 * This will do a SHOW SLAVE STATUS
629 *
630 * @return int
631 */
632 function getLag() {
633 if ( !is_null( $this->mFakeSlaveLag ) ) {
634 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
635
636 return $this->mFakeSlaveLag;
637 }
638
639 return $this->getLagFromSlaveStatus();
640 }
641
642 /**
643 * @return bool|int
644 */
645 function getLagFromSlaveStatus() {
646 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
647 if ( !$res ) {
648 return false;
649 }
650 $row = $res->fetchObject();
651 if ( !$row ) {
652 return false;
653 }
654 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
655 return false;
656 } else {
657 return intval( $row->Seconds_Behind_Master );
658 }
659 }
660
661 /**
662 * Wait for the slave to catch up to a given master position.
663 * @todo Return values for this and base class are rubbish
664 *
665 * @param DBMasterPos|MySQLMasterPos $pos
666 * @param int $timeout The maximum number of seconds to wait for synchronisation
667 * @return int Zero if the slave was past that position already,
668 * greater than zero if we waited for some period of time, less than
669 * zero if we timed out.
670 */
671 function masterPosWait( DBMasterPos $pos, $timeout ) {
672 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
673 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
674 }
675
676 # Commit any open transactions
677 $this->commit( __METHOD__, 'flush' );
678
679 if ( !is_null( $this->mFakeSlaveLag ) ) {
680 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
681
682 if ( $wait > $timeout * 1e6 ) {
683 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
684
685 return -1;
686 } elseif ( $wait > 0 ) {
687 wfDebug( "Fake slave waiting $wait us\n" );
688 usleep( $wait );
689
690 return 1;
691 } else {
692 wfDebug( "Fake slave up to date ($wait us)\n" );
693
694 return 0;
695 }
696 }
697
698 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
699 $encFile = $this->addQuotes( $pos->file );
700 $encPos = intval( $pos->pos );
701 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
702 $res = $this->doQuery( $sql );
703
704 $status = false;
705 if ( $res && $row = $this->fetchRow( $res ) ) {
706 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
707 if ( ctype_digit( $status ) ) { // success
708 $this->lastKnownSlavePos = $pos;
709 }
710 }
711
712 return $status;
713 }
714
715 /**
716 * Get the position of the master from SHOW SLAVE STATUS
717 *
718 * @return MySQLMasterPos|bool
719 */
720 function getSlavePos() {
721 if ( !is_null( $this->mFakeSlaveLag ) ) {
722 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
723 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
724
725 return $pos;
726 }
727
728 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
729 $row = $this->fetchObject( $res );
730
731 if ( $row ) {
732 $pos = isset( $row->Exec_master_log_pos )
733 ? $row->Exec_master_log_pos
734 : $row->Exec_Master_Log_Pos;
735
736 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
737 } else {
738 return false;
739 }
740 }
741
742 /**
743 * Get the position of the master from SHOW MASTER STATUS
744 *
745 * @return MySQLMasterPos|bool
746 */
747 function getMasterPos() {
748 if ( $this->mFakeMaster ) {
749 return new MySQLMasterPos( 'fake', microtime( true ) );
750 }
751
752 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
753 $row = $this->fetchObject( $res );
754
755 if ( $row ) {
756 return new MySQLMasterPos( $row->File, $row->Position );
757 } else {
758 return false;
759 }
760 }
761
762 /**
763 * @param string $index
764 * @return string
765 */
766 function useIndexClause( $index ) {
767 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
768 }
769
770 /**
771 * @return string
772 */
773 function lowPriorityOption() {
774 return 'LOW_PRIORITY';
775 }
776
777 /**
778 * @return string
779 */
780 public function getSoftwareLink() {
781 // MariaDB includes its name in its version string; this is how MariaDB's version of
782 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
783 // in libmysql/libmysql.c).
784 $version = $this->getServerVersion();
785 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
786 return '[{{int:version-db-mariadb-url}} MariaDB]';
787 }
788
789 // Percona Server's version suffix is not very distinctive, and @@version_comment
790 // doesn't give the necessary info for source builds, so assume the server is MySQL.
791 // (Even Percona's version of mysql doesn't try to make the distinction.)
792 return '[{{int:version-db-mysql-url}} MySQL]';
793 }
794
795 /**
796 * @return string
797 */
798 public function getServerVersion() {
799 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
800 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
801 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
802 if ( $this->serverVersion === null ) {
803 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
804 }
805 return $this->serverVersion;
806 }
807
808 /**
809 * @param array $options
810 */
811 public function setSessionOptions( array $options ) {
812 if ( isset( $options['connTimeout'] ) ) {
813 $timeout = (int)$options['connTimeout'];
814 $this->query( "SET net_read_timeout=$timeout" );
815 $this->query( "SET net_write_timeout=$timeout" );
816 }
817 }
818
819 /**
820 * @param string $sql
821 * @param string $newLine
822 * @return bool
823 */
824 public function streamStatementEnd( &$sql, &$newLine ) {
825 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
826 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
827 $this->delimiter = $m[1];
828 $newLine = '';
829 }
830
831 return parent::streamStatementEnd( $sql, $newLine );
832 }
833
834 /**
835 * Check to see if a named lock is available. This is non-blocking.
836 *
837 * @param string $lockName Name of lock to poll
838 * @param string $method Name of method calling us
839 * @return bool
840 * @since 1.20
841 */
842 public function lockIsFree( $lockName, $method ) {
843 $lockName = $this->addQuotes( $lockName );
844 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
845 $row = $this->fetchObject( $result );
846
847 return ( $row->lockstatus == 1 );
848 }
849
850 /**
851 * @param string $lockName
852 * @param string $method
853 * @param int $timeout
854 * @return bool
855 */
856 public function lock( $lockName, $method, $timeout = 5 ) {
857 $lockName = $this->addQuotes( $lockName );
858 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
859 $row = $this->fetchObject( $result );
860
861 if ( $row->lockstatus == 1 ) {
862 return true;
863 } else {
864 wfDebug( __METHOD__ . " failed to acquire lock\n" );
865
866 return false;
867 }
868 }
869
870 /**
871 * FROM MYSQL DOCS:
872 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
873 * @param string $lockName
874 * @param string $method
875 * @return bool
876 */
877 public function unlock( $lockName, $method ) {
878 $lockName = $this->addQuotes( $lockName );
879 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
880 $row = $this->fetchObject( $result );
881
882 return ( $row->lockstatus == 1 );
883 }
884
885 public function namedLocksEnqueue() {
886 return true;
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 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1206
1207 function __construct( $info ) {
1208 $this->name = $info->name;
1209 $this->tablename = $info->table;
1210 $this->default = $info->def;
1211 $this->max_length = $info->max_length;
1212 $this->nullable = !$info->not_null;
1213 $this->is_pk = $info->primary_key;
1214 $this->is_unique = $info->unique_key;
1215 $this->is_multiple = $info->multiple_key;
1216 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1217 $this->type = $info->type;
1218 $this->binary = isset( $info->binary ) ? $info->binary : false;
1219 $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1220 $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1221 $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1222 $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1223 }
1224
1225 /**
1226 * @return string
1227 */
1228 function name() {
1229 return $this->name;
1230 }
1231
1232 /**
1233 * @return string
1234 */
1235 function tableName() {
1236 return $this->tableName;
1237 }
1238
1239 /**
1240 * @return string
1241 */
1242 function type() {
1243 return $this->type;
1244 }
1245
1246 /**
1247 * @return bool
1248 */
1249 function isNullable() {
1250 return $this->nullable;
1251 }
1252
1253 function defaultValue() {
1254 return $this->default;
1255 }
1256
1257 /**
1258 * @return bool
1259 */
1260 function isKey() {
1261 return $this->is_key;
1262 }
1263
1264 /**
1265 * @return bool
1266 */
1267 function isMultipleKey() {
1268 return $this->is_multiple;
1269 }
1270
1271 /**
1272 * @return bool
1273 */
1274 function isBinary() {
1275 return $this->binary;
1276 }
1277
1278 /**
1279 * @return bool
1280 */
1281 function isNumeric() {
1282 return $this->is_numeric;
1283 }
1284
1285 /**
1286 * @return bool
1287 */
1288 function isBlob() {
1289 return $this->is_blob;
1290 }
1291
1292 /**
1293 * @return bool
1294 */
1295 function isUnsigned() {
1296 return $this->is_unsigned;
1297 }
1298
1299 /**
1300 * @return bool
1301 */
1302 function isZerofill() {
1303 return $this->is_zerofill;
1304 }
1305 }
1306
1307 class MySQLMasterPos implements DBMasterPos {
1308 /** @var string */
1309 public $file;
1310 /** @var int Position */
1311 public $pos;
1312 /** @var float UNIX timestamp */
1313 public $asOfTime = 0.0;
1314
1315 function __construct( $file, $pos ) {
1316 $this->file = $file;
1317 $this->pos = $pos;
1318 $this->asOfTime = microtime( true );
1319 }
1320
1321 function __toString() {
1322 // e.g db1034-bin.000976/843431247
1323 return "{$this->file}/{$this->pos}";
1324 }
1325
1326 /**
1327 * @return array|bool (int, int)
1328 */
1329 protected function getCoordinates() {
1330 $m = array();
1331 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1332 return array( (int)$m[1], (int)$m[2] );
1333 }
1334
1335 return false;
1336 }
1337
1338 function hasReached( MySQLMasterPos $pos ) {
1339 $thisPos = $this->getCoordinates();
1340 $thatPos = $pos->getCoordinates();
1341
1342 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1343 }
1344
1345 function asOfTime() {
1346 return $this->asOfTime;
1347 }
1348 }