Adding $wgSQLMode
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
5 *
6 * @ingroup Database
7 * @see Database
8 */
9 class DatabaseMysql extends DatabaseBase {
10 function getType() {
11 return 'mysql';
12 }
13
14 /*private*/ function doQuery( $sql ) {
15 if( $this->bufferResults() ) {
16 $ret = mysql_query( $sql, $this->mConn );
17 } else {
18 $ret = mysql_unbuffered_query( $sql, $this->mConn );
19 }
20 return $ret;
21 }
22
23 function open( $server, $user, $password, $dbName ) {
24 global $wgAllDBsAreLocalhost;
25 wfProfileIn( __METHOD__ );
26
27 # Test for missing mysql.so
28 # First try to load it
29 wfDl( 'mysql' );
30
31 # Fail now
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" );
35 }
36
37 # Debugging hack -- fake cluster
38 if ( $wgAllDBsAreLocalhost ) {
39 $realServer = 'localhost';
40 } else {
41 $realServer = $server;
42 }
43 $this->close();
44 $this->mServer = $server;
45 $this->mUser = $user;
46 $this->mPassword = $password;
47 $this->mDBname = $dbName;
48
49 $success = false;
50
51 wfProfileIn("dbconnect-$server");
52
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.
56 $this->mConn = false;
57 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
58 $numAttempts = 2;
59 } else {
60 $numAttempts = 1;
61 }
62 $this->installErrorHandler();
63 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
64 if ( $i > 1 ) {
65 usleep( 1000 );
66 }
67 if ( $this->mFlags & DBO_PERSISTENT ) {
68 $this->mConn = mysql_pconnect( $realServer, $user, $password );
69 } else {
70 # Create a new connection...
71 $this->mConn = mysql_connect( $realServer, $user, $password, true );
72 }
73 if ($this->mConn === false) {
74 #$iplus = $i + 1;
75 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
76 }
77 }
78 $phpError = $this->restoreErrorHandler();
79 # Always log connection errors
80 if ( !$this->mConn ) {
81 $error = $this->lastError();
82 if ( !$error ) {
83 $error = $phpError;
84 }
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" );
89 $success = false;
90 }
91
92 wfProfileOut("dbconnect-$server");
93
94 if ( $dbName != '' && $this->mConn !== false ) {
95 $success = @/**/mysql_select_db( $dbName, $this->mConn );
96 if ( !$success ) {
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");
100 wfDebug( $error );
101 }
102 } else {
103 # Delay USE query
104 $success = (bool)$this->mConn;
105 }
106
107 if ( $success ) {
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.
112 global $wgDBmysql5;
113 if( $wgDBmysql5 ) {
114 $this->query( 'SET NAMES utf8', __METHOD__ );
115 }
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__ );
119 }
120 }
121
122 // Turn off strict mode if it is on
123 } else {
124 $this->reportConnectionError( $phpError );
125 }
126
127 $this->mOpened = $success;
128 wfProfileOut( __METHOD__ );
129 return $success;
130 }
131
132 function close() {
133 $this->mOpened = false;
134 if ( $this->mConn ) {
135 if ( $this->trxLevel() ) {
136 $this->commit();
137 }
138 return mysql_close( $this->mConn );
139 } else {
140 return true;
141 }
142 }
143
144 function freeResult( $res ) {
145 if ( $res instanceof ResultWrapper ) {
146 $res = $res->result;
147 }
148 if ( !@/**/mysql_free_result( $res ) ) {
149 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
150 }
151 }
152
153 function fetchObject( $res ) {
154 if ( $res instanceof ResultWrapper ) {
155 $res = $res->result;
156 }
157 @/**/$row = mysql_fetch_object( $res );
158 if( $this->lastErrno() ) {
159 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
160 }
161 return $row;
162 }
163
164 function fetchRow( $res ) {
165 if ( $res instanceof ResultWrapper ) {
166 $res = $res->result;
167 }
168 @/**/$row = mysql_fetch_array( $res );
169 if ( $this->lastErrno() ) {
170 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
171 }
172 return $row;
173 }
174
175 function numRows( $res ) {
176 if ( $res instanceof ResultWrapper ) {
177 $res = $res->result;
178 }
179 @/**/$n = mysql_num_rows( $res );
180 if( $this->lastErrno() ) {
181 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
182 }
183 return $n;
184 }
185
186 function numFields( $res ) {
187 if ( $res instanceof ResultWrapper ) {
188 $res = $res->result;
189 }
190 return mysql_num_fields( $res );
191 }
192
193 function fieldName( $res, $n ) {
194 if ( $res instanceof ResultWrapper ) {
195 $res = $res->result;
196 }
197 return mysql_field_name( $res, $n );
198 }
199
200 function insertId() { return mysql_insert_id( $this->mConn ); }
201
202 function dataSeek( $res, $row ) {
203 if ( $res instanceof ResultWrapper ) {
204 $res = $res->result;
205 }
206 return mysql_data_seek( $res, $row );
207 }
208
209 function lastErrno() {
210 if ( $this->mConn ) {
211 return mysql_errno( $this->mConn );
212 } else {
213 return mysql_errno();
214 }
215 }
216
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 );
222 if ( !$error ) {
223 $error = mysql_error();
224 }
225 wfRestoreWarnings();
226 } else {
227 $error = mysql_error();
228 }
229 if( $error ) {
230 $error .= ' (' . $this->mServer . ')';
231 }
232 return $error;
233 }
234
235 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
236
237 /**
238 * Estimate rows in dataset
239 * Returns estimated count, based on EXPLAIN output
240 * Takes same arguments as Database::select()
241 */
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 )
246 return false;
247 if ( !$this->numRows( $res ) ) {
248 $this->freeResult($res);
249 return 0;
250 }
251
252 $rows = 1;
253 while( $plan = $this->fetchObject( $res ) ) {
254 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
255 }
256
257 $this->freeResult($res);
258 return $rows;
259 }
260
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);
269 }
270 }
271 return false;
272 }
273
274 function selectDB( $db ) {
275 $this->mDBname = $db;
276 return mysql_select_db( $db, $this->mConn );
277 }
278
279 function strencode( $s ) {
280 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
281
282 if($sQuoted === false) {
283 $this->ping();
284 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
285 }
286 return $sQuoted;
287 }
288
289 function ping() {
290 $ping = mysql_ping( $this->mConn );
291 if ( $ping ) {
292 return true;
293 }
294
295 mysql_close( $this->mConn );
296 $this->mOpened = false;
297 $this->mConn = false;
298 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
299 return true;
300 }
301
302 function getServerVersion() {
303 return mysql_get_server_info( $this->mConn );
304 }
305
306 function useIndexClause( $index ) {
307 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
308 }
309
310 function lowPriorityOption() {
311 return 'LOW_PRIORITY';
312 }
313
314 function getSoftwareLink() {
315 return '[http://www.mysql.com/ MySQL]';
316 }
317
318 function standardSelectDistinct() {
319 return false;
320 }
321
322 public function setTimeout( $timeout ) {
323 $this->query( "SET net_read_timeout=$timeout" );
324 $this->query( "SET net_write_timeout=$timeout" );
325 }
326
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 );
332
333 if( $row->lockstatus == 1 ) {
334 return true;
335 } else {
336 wfDebug( __METHOD__." failed to acquire lock\n" );
337 return false;
338 }
339 }
340
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;
346 }
347
348 public function lockTables( $read, $write, $method, $lowPriority = true ) {
349 $items = array();
350
351 foreach( $write as $table ) {
352 $tbl = $this->tableName( $table ) .
353 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
354 ' WRITE';
355 $items[] = $tbl;
356 }
357 foreach( $read as $table ) {
358 $items[] = $this->tableName( $table ) . ' READ';
359 }
360 $sql = "LOCK TABLES " . implode( ',', $items );
361 $this->query( $sql, $method );
362 }
363
364 public function unlockTables( $method ) {
365 $this->query( "UNLOCK TABLES", $method );
366 }
367
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
372 return;
373 } else {
374 $value = $this->mDefaultBigSelects;
375 }
376 } elseif ( $this->mDefaultBigSelects === null ) {
377 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
378 }
379 $encValue = $value ? '1' : '0';
380 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
381 }
382
383
384 /**
385 * Determines if the last failure was due to a deadlock
386 */
387 function wasDeadlock() {
388 return $this->lastErrno() == 1213;
389 }
390
391 /**
392 * Determines if the last query error was something that should be dealt
393 * with by pinging the connection and reissuing the query
394 */
395 function wasErrorReissuable() {
396 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
397 }
398
399 /**
400 * Determines if the last failure was due to the database being read-only.
401 */
402 function wasReadOnlyError() {
403 return $this->lastErrno() == 1223 ||
404 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
405 }
406
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....
414 #
415 # Note that we don't bother changing around the prefixes here be-
416 # cause we know we're using MySQL anyway.
417
418 $res = $this->query( "SHOW CREATE TABLE $oldName" );
419 $row = $this->fetchRow( $res );
420 $oldQuery = $row[1];
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" );
426 }
427 } else {
428 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
429 }
430 $this->query( $query, $fname );
431 }
432
433 }
434
435 /**
436 * Legacy support: Database == DatabaseMysql
437 */
438 class Database extends DatabaseMysql {}
439
440 class MySQLMasterPos {
441 var $file, $pos;
442
443 function __construct( $file, $pos ) {
444 $this->file = $file;
445 $this->pos = $pos;
446 }
447
448 function __toString() {
449 return "{$this->file}/{$this->pos}";
450 }
451 }