Merge "(bug 43052) dblClickEdit/rightClickEdit: Trigger ca-edit click."
[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 return $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 return $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 }
601 wfProfileOut( $fname );
602 return false;
603 }
604
605 /**
606 * Get the position of the master from SHOW SLAVE STATUS
607 *
608 * @return MySQLMasterPos|bool
609 */
610 function getSlavePos() {
611 if ( !is_null( $this->mFakeSlaveLag ) ) {
612 return parent::getSlavePos();
613 }
614
615 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
616 $row = $this->fetchObject( $res );
617
618 if ( $row ) {
619 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
620 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
621 } else {
622 return false;
623 }
624 }
625
626 /**
627 * Get the position of the master from SHOW MASTER STATUS
628 *
629 * @return MySQLMasterPos|bool
630 */
631 function getMasterPos() {
632 if ( $this->mFakeMaster ) {
633 return parent::getMasterPos();
634 }
635
636 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
637 $row = $this->fetchObject( $res );
638
639 if ( $row ) {
640 return new MySQLMasterPos( $row->File, $row->Position );
641 } else {
642 return false;
643 }
644 }
645
646 /**
647 * @return string
648 */
649 function getServerVersion() {
650 return mysql_get_server_info( $this->mConn );
651 }
652
653 /**
654 * @param $index
655 * @return string
656 */
657 function useIndexClause( $index ) {
658 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
659 }
660
661 /**
662 * @return string
663 */
664 function lowPriorityOption() {
665 return 'LOW_PRIORITY';
666 }
667
668 /**
669 * @return string
670 */
671 public static function getSoftwareLink() {
672 return '[http://www.mysql.com/ MySQL]';
673 }
674
675 /**
676 * @param $options array
677 */
678 public function setSessionOptions( array $options ) {
679 if ( isset( $options['connTimeout'] ) ) {
680 $timeout = (int)$options['connTimeout'];
681 $this->query( "SET net_read_timeout=$timeout" );
682 $this->query( "SET net_write_timeout=$timeout" );
683 }
684 }
685
686 public function streamStatementEnd( &$sql, &$newLine ) {
687 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
688 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
689 $this->delimiter = $m[1];
690 $newLine = '';
691 }
692 return parent::streamStatementEnd( $sql, $newLine );
693 }
694
695 /**
696 * Check to see if a named lock is available. This is non-blocking.
697 *
698 * @param $lockName String: name of lock to poll
699 * @param $method String: name of method calling us
700 * @return Boolean
701 * @since 1.20
702 */
703 public function lockIsFree( $lockName, $method ) {
704 $lockName = $this->addQuotes( $lockName );
705 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
706 $row = $this->fetchObject( $result );
707 return ( $row->lockstatus == 1 );
708 }
709
710 /**
711 * @param $lockName string
712 * @param $method string
713 * @param $timeout int
714 * @return bool
715 */
716 public function lock( $lockName, $method, $timeout = 5 ) {
717 $lockName = $this->addQuotes( $lockName );
718 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
719 $row = $this->fetchObject( $result );
720
721 if( $row->lockstatus == 1 ) {
722 return true;
723 } else {
724 wfDebug( __METHOD__." failed to acquire lock\n" );
725 return false;
726 }
727 }
728
729 /**
730 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
731 * @param $lockName string
732 * @param $method string
733 * @return bool
734 */
735 public function unlock( $lockName, $method ) {
736 $lockName = $this->addQuotes( $lockName );
737 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
738 $row = $this->fetchObject( $result );
739 return ( $row->lockstatus == 1 );
740 }
741
742 /**
743 * @param $read array
744 * @param $write array
745 * @param $method string
746 * @param $lowPriority bool
747 */
748 public function lockTables( $read, $write, $method, $lowPriority = true ) {
749 $items = array();
750
751 foreach( $write as $table ) {
752 $tbl = $this->tableName( $table ) .
753 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
754 ' WRITE';
755 $items[] = $tbl;
756 }
757 foreach( $read as $table ) {
758 $items[] = $this->tableName( $table ) . ' READ';
759 }
760 $sql = "LOCK TABLES " . implode( ',', $items );
761 $this->query( $sql, $method );
762 }
763
764 /**
765 * @param $method string
766 */
767 public function unlockTables( $method ) {
768 $this->query( "UNLOCK TABLES", $method );
769 }
770
771 /**
772 * Get search engine class. All subclasses of this
773 * need to implement this if they wish to use searching.
774 *
775 * @return String
776 */
777 public function getSearchEngine() {
778 return 'SearchMySQL';
779 }
780
781 /**
782 * @param bool $value
783 * @return mixed
784 */
785 public function setBigSelects( $value = true ) {
786 if ( $value === 'default' ) {
787 if ( $this->mDefaultBigSelects === null ) {
788 # Function hasn't been called before so it must already be set to the default
789 return;
790 } else {
791 $value = $this->mDefaultBigSelects;
792 }
793 } elseif ( $this->mDefaultBigSelects === null ) {
794 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
795 }
796 $encValue = $value ? '1' : '0';
797 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
798 }
799
800 /**
801 * DELETE where the condition is a join. MySql uses multi-table deletes.
802 * @param $delTable string
803 * @param $joinTable string
804 * @param $delVar string
805 * @param $joinVar string
806 * @param $conds array|string
807 * @param bool|string $fname bool
808 * @throws DBUnexpectedError
809 * @return bool|ResultWrapper
810 */
811 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
812 if ( !$conds ) {
813 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
814 }
815
816 $delTable = $this->tableName( $delTable );
817 $joinTable = $this->tableName( $joinTable );
818 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
819
820 if ( $conds != '*' ) {
821 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
822 }
823
824 return $this->query( $sql, $fname );
825 }
826
827 /**
828 * Determines how long the server has been up
829 *
830 * @return int
831 */
832 function getServerUptime() {
833 $vars = $this->getMysqlStatus( 'Uptime' );
834 return (int)$vars['Uptime'];
835 }
836
837 /**
838 * Determines if the last failure was due to a deadlock
839 *
840 * @return bool
841 */
842 function wasDeadlock() {
843 return $this->lastErrno() == 1213;
844 }
845
846 /**
847 * Determines if the last failure was due to a lock timeout
848 *
849 * @return bool
850 */
851 function wasLockTimeout() {
852 return $this->lastErrno() == 1205;
853 }
854
855 /**
856 * Determines if the last query error was something that should be dealt
857 * with by pinging the connection and reissuing the query
858 *
859 * @return bool
860 */
861 function wasErrorReissuable() {
862 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
863 }
864
865 /**
866 * Determines if the last failure was due to the database being read-only.
867 *
868 * @return bool
869 */
870 function wasReadOnlyError() {
871 return $this->lastErrno() == 1223 ||
872 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
873 }
874
875 /**
876 * @param $oldName
877 * @param $newName
878 * @param $temporary bool
879 * @param $fname string
880 */
881 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
882 $tmp = $temporary ? 'TEMPORARY ' : '';
883 $newName = $this->addIdentifierQuotes( $newName );
884 $oldName = $this->addIdentifierQuotes( $oldName );
885 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
886 $this->query( $query, $fname );
887 }
888
889 /**
890 * List all tables on the database
891 *
892 * @param $prefix string Only show tables with this prefix, e.g. mw_
893 * @param $fname String: calling function name
894 * @return array
895 */
896 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
897 $result = $this->query( "SHOW TABLES", $fname);
898
899 $endArray = array();
900
901 foreach( $result as $table ) {
902 $vars = get_object_vars($table);
903 $table = array_pop( $vars );
904
905 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
906 $endArray[] = $table;
907 }
908 }
909
910 return $endArray;
911 }
912
913 /**
914 * @param $tableName
915 * @param $fName string
916 * @return bool|ResultWrapper
917 */
918 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
919 if( !$this->tableExists( $tableName, $fName ) ) {
920 return false;
921 }
922 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
923 }
924
925 /**
926 * @return array
927 */
928 protected function getDefaultSchemaVars() {
929 $vars = parent::getDefaultSchemaVars();
930 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
931 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
932 return $vars;
933 }
934
935 /**
936 * Get status information from SHOW STATUS in an associative array
937 *
938 * @param $which string
939 * @return array
940 */
941 function getMysqlStatus( $which = "%" ) {
942 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
943 $status = array();
944
945 foreach ( $res as $row ) {
946 $status[$row->Variable_name] = $row->Value;
947 }
948
949 return $status;
950 }
951
952 }
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 }