Change @since and @deprecated notes to 1.22
[lhc/web/wiklou.git] / includes / db / DatabaseMysqlBase.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
27 *
28 * @ingroup Database
29 * @since 1.22
30 * @see Database
31 */
32 abstract class DatabaseMysqlBase extends DatabaseBase {
33
34 /**
35 * @return string
36 */
37 function getType() {
38 return 'mysql';
39 }
40
41 /**
42 * @param $server string
43 * @param $user string
44 * @param $password string
45 * @param $dbName string
46 * @return bool
47 * @throws DBConnectionError
48 */
49 function open( $server, $user, $password, $dbName ) {
50 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
51 wfProfileIn( __METHOD__ );
52
53 # Debugging hack -- fake cluster
54 if ( $wgAllDBsAreLocalhost ) {
55 $realServer = 'localhost';
56 } else {
57 $realServer = $server;
58 }
59 $this->close();
60 $this->mServer = $server;
61 $this->mUser = $user;
62 $this->mPassword = $password;
63 $this->mDBname = $dbName;
64
65 wfProfileIn( "dbconnect-$server" );
66
67 # The kernel's default SYN retransmission period is far too slow for us,
68 # so we use a short timeout plus a manual retry. Retrying means that a small
69 # but finite rate of SYN packet loss won't cause user-visible errors.
70 $this->mConn = false;
71 $this->installErrorHandler();
72 try {
73 $this->mConn = $this->mysqlConnect( $realServer );
74 } catch (Exception $ex) {
75 wfProfileOut( "dbconnect-$server" );
76 wfProfileOut( __METHOD__ );
77 throw $ex;
78 }
79 $error = $this->restoreErrorHandler();
80
81 wfProfileOut( "dbconnect-$server" );
82
83 # Always log connection errors
84 if ( !$this->mConn ) {
85 if ( !$error ) {
86 $error = $this->lastError();
87 }
88 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
89 wfDebug( "DB connection error\n" .
90 "Server: $server, User: $user, Password: " .
91 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
92
93 wfProfileOut( __METHOD__ );
94 return $this->reportConnectionError( $error );
95 }
96
97 if ( $dbName != '' ) {
98 wfSuppressWarnings();
99 $success = $this->selectDB( $dbName );
100 wfRestoreWarnings();
101 if ( !$success ) {
102 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
103 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
104 "from client host " . wfHostname() . "\n" );
105
106 wfProfileOut( __METHOD__ );
107 return $this->reportConnectionError( "Error selecting database $dbName" );
108 }
109 }
110
111 // Tell the server we're communicating with it in UTF-8.
112 // This may engage various charset conversions.
113 if ( $wgDBmysql5 ) {
114 $this->query( 'SET NAMES utf8', __METHOD__ );
115 } else {
116 $this->query( 'SET NAMES binary', __METHOD__ );
117 }
118 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
119 if ( is_string( $wgSQLMode ) ) {
120 $mode = $this->addQuotes( $wgSQLMode );
121 $this->query( "SET sql_mode = $mode", __METHOD__ );
122 }
123
124 $this->mOpened = true;
125 wfProfileOut( __METHOD__ );
126 return true;
127 }
128
129 /**
130 * Open a connection to a MySQL server
131 *
132 * @param $realServer string
133 * @return mixed Raw connection
134 * @throws DBConnectionError
135 */
136 abstract protected function mysqlConnect( $realServer );
137
138 /**
139 * @param $res ResultWrapper
140 * @throws DBUnexpectedError
141 */
142 function freeResult( $res ) {
143 if ( $res instanceof ResultWrapper ) {
144 $res = $res->result;
145 }
146 wfSuppressWarnings();
147 $ok = $this->mysqlFreeResult( $res );
148 wfRestoreWarnings();
149 if ( !$ok ) {
150 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
151 }
152 }
153
154 /**
155 * Free result memory
156 *
157 * @param $res Raw result
158 * @return bool
159 */
160 abstract protected function mysqlFreeResult( $res );
161
162 /**
163 * @param $res ResultWrapper
164 * @return object|bool
165 * @throws DBUnexpectedError
166 */
167 function fetchObject( $res ) {
168 if ( $res instanceof ResultWrapper ) {
169 $res = $res->result;
170 }
171 wfSuppressWarnings();
172 $row = $this->mysqlFetchObject( $res );
173 wfRestoreWarnings();
174
175 $errno = $this->lastErrno();
176 // Unfortunately, mysql_fetch_object does not reset the last errno.
177 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
178 // these are the only errors mysql_fetch_object can cause.
179 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
180 if ( $errno == 2000 || $errno == 2013 ) {
181 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
182 }
183 return $row;
184 }
185
186 /**
187 * Fetch a result row as an object
188 *
189 * @param $res Raw result
190 * @return stdClass
191 */
192 abstract protected function mysqlFetchObject( $res );
193
194 /**
195 * @param $res ResultWrapper
196 * @return array|bool
197 * @throws DBUnexpectedError
198 */
199 function fetchRow( $res ) {
200 if ( $res instanceof ResultWrapper ) {
201 $res = $res->result;
202 }
203 wfSuppressWarnings();
204 $row = $this->mysqlFetchArray( $res );
205 wfRestoreWarnings();
206
207 $errno = $this->lastErrno();
208 // Unfortunately, mysql_fetch_array 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_array can cause.
211 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
212 if ( $errno == 2000 || $errno == 2013 ) {
213 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
214 }
215 return $row;
216 }
217
218 /**
219 * Fetch a result row as an associative and numeric array
220 *
221 * @param $res Raw result
222 * @return array
223 */
224 abstract protected function mysqlFetchArray( $res );
225
226 /**
227 * @throws DBUnexpectedError
228 * @param $res ResultWrapper
229 * @return int
230 */
231 function numRows( $res ) {
232 if ( $res instanceof ResultWrapper ) {
233 $res = $res->result;
234 }
235 wfSuppressWarnings();
236 $n = $this->mysqlNumRows( $res );
237 wfRestoreWarnings();
238 // Unfortunately, mysql_num_rows does not reset the last errno.
239 // We are not checking for any errors here, since
240 // these are no errors mysql_num_rows can cause.
241 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
242 // See https://bugzilla.wikimedia.org/42430
243 return $n;
244 }
245
246 /**
247 * Get number of rows in result
248 *
249 * @param $res Raw result
250 * @return int
251 */
252 abstract protected function mysqlNumRows( $res );
253
254 /**
255 * @param $res ResultWrapper
256 * @return int
257 */
258 function numFields( $res ) {
259 if ( $res instanceof ResultWrapper ) {
260 $res = $res->result;
261 }
262 return $this->mysqlNumFields( $res );
263 }
264
265 /**
266 * Get number of fields in result
267 *
268 * @param $res Raw result
269 * @return int
270 */
271 abstract protected function mysqlNumFields( $res );
272
273 /**
274 * @param $res ResultWrapper
275 * @param $n string
276 * @return string
277 */
278 function fieldName( $res, $n ) {
279 if ( $res instanceof ResultWrapper ) {
280 $res = $res->result;
281 }
282 return $this->mysqlFieldName( $res, $n );
283 }
284
285 /**
286 * Get the name of the specified field in a result
287 *
288 * @param $res Raw result
289 * @param $n int
290 * @return string
291 */
292 abstract protected function mysqlFieldName( $res, $n );
293
294 /**
295 * @param $res ResultWrapper
296 * @param $row
297 * @return bool
298 */
299 function dataSeek( $res, $row ) {
300 if ( $res instanceof ResultWrapper ) {
301 $res = $res->result;
302 }
303 return $this->mysqlDataSeek( $res, $row );
304 }
305
306 /**
307 * Move internal result pointer
308 *
309 * @param $res Raw result
310 * @param $row int
311 * @return bool
312 */
313 abstract protected function mysqlDataSeek( $res, $row );
314
315 /**
316 * @return string
317 */
318 function lastError() {
319 if ( $this->mConn ) {
320 # Even if it's non-zero, it can still be invalid
321 wfSuppressWarnings();
322 $error = $this->mysqlError( $this->mConn );
323 if ( !$error ) {
324 $error = $this->mysqlError();
325 }
326 wfRestoreWarnings();
327 } else {
328 $error = $this->mysqlError();
329 }
330 if ( $error ) {
331 $error .= ' (' . $this->mServer . ')';
332 }
333 return $error;
334 }
335
336 /**
337 * Returns the text of the error message from previous MySQL operation
338 *
339 * @param $conn Raw connection
340 * @return string
341 */
342 abstract protected function mysqlError( $conn = null );
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 = __METHOD__ ) {
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 = __METHOD__, $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 = $this->mysqlNumFields( $res->result );
396 for ( $i = 0; $i < $n; $i++ ) {
397 $meta = $this->mysqlFetchField( $res->result, $i );
398 if ( $field == $meta->name ) {
399 return new MySQLField( $meta );
400 }
401 }
402 return false;
403 }
404
405 /**
406 * Get column information from a result
407 *
408 * @param $res Raw result
409 * @param $n int
410 * @return stdClass
411 */
412 abstract protected function mysqlFetchField( $res, $n );
413
414 /**
415 * Get information about an index into an object
416 * Returns false if the index does not exist
417 *
418 * @param $table string
419 * @param $index string
420 * @param $fname string
421 * @return bool|array|null False or null on failure
422 */
423 function indexInfo( $table, $index, $fname = __METHOD__ ) {
424 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
425 # SHOW INDEX should work for 3.x and up:
426 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
427 $table = $this->tableName( $table );
428 $index = $this->indexName( $index );
429
430 $sql = 'SHOW INDEX FROM ' . $table;
431 $res = $this->query( $sql, $fname );
432
433 if ( !$res ) {
434 return null;
435 }
436
437 $result = array();
438
439 foreach ( $res as $row ) {
440 if ( $row->Key_name == $index ) {
441 $result[] = $row;
442 }
443 }
444 return empty( $result ) ? false : $result;
445 }
446
447 /**
448 * @param $s string
449 *
450 * @return string
451 */
452 function strencode( $s ) {
453 $sQuoted = $this->mysqlRealEscapeString( $s );
454
455 if ( $sQuoted === false ) {
456 $this->ping();
457 $sQuoted = $this->mysqlRealEscapeString( $s );
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 = $this->mysqlPing();
486 if ( $ping ) {
487 return true;
488 }
489
490 $this->closeConnection();
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 * Ping a server connection or reconnect if there is no connection
499 *
500 * @return bool
501 */
502 abstract protected function mysqlPing();
503
504 /**
505 * Returns slave lag.
506 *
507 * This will do a SHOW SLAVE STATUS
508 *
509 * @return int
510 */
511 function getLag() {
512 if ( !is_null( $this->mFakeSlaveLag ) ) {
513 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
514 return $this->mFakeSlaveLag;
515 }
516
517 return $this->getLagFromSlaveStatus();
518 }
519
520 /**
521 * @return bool|int
522 */
523 function getLagFromSlaveStatus() {
524 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
525 if ( !$res ) {
526 return false;
527 }
528 $row = $res->fetchObject();
529 if ( !$row ) {
530 return false;
531 }
532 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
533 return false;
534 } else {
535 return intval( $row->Seconds_Behind_Master );
536 }
537 }
538
539 /**
540 * @deprecated in 1.19, use getLagFromSlaveStatus
541 *
542 * @return bool|int
543 */
544 function getLagFromProcesslist() {
545 wfDeprecated( __METHOD__, '1.19' );
546 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
547 if ( !$res ) {
548 return false;
549 }
550 # Find slave SQL thread
551 foreach ( $res as $row ) {
552 /* This should work for most situations - when default db
553 * for thread is not specified, it had no events executed,
554 * and therefore it doesn't know yet how lagged it is.
555 *
556 * Relay log I/O thread does not select databases.
557 */
558 if ( $row->User == 'system user' &&
559 $row->State != 'Waiting for master to send event' &&
560 $row->State != 'Connecting to master' &&
561 $row->State != 'Queueing master event to the relay log' &&
562 $row->State != 'Waiting for master update' &&
563 $row->State != 'Requesting binlog dump' &&
564 $row->State != 'Waiting to reconnect after a failed master event read' &&
565 $row->State != 'Reconnecting after a failed master event read' &&
566 $row->State != 'Registering slave on master'
567 ) {
568 # This is it, return the time (except -ve)
569 if ( $row->Time > 0x7fffffff ) {
570 return false;
571 } else {
572 return $row->Time;
573 }
574 }
575 }
576 return false;
577 }
578
579 /**
580 * Wait for the slave to catch up to a given master position.
581 *
582 * @param $pos DBMasterPos object
583 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
584 * @return bool|string
585 */
586 function masterPosWait( DBMasterPos $pos, $timeout ) {
587 $fname = __METHOD__;
588 wfProfileIn( $fname );
589
590 # Commit any open transactions
591 if ( $this->mTrxLevel ) {
592 $this->commit( $fname );
593 }
594
595 if ( !is_null( $this->mFakeSlaveLag ) ) {
596 $status = parent::masterPosWait( $pos, $timeout );
597 wfProfileOut( $fname );
598 return $status;
599 }
600
601 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
602 $encFile = $this->addQuotes( $pos->file );
603 $encPos = intval( $pos->pos );
604 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
605 $res = $this->doQuery( $sql );
606
607 if ( $res && $row = $this->fetchRow( $res ) ) {
608 wfProfileOut( $fname );
609 return $row[0];
610 }
611 wfProfileOut( $fname );
612 return false;
613 }
614
615 /**
616 * Get the position of the master from SHOW SLAVE STATUS
617 *
618 * @return MySQLMasterPos|bool
619 */
620 function getSlavePos() {
621 if ( !is_null( $this->mFakeSlaveLag ) ) {
622 return parent::getSlavePos();
623 }
624
625 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
626 $row = $this->fetchObject( $res );
627
628 if ( $row ) {
629 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
630 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
631 } else {
632 return false;
633 }
634 }
635
636 /**
637 * Get the position of the master from SHOW MASTER STATUS
638 *
639 * @return MySQLMasterPos|bool
640 */
641 function getMasterPos() {
642 if ( $this->mFakeMaster ) {
643 return parent::getMasterPos();
644 }
645
646 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
647 $row = $this->fetchObject( $res );
648
649 if ( $row ) {
650 return new MySQLMasterPos( $row->File, $row->Position );
651 } else {
652 return false;
653 }
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 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 = __METHOD__ ) {
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 * @param string $table
836 * @param array $rows
837 * @param array $uniqueIndexes
838 * @param array $set
839 * @param string $fname
840 * @param array $options
841 * @return bool
842 */
843 public function upsert(
844 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
845 ) {
846 if ( !count( $rows ) ) {
847 return true; // nothing to do
848 }
849 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
850
851 $table = $this->tableName( $table );
852 $columns = array_keys( $rows[0] );
853
854 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
855 $rowTuples = array();
856 foreach ( $rows as $row ) {
857 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
858 }
859 $sql .= implode( ',', $rowTuples );
860 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
861
862 return (bool)$this->query( $sql, $fname );
863 }
864
865 /**
866 * Determines how long the server has been up
867 *
868 * @return int
869 */
870 function getServerUptime() {
871 $vars = $this->getMysqlStatus( 'Uptime' );
872 return (int)$vars['Uptime'];
873 }
874
875 /**
876 * Determines if the last failure was due to a deadlock
877 *
878 * @return bool
879 */
880 function wasDeadlock() {
881 return $this->lastErrno() == 1213;
882 }
883
884 /**
885 * Determines if the last failure was due to a lock timeout
886 *
887 * @return bool
888 */
889 function wasLockTimeout() {
890 return $this->lastErrno() == 1205;
891 }
892
893 /**
894 * Determines if the last query error was something that should be dealt
895 * with by pinging the connection and reissuing the query
896 *
897 * @return bool
898 */
899 function wasErrorReissuable() {
900 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
901 }
902
903 /**
904 * Determines if the last failure was due to the database being read-only.
905 *
906 * @return bool
907 */
908 function wasReadOnlyError() {
909 return $this->lastErrno() == 1223 ||
910 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
911 }
912
913 /**
914 * @param $oldName
915 * @param $newName
916 * @param $temporary bool
917 * @param $fname string
918 */
919 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
920 $tmp = $temporary ? 'TEMPORARY ' : '';
921 $newName = $this->addIdentifierQuotes( $newName );
922 $oldName = $this->addIdentifierQuotes( $oldName );
923 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
924 $this->query( $query, $fname );
925 }
926
927 /**
928 * List all tables on the database
929 *
930 * @param string $prefix Only show tables with this prefix, e.g. mw_
931 * @param string $fname calling function name
932 * @return array
933 */
934 function listTables( $prefix = null, $fname = __METHOD__ ) {
935 $result = $this->query( "SHOW TABLES", $fname );
936
937 $endArray = array();
938
939 foreach ( $result as $table ) {
940 $vars = get_object_vars( $table );
941 $table = array_pop( $vars );
942
943 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
944 $endArray[] = $table;
945 }
946 }
947
948 return $endArray;
949 }
950
951 /**
952 * @param $tableName
953 * @param $fName string
954 * @return bool|ResultWrapper
955 */
956 public function dropTable( $tableName, $fName = __METHOD__ ) {
957 if ( !$this->tableExists( $tableName, $fName ) ) {
958 return false;
959 }
960 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
961 }
962
963 /**
964 * @return array
965 */
966 protected function getDefaultSchemaVars() {
967 $vars = parent::getDefaultSchemaVars();
968 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
969 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
970 return $vars;
971 }
972
973 /**
974 * Get status information from SHOW STATUS in an associative array
975 *
976 * @param $which string
977 * @return array
978 */
979 function getMysqlStatus( $which = "%" ) {
980 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
981 $status = array();
982
983 foreach ( $res as $row ) {
984 $status[$row->Variable_name] = $row->Value;
985 }
986
987 return $status;
988 }
989
990 }
991
992
993
994 /**
995 * Utility class.
996 * @ingroup Database
997 */
998 class MySQLField implements Field {
999 private $name, $tablename, $default, $max_length, $nullable,
1000 $is_pk, $is_unique, $is_multiple, $is_key, $type;
1001
1002 function __construct( $info ) {
1003 $this->name = $info->name;
1004 $this->tablename = $info->table;
1005 $this->default = $info->def;
1006 $this->max_length = $info->max_length;
1007 $this->nullable = !$info->not_null;
1008 $this->is_pk = $info->primary_key;
1009 $this->is_unique = $info->unique_key;
1010 $this->is_multiple = $info->multiple_key;
1011 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1012 $this->type = $info->type;
1013 }
1014
1015 /**
1016 * @return string
1017 */
1018 function name() {
1019 return $this->name;
1020 }
1021
1022 /**
1023 * @return string
1024 */
1025 function tableName() {
1026 return $this->tableName;
1027 }
1028
1029 /**
1030 * @return string
1031 */
1032 function type() {
1033 return $this->type;
1034 }
1035
1036 /**
1037 * @return bool
1038 */
1039 function isNullable() {
1040 return $this->nullable;
1041 }
1042
1043 function defaultValue() {
1044 return $this->default;
1045 }
1046
1047 /**
1048 * @return bool
1049 */
1050 function isKey() {
1051 return $this->is_key;
1052 }
1053
1054 /**
1055 * @return bool
1056 */
1057 function isMultipleKey() {
1058 return $this->is_multiple;
1059 }
1060 }
1061
1062 class MySQLMasterPos implements DBMasterPos {
1063 var $file, $pos;
1064
1065 function __construct( $file, $pos ) {
1066 $this->file = $file;
1067 $this->pos = $pos;
1068 }
1069
1070 function __toString() {
1071 return "{$this->file}/{$this->pos}";
1072 }
1073 }