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