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