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