3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
9 class DatabaseMysql
extends DatabaseBase
{
14 /*private*/ function doQuery( $sql ) {
15 if( $this->bufferResults() ) {
16 $ret = mysql_query( $sql, $this->mConn
);
18 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
23 function open( $server, $user, $password, $dbName ) {
24 global $wgAllDBsAreLocalhost;
25 wfProfileIn( __METHOD__
);
27 # Test for missing mysql.so
28 # First try to load it
32 # Otherwise we get a suppressed fatal error, which is very hard to track down
33 if ( !function_exists( 'mysql_connect' ) ) {
34 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
37 # Debugging hack -- fake cluster
38 if ( $wgAllDBsAreLocalhost ) {
39 $realServer = 'localhost';
41 $realServer = $server;
44 $this->mServer
= $server;
46 $this->mPassword
= $password;
47 $this->mDBname
= $dbName;
51 wfProfileIn("dbconnect-$server");
53 # The kernel's default SYN retransmission period is far too slow for us,
54 # so we use a short timeout plus a manual retry. Retrying means that a small
55 # but finite rate of SYN packet loss won't cause user-visible errors.
57 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
62 $this->installErrorHandler();
63 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
67 if ( $this->mFlags
& DBO_PERSISTENT
) {
68 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
70 # Create a new connection...
71 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
73 if ($this->mConn
=== false) {
75 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
78 $phpError = $this->restoreErrorHandler();
79 # Always log connection errors
80 if ( !$this->mConn
) {
81 $error = $this->lastError();
85 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
86 wfDebug( "DB connection error\n" );
87 wfDebug( "Server: $server, User: $user, Password: " .
88 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
92 wfProfileOut("dbconnect-$server");
94 if ( $dbName != '' && $this->mConn
!== false ) {
95 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
97 $error = "Error selecting database $dbName on server {$this->mServer} " .
98 "from client host " . wfHostname() . "\n";
99 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
104 $success = (bool)$this->mConn
;
108 $version = $this->getServerVersion();
109 if ( version_compare( $version, '4.1' ) >= 0 ) {
110 // Tell the server we're communicating with it in UTF-8.
111 // This may engage various charset conversions.
114 $this->query( 'SET NAMES utf8', __METHOD__
);
116 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
117 if (is_string($wgSQLMode)) {
118 $this->query( "SET sql_mode = '$wgSQLMode'", __METHOD__
);
122 // Turn off strict mode if it is on
124 $this->reportConnectionError( $phpError );
127 $this->mOpened
= $success;
128 wfProfileOut( __METHOD__
);
133 $this->mOpened
= false;
134 if ( $this->mConn
) {
135 if ( $this->trxLevel() ) {
138 return mysql_close( $this->mConn
);
144 function freeResult( $res ) {
145 if ( $res instanceof ResultWrapper
) {
148 if ( !@/**/mysql_free_result( $res ) ) {
149 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
153 function fetchObject( $res ) {
154 if ( $res instanceof ResultWrapper
) {
157 @/**/$row = mysql_fetch_object( $res );
158 if( $this->lastErrno() ) {
159 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
164 function fetchRow( $res ) {
165 if ( $res instanceof ResultWrapper
) {
168 @/**/$row = mysql_fetch_array( $res );
169 if ( $this->lastErrno() ) {
170 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
175 function numRows( $res ) {
176 if ( $res instanceof ResultWrapper
) {
179 @/**/$n = mysql_num_rows( $res );
180 if( $this->lastErrno() ) {
181 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
186 function numFields( $res ) {
187 if ( $res instanceof ResultWrapper
) {
190 return mysql_num_fields( $res );
193 function fieldName( $res, $n ) {
194 if ( $res instanceof ResultWrapper
) {
197 return mysql_field_name( $res, $n );
200 function insertId() { return mysql_insert_id( $this->mConn
); }
202 function dataSeek( $res, $row ) {
203 if ( $res instanceof ResultWrapper
) {
206 return mysql_data_seek( $res, $row );
209 function lastErrno() {
210 if ( $this->mConn
) {
211 return mysql_errno( $this->mConn
);
213 return mysql_errno();
217 function lastError() {
218 if ( $this->mConn
) {
219 # Even if it's non-zero, it can still be invalid
220 wfSuppressWarnings();
221 $error = mysql_error( $this->mConn
);
223 $error = mysql_error();
227 $error = mysql_error();
230 $error .= ' (' . $this->mServer
. ')';
235 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
238 * Estimate rows in dataset
239 * Returns estimated count, based on EXPLAIN output
240 * Takes same arguments as Database::select()
242 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
243 $options['EXPLAIN'] = true;
244 $res = $this->select( $table, $vars, $conds, $fname, $options );
245 if ( $res === false )
247 if ( !$this->numRows( $res ) ) {
248 $this->freeResult($res);
253 while( $plan = $this->fetchObject( $res ) ) {
254 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
257 $this->freeResult($res);
261 function fieldInfo( $table, $field ) {
262 $table = $this->tableName( $table );
263 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
264 $n = mysql_num_fields( $res->result
);
265 for( $i = 0; $i < $n; $i++
) {
266 $meta = mysql_fetch_field( $res->result
, $i );
267 if( $field == $meta->name
) {
268 return new MySQLField($meta);
274 function selectDB( $db ) {
275 $this->mDBname
= $db;
276 return mysql_select_db( $db, $this->mConn
);
279 function strencode( $s ) {
280 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
282 if($sQuoted === false) {
284 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
290 $ping = mysql_ping( $this->mConn
);
295 mysql_close( $this->mConn
);
296 $this->mOpened
= false;
297 $this->mConn
= false;
298 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
302 function getServerVersion() {
303 return mysql_get_server_info( $this->mConn
);
306 function useIndexClause( $index ) {
307 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
310 function lowPriorityOption() {
311 return 'LOW_PRIORITY';
314 function getSoftwareLink() {
315 return '[http://www.mysql.com/ MySQL]';
318 function standardSelectDistinct() {
322 public function setTimeout( $timeout ) {
323 $this->query( "SET net_read_timeout=$timeout" );
324 $this->query( "SET net_write_timeout=$timeout" );
327 public function lock( $lockName, $method, $timeout = 5 ) {
328 $lockName = $this->addQuotes( $lockName );
329 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
330 $row = $this->fetchObject( $result );
331 $this->freeResult( $result );
333 if( $row->lockstatus
== 1 ) {
336 wfDebug( __METHOD__
." failed to acquire lock\n" );
341 public function unlock( $lockName, $method ) {
342 $lockName = $this->addQuotes( $lockName );
343 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
344 $row = $this->fetchObject( $result );
345 return $row->lockstatus
;
348 public function lockTables( $read, $write, $method, $lowPriority = true ) {
351 foreach( $write as $table ) {
352 $tbl = $this->tableName( $table ) .
353 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
357 foreach( $read as $table ) {
358 $items[] = $this->tableName( $table ) . ' READ';
360 $sql = "LOCK TABLES " . implode( ',', $items );
361 $this->query( $sql, $method );
364 public function unlockTables( $method ) {
365 $this->query( "UNLOCK TABLES", $method );
368 public function setBigSelects( $value = true ) {
369 if ( $value === 'default' ) {
370 if ( $this->mDefaultBigSelects
=== null ) {
371 # Function hasn't been called before so it must already be set to the default
374 $value = $this->mDefaultBigSelects
;
376 } elseif ( $this->mDefaultBigSelects
=== null ) {
377 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
379 $encValue = $value ?
'1' : '0';
380 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
385 * Determines if the last failure was due to a deadlock
387 function wasDeadlock() {
388 return $this->lastErrno() == 1213;
392 * Determines if the last query error was something that should be dealt
393 * with by pinging the connection and reissuing the query
395 function wasErrorReissuable() {
396 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
400 * Determines if the last failure was due to the database being read-only.
402 function wasReadOnlyError() {
403 return $this->lastErrno() == 1223 ||
404 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
407 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
408 $tmp = $temporary ?
'TEMPORARY ' : '';
409 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
410 # Hack for MySQL versions < 4.1, which don't support
411 # "CREATE TABLE ... LIKE". Note that
412 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
413 # would not create the indexes we need....
415 # Note that we don't bother changing around the prefixes here be-
416 # cause we know we're using MySQL anyway.
418 $res = $this->query( "SHOW CREATE TABLE $oldName" );
419 $row = $this->fetchRow( $res );
421 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
422 "CREATE $tmp TABLE `$newName`", $oldQuery );
423 if ($oldQuery === $query) {
424 # Couldn't do replacement
425 throw new MWException( "could not create temporary table $newName" );
428 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
430 $this->query( $query, $fname );
436 * Legacy support: Database == DatabaseMysql
438 class Database
extends DatabaseMysql
{}
440 class MySQLMasterPos
{
443 function __construct( $file, $pos ) {
448 function __toString() {
449 return "{$this->file}/{$this->pos}";