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