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