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