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