database: Small DB class cleanups
[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 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35
36 /** @var null|int */
37 protected $mFakeSlaveLag = null;
38
39 protected $mFakeMaster = false;
40
41 /** @var string|null */
42 private $serverVersion = null;
43
44 /**
45 * @return string
46 */
47 function getType() {
48 return 'mysql';
49 }
50
51 /**
52 * @param string $server
53 * @param string $user
54 * @param string $password
55 * @param string $dbName
56 * @throws Exception|DBConnectionError
57 * @return bool
58 */
59 function open( $server, $user, $password, $dbName ) {
60 global $wgAllDBsAreLocalhost, $wgSQLMode;
61
62 # Close/unset connection handle
63 $this->close();
64
65 # Debugging hack -- fake cluster
66 $realServer = $wgAllDBsAreLocalhost ? 'localhost' : $server;
67 $this->mServer = $server;
68 $this->mUser = $user;
69 $this->mPassword = $password;
70 $this->mDBname = $dbName;
71
72 $this->installErrorHandler();
73 try {
74 $this->mConn = $this->mysqlConnect( $realServer );
75 } catch ( Exception $ex ) {
76 $this->restoreErrorHandler();
77 throw $ex;
78 }
79 $error = $this->restoreErrorHandler();
80
81 # Always log connection errors
82 if ( !$this->mConn ) {
83 if ( !$error ) {
84 $error = $this->lastError();
85 }
86 wfLogDBError(
87 "Error connecting to {db_server}: {error}",
88 $this->getLogContext( array(
89 'method' => __METHOD__,
90 'error' => $error,
91 ) )
92 );
93 wfDebug( "DB connection error\n" .
94 "Server: $server, User: $user, Password: " .
95 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
96
97 $this->reportConnectionError( $error );
98 }
99
100 if ( $dbName != '' ) {
101 MediaWiki\suppressWarnings();
102 $success = $this->selectDB( $dbName );
103 MediaWiki\restoreWarnings();
104 if ( !$success ) {
105 wfLogDBError(
106 "Error selecting database {db_name} on server {db_server}",
107 $this->getLogContext( array(
108 'method' => __METHOD__,
109 ) )
110 );
111 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
112 "from client host " . wfHostname() . "\n" );
113
114 $this->reportConnectionError( "Error selecting database $dbName" );
115 }
116 }
117
118 // Tell the server what we're communicating with
119 if ( !$this->connectInitCharset() ) {
120 $this->reportConnectionError( "Error setting character set" );
121 }
122
123 // Abstract over any insane MySQL defaults
124 $set = array( 'group_concat_max_len = 262144' );
125 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
126 if ( is_string( $wgSQLMode ) ) {
127 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
128 }
129 // Set any custom settings defined by site config
130 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
131 foreach ( $this->mSessionVars as $var => $val ) {
132 // Escape strings but not numbers to avoid MySQL complaining
133 if ( !is_int( $val ) && !is_float( $val ) ) {
134 $val = $this->addQuotes( $val );
135 }
136 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
137 }
138
139 if ( $set ) {
140 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
141 $success = $this->doQuery( 'SET ' . implode( ', ', $set ), __METHOD__ );
142 if ( !$success ) {
143 wfLogDBError(
144 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
145 $this->getLogContext( array(
146 'method' => __METHOD__,
147 ) )
148 );
149 $this->reportConnectionError(
150 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
151 }
152 }
153
154 $this->mOpened = true;
155
156 return true;
157 }
158
159 /**
160 * Set the character set information right after connection
161 * @return bool
162 */
163 protected function connectInitCharset() {
164 global $wgDBmysql5;
165
166 if ( $wgDBmysql5 ) {
167 // Tell the server we're communicating with it in UTF-8.
168 // This may engage various charset conversions.
169 return $this->mysqlSetCharset( 'utf8' );
170 } else {
171 return $this->mysqlSetCharset( 'binary' );
172 }
173 }
174
175 /**
176 * Open a connection to a MySQL server
177 *
178 * @param string $realServer
179 * @return mixed Raw connection
180 * @throws DBConnectionError
181 */
182 abstract protected function mysqlConnect( $realServer );
183
184 /**
185 * Set the character set of the MySQL link
186 *
187 * @param string $charset
188 * @return bool
189 */
190 abstract protected function mysqlSetCharset( $charset );
191
192 /**
193 * @param ResultWrapper|resource $res
194 * @throws DBUnexpectedError
195 */
196 function freeResult( $res ) {
197 if ( $res instanceof ResultWrapper ) {
198 $res = $res->result;
199 }
200 MediaWiki\suppressWarnings();
201 $ok = $this->mysqlFreeResult( $res );
202 MediaWiki\restoreWarnings();
203 if ( !$ok ) {
204 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
205 }
206 }
207
208 /**
209 * Free result memory
210 *
211 * @param resource $res Raw result
212 * @return bool
213 */
214 abstract protected function mysqlFreeResult( $res );
215
216 /**
217 * @param ResultWrapper|resource $res
218 * @return stdClass|bool
219 * @throws DBUnexpectedError
220 */
221 function fetchObject( $res ) {
222 if ( $res instanceof ResultWrapper ) {
223 $res = $res->result;
224 }
225 MediaWiki\suppressWarnings();
226 $row = $this->mysqlFetchObject( $res );
227 MediaWiki\restoreWarnings();
228
229 $errno = $this->lastErrno();
230 // Unfortunately, mysql_fetch_object does not reset the last errno.
231 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
232 // these are the only errors mysql_fetch_object can cause.
233 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
234 if ( $errno == 2000 || $errno == 2013 ) {
235 throw new DBUnexpectedError(
236 $this,
237 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
238 );
239 }
240
241 return $row;
242 }
243
244 /**
245 * Fetch a result row as an object
246 *
247 * @param resource $res Raw result
248 * @return stdClass
249 */
250 abstract protected function mysqlFetchObject( $res );
251
252 /**
253 * @param ResultWrapper|resource $res
254 * @return array|bool
255 * @throws DBUnexpectedError
256 */
257 function fetchRow( $res ) {
258 if ( $res instanceof ResultWrapper ) {
259 $res = $res->result;
260 }
261 MediaWiki\suppressWarnings();
262 $row = $this->mysqlFetchArray( $res );
263 MediaWiki\restoreWarnings();
264
265 $errno = $this->lastErrno();
266 // Unfortunately, mysql_fetch_array does not reset the last errno.
267 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
268 // these are the only errors mysql_fetch_array can cause.
269 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
270 if ( $errno == 2000 || $errno == 2013 ) {
271 throw new DBUnexpectedError(
272 $this,
273 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
274 );
275 }
276
277 return $row;
278 }
279
280 /**
281 * Fetch a result row as an associative and numeric array
282 *
283 * @param resource $res Raw result
284 * @return array
285 */
286 abstract protected function mysqlFetchArray( $res );
287
288 /**
289 * @throws DBUnexpectedError
290 * @param ResultWrapper|resource $res
291 * @return int
292 */
293 function numRows( $res ) {
294 if ( $res instanceof ResultWrapper ) {
295 $res = $res->result;
296 }
297 MediaWiki\suppressWarnings();
298 $n = $this->mysqlNumRows( $res );
299 MediaWiki\restoreWarnings();
300
301 // Unfortunately, mysql_num_rows does not reset the last errno.
302 // We are not checking for any errors here, since
303 // these are no errors mysql_num_rows can cause.
304 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
305 // See https://bugzilla.wikimedia.org/42430
306 return $n;
307 }
308
309 /**
310 * Get number of rows in result
311 *
312 * @param resource $res Raw result
313 * @return int
314 */
315 abstract protected function mysqlNumRows( $res );
316
317 /**
318 * @param ResultWrapper|resource $res
319 * @return int
320 */
321 function numFields( $res ) {
322 if ( $res instanceof ResultWrapper ) {
323 $res = $res->result;
324 }
325
326 return $this->mysqlNumFields( $res );
327 }
328
329 /**
330 * Get number of fields in result
331 *
332 * @param resource $res Raw result
333 * @return int
334 */
335 abstract protected function mysqlNumFields( $res );
336
337 /**
338 * @param ResultWrapper|resource $res
339 * @param int $n
340 * @return string
341 */
342 function fieldName( $res, $n ) {
343 if ( $res instanceof ResultWrapper ) {
344 $res = $res->result;
345 }
346
347 return $this->mysqlFieldName( $res, $n );
348 }
349
350 /**
351 * Get the name of the specified field in a result
352 *
353 * @param ResultWrapper|resource $res
354 * @param int $n
355 * @return string
356 */
357 abstract protected function mysqlFieldName( $res, $n );
358
359 /**
360 * mysql_field_type() wrapper
361 * @param ResultWrapper|resource $res
362 * @param int $n
363 * @return string
364 */
365 public function fieldType( $res, $n ) {
366 if ( $res instanceof ResultWrapper ) {
367 $res = $res->result;
368 }
369
370 return $this->mysqlFieldType( $res, $n );
371 }
372
373 /**
374 * Get the type of the specified field in a result
375 *
376 * @param ResultWrapper|resource $res
377 * @param int $n
378 * @return string
379 */
380 abstract protected function mysqlFieldType( $res, $n );
381
382 /**
383 * @param ResultWrapper|resource $res
384 * @param int $row
385 * @return bool
386 */
387 function dataSeek( $res, $row ) {
388 if ( $res instanceof ResultWrapper ) {
389 $res = $res->result;
390 }
391
392 return $this->mysqlDataSeek( $res, $row );
393 }
394
395 /**
396 * Move internal result pointer
397 *
398 * @param ResultWrapper|resource $res
399 * @param int $row
400 * @return bool
401 */
402 abstract protected function mysqlDataSeek( $res, $row );
403
404 /**
405 * @return string
406 */
407 function lastError() {
408 if ( $this->mConn ) {
409 # Even if it's non-zero, it can still be invalid
410 MediaWiki\suppressWarnings();
411 $error = $this->mysqlError( $this->mConn );
412 if ( !$error ) {
413 $error = $this->mysqlError();
414 }
415 MediaWiki\restoreWarnings();
416 } else {
417 $error = $this->mysqlError();
418 }
419 if ( $error ) {
420 $error .= ' (' . $this->mServer . ')';
421 }
422
423 return $error;
424 }
425
426 /**
427 * Returns the text of the error message from previous MySQL operation
428 *
429 * @param resource $conn Raw connection
430 * @return string
431 */
432 abstract protected function mysqlError( $conn = null );
433
434 /**
435 * @param string $table
436 * @param array $uniqueIndexes
437 * @param array $rows
438 * @param string $fname
439 * @return ResultWrapper
440 */
441 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
442 return $this->nativeReplace( $table, $rows, $fname );
443 }
444
445 /**
446 * Estimate rows in dataset
447 * Returns estimated count, based on EXPLAIN output
448 * Takes same arguments as Database::select()
449 *
450 * @param string|array $table
451 * @param string|array $vars
452 * @param string|array $conds
453 * @param string $fname
454 * @param string|array $options
455 * @return bool|int
456 */
457 public function estimateRowCount( $table, $vars = '*', $conds = '',
458 $fname = __METHOD__, $options = array()
459 ) {
460 $options['EXPLAIN'] = true;
461 $res = $this->select( $table, $vars, $conds, $fname, $options );
462 if ( $res === false ) {
463 return false;
464 }
465 if ( !$this->numRows( $res ) ) {
466 return 0;
467 }
468
469 $rows = 1;
470 foreach ( $res as $plan ) {
471 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
472 }
473
474 return (int)$rows;
475 }
476
477 /**
478 * @param string $table
479 * @param string $field
480 * @return bool|MySQLField
481 */
482 function fieldInfo( $table, $field ) {
483 $table = $this->tableName( $table );
484 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
485 if ( !$res ) {
486 return false;
487 }
488 $n = $this->mysqlNumFields( $res->result );
489 for ( $i = 0; $i < $n; $i++ ) {
490 $meta = $this->mysqlFetchField( $res->result, $i );
491 if ( $field == $meta->name ) {
492 return new MySQLField( $meta );
493 }
494 }
495
496 return false;
497 }
498
499 /**
500 * Get column information from a result
501 *
502 * @param resource $res Raw result
503 * @param int $n
504 * @return stdClass
505 */
506 abstract protected function mysqlFetchField( $res, $n );
507
508 /**
509 * Get information about an index into an object
510 * Returns false if the index does not exist
511 *
512 * @param string $table
513 * @param string $index
514 * @param string $fname
515 * @return bool|array|null False or null on failure
516 */
517 function indexInfo( $table, $index, $fname = __METHOD__ ) {
518 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
519 # SHOW INDEX should work for 3.x and up:
520 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
521 $table = $this->tableName( $table );
522 $index = $this->indexName( $index );
523
524 $sql = 'SHOW INDEX FROM ' . $table;
525 $res = $this->query( $sql, $fname );
526
527 if ( !$res ) {
528 return null;
529 }
530
531 $result = array();
532
533 foreach ( $res as $row ) {
534 if ( $row->Key_name == $index ) {
535 $result[] = $row;
536 }
537 }
538
539 return empty( $result ) ? false : $result;
540 }
541
542 /**
543 * @param string $s
544 * @return string
545 */
546 function strencode( $s ) {
547 $sQuoted = $this->mysqlRealEscapeString( $s );
548
549 if ( $sQuoted === false ) {
550 $this->ping();
551 $sQuoted = $this->mysqlRealEscapeString( $s );
552 }
553
554 return $sQuoted;
555 }
556
557 /**
558 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
559 *
560 * @param string $s
561 * @return string
562 */
563 public function addIdentifierQuotes( $s ) {
564 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
565 // Remove NUL bytes and escape backticks by doubling
566 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
567 }
568
569 /**
570 * @param string $name
571 * @return bool
572 */
573 public function isQuotedIdentifier( $name ) {
574 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
575 }
576
577 /**
578 * @return bool
579 */
580 function ping() {
581 $ping = $this->mysqlPing();
582 if ( $ping ) {
583 return true;
584 }
585
586 $this->closeConnection();
587 $this->mOpened = false;
588 $this->mConn = false;
589 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
590
591 return true;
592 }
593
594 /**
595 * Ping a server connection or reconnect if there is no connection
596 *
597 * @return bool
598 */
599 abstract protected function mysqlPing();
600
601 /**
602 * Set lag time in seconds for a fake slave
603 *
604 * @param int $lag
605 */
606 public function setFakeSlaveLag( $lag ) {
607 $this->mFakeSlaveLag = $lag;
608 }
609
610 /**
611 * Make this connection a fake master
612 *
613 * @param bool $enabled
614 */
615 public function setFakeMaster( $enabled = true ) {
616 $this->mFakeMaster = $enabled;
617 }
618
619 /**
620 * Returns slave lag.
621 *
622 * This will do a SHOW SLAVE STATUS
623 *
624 * @return int
625 */
626 function getLag() {
627 if ( !is_null( $this->mFakeSlaveLag ) ) {
628 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
629
630 return $this->mFakeSlaveLag;
631 }
632
633 return $this->getLagFromSlaveStatus();
634 }
635
636 /**
637 * @return bool|int
638 */
639 function getLagFromSlaveStatus() {
640 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
641 if ( !$res ) {
642 return false;
643 }
644 $row = $res->fetchObject();
645 if ( !$row ) {
646 return false;
647 }
648 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
649 return false;
650 } else {
651 return intval( $row->Seconds_Behind_Master );
652 }
653 }
654
655 /**
656 * Wait for the slave to catch up to a given master position.
657 * @todo Return values for this and base class are rubbish
658 *
659 * @param DBMasterPos|MySQLMasterPos $pos
660 * @param int $timeout The maximum number of seconds to wait for synchronisation
661 * @return int Zero if the slave was past that position already,
662 * greater than zero if we waited for some period of time, less than
663 * zero if we timed out.
664 */
665 function masterPosWait( DBMasterPos $pos, $timeout ) {
666 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
667 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
668 }
669
670 # Commit any open transactions
671 $this->commit( __METHOD__, 'flush' );
672
673 if ( !is_null( $this->mFakeSlaveLag ) ) {
674 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
675
676 if ( $wait > $timeout * 1e6 ) {
677 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
678
679 return -1;
680 } elseif ( $wait > 0 ) {
681 wfDebug( "Fake slave waiting $wait us\n" );
682 usleep( $wait );
683
684 return 1;
685 } else {
686 wfDebug( "Fake slave up to date ($wait us)\n" );
687
688 return 0;
689 }
690 }
691
692 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
693 $encFile = $this->addQuotes( $pos->file );
694 $encPos = intval( $pos->pos );
695 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
696 $res = $this->doQuery( $sql );
697
698 $status = false;
699 if ( $res && $row = $this->fetchRow( $res ) ) {
700 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
701 if ( ctype_digit( $status ) ) { // success
702 $this->lastKnownSlavePos = $pos;
703 }
704 }
705
706 return $status;
707 }
708
709 /**
710 * Get the position of the master from SHOW SLAVE STATUS
711 *
712 * @return MySQLMasterPos|bool
713 */
714 function getSlavePos() {
715 if ( !is_null( $this->mFakeSlaveLag ) ) {
716 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
717 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
718
719 return $pos;
720 }
721
722 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
723 $row = $this->fetchObject( $res );
724
725 if ( $row ) {
726 $pos = isset( $row->Exec_master_log_pos )
727 ? $row->Exec_master_log_pos
728 : $row->Exec_Master_Log_Pos;
729
730 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
731 } else {
732 return false;
733 }
734 }
735
736 /**
737 * Get the position of the master from SHOW MASTER STATUS
738 *
739 * @return MySQLMasterPos|bool
740 */
741 function getMasterPos() {
742 if ( $this->mFakeMaster ) {
743 return new MySQLMasterPos( 'fake', microtime( true ) );
744 }
745
746 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
747 $row = $this->fetchObject( $res );
748
749 if ( $row ) {
750 return new MySQLMasterPos( $row->File, $row->Position );
751 } else {
752 return false;
753 }
754 }
755
756 /**
757 * @param string $index
758 * @return string
759 */
760 function useIndexClause( $index ) {
761 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
762 }
763
764 /**
765 * @return string
766 */
767 function lowPriorityOption() {
768 return 'LOW_PRIORITY';
769 }
770
771 /**
772 * @return string
773 */
774 public function getSoftwareLink() {
775 // MariaDB includes its name in its version string; this is how MariaDB's version of
776 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
777 // in libmysql/libmysql.c).
778 $version = $this->getServerVersion();
779 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
780 return '[{{int:version-db-mariadb-url}} MariaDB]';
781 }
782
783 // Percona Server's version suffix is not very distinctive, and @@version_comment
784 // doesn't give the necessary info for source builds, so assume the server is MySQL.
785 // (Even Percona's version of mysql doesn't try to make the distinction.)
786 return '[{{int:version-db-mysql-url}} MySQL]';
787 }
788
789 /**
790 * @return string
791 */
792 public function getServerVersion() {
793 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
794 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
795 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
796 if ( $this->serverVersion === null ) {
797 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
798 }
799 return $this->serverVersion;
800 }
801
802 /**
803 * @param array $options
804 */
805 public function setSessionOptions( array $options ) {
806 if ( isset( $options['connTimeout'] ) ) {
807 $timeout = (int)$options['connTimeout'];
808 $this->query( "SET net_read_timeout=$timeout" );
809 $this->query( "SET net_write_timeout=$timeout" );
810 }
811 }
812
813 /**
814 * @param string $sql
815 * @param string $newLine
816 * @return bool
817 */
818 public function streamStatementEnd( &$sql, &$newLine ) {
819 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
820 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
821 $this->delimiter = $m[1];
822 $newLine = '';
823 }
824
825 return parent::streamStatementEnd( $sql, $newLine );
826 }
827
828 /**
829 * Check to see if a named lock is available. This is non-blocking.
830 *
831 * @param string $lockName Name of lock to poll
832 * @param string $method Name of method calling us
833 * @return bool
834 * @since 1.20
835 */
836 public function lockIsFree( $lockName, $method ) {
837 $lockName = $this->addQuotes( $lockName );
838 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
839 $row = $this->fetchObject( $result );
840
841 return ( $row->lockstatus == 1 );
842 }
843
844 /**
845 * @param string $lockName
846 * @param string $method
847 * @param int $timeout
848 * @return bool
849 */
850 public function lock( $lockName, $method, $timeout = 5 ) {
851 $lockName = $this->addQuotes( $lockName );
852 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
853 $row = $this->fetchObject( $result );
854
855 if ( $row->lockstatus == 1 ) {
856 return true;
857 } else {
858 wfDebug( __METHOD__ . " failed to acquire lock\n" );
859
860 return false;
861 }
862 }
863
864 /**
865 * FROM MYSQL DOCS:
866 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
867 * @param string $lockName
868 * @param string $method
869 * @return bool
870 */
871 public function unlock( $lockName, $method ) {
872 $lockName = $this->addQuotes( $lockName );
873 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
874 $row = $this->fetchObject( $result );
875
876 return ( $row->lockstatus == 1 );
877 }
878
879 public function namedLocksEnqueue() {
880 return true;
881 }
882
883 /**
884 * @param array $read
885 * @param array $write
886 * @param string $method
887 * @param bool $lowPriority
888 * @return bool
889 */
890 public function lockTables( $read, $write, $method, $lowPriority = true ) {
891 $items = array();
892
893 foreach ( $write as $table ) {
894 $tbl = $this->tableName( $table ) .
895 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
896 ' WRITE';
897 $items[] = $tbl;
898 }
899 foreach ( $read as $table ) {
900 $items[] = $this->tableName( $table ) . ' READ';
901 }
902 $sql = "LOCK TABLES " . implode( ',', $items );
903 $this->query( $sql, $method );
904
905 return true;
906 }
907
908 /**
909 * @param string $method
910 * @return bool
911 */
912 public function unlockTables( $method ) {
913 $this->query( "UNLOCK TABLES", $method );
914
915 return true;
916 }
917
918 /**
919 * Get search engine class. All subclasses of this
920 * need to implement this if they wish to use searching.
921 *
922 * @return string
923 */
924 public function getSearchEngine() {
925 return 'SearchMySQL';
926 }
927
928 /**
929 * @param bool $value
930 */
931 public function setBigSelects( $value = true ) {
932 if ( $value === 'default' ) {
933 if ( $this->mDefaultBigSelects === null ) {
934 # Function hasn't been called before so it must already be set to the default
935 return;
936 } else {
937 $value = $this->mDefaultBigSelects;
938 }
939 } elseif ( $this->mDefaultBigSelects === null ) {
940 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
941 }
942 $encValue = $value ? '1' : '0';
943 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
944 }
945
946 /**
947 * DELETE where the condition is a join. MySql uses multi-table deletes.
948 * @param string $delTable
949 * @param string $joinTable
950 * @param string $delVar
951 * @param string $joinVar
952 * @param array|string $conds
953 * @param bool|string $fname
954 * @throws DBUnexpectedError
955 * @return bool|ResultWrapper
956 */
957 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
958 if ( !$conds ) {
959 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
960 }
961
962 $delTable = $this->tableName( $delTable );
963 $joinTable = $this->tableName( $joinTable );
964 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
965
966 if ( $conds != '*' ) {
967 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
968 }
969
970 return $this->query( $sql, $fname );
971 }
972
973 /**
974 * @param string $table
975 * @param array $rows
976 * @param array $uniqueIndexes
977 * @param array $set
978 * @param string $fname
979 * @return bool
980 */
981 public function upsert( $table, array $rows, array $uniqueIndexes,
982 array $set, $fname = __METHOD__
983 ) {
984 if ( !count( $rows ) ) {
985 return true; // nothing to do
986 }
987
988 if ( !is_array( reset( $rows ) ) ) {
989 $rows = array( $rows );
990 }
991
992 $table = $this->tableName( $table );
993 $columns = array_keys( $rows[0] );
994
995 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
996 $rowTuples = array();
997 foreach ( $rows as $row ) {
998 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
999 }
1000 $sql .= implode( ',', $rowTuples );
1001 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
1002
1003 return (bool)$this->query( $sql, $fname );
1004 }
1005
1006 /**
1007 * Determines how long the server has been up
1008 *
1009 * @return int
1010 */
1011 function getServerUptime() {
1012 $vars = $this->getMysqlStatus( 'Uptime' );
1013
1014 return (int)$vars['Uptime'];
1015 }
1016
1017 /**
1018 * Determines if the last failure was due to a deadlock
1019 *
1020 * @return bool
1021 */
1022 function wasDeadlock() {
1023 return $this->lastErrno() == 1213;
1024 }
1025
1026 /**
1027 * Determines if the last failure was due to a lock timeout
1028 *
1029 * @return bool
1030 */
1031 function wasLockTimeout() {
1032 return $this->lastErrno() == 1205;
1033 }
1034
1035 /**
1036 * Determines if the last query error was something that should be dealt
1037 * with by pinging the connection and reissuing the query
1038 *
1039 * @return bool
1040 */
1041 function wasErrorReissuable() {
1042 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1043 }
1044
1045 /**
1046 * Determines if the last failure was due to the database being read-only.
1047 *
1048 * @return bool
1049 */
1050 function wasReadOnlyError() {
1051 return $this->lastErrno() == 1223 ||
1052 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1053 }
1054
1055 /**
1056 * @param string $oldName
1057 * @param string $newName
1058 * @param bool $temporary
1059 * @param string $fname
1060 * @return bool
1061 */
1062 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1063 $tmp = $temporary ? 'TEMPORARY ' : '';
1064 $newName = $this->addIdentifierQuotes( $newName );
1065 $oldName = $this->addIdentifierQuotes( $oldName );
1066 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1067
1068 return $this->query( $query, $fname );
1069 }
1070
1071 /**
1072 * List all tables on the database
1073 *
1074 * @param string $prefix Only show tables with this prefix, e.g. mw_
1075 * @param string $fname Calling function name
1076 * @return array
1077 */
1078 function listTables( $prefix = null, $fname = __METHOD__ ) {
1079 $result = $this->query( "SHOW TABLES", $fname );
1080
1081 $endArray = array();
1082
1083 foreach ( $result as $table ) {
1084 $vars = get_object_vars( $table );
1085 $table = array_pop( $vars );
1086
1087 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1088 $endArray[] = $table;
1089 }
1090 }
1091
1092 return $endArray;
1093 }
1094
1095 /**
1096 * @param string $tableName
1097 * @param string $fName
1098 * @return bool|ResultWrapper
1099 */
1100 public function dropTable( $tableName, $fName = __METHOD__ ) {
1101 if ( !$this->tableExists( $tableName, $fName ) ) {
1102 return false;
1103 }
1104
1105 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1106 }
1107
1108 /**
1109 * @return array
1110 */
1111 protected function getDefaultSchemaVars() {
1112 $vars = parent::getDefaultSchemaVars();
1113 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1114 $vars['wgDBTableOptions'] = str_replace(
1115 'CHARSET=mysql4',
1116 'CHARSET=binary',
1117 $vars['wgDBTableOptions']
1118 );
1119
1120 return $vars;
1121 }
1122
1123 /**
1124 * Get status information from SHOW STATUS in an associative array
1125 *
1126 * @param string $which
1127 * @return array
1128 */
1129 function getMysqlStatus( $which = "%" ) {
1130 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1131 $status = array();
1132
1133 foreach ( $res as $row ) {
1134 $status[$row->Variable_name] = $row->Value;
1135 }
1136
1137 return $status;
1138 }
1139
1140 /**
1141 * Lists VIEWs in the database
1142 *
1143 * @param string $prefix Only show VIEWs with this prefix, eg.
1144 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1145 * @param string $fname Name of calling function
1146 * @return array
1147 * @since 1.22
1148 */
1149 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1150
1151 if ( !isset( $this->allViews ) ) {
1152
1153 // The name of the column containing the name of the VIEW
1154 $propertyName = 'Tables_in_' . $this->mDBname;
1155
1156 // Query for the VIEWS
1157 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1158 $this->allViews = array();
1159 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1160 array_push( $this->allViews, $row[$propertyName] );
1161 }
1162 }
1163
1164 if ( is_null( $prefix ) || $prefix === '' ) {
1165 return $this->allViews;
1166 }
1167
1168 $filteredViews = array();
1169 foreach ( $this->allViews as $viewName ) {
1170 // Does the name of this VIEW start with the table-prefix?
1171 if ( strpos( $viewName, $prefix ) === 0 ) {
1172 array_push( $filteredViews, $viewName );
1173 }
1174 }
1175
1176 return $filteredViews;
1177 }
1178
1179 /**
1180 * Differentiates between a TABLE and a VIEW.
1181 *
1182 * @param string $name Name of the TABLE/VIEW to test
1183 * @param string $prefix
1184 * @return bool
1185 * @since 1.22
1186 */
1187 public function isView( $name, $prefix = null ) {
1188 return in_array( $name, $this->listViews( $prefix ) );
1189 }
1190 }
1191
1192 /**
1193 * Utility class.
1194 * @ingroup Database
1195 */
1196 class MySQLField implements Field {
1197 private $name, $tablename, $default, $max_length, $nullable,
1198 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1199 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1200
1201 function __construct( $info ) {
1202 $this->name = $info->name;
1203 $this->tablename = $info->table;
1204 $this->default = $info->def;
1205 $this->max_length = $info->max_length;
1206 $this->nullable = !$info->not_null;
1207 $this->is_pk = $info->primary_key;
1208 $this->is_unique = $info->unique_key;
1209 $this->is_multiple = $info->multiple_key;
1210 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1211 $this->type = $info->type;
1212 $this->binary = isset( $info->binary ) ? $info->binary : false;
1213 $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1214 $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1215 $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1216 $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1217 }
1218
1219 /**
1220 * @return string
1221 */
1222 function name() {
1223 return $this->name;
1224 }
1225
1226 /**
1227 * @return string
1228 */
1229 function tableName() {
1230 return $this->tableName;
1231 }
1232
1233 /**
1234 * @return string
1235 */
1236 function type() {
1237 return $this->type;
1238 }
1239
1240 /**
1241 * @return bool
1242 */
1243 function isNullable() {
1244 return $this->nullable;
1245 }
1246
1247 function defaultValue() {
1248 return $this->default;
1249 }
1250
1251 /**
1252 * @return bool
1253 */
1254 function isKey() {
1255 return $this->is_key;
1256 }
1257
1258 /**
1259 * @return bool
1260 */
1261 function isMultipleKey() {
1262 return $this->is_multiple;
1263 }
1264
1265 /**
1266 * @return bool
1267 */
1268 function isBinary() {
1269 return $this->binary;
1270 }
1271
1272 /**
1273 * @return bool
1274 */
1275 function isNumeric() {
1276 return $this->is_numeric;
1277 }
1278
1279 /**
1280 * @return bool
1281 */
1282 function isBlob() {
1283 return $this->is_blob;
1284 }
1285
1286 /**
1287 * @return bool
1288 */
1289 function isUnsigned() {
1290 return $this->is_unsigned;
1291 }
1292
1293 /**
1294 * @return bool
1295 */
1296 function isZerofill() {
1297 return $this->is_zerofill;
1298 }
1299 }
1300
1301 class MySQLMasterPos implements DBMasterPos {
1302 /** @var string */
1303 public $file;
1304 /** @var int Position */
1305 public $pos;
1306 /** @var float UNIX timestamp */
1307 public $asOfTime = 0.0;
1308
1309 function __construct( $file, $pos ) {
1310 $this->file = $file;
1311 $this->pos = $pos;
1312 $this->asOfTime = microtime( true );
1313 }
1314
1315 function __toString() {
1316 // e.g db1034-bin.000976/843431247
1317 return "{$this->file}/{$this->pos}";
1318 }
1319
1320 /**
1321 * @return array|bool (int, int)
1322 */
1323 protected function getCoordinates() {
1324 $m = array();
1325 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1326 return array( (int)$m[1], (int)$m[2] );
1327 }
1328
1329 return false;
1330 }
1331
1332 function hasReached( MySQLMasterPos $pos ) {
1333 $thisPos = $this->getCoordinates();
1334 $thatPos = $pos->getCoordinates();
1335
1336 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1337 }
1338
1339 function asOfTime() {
1340 return $this->asOfTime;
1341 }
1342 }