3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
9 class DatabaseMysql
extends DatabaseBase
{
10 static $mMinSearchLength;
16 /*private*/ function doQuery( $sql ) {
17 if( $this->bufferResults() ) {
18 $ret = mysql_query( $sql, $this->mConn
);
20 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
25 function open( $server, $user, $password, $dbName ) {
26 global $wgAllDBsAreLocalhost;
27 wfProfileIn( __METHOD__
);
29 # Test for missing mysql.so
30 # First try to load it
31 if (!@extension_loaded
('mysql')) {
36 # Otherwise we get a suppressed fatal error, which is very hard to track down
37 if ( !function_exists( 'mysql_connect' ) ) {
38 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
41 # Debugging hack -- fake cluster
42 if ( $wgAllDBsAreLocalhost ) {
43 $realServer = 'localhost';
45 $realServer = $server;
48 $this->mServer
= $server;
50 $this->mPassword
= $password;
51 $this->mDBname
= $dbName;
55 wfProfileIn("dbconnect-$server");
57 # The kernel's default SYN retransmission period is far too slow for us,
58 # so we use a short timeout plus a manual retry. Retrying means that a small
59 # but finite rate of SYN packet loss won't cause user-visible errors.
61 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
66 $this->installErrorHandler();
67 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
71 if ( $this->mFlags
& DBO_PERSISTENT
) {
72 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
74 # Create a new connection...
75 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
77 if ($this->mConn
=== false) {
79 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
82 $phpError = $this->restoreErrorHandler();
83 # Always log connection errors
84 if ( !$this->mConn
) {
85 $error = $this->lastError();
89 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
90 wfDebug( "DB connection error\n" );
91 wfDebug( "Server: $server, User: $user, Password: " .
92 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
96 wfProfileOut("dbconnect-$server");
98 if ( $dbName != '' && $this->mConn
!== false ) {
99 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
101 $error = "Error selecting database $dbName on server {$this->mServer} " .
102 "from client host " . wfHostname() . "\n";
103 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
108 $success = (bool)$this->mConn
;
112 $version = $this->getServerVersion();
113 if ( version_compare( $version, '4.1' ) >= 0 ) {
114 // Tell the server we're communicating with it in UTF-8.
115 // This may engage various charset conversions.
118 $this->query( 'SET NAMES utf8', __METHOD__
);
120 // Turn off strict mode
121 $this->query( "SET sql_mode = ''", __METHOD__
);
124 // Turn off strict mode if it is on
126 $this->reportConnectionError( $phpError );
129 $this->mOpened
= $success;
130 wfProfileOut( __METHOD__
);
135 $this->mOpened
= false;
136 if ( $this->mConn
) {
137 if ( $this->trxLevel() ) {
140 return mysql_close( $this->mConn
);
146 function freeResult( $res ) {
147 if ( $res instanceof ResultWrapper
) {
150 if ( !@/**/mysql_free_result( $res ) ) {
151 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
155 function fetchObject( $res ) {
156 if ( $res instanceof ResultWrapper
) {
159 @/**/$row = mysql_fetch_object( $res );
160 if( $this->lastErrno() ) {
161 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
166 function fetchRow( $res ) {
167 if ( $res instanceof ResultWrapper
) {
170 @/**/$row = mysql_fetch_array( $res );
171 if ( $this->lastErrno() ) {
172 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
177 function numRows( $res ) {
178 if ( $res instanceof ResultWrapper
) {
181 @/**/$n = mysql_num_rows( $res );
182 if( $this->lastErrno() ) {
183 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
188 function numFields( $res ) {
189 if ( $res instanceof ResultWrapper
) {
192 return mysql_num_fields( $res );
195 function fieldName( $res, $n ) {
196 if ( $res instanceof ResultWrapper
) {
199 return mysql_field_name( $res, $n );
202 function insertId() { return mysql_insert_id( $this->mConn
); }
204 function dataSeek( $res, $row ) {
205 if ( $res instanceof ResultWrapper
) {
208 return mysql_data_seek( $res, $row );
211 function lastErrno() {
212 if ( $this->mConn
) {
213 return mysql_errno( $this->mConn
);
215 return mysql_errno();
219 function lastError() {
220 if ( $this->mConn
) {
221 # Even if it's non-zero, it can still be invalid
222 wfSuppressWarnings();
223 $error = mysql_error( $this->mConn
);
225 $error = mysql_error();
229 $error = mysql_error();
232 $error .= ' (' . $this->mServer
. ')';
237 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
240 * Estimate rows in dataset
241 * Returns estimated count, based on EXPLAIN output
242 * Takes same arguments as Database::select()
244 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
245 $options['EXPLAIN'] = true;
246 $res = $this->select( $table, $vars, $conds, $fname, $options );
247 if ( $res === false )
249 if ( !$this->numRows( $res ) ) {
250 $this->freeResult($res);
255 while( $plan = $this->fetchObject( $res ) ) {
256 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
259 $this->freeResult($res);
263 function fieldInfo( $table, $field ) {
264 $table = $this->tableName( $table );
265 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
266 $n = mysql_num_fields( $res->result
);
267 for( $i = 0; $i < $n; $i++
) {
268 $meta = mysql_fetch_field( $res->result
, $i );
269 if( $field == $meta->name
) {
270 return new MySQLField($meta);
276 function selectDB( $db ) {
277 $this->mDBname
= $db;
278 return mysql_select_db( $db, $this->mConn
);
281 function strencode( $s ) {
282 return mysql_real_escape_string( $s, $this->mConn
);
286 if( !function_exists( 'mysql_ping' ) ) {
287 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
290 $ping = mysql_ping( $this->mConn
);
295 // Need to reconnect manually in MySQL client 5.0.13+
296 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
297 mysql_close( $this->mConn
);
298 $this->mOpened
= false;
299 $this->mConn
= false;
300 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
306 function getServerVersion() {
307 return mysql_get_server_info( $this->mConn
);
310 function useIndexClause( $index ) {
311 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
314 function lowPriorityOption() {
315 return 'LOW_PRIORITY';
318 function getSoftwareLink() {
319 return '[http://www.mysql.com/ MySQL]';
322 function standardSelectDistinct() {
326 public function setTimeout( $timeout ) {
327 $this->query( "SET net_read_timeout=$timeout" );
328 $this->query( "SET net_write_timeout=$timeout" );
331 public function lock( $lockName, $method, $timeout = 5 ) {
332 $lockName = $this->addQuotes( $lockName );
333 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
334 $row = $this->fetchObject( $result );
335 $this->freeResult( $result );
337 if( $row->lockstatus
== 1 ) {
340 wfDebug( __METHOD__
." failed to acquire lock\n" );
345 public function unlock( $lockName, $method ) {
346 $lockName = $this->addQuotes( $lockName );
347 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
348 $row = $this->fetchObject( $result );
349 return $row->lockstatus
;
352 public function lockTables( $read, $write, $method, $lowPriority = true ) {
355 foreach( $write as $table ) {
356 $tbl = $this->tableName( $table ) .
357 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
361 foreach( $read as $table ) {
362 $items[] = $this->tableName( $table ) . ' READ';
364 $sql = "LOCK TABLES " . implode( ',', $items );
365 $this->query( $sql, $method );
368 public function unlockTables( $method ) {
369 $this->query( "UNLOCK TABLES", $method );
373 * Converts some characters for MySQL's indexing to grok it correctly,
374 * and pads short words to overcome limitations.
376 function stripForSearch( $string ) {
379 wfProfileIn( __METHOD__
);
381 // MySQL fulltext index doesn't grok utf-8, so we
382 // need to fold cases and convert to hex
383 $out = preg_replace_callback(
384 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
385 array( $this, 'stripForSearchCallback' ),
386 $wgContLang->lc( $string ) );
388 // And to add insult to injury, the default indexing
389 // ignores short words... Pad them so we can pass them
390 // through without reconfiguring the server...
391 $minLength = $this->minSearchLength();
392 if( $minLength > 1 ) {
400 // Periods within things like hostnames and IP addresses
401 // are also important -- we want a search for "example.com"
402 // or "192.168.1.1" to work sanely.
404 // MySQL's search seems to ignore them, so you'd match on
405 // "example.wikipedia.com" and "192.168.83.1" as well.
411 wfProfileOut( __METHOD__
);
417 * Armor a case-folded UTF-8 string to get through MySQL's
418 * fulltext search without being mucked up by funny charset
419 * settings or anything else of the sort.
421 protected function stripForSearchCallback( $matches ) {
422 return 'u8' . bin2hex( $matches[1] );
426 * Check MySQL server's ft_min_word_len setting so we know
427 * if we need to pad short words...
431 protected function minSearchLength() {
432 if( is_null( self
::$mMinSearchLength ) ) {
433 $sql = "show global variables like 'ft\\_min\\_word\\_len'";
435 // Even though this query is pretty fast, let's not overload the master
436 $dbr = wfGetDB( DB_SLAVE
);
437 $result = $dbr->query( $sql );
438 $row = $result->fetchObject();
441 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
442 self
::$mMinSearchLength = intval( $row->Value
);
444 self
::$mMinSearchLength = 0;
447 return self
::$mMinSearchLength;
450 public function setBigSelects( $value = true ) {
451 if ( $value === 'default' ) {
452 if ( $this->mDefaultBigSelects
=== null ) {
453 # Function hasn't been called before so it must already be set to the default
456 $value = $this->mDefaultBigSelects
;
458 } elseif ( $this->mDefaultBigSelects
=== null ) {
459 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
461 $encValue = $value ?
'1' : '0';
462 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
467 * Determines if the last failure was due to a deadlock
469 function wasDeadlock() {
470 return $this->lastErrno() == 1213;
474 * Determines if the last query error was something that should be dealt
475 * with by pinging the connection and reissuing the query
477 function wasErrorReissuable() {
478 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
482 * Determines if the last failure was due to the database being read-only.
484 function wasReadOnlyError() {
485 return $this->lastErrno() == 1223 ||
486 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
489 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
490 $tmp = $temporary ?
'TEMPORARY ' : '';
491 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
492 # Hack for MySQL versions < 4.1, which don't support
493 # "CREATE TABLE ... LIKE". Note that
494 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
495 # would not create the indexes we need....
497 # Note that we don't bother changing around the prefixes here be-
498 # cause we know we're using MySQL anyway.
500 $res = $this->query( "SHOW CREATE TABLE $oldName" );
501 $row = $this->fetchRow( $res );
503 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
504 "CREATE $tmp TABLE `$newName`", $oldQuery );
505 if ($oldQuery === $query) {
506 # Couldn't do replacement
507 throw new MWException( "could not create temporary table $newName" );
510 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
512 $this->query( $query, $fname );
518 * Legacy support: Database == DatabaseMysql
520 class Database
extends DatabaseMysql
{}
522 class MySQLMasterPos
{
525 function __construct( $file, $pos ) {
530 function __toString() {
531 return "{$this->file}/{$this->pos}";