Add forgotten RELEASE-NOTES line
[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 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
473 // Remove NUL bytes and escape backticks by doubling
474 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
475 }
476
477 /**
478 * @param $name string
479 * @return bool
480 */
481 public function isQuotedIdentifier( $name ) {
482 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
483 }
484
485 /**
486 * @return bool
487 */
488 function ping() {
489 $ping = $this->mysqlPing();
490 if ( $ping ) {
491 return true;
492 }
493
494 $this->closeConnection();
495 $this->mOpened = false;
496 $this->mConn = false;
497 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
498 return true;
499 }
500
501 /**
502 * Ping a server connection or reconnect if there is no connection
503 *
504 * @return bool
505 */
506 abstract protected function mysqlPing();
507
508 /**
509 * Returns slave lag.
510 *
511 * This will do a SHOW SLAVE STATUS
512 *
513 * @return int
514 */
515 function getLag() {
516 if ( !is_null( $this->mFakeSlaveLag ) ) {
517 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
518 return $this->mFakeSlaveLag;
519 }
520
521 return $this->getLagFromSlaveStatus();
522 }
523
524 /**
525 * @return bool|int
526 */
527 function getLagFromSlaveStatus() {
528 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
529 if ( !$res ) {
530 return false;
531 }
532 $row = $res->fetchObject();
533 if ( !$row ) {
534 return false;
535 }
536 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
537 return false;
538 } else {
539 return intval( $row->Seconds_Behind_Master );
540 }
541 }
542
543 /**
544 * @deprecated in 1.19, use getLagFromSlaveStatus
545 *
546 * @return bool|int
547 */
548 function getLagFromProcesslist() {
549 wfDeprecated( __METHOD__, '1.19' );
550 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
551 if ( !$res ) {
552 return false;
553 }
554 # Find slave SQL thread
555 foreach ( $res as $row ) {
556 /* This should work for most situations - when default db
557 * for thread is not specified, it had no events executed,
558 * and therefore it doesn't know yet how lagged it is.
559 *
560 * Relay log I/O thread does not select databases.
561 */
562 if ( $row->User == 'system user' &&
563 $row->State != 'Waiting for master to send event' &&
564 $row->State != 'Connecting to master' &&
565 $row->State != 'Queueing master event to the relay log' &&
566 $row->State != 'Waiting for master update' &&
567 $row->State != 'Requesting binlog dump' &&
568 $row->State != 'Waiting to reconnect after a failed master event read' &&
569 $row->State != 'Reconnecting after a failed master event read' &&
570 $row->State != 'Registering slave on master'
571 ) {
572 # This is it, return the time (except -ve)
573 if ( $row->Time > 0x7fffffff ) {
574 return false;
575 } else {
576 return $row->Time;
577 }
578 }
579 }
580 return false;
581 }
582
583 /**
584 * Wait for the slave to catch up to a given master position.
585 * @TODO: return values for this and base class are rubbish
586 *
587 * @param $pos DBMasterPos object
588 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
589 * @return bool|string
590 */
591 function masterPosWait( DBMasterPos $pos, $timeout ) {
592 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
593 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
594 }
595
596 wfProfileIn( __METHOD__ );
597 # Commit any open transactions
598 $this->commit( __METHOD__, 'flush' );
599
600 if ( !is_null( $this->mFakeSlaveLag ) ) {
601 $status = parent::masterPosWait( $pos, $timeout );
602 wfProfileOut( __METHOD__ );
603 return $status;
604 }
605
606 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
607 $encFile = $this->addQuotes( $pos->file );
608 $encPos = intval( $pos->pos );
609 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
610 $res = $this->doQuery( $sql );
611
612 $status = false;
613 if ( $res && $row = $this->fetchRow( $res ) ) {
614 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
615 if ( ctype_digit( $status ) ) { // success
616 $this->lastKnownSlavePos = $pos;
617 }
618 }
619
620 wfProfileOut( __METHOD__ );
621 return $status;
622 }
623
624 /**
625 * Get the position of the master from SHOW SLAVE STATUS
626 *
627 * @return MySQLMasterPos|bool
628 */
629 function getSlavePos() {
630 if ( !is_null( $this->mFakeSlaveLag ) ) {
631 return parent::getSlavePos();
632 }
633
634 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
635 $row = $this->fetchObject( $res );
636
637 if ( $row ) {
638 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
639 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
640 } else {
641 return false;
642 }
643 }
644
645 /**
646 * Get the position of the master from SHOW MASTER STATUS
647 *
648 * @return MySQLMasterPos|bool
649 */
650 function getMasterPos() {
651 if ( $this->mFakeMaster ) {
652 return parent::getMasterPos();
653 }
654
655 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
656 $row = $this->fetchObject( $res );
657
658 if ( $row ) {
659 return new MySQLMasterPos( $row->File, $row->Position );
660 } else {
661 return false;
662 }
663 }
664
665 /**
666 * @param $index
667 * @return string
668 */
669 function useIndexClause( $index ) {
670 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
671 }
672
673 /**
674 * @return string
675 */
676 function lowPriorityOption() {
677 return 'LOW_PRIORITY';
678 }
679
680 /**
681 * @return string
682 */
683 public function getSoftwareLink() {
684 return '[http://www.mysql.com/ MySQL]';
685 }
686
687 /**
688 * @param $options array
689 */
690 public function setSessionOptions( array $options ) {
691 if ( isset( $options['connTimeout'] ) ) {
692 $timeout = (int)$options['connTimeout'];
693 $this->query( "SET net_read_timeout=$timeout" );
694 $this->query( "SET net_write_timeout=$timeout" );
695 }
696 }
697
698 public function streamStatementEnd( &$sql, &$newLine ) {
699 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
700 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
701 $this->delimiter = $m[1];
702 $newLine = '';
703 }
704 return parent::streamStatementEnd( $sql, $newLine );
705 }
706
707 /**
708 * Check to see if a named lock is available. This is non-blocking.
709 *
710 * @param string $lockName name of lock to poll
711 * @param string $method name of method calling us
712 * @return Boolean
713 * @since 1.20
714 */
715 public function lockIsFree( $lockName, $method ) {
716 $lockName = $this->addQuotes( $lockName );
717 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
718 $row = $this->fetchObject( $result );
719 return ( $row->lockstatus == 1 );
720 }
721
722 /**
723 * @param $lockName string
724 * @param $method string
725 * @param $timeout int
726 * @return bool
727 */
728 public function lock( $lockName, $method, $timeout = 5 ) {
729 $lockName = $this->addQuotes( $lockName );
730 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
731 $row = $this->fetchObject( $result );
732
733 if ( $row->lockstatus == 1 ) {
734 return true;
735 } else {
736 wfDebug( __METHOD__ . " failed to acquire lock\n" );
737 return false;
738 }
739 }
740
741 /**
742 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
743 * @param $lockName string
744 * @param $method string
745 * @return bool
746 */
747 public function unlock( $lockName, $method ) {
748 $lockName = $this->addQuotes( $lockName );
749 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
750 $row = $this->fetchObject( $result );
751 return ( $row->lockstatus == 1 );
752 }
753
754 /**
755 * @param $read array
756 * @param $write array
757 * @param $method string
758 * @param $lowPriority bool
759 * @return bool
760 */
761 public function lockTables( $read, $write, $method, $lowPriority = true ) {
762 $items = array();
763
764 foreach ( $write as $table ) {
765 $tbl = $this->tableName( $table ) .
766 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
767 ' WRITE';
768 $items[] = $tbl;
769 }
770 foreach ( $read as $table ) {
771 $items[] = $this->tableName( $table ) . ' READ';
772 }
773 $sql = "LOCK TABLES " . implode( ',', $items );
774 $this->query( $sql, $method );
775 return true;
776 }
777
778 /**
779 * @param $method string
780 * @return bool
781 */
782 public function unlockTables( $method ) {
783 $this->query( "UNLOCK TABLES", $method );
784 return true;
785 }
786
787 /**
788 * Get search engine class. All subclasses of this
789 * need to implement this if they wish to use searching.
790 *
791 * @return String
792 */
793 public function getSearchEngine() {
794 return 'SearchMySQL';
795 }
796
797 /**
798 * @param bool $value
799 * @return mixed
800 */
801 public function setBigSelects( $value = true ) {
802 if ( $value === 'default' ) {
803 if ( $this->mDefaultBigSelects === null ) {
804 # Function hasn't been called before so it must already be set to the default
805 return;
806 } else {
807 $value = $this->mDefaultBigSelects;
808 }
809 } elseif ( $this->mDefaultBigSelects === null ) {
810 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
811 }
812 $encValue = $value ? '1' : '0';
813 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
814 }
815
816 /**
817 * DELETE where the condition is a join. MySql uses multi-table deletes.
818 * @param $delTable string
819 * @param $joinTable string
820 * @param $delVar string
821 * @param $joinVar string
822 * @param $conds array|string
823 * @param bool|string $fname bool
824 * @throws DBUnexpectedError
825 * @return bool|ResultWrapper
826 */
827 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
828 if ( !$conds ) {
829 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
830 }
831
832 $delTable = $this->tableName( $delTable );
833 $joinTable = $this->tableName( $joinTable );
834 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
835
836 if ( $conds != '*' ) {
837 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
838 }
839
840 return $this->query( $sql, $fname );
841 }
842
843 /**
844 * @param string $table
845 * @param array $rows
846 * @param array $uniqueIndexes
847 * @param array $set
848 * @param string $fname
849 * @param array $options
850 * @return bool
851 */
852 public function upsert(
853 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
854 ) {
855 if ( !count( $rows ) ) {
856 return true; // nothing to do
857 }
858 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
859
860 $table = $this->tableName( $table );
861 $columns = array_keys( $rows[0] );
862
863 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
864 $rowTuples = array();
865 foreach ( $rows as $row ) {
866 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
867 }
868 $sql .= implode( ',', $rowTuples );
869 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
870
871 return (bool)$this->query( $sql, $fname );
872 }
873
874 /**
875 * Determines how long the server has been up
876 *
877 * @return int
878 */
879 function getServerUptime() {
880 $vars = $this->getMysqlStatus( 'Uptime' );
881 return (int)$vars['Uptime'];
882 }
883
884 /**
885 * Determines if the last failure was due to a deadlock
886 *
887 * @return bool
888 */
889 function wasDeadlock() {
890 return $this->lastErrno() == 1213;
891 }
892
893 /**
894 * Determines if the last failure was due to a lock timeout
895 *
896 * @return bool
897 */
898 function wasLockTimeout() {
899 return $this->lastErrno() == 1205;
900 }
901
902 /**
903 * Determines if the last query error was something that should be dealt
904 * with by pinging the connection and reissuing the query
905 *
906 * @return bool
907 */
908 function wasErrorReissuable() {
909 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
910 }
911
912 /**
913 * Determines if the last failure was due to the database being read-only.
914 *
915 * @return bool
916 */
917 function wasReadOnlyError() {
918 return $this->lastErrno() == 1223 ||
919 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
920 }
921
922 /**
923 * @param $oldName
924 * @param $newName
925 * @param $temporary bool
926 * @param $fname string
927 */
928 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
929 $tmp = $temporary ? 'TEMPORARY ' : '';
930 $newName = $this->addIdentifierQuotes( $newName );
931 $oldName = $this->addIdentifierQuotes( $oldName );
932 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
933 $this->query( $query, $fname );
934 }
935
936 /**
937 * List all tables on the database
938 *
939 * @param string $prefix Only show tables with this prefix, e.g. mw_
940 * @param string $fname calling function name
941 * @return array
942 */
943 function listTables( $prefix = null, $fname = __METHOD__ ) {
944 $result = $this->query( "SHOW TABLES", $fname );
945
946 $endArray = array();
947
948 foreach ( $result as $table ) {
949 $vars = get_object_vars( $table );
950 $table = array_pop( $vars );
951
952 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
953 $endArray[] = $table;
954 }
955 }
956
957 return $endArray;
958 }
959
960 /**
961 * @param $tableName
962 * @param $fName string
963 * @return bool|ResultWrapper
964 */
965 public function dropTable( $tableName, $fName = __METHOD__ ) {
966 if ( !$this->tableExists( $tableName, $fName ) ) {
967 return false;
968 }
969 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
970 }
971
972 /**
973 * @return array
974 */
975 protected function getDefaultSchemaVars() {
976 $vars = parent::getDefaultSchemaVars();
977 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
978 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
979 return $vars;
980 }
981
982 /**
983 * Get status information from SHOW STATUS in an associative array
984 *
985 * @param $which string
986 * @return array
987 */
988 function getMysqlStatus( $which = "%" ) {
989 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
990 $status = array();
991
992 foreach ( $res as $row ) {
993 $status[$row->Variable_name] = $row->Value;
994 }
995
996 return $status;
997 }
998
999 }
1000
1001
1002
1003 /**
1004 * Utility class.
1005 * @ingroup Database
1006 */
1007 class MySQLField implements Field {
1008 private $name, $tablename, $default, $max_length, $nullable,
1009 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1010
1011 function __construct( $info ) {
1012 $this->name = $info->name;
1013 $this->tablename = $info->table;
1014 $this->default = $info->def;
1015 $this->max_length = $info->max_length;
1016 $this->nullable = !$info->not_null;
1017 $this->is_pk = $info->primary_key;
1018 $this->is_unique = $info->unique_key;
1019 $this->is_multiple = $info->multiple_key;
1020 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1021 $this->type = $info->type;
1022 $this->binary = isset( $info->binary ) ? $info->binary : false;
1023 }
1024
1025 /**
1026 * @return string
1027 */
1028 function name() {
1029 return $this->name;
1030 }
1031
1032 /**
1033 * @return string
1034 */
1035 function tableName() {
1036 return $this->tableName;
1037 }
1038
1039 /**
1040 * @return string
1041 */
1042 function type() {
1043 return $this->type;
1044 }
1045
1046 /**
1047 * @return bool
1048 */
1049 function isNullable() {
1050 return $this->nullable;
1051 }
1052
1053 function defaultValue() {
1054 return $this->default;
1055 }
1056
1057 /**
1058 * @return bool
1059 */
1060 function isKey() {
1061 return $this->is_key;
1062 }
1063
1064 /**
1065 * @return bool
1066 */
1067 function isMultipleKey() {
1068 return $this->is_multiple;
1069 }
1070
1071 function isBinary() {
1072 return $this->binary;
1073 }
1074 }
1075
1076 class MySQLMasterPos implements DBMasterPos {
1077 var $file, $pos;
1078
1079 function __construct( $file, $pos ) {
1080 $this->file = $file;
1081 $this->pos = $pos;
1082 }
1083
1084 function __toString() {
1085 // e.g db1034-bin.000976/843431247
1086 return "{$this->file}/{$this->pos}";
1087 }
1088
1089 /**
1090 * @return array|false (int, int)
1091 */
1092 protected function getCoordinates() {
1093 $m = array();
1094 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1095 return array( (int)$m[1], (int)$m[2] );
1096 }
1097 return false;
1098 }
1099
1100 function hasReached( MySQLMasterPos $pos ) {
1101 $thisPos = $this->getCoordinates();
1102 $thatPos = $pos->getCoordinates();
1103 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1104 }
1105 }