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