Follow-up I0b781c11 (2a55449): use User::getAutomaticGroups().
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.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 * Inherit all methods and properties of Database::Database()
27 *
28 * @ingroup Database
29 * @see Database
30 */
31 class DatabaseMysql extends DatabaseBase {
32
33 /**
34 * @return string
35 */
36 function getType() {
37 return 'mysql';
38 }
39
40 /**
41 * @param $sql string
42 * @return resource
43 */
44 protected function doQuery( $sql ) {
45 if( $this->bufferResults() ) {
46 $ret = mysql_query( $sql, $this->mConn );
47 } else {
48 $ret = mysql_unbuffered_query( $sql, $this->mConn );
49 }
50 return $ret;
51 }
52
53 /**
54 * @param $server string
55 * @param $user string
56 * @param $password string
57 * @param $dbName string
58 * @return bool
59 * @throws DBConnectionError
60 */
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost;
63 wfProfileIn( __METHOD__ );
64
65 # Load mysql.so if we don't have it
66 wfDl( 'mysql' );
67
68 # Fail now
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if ( !function_exists( 'mysql_connect' ) ) {
71 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
72 }
73
74 # Debugging hack -- fake cluster
75 if ( $wgAllDBsAreLocalhost ) {
76 $realServer = 'localhost';
77 } else {
78 $realServer = $server;
79 }
80 $this->close();
81 $this->mServer = $server;
82 $this->mUser = $user;
83 $this->mPassword = $password;
84 $this->mDBname = $dbName;
85
86 wfProfileIn("dbconnect-$server");
87
88 # The kernel's default SYN retransmission period is far too slow for us,
89 # so we use a short timeout plus a manual retry. Retrying means that a small
90 # but finite rate of SYN packet loss won't cause user-visible errors.
91 $this->mConn = false;
92 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
93 $numAttempts = 2;
94 } else {
95 $numAttempts = 1;
96 }
97 $this->installErrorHandler();
98 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
99 if ( $i > 1 ) {
100 usleep( 1000 );
101 }
102 if ( $this->mFlags & DBO_PERSISTENT ) {
103 $this->mConn = mysql_pconnect( $realServer, $user, $password );
104 } else {
105 # Create a new connection...
106 $this->mConn = mysql_connect( $realServer, $user, $password, true );
107 }
108 #if ( $this->mConn === false ) {
109 #$iplus = $i + 1;
110 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
111 #}
112 }
113 $phpError = $this->restoreErrorHandler();
114 # Always log connection errors
115 if ( !$this->mConn ) {
116 $error = $phpError;
117 if ( !$error ) {
118 $error = $this->lastError();
119 }
120 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
121 wfDebug( "DB connection error\n" );
122 wfDebug( "Server: $server, User: $user, Password: " .
123 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
124 }
125
126 wfProfileOut("dbconnect-$server");
127
128 if ( $dbName != '' && $this->mConn !== false ) {
129 wfSuppressWarnings();
130 $success = mysql_select_db( $dbName, $this->mConn );
131 wfRestoreWarnings();
132 if ( !$success ) {
133 $error = "Error selecting database $dbName on server {$this->mServer} " .
134 "from client host " . wfHostname() . "\n";
135 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
136 wfDebug( $error );
137 }
138 } else {
139 # Delay USE query
140 $success = (bool)$this->mConn;
141 }
142
143 if ( $success ) {
144 // Tell the server we're communicating with it in UTF-8.
145 // This may engage various charset conversions.
146 global $wgDBmysql5;
147 if( $wgDBmysql5 ) {
148 $this->query( 'SET NAMES utf8', __METHOD__ );
149 } else {
150 $this->query( 'SET NAMES binary', __METHOD__ );
151 }
152 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
153 global $wgSQLMode;
154 if ( is_string( $wgSQLMode ) ) {
155 $mode = $this->addQuotes( $wgSQLMode );
156 $this->query( "SET sql_mode = $mode", __METHOD__ );
157 }
158
159 // Turn off strict mode if it is on
160 } else {
161 $this->reportConnectionError( $phpError );
162 }
163
164 $this->mOpened = $success;
165 wfProfileOut( __METHOD__ );
166 return $success;
167 }
168
169 /**
170 * @return bool
171 */
172 protected function closeConnection() {
173 return mysql_close( $this->mConn );
174 }
175
176 /**
177 * @param $res ResultWrapper
178 * @throws DBUnexpectedError
179 */
180 function freeResult( $res ) {
181 if ( $res instanceof ResultWrapper ) {
182 $res = $res->result;
183 }
184 wfSuppressWarnings();
185 $ok = mysql_free_result( $res );
186 wfRestoreWarnings();
187 if ( !$ok ) {
188 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
189 }
190 }
191
192 /**
193 * @param $res ResultWrapper
194 * @return object|stdClass
195 * @throws DBUnexpectedError
196 */
197 function fetchObject( $res ) {
198 if ( $res instanceof ResultWrapper ) {
199 $res = $res->result;
200 }
201 wfSuppressWarnings();
202 $row = mysql_fetch_object( $res );
203 wfRestoreWarnings();
204 if( $this->lastErrno() ) {
205 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
206 }
207 return $row;
208 }
209
210 /**
211 * @param $res ResultWrapper
212 * @return array
213 * @throws DBUnexpectedError
214 */
215 function fetchRow( $res ) {
216 if ( $res instanceof ResultWrapper ) {
217 $res = $res->result;
218 }
219 wfSuppressWarnings();
220 $row = mysql_fetch_array( $res );
221 wfRestoreWarnings();
222 if ( $this->lastErrno() ) {
223 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
224 }
225 return $row;
226 }
227
228 /**
229 * @throws DBUnexpectedError
230 * @param $res ResultWrapper
231 * @return int
232 */
233 function numRows( $res ) {
234 if ( $res instanceof ResultWrapper ) {
235 $res = $res->result;
236 }
237 wfSuppressWarnings();
238 $n = mysql_num_rows( $res );
239 wfRestoreWarnings();
240 if( $this->lastErrno() ) {
241 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
242 }
243 return $n;
244 }
245
246 /**
247 * @param $res ResultWrapper
248 * @return int
249 */
250 function numFields( $res ) {
251 if ( $res instanceof ResultWrapper ) {
252 $res = $res->result;
253 }
254 return mysql_num_fields( $res );
255 }
256
257 /**
258 * @param $res ResultWrapper
259 * @param $n string
260 * @return string
261 */
262 function fieldName( $res, $n ) {
263 if ( $res instanceof ResultWrapper ) {
264 $res = $res->result;
265 }
266 return mysql_field_name( $res, $n );
267 }
268
269 /**
270 * @return int
271 */
272 function insertId() {
273 return mysql_insert_id( $this->mConn );
274 }
275
276 /**
277 * @param $res ResultWrapper
278 * @param $row
279 * @return bool
280 */
281 function dataSeek( $res, $row ) {
282 if ( $res instanceof ResultWrapper ) {
283 $res = $res->result;
284 }
285 return mysql_data_seek( $res, $row );
286 }
287
288 /**
289 * @return int
290 */
291 function lastErrno() {
292 if ( $this->mConn ) {
293 return mysql_errno( $this->mConn );
294 } else {
295 return mysql_errno();
296 }
297 }
298
299 /**
300 * @return string
301 */
302 function lastError() {
303 if ( $this->mConn ) {
304 # Even if it's non-zero, it can still be invalid
305 wfSuppressWarnings();
306 $error = mysql_error( $this->mConn );
307 if ( !$error ) {
308 $error = mysql_error();
309 }
310 wfRestoreWarnings();
311 } else {
312 $error = mysql_error();
313 }
314 if( $error ) {
315 $error .= ' (' . $this->mServer . ')';
316 }
317 return $error;
318 }
319
320 /**
321 * @return int
322 */
323 function affectedRows() {
324 return mysql_affected_rows( $this->mConn );
325 }
326
327 /**
328 * @param $table string
329 * @param $uniqueIndexes
330 * @param $rows array
331 * @param $fname string
332 * @return ResultWrapper
333 */
334 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
335 return $this->nativeReplace( $table, $rows, $fname );
336 }
337
338 /**
339 * Estimate rows in dataset
340 * Returns estimated count, based on EXPLAIN output
341 * Takes same arguments as Database::select()
342 *
343 * @param $table string|array
344 * @param $vars string|array
345 * @param $conds string|array
346 * @param $fname string
347 * @param $options string|array
348 * @return int
349 */
350 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
351 $options['EXPLAIN'] = true;
352 $res = $this->select( $table, $vars, $conds, $fname, $options );
353 if ( $res === false ) {
354 return false;
355 }
356 if ( !$this->numRows( $res ) ) {
357 return 0;
358 }
359
360 $rows = 1;
361 foreach ( $res as $plan ) {
362 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
363 }
364 return $rows;
365 }
366
367 /**
368 * @param $table string
369 * @param $field string
370 * @return bool|MySQLField
371 */
372 function fieldInfo( $table, $field ) {
373 $table = $this->tableName( $table );
374 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
375 if ( !$res ) {
376 return false;
377 }
378 $n = mysql_num_fields( $res->result );
379 for( $i = 0; $i < $n; $i++ ) {
380 $meta = mysql_fetch_field( $res->result, $i );
381 if( $field == $meta->name ) {
382 return new MySQLField($meta);
383 }
384 }
385 return false;
386 }
387
388 /**
389 * Get information about an index into an object
390 * Returns false if the index does not exist
391 *
392 * @param $table string
393 * @param $index string
394 * @param $fname string
395 * @return bool|array|null False or null on failure
396 */
397 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
398 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
399 # SHOW INDEX should work for 3.x and up:
400 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
401 $table = $this->tableName( $table );
402 $index = $this->indexName( $index );
403 $sql = 'SHOW INDEX FROM ' . $table;
404 $res = $this->query( $sql, $fname );
405
406 if ( !$res ) {
407 return null;
408 }
409
410 $result = array();
411
412 foreach ( $res as $row ) {
413 if ( $row->Key_name == $index ) {
414 $result[] = $row;
415 }
416 }
417
418 return empty( $result ) ? false : $result;
419 }
420
421 /**
422 * @param $db
423 * @return bool
424 */
425 function selectDB( $db ) {
426 $this->mDBname = $db;
427 return mysql_select_db( $db, $this->mConn );
428 }
429
430 /**
431 * @param $s string
432 *
433 * @return string
434 */
435 function strencode( $s ) {
436 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
437
438 if($sQuoted === false) {
439 $this->ping();
440 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
441 }
442 return $sQuoted;
443 }
444
445 /**
446 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
447 *
448 * @param $s string
449 *
450 * @return string
451 */
452 public function addIdentifierQuotes( $s ) {
453 return "`" . $this->strencode( $s ) . "`";
454 }
455
456 /**
457 * @param $name string
458 * @return bool
459 */
460 public function isQuotedIdentifier( $name ) {
461 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
462 }
463
464 /**
465 * @return bool
466 */
467 function ping() {
468 $ping = mysql_ping( $this->mConn );
469 if ( $ping ) {
470 return true;
471 }
472
473 mysql_close( $this->mConn );
474 $this->mOpened = false;
475 $this->mConn = false;
476 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
477 return true;
478 }
479
480 /**
481 * Returns slave lag.
482 *
483 * This will do a SHOW SLAVE STATUS
484 *
485 * @return int
486 */
487 function getLag() {
488 if ( !is_null( $this->mFakeSlaveLag ) ) {
489 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
490 return $this->mFakeSlaveLag;
491 }
492
493 return $this->getLagFromSlaveStatus();
494 }
495
496 /**
497 * @return bool|int
498 */
499 function getLagFromSlaveStatus() {
500 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
501 if ( !$res ) {
502 return false;
503 }
504 $row = $res->fetchObject();
505 if ( !$row ) {
506 return false;
507 }
508 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
509 return false;
510 } else {
511 return intval( $row->Seconds_Behind_Master );
512 }
513 }
514
515 /**
516 * @deprecated in 1.19, use getLagFromSlaveStatus
517 *
518 * @return bool|int
519 */
520 function getLagFromProcesslist() {
521 wfDeprecated( __METHOD__, '1.19' );
522 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
523 if( !$res ) {
524 return false;
525 }
526 # Find slave SQL thread
527 foreach( $res as $row ) {
528 /* This should work for most situations - when default db
529 * for thread is not specified, it had no events executed,
530 * and therefore it doesn't know yet how lagged it is.
531 *
532 * Relay log I/O thread does not select databases.
533 */
534 if ( $row->User == 'system user' &&
535 $row->State != 'Waiting for master to send event' &&
536 $row->State != 'Connecting to master' &&
537 $row->State != 'Queueing master event to the relay log' &&
538 $row->State != 'Waiting for master update' &&
539 $row->State != 'Requesting binlog dump' &&
540 $row->State != 'Waiting to reconnect after a failed master event read' &&
541 $row->State != 'Reconnecting after a failed master event read' &&
542 $row->State != 'Registering slave on master'
543 ) {
544 # This is it, return the time (except -ve)
545 if ( $row->Time > 0x7fffffff ) {
546 return false;
547 } else {
548 return $row->Time;
549 }
550 }
551 }
552 return false;
553 }
554
555 /**
556 * Wait for the slave to catch up to a given master position.
557 *
558 * @param $pos DBMasterPos object
559 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
560 * @return bool|string
561 */
562 function masterPosWait( DBMasterPos $pos, $timeout ) {
563 $fname = 'DatabaseBase::masterPosWait';
564 wfProfileIn( $fname );
565
566 # Commit any open transactions
567 if ( $this->mTrxLevel ) {
568 $this->commit( __METHOD__ );
569 }
570
571 if ( !is_null( $this->mFakeSlaveLag ) ) {
572 $status = parent::masterPosWait( $pos, $timeout );
573 wfProfileOut( $fname );
574 return $status;
575 }
576
577 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
578 $encFile = $this->addQuotes( $pos->file );
579 $encPos = intval( $pos->pos );
580 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
581 $res = $this->doQuery( $sql );
582
583 if ( $res && $row = $this->fetchRow( $res ) ) {
584 wfProfileOut( $fname );
585 return $row[0];
586 } else {
587 wfProfileOut( $fname );
588 return false;
589 }
590 }
591
592 /**
593 * Get the position of the master from SHOW SLAVE STATUS
594 *
595 * @return MySQLMasterPos|bool
596 */
597 function getSlavePos() {
598 if ( !is_null( $this->mFakeSlaveLag ) ) {
599 return parent::getSlavePos();
600 }
601
602 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
603 $row = $this->fetchObject( $res );
604
605 if ( $row ) {
606 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
607 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
608 } else {
609 return false;
610 }
611 }
612
613 /**
614 * Get the position of the master from SHOW MASTER STATUS
615 *
616 * @return MySQLMasterPos|bool
617 */
618 function getMasterPos() {
619 if ( $this->mFakeMaster ) {
620 return parent::getMasterPos();
621 }
622
623 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
624 $row = $this->fetchObject( $res );
625
626 if ( $row ) {
627 return new MySQLMasterPos( $row->File, $row->Position );
628 } else {
629 return false;
630 }
631 }
632
633 /**
634 * @return string
635 */
636 function getServerVersion() {
637 return mysql_get_server_info( $this->mConn );
638 }
639
640 /**
641 * @param $index
642 * @return string
643 */
644 function useIndexClause( $index ) {
645 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
646 }
647
648 /**
649 * @return string
650 */
651 function lowPriorityOption() {
652 return 'LOW_PRIORITY';
653 }
654
655 /**
656 * @return string
657 */
658 public static function getSoftwareLink() {
659 return '[http://www.mysql.com/ MySQL]';
660 }
661
662 /**
663 * @return bool
664 */
665 function standardSelectDistinct() {
666 return false;
667 }
668
669 /**
670 * @param $options array
671 */
672 public function setSessionOptions( array $options ) {
673 if ( isset( $options['connTimeout'] ) ) {
674 $timeout = (int)$options['connTimeout'];
675 $this->query( "SET net_read_timeout=$timeout" );
676 $this->query( "SET net_write_timeout=$timeout" );
677 }
678 }
679
680 public function streamStatementEnd( &$sql, &$newLine ) {
681 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
682 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
683 $this->delimiter = $m[1];
684 $newLine = '';
685 }
686 return parent::streamStatementEnd( $sql, $newLine );
687 }
688
689 /**
690 * Check to see if a named lock is available. This is non-blocking.
691 *
692 * @param $lockName String: name of lock to poll
693 * @param $method String: name of method calling us
694 * @return Boolean
695 * @since 1.20
696 */
697 public function lockIsFree( $lockName, $method ) {
698 $lockName = $this->addQuotes( $lockName );
699 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
700 $row = $this->fetchObject( $result );
701 return ( $row->lockstatus == 1 );
702 }
703
704 /**
705 * @param $lockName string
706 * @param $method string
707 * @param $timeout int
708 * @return bool
709 */
710 public function lock( $lockName, $method, $timeout = 5 ) {
711 $lockName = $this->addQuotes( $lockName );
712 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
713 $row = $this->fetchObject( $result );
714
715 if( $row->lockstatus == 1 ) {
716 return true;
717 } else {
718 wfDebug( __METHOD__." failed to acquire lock\n" );
719 return false;
720 }
721 }
722
723 /**
724 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
725 * @param $lockName string
726 * @param $method string
727 * @return bool
728 */
729 public function unlock( $lockName, $method ) {
730 $lockName = $this->addQuotes( $lockName );
731 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
732 $row = $this->fetchObject( $result );
733 return ( $row->lockstatus == 1 );
734 }
735
736 /**
737 * @param $read array
738 * @param $write array
739 * @param $method string
740 * @param $lowPriority bool
741 */
742 public function lockTables( $read, $write, $method, $lowPriority = true ) {
743 $items = array();
744
745 foreach( $write as $table ) {
746 $tbl = $this->tableName( $table ) .
747 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
748 ' WRITE';
749 $items[] = $tbl;
750 }
751 foreach( $read as $table ) {
752 $items[] = $this->tableName( $table ) . ' READ';
753 }
754 $sql = "LOCK TABLES " . implode( ',', $items );
755 $this->query( $sql, $method );
756 }
757
758 /**
759 * @param $method string
760 */
761 public function unlockTables( $method ) {
762 $this->query( "UNLOCK TABLES", $method );
763 }
764
765 /**
766 * Get search engine class. All subclasses of this
767 * need to implement this if they wish to use searching.
768 *
769 * @return String
770 */
771 public function getSearchEngine() {
772 return 'SearchMySQL';
773 }
774
775 /**
776 * @param bool $value
777 * @return mixed
778 */
779 public function setBigSelects( $value = true ) {
780 if ( $value === 'default' ) {
781 if ( $this->mDefaultBigSelects === null ) {
782 # Function hasn't been called before so it must already be set to the default
783 return;
784 } else {
785 $value = $this->mDefaultBigSelects;
786 }
787 } elseif ( $this->mDefaultBigSelects === null ) {
788 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
789 }
790 $encValue = $value ? '1' : '0';
791 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
792 }
793
794 /**
795 * DELETE where the condition is a join. MySql uses multi-table deletes.
796 * @param $delTable string
797 * @param $joinTable string
798 * @param $delVar string
799 * @param $joinVar string
800 * @param $conds array|string
801 * @param $fname bool
802 * @return bool|ResultWrapper
803 */
804 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
805 if ( !$conds ) {
806 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
807 }
808
809 $delTable = $this->tableName( $delTable );
810 $joinTable = $this->tableName( $joinTable );
811 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
812
813 if ( $conds != '*' ) {
814 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
815 }
816
817 return $this->query( $sql, $fname );
818 }
819
820 /**
821 * Determines how long the server has been up
822 *
823 * @return int
824 */
825 function getServerUptime() {
826 $vars = $this->getMysqlStatus( 'Uptime' );
827 return (int)$vars['Uptime'];
828 }
829
830 /**
831 * Determines if the last failure was due to a deadlock
832 *
833 * @return bool
834 */
835 function wasDeadlock() {
836 return $this->lastErrno() == 1213;
837 }
838
839 /**
840 * Determines if the last failure was due to a lock timeout
841 *
842 * @return bool
843 */
844 function wasLockTimeout() {
845 return $this->lastErrno() == 1205;
846 }
847
848 /**
849 * Determines if the last query error was something that should be dealt
850 * with by pinging the connection and reissuing the query
851 *
852 * @return bool
853 */
854 function wasErrorReissuable() {
855 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
856 }
857
858 /**
859 * Determines if the last failure was due to the database being read-only.
860 *
861 * @return bool
862 */
863 function wasReadOnlyError() {
864 return $this->lastErrno() == 1223 ||
865 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
866 }
867
868 /**
869 * @param $oldName
870 * @param $newName
871 * @param $temporary bool
872 * @param $fname string
873 */
874 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
875 $tmp = $temporary ? 'TEMPORARY ' : '';
876 $newName = $this->addIdentifierQuotes( $newName );
877 $oldName = $this->addIdentifierQuotes( $oldName );
878 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
879 $this->query( $query, $fname );
880 }
881
882 /**
883 * List all tables on the database
884 *
885 * @param $prefix string Only show tables with this prefix, e.g. mw_
886 * @param $fname String: calling function name
887 * @return array
888 */
889 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
890 $result = $this->query( "SHOW TABLES", $fname);
891
892 $endArray = array();
893
894 foreach( $result as $table ) {
895 $vars = get_object_vars($table);
896 $table = array_pop( $vars );
897
898 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
899 $endArray[] = $table;
900 }
901 }
902
903 return $endArray;
904 }
905
906 /**
907 * @param $tableName
908 * @param $fName string
909 * @return bool|ResultWrapper
910 */
911 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
912 if( !$this->tableExists( $tableName, $fName ) ) {
913 return false;
914 }
915 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
916 }
917
918 /**
919 * @return array
920 */
921 protected function getDefaultSchemaVars() {
922 $vars = parent::getDefaultSchemaVars();
923 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
924 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
925 return $vars;
926 }
927
928 /**
929 * Get status information from SHOW STATUS in an associative array
930 *
931 * @param $which string
932 * @return array
933 */
934 function getMysqlStatus( $which = "%" ) {
935 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
936 $status = array();
937
938 foreach ( $res as $row ) {
939 $status[$row->Variable_name] = $row->Value;
940 }
941
942 return $status;
943 }
944
945 }
946
947 /**
948 * Legacy support: Database == DatabaseMysql
949 *
950 * @deprecated in 1.16
951 */
952 class Database extends DatabaseMysql {}
953
954 /**
955 * Utility class.
956 * @ingroup Database
957 */
958 class MySQLField implements Field {
959 private $name, $tablename, $default, $max_length, $nullable,
960 $is_pk, $is_unique, $is_multiple, $is_key, $type;
961
962 function __construct ( $info ) {
963 $this->name = $info->name;
964 $this->tablename = $info->table;
965 $this->default = $info->def;
966 $this->max_length = $info->max_length;
967 $this->nullable = !$info->not_null;
968 $this->is_pk = $info->primary_key;
969 $this->is_unique = $info->unique_key;
970 $this->is_multiple = $info->multiple_key;
971 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
972 $this->type = $info->type;
973 }
974
975 /**
976 * @return string
977 */
978 function name() {
979 return $this->name;
980 }
981
982 /**
983 * @return string
984 */
985 function tableName() {
986 return $this->tableName;
987 }
988
989 /**
990 * @return string
991 */
992 function type() {
993 return $this->type;
994 }
995
996 /**
997 * @return bool
998 */
999 function isNullable() {
1000 return $this->nullable;
1001 }
1002
1003 function defaultValue() {
1004 return $this->default;
1005 }
1006
1007 /**
1008 * @return bool
1009 */
1010 function isKey() {
1011 return $this->is_key;
1012 }
1013
1014 /**
1015 * @return bool
1016 */
1017 function isMultipleKey() {
1018 return $this->is_multiple;
1019 }
1020 }
1021
1022 class MySQLMasterPos implements DBMasterPos {
1023 var $file, $pos;
1024
1025 function __construct( $file, $pos ) {
1026 $this->file = $file;
1027 $this->pos = $pos;
1028 }
1029
1030 function __toString() {
1031 return "{$this->file}/{$this->pos}";
1032 }
1033 }