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