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