Merge "Fix bad copy-paste error in deprecated method"
[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 = __METHOD__ ) {
352 return $this->nativeReplace( $table, $rows, $fname );
353 }
354
355 /**
356 * @param string $table
357 * @param array $rows
358 * @param array $uniqueIndexes
359 * @param array $set
360 * @param string $fname
361 * @param array $options
362 * @return bool
363 */
364 public function upsert(
365 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
366 ) {
367 if ( !count( $rows ) ) {
368 return true; // nothing to do
369 }
370 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
371
372 $table = $this->tableName( $table );
373 $columns = array_keys( $rows[0] );
374
375 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
376 $rowTuples = array();
377 foreach ( $rows as $row ) {
378 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
379 }
380 $sql .= implode( ',', $rowTuples );
381 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
382
383 return (bool)$this->query( $sql, $fname );
384 }
385
386 /**
387 * Estimate rows in dataset
388 * Returns estimated count, based on EXPLAIN output
389 * Takes same arguments as Database::select()
390 *
391 * @param $table string|array
392 * @param $vars string|array
393 * @param $conds string|array
394 * @param $fname string
395 * @param $options string|array
396 * @return int
397 */
398 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
399 $options['EXPLAIN'] = true;
400 $res = $this->select( $table, $vars, $conds, $fname, $options );
401 if ( $res === false ) {
402 return false;
403 }
404 if ( !$this->numRows( $res ) ) {
405 return 0;
406 }
407
408 $rows = 1;
409 foreach ( $res as $plan ) {
410 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
411 }
412 return $rows;
413 }
414
415 /**
416 * @param $table string
417 * @param $field string
418 * @return bool|MySQLField
419 */
420 function fieldInfo( $table, $field ) {
421 $table = $this->tableName( $table );
422 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
423 if ( !$res ) {
424 return false;
425 }
426 $n = mysql_num_fields( $res->result );
427 for ( $i = 0; $i < $n; $i++ ) {
428 $meta = mysql_fetch_field( $res->result, $i );
429 if ( $field == $meta->name ) {
430 return new MySQLField( $meta );
431 }
432 }
433 return false;
434 }
435
436 /**
437 * Get information about an index into an object
438 * Returns false if the index does not exist
439 *
440 * @param $table string
441 * @param $index string
442 * @param $fname string
443 * @return bool|array|null False or null on failure
444 */
445 function indexInfo( $table, $index, $fname = __METHOD__ ) {
446 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
447 # SHOW INDEX should work for 3.x and up:
448 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
449 $table = $this->tableName( $table );
450 $index = $this->indexName( $index );
451
452 $sql = 'SHOW INDEX FROM ' . $table;
453 $res = $this->query( $sql, $fname );
454
455 if ( !$res ) {
456 return null;
457 }
458
459 $result = array();
460
461 foreach ( $res as $row ) {
462 if ( $row->Key_name == $index ) {
463 $result[] = $row;
464 }
465 }
466 return empty( $result ) ? false : $result;
467 }
468
469 /**
470 * @param $db
471 * @return bool
472 */
473 function selectDB( $db ) {
474 $this->mDBname = $db;
475 return mysql_select_db( $db, $this->mConn );
476 }
477
478 /**
479 * @param $s string
480 *
481 * @return string
482 */
483 function strencode( $s ) {
484 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
485
486 if ( $sQuoted === false ) {
487 $this->ping();
488 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
489 }
490 return $sQuoted;
491 }
492
493 /**
494 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
495 *
496 * @param $s string
497 *
498 * @return string
499 */
500 public function addIdentifierQuotes( $s ) {
501 return "`" . $this->strencode( $s ) . "`";
502 }
503
504 /**
505 * @param $name string
506 * @return bool
507 */
508 public function isQuotedIdentifier( $name ) {
509 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
510 }
511
512 /**
513 * @return bool
514 */
515 function ping() {
516 $ping = mysql_ping( $this->mConn );
517 if ( $ping ) {
518 return true;
519 }
520
521 mysql_close( $this->mConn );
522 $this->mOpened = false;
523 $this->mConn = false;
524 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
525 return true;
526 }
527
528 /**
529 * Returns slave lag.
530 *
531 * This will do a SHOW SLAVE STATUS
532 *
533 * @return int
534 */
535 function getLag() {
536 if ( !is_null( $this->mFakeSlaveLag ) ) {
537 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
538 return $this->mFakeSlaveLag;
539 }
540
541 return $this->getLagFromSlaveStatus();
542 }
543
544 /**
545 * @return bool|int
546 */
547 function getLagFromSlaveStatus() {
548 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
549 if ( !$res ) {
550 return false;
551 }
552 $row = $res->fetchObject();
553 if ( !$row ) {
554 return false;
555 }
556 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
557 return false;
558 } else {
559 return intval( $row->Seconds_Behind_Master );
560 }
561 }
562
563 /**
564 * @deprecated in 1.19, use getLagFromSlaveStatus
565 *
566 * @return bool|int
567 */
568 function getLagFromProcesslist() {
569 wfDeprecated( __METHOD__, '1.19' );
570 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
571 if ( !$res ) {
572 return false;
573 }
574 # Find slave SQL thread
575 foreach ( $res as $row ) {
576 /* This should work for most situations - when default db
577 * for thread is not specified, it had no events executed,
578 * and therefore it doesn't know yet how lagged it is.
579 *
580 * Relay log I/O thread does not select databases.
581 */
582 if ( $row->User == 'system user' &&
583 $row->State != 'Waiting for master to send event' &&
584 $row->State != 'Connecting to master' &&
585 $row->State != 'Queueing master event to the relay log' &&
586 $row->State != 'Waiting for master update' &&
587 $row->State != 'Requesting binlog dump' &&
588 $row->State != 'Waiting to reconnect after a failed master event read' &&
589 $row->State != 'Reconnecting after a failed master event read' &&
590 $row->State != 'Registering slave on master'
591 ) {
592 # This is it, return the time (except -ve)
593 if ( $row->Time > 0x7fffffff ) {
594 return false;
595 } else {
596 return $row->Time;
597 }
598 }
599 }
600 return false;
601 }
602
603 /**
604 * Wait for the slave to catch up to a given master position.
605 *
606 * @param $pos DBMasterPos object
607 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
608 * @return bool|string
609 */
610 function masterPosWait( DBMasterPos $pos, $timeout ) {
611 $fname = __METHOD__;
612 wfProfileIn( $fname );
613
614 # Commit any open transactions
615 if ( $this->mTrxLevel ) {
616 $this->commit( $fname );
617 }
618
619 if ( !is_null( $this->mFakeSlaveLag ) ) {
620 $status = parent::masterPosWait( $pos, $timeout );
621 wfProfileOut( $fname );
622 return $status;
623 }
624
625 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
626 $encFile = $this->addQuotes( $pos->file );
627 $encPos = intval( $pos->pos );
628 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
629 $res = $this->doQuery( $sql );
630
631 if ( $res && $row = $this->fetchRow( $res ) ) {
632 wfProfileOut( $fname );
633 return $row[0];
634 }
635 wfProfileOut( $fname );
636 return false;
637 }
638
639 /**
640 * Get the position of the master from SHOW SLAVE STATUS
641 *
642 * @return MySQLMasterPos|bool
643 */
644 function getSlavePos() {
645 if ( !is_null( $this->mFakeSlaveLag ) ) {
646 return parent::getSlavePos();
647 }
648
649 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
650 $row = $this->fetchObject( $res );
651
652 if ( $row ) {
653 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
654 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
655 } else {
656 return false;
657 }
658 }
659
660 /**
661 * Get the position of the master from SHOW MASTER STATUS
662 *
663 * @return MySQLMasterPos|bool
664 */
665 function getMasterPos() {
666 if ( $this->mFakeMaster ) {
667 return parent::getMasterPos();
668 }
669
670 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
671 $row = $this->fetchObject( $res );
672
673 if ( $row ) {
674 return new MySQLMasterPos( $row->File, $row->Position );
675 } else {
676 return false;
677 }
678 }
679
680 /**
681 * @return string
682 */
683 function getServerVersion() {
684 return mysql_get_server_info( $this->mConn );
685 }
686
687 /**
688 * @param $index
689 * @return string
690 */
691 function useIndexClause( $index ) {
692 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
693 }
694
695 /**
696 * @return string
697 */
698 function lowPriorityOption() {
699 return 'LOW_PRIORITY';
700 }
701
702 /**
703 * @return string
704 */
705 public function getSoftwareLink() {
706 return '[http://www.mysql.com/ MySQL]';
707 }
708
709 /**
710 * @param $options array
711 */
712 public function setSessionOptions( array $options ) {
713 if ( isset( $options['connTimeout'] ) ) {
714 $timeout = (int)$options['connTimeout'];
715 $this->query( "SET net_read_timeout=$timeout" );
716 $this->query( "SET net_write_timeout=$timeout" );
717 }
718 }
719
720 public function streamStatementEnd( &$sql, &$newLine ) {
721 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
722 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
723 $this->delimiter = $m[1];
724 $newLine = '';
725 }
726 return parent::streamStatementEnd( $sql, $newLine );
727 }
728
729 /**
730 * Check to see if a named lock is available. This is non-blocking.
731 *
732 * @param string $lockName name of lock to poll
733 * @param string $method name of method calling us
734 * @return Boolean
735 * @since 1.20
736 */
737 public function lockIsFree( $lockName, $method ) {
738 $lockName = $this->addQuotes( $lockName );
739 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
740 $row = $this->fetchObject( $result );
741 return ( $row->lockstatus == 1 );
742 }
743
744 /**
745 * @param $lockName string
746 * @param $method string
747 * @param $timeout int
748 * @return bool
749 */
750 public function lock( $lockName, $method, $timeout = 5 ) {
751 $lockName = $this->addQuotes( $lockName );
752 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
753 $row = $this->fetchObject( $result );
754
755 if ( $row->lockstatus == 1 ) {
756 return true;
757 } else {
758 wfDebug( __METHOD__ . " failed to acquire lock\n" );
759 return false;
760 }
761 }
762
763 /**
764 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
765 * @param $lockName string
766 * @param $method string
767 * @return bool
768 */
769 public function unlock( $lockName, $method ) {
770 $lockName = $this->addQuotes( $lockName );
771 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
772 $row = $this->fetchObject( $result );
773 return ( $row->lockstatus == 1 );
774 }
775
776 /**
777 * @param $read array
778 * @param $write array
779 * @param $method string
780 * @param $lowPriority bool
781 * @return bool
782 */
783 public function lockTables( $read, $write, $method, $lowPriority = true ) {
784 $items = array();
785
786 foreach ( $write as $table ) {
787 $tbl = $this->tableName( $table ) .
788 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
789 ' WRITE';
790 $items[] = $tbl;
791 }
792 foreach ( $read as $table ) {
793 $items[] = $this->tableName( $table ) . ' READ';
794 }
795 $sql = "LOCK TABLES " . implode( ',', $items );
796 $this->query( $sql, $method );
797 return true;
798 }
799
800 /**
801 * @param $method string
802 * @return bool
803 */
804 public function unlockTables( $method ) {
805 $this->query( "UNLOCK TABLES", $method );
806 return true;
807 }
808
809 /**
810 * Get search engine class. All subclasses of this
811 * need to implement this if they wish to use searching.
812 *
813 * @return String
814 */
815 public function getSearchEngine() {
816 return 'SearchMySQL';
817 }
818
819 /**
820 * @param bool $value
821 * @return mixed
822 */
823 public function setBigSelects( $value = true ) {
824 if ( $value === 'default' ) {
825 if ( $this->mDefaultBigSelects === null ) {
826 # Function hasn't been called before so it must already be set to the default
827 return;
828 } else {
829 $value = $this->mDefaultBigSelects;
830 }
831 } elseif ( $this->mDefaultBigSelects === null ) {
832 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
833 }
834 $encValue = $value ? '1' : '0';
835 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
836 }
837
838 /**
839 * DELETE where the condition is a join. MySql uses multi-table deletes.
840 * @param $delTable string
841 * @param $joinTable string
842 * @param $delVar string
843 * @param $joinVar string
844 * @param $conds array|string
845 * @param bool|string $fname bool
846 * @throws DBUnexpectedError
847 * @return bool|ResultWrapper
848 */
849 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
850 if ( !$conds ) {
851 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
852 }
853
854 $delTable = $this->tableName( $delTable );
855 $joinTable = $this->tableName( $joinTable );
856 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
857
858 if ( $conds != '*' ) {
859 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
860 }
861
862 return $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 * Utility class.
994 * @ingroup Database
995 */
996 class MySQLField implements Field {
997 private $name, $tablename, $default, $max_length, $nullable,
998 $is_pk, $is_unique, $is_multiple, $is_key, $type;
999
1000 function __construct( $info ) {
1001 $this->name = $info->name;
1002 $this->tablename = $info->table;
1003 $this->default = $info->def;
1004 $this->max_length = $info->max_length;
1005 $this->nullable = !$info->not_null;
1006 $this->is_pk = $info->primary_key;
1007 $this->is_unique = $info->unique_key;
1008 $this->is_multiple = $info->multiple_key;
1009 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1010 $this->type = $info->type;
1011 }
1012
1013 /**
1014 * @return string
1015 */
1016 function name() {
1017 return $this->name;
1018 }
1019
1020 /**
1021 * @return string
1022 */
1023 function tableName() {
1024 return $this->tableName;
1025 }
1026
1027 /**
1028 * @return string
1029 */
1030 function type() {
1031 return $this->type;
1032 }
1033
1034 /**
1035 * @return bool
1036 */
1037 function isNullable() {
1038 return $this->nullable;
1039 }
1040
1041 function defaultValue() {
1042 return $this->default;
1043 }
1044
1045 /**
1046 * @return bool
1047 */
1048 function isKey() {
1049 return $this->is_key;
1050 }
1051
1052 /**
1053 * @return bool
1054 */
1055 function isMultipleKey() {
1056 return $this->is_multiple;
1057 }
1058 }
1059
1060 class MySQLMasterPos implements DBMasterPos {
1061 var $file, $pos;
1062
1063 function __construct( $file, $pos ) {
1064 $this->file = $file;
1065 $this->pos = $pos;
1066 }
1067
1068 function __toString() {
1069 return "{$this->file}/{$this->pos}";
1070 }
1071 }