Tweak to insertOnDupeUpdate in DatabaseMysql to split how wanted ( foo = bar )
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * Database abstraction object for mySQL
11 * Inherit all methods and properties of Database::Database()
12 *
13 * @ingroup Database
14 * @see Database
15 */
16 class DatabaseMysql extends DatabaseBase {
17 function getType() {
18 return 'mysql';
19 }
20
21 /*private*/ function doQuery( $sql ) {
22 if( $this->bufferResults() ) {
23 $ret = mysql_query( $sql, $this->mConn );
24 } else {
25 $ret = mysql_unbuffered_query( $sql, $this->mConn );
26 }
27 return $ret;
28 }
29
30 function open( $server, $user, $password, $dbName ) {
31 global $wgAllDBsAreLocalhost;
32 wfProfileIn( __METHOD__ );
33
34 # Test for missing mysql.so
35 # First try to load it
36 wfDl( 'mysql' );
37
38 # Fail now
39 # Otherwise we get a suppressed fatal error, which is very hard to track down
40 if ( !function_exists( 'mysql_connect' ) ) {
41 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
42 }
43
44 # Debugging hack -- fake cluster
45 if ( $wgAllDBsAreLocalhost ) {
46 $realServer = 'localhost';
47 } else {
48 $realServer = $server;
49 }
50 $this->close();
51 $this->mServer = $server;
52 $this->mUser = $user;
53 $this->mPassword = $password;
54 $this->mDBname = $dbName;
55
56 $success = false;
57
58 wfProfileIn("dbconnect-$server");
59
60 # The kernel's default SYN retransmission period is far too slow for us,
61 # so we use a short timeout plus a manual retry. Retrying means that a small
62 # but finite rate of SYN packet loss won't cause user-visible errors.
63 $this->mConn = false;
64 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
65 $numAttempts = 2;
66 } else {
67 $numAttempts = 1;
68 }
69 $this->installErrorHandler();
70 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
71 if ( $i > 1 ) {
72 usleep( 1000 );
73 }
74 if ( $this->mFlags & DBO_PERSISTENT ) {
75 $this->mConn = mysql_pconnect( $realServer, $user, $password );
76 } else {
77 # Create a new connection...
78 $this->mConn = mysql_connect( $realServer, $user, $password, true );
79 }
80 if ($this->mConn === false) {
81 #$iplus = $i + 1;
82 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
83 }
84 }
85 $phpError = $this->restoreErrorHandler();
86 # Always log connection errors
87 if ( !$this->mConn ) {
88 $error = $this->lastError();
89 if ( !$error ) {
90 $error = $phpError;
91 }
92 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
93 wfDebug( "DB connection error\n" );
94 wfDebug( "Server: $server, User: $user, Password: " .
95 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
96 $success = false;
97 }
98
99 wfProfileOut("dbconnect-$server");
100
101 if ( $dbName != '' && $this->mConn !== false ) {
102 $success = @/**/mysql_select_db( $dbName, $this->mConn );
103 if ( !$success ) {
104 $error = "Error selecting database $dbName on server {$this->mServer} " .
105 "from client host " . wfHostname() . "\n";
106 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
107 wfDebug( $error );
108 }
109 } else {
110 # Delay USE query
111 $success = (bool)$this->mConn;
112 }
113
114 if ( $success ) {
115 $version = $this->getServerVersion();
116 if ( version_compare( $version, '4.1' ) >= 0 ) {
117 // Tell the server we're communicating with it in UTF-8.
118 // This may engage various charset conversions.
119 global $wgDBmysql5;
120 if( $wgDBmysql5 ) {
121 $this->query( 'SET NAMES utf8', __METHOD__ );
122 } else {
123 $this->query( 'SET NAMES binary', __METHOD__ );
124 }
125 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
126 global $wgSQLMode;
127 if ( is_string( $wgSQLMode ) ) {
128 $mode = $this->addQuotes( $wgSQLMode );
129 $this->query( "SET sql_mode = $mode", __METHOD__ );
130 }
131 }
132
133 // Turn off strict mode if it is on
134 } else {
135 $this->reportConnectionError( $phpError );
136 }
137
138 $this->mOpened = $success;
139 wfProfileOut( __METHOD__ );
140 return $success;
141 }
142
143 function close() {
144 $this->mOpened = false;
145 if ( $this->mConn ) {
146 if ( $this->trxLevel() ) {
147 $this->commit();
148 }
149 return mysql_close( $this->mConn );
150 } else {
151 return true;
152 }
153 }
154
155 function freeResult( $res ) {
156 if ( $res instanceof ResultWrapper ) {
157 $res = $res->result;
158 }
159 if ( !@/**/mysql_free_result( $res ) ) {
160 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
161 }
162 }
163
164 function fetchObject( $res ) {
165 if ( $res instanceof ResultWrapper ) {
166 $res = $res->result;
167 }
168 @/**/$row = mysql_fetch_object( $res );
169 if( $this->lastErrno() ) {
170 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
171 }
172 return $row;
173 }
174
175 function fetchRow( $res ) {
176 if ( $res instanceof ResultWrapper ) {
177 $res = $res->result;
178 }
179 @/**/$row = mysql_fetch_array( $res );
180 if ( $this->lastErrno() ) {
181 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
182 }
183 return $row;
184 }
185
186 function numRows( $res ) {
187 if ( $res instanceof ResultWrapper ) {
188 $res = $res->result;
189 }
190 @/**/$n = mysql_num_rows( $res );
191 if( $this->lastErrno() ) {
192 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
193 }
194 return $n;
195 }
196
197 function numFields( $res ) {
198 if ( $res instanceof ResultWrapper ) {
199 $res = $res->result;
200 }
201 return mysql_num_fields( $res );
202 }
203
204 function fieldName( $res, $n ) {
205 if ( $res instanceof ResultWrapper ) {
206 $res = $res->result;
207 }
208 return mysql_field_name( $res, $n );
209 }
210
211 function insertId() { return mysql_insert_id( $this->mConn ); }
212
213 function dataSeek( $res, $row ) {
214 if ( $res instanceof ResultWrapper ) {
215 $res = $res->result;
216 }
217 return mysql_data_seek( $res, $row );
218 }
219
220 function lastErrno() {
221 if ( $this->mConn ) {
222 return mysql_errno( $this->mConn );
223 } else {
224 return mysql_errno();
225 }
226 }
227
228 function lastError() {
229 if ( $this->mConn ) {
230 # Even if it's non-zero, it can still be invalid
231 wfSuppressWarnings();
232 $error = mysql_error( $this->mConn );
233 if ( !$error ) {
234 $error = mysql_error();
235 }
236 wfRestoreWarnings();
237 } else {
238 $error = mysql_error();
239 }
240 if( $error ) {
241 $error .= ' (' . $this->mServer . ')';
242 }
243 return $error;
244 }
245
246 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
247
248 /**
249 * Estimate rows in dataset
250 * Returns estimated count, based on EXPLAIN output
251 * Takes same arguments as Database::select()
252 */
253 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
254 $options['EXPLAIN'] = true;
255 $res = $this->select( $table, $vars, $conds, $fname, $options );
256 if ( $res === false ) {
257 return false;
258 }
259 if ( !$this->numRows( $res ) ) {
260 return 0;
261 }
262
263 $rows = 1;
264 while( $plan = $this->fetchObject( $res ) ) {
265 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
266 }
267 return $rows;
268 }
269
270 function fieldInfo( $table, $field ) {
271 $table = $this->tableName( $table );
272 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
273 if ( !$res ) {
274 return false;
275 }
276 $n = mysql_num_fields( $res->result );
277 for( $i = 0; $i < $n; $i++ ) {
278 $meta = mysql_fetch_field( $res->result, $i );
279 if( $field == $meta->name ) {
280 return new MySQLField($meta);
281 }
282 }
283 return false;
284 }
285
286 function selectDB( $db ) {
287 $this->mDBname = $db;
288 return mysql_select_db( $db, $this->mConn );
289 }
290
291 function strencode( $s ) {
292 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
293
294 if($sQuoted === false) {
295 $this->ping();
296 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
297 }
298 return $sQuoted;
299 }
300
301 function ping() {
302 $ping = mysql_ping( $this->mConn );
303 if ( $ping ) {
304 return true;
305 }
306
307 mysql_close( $this->mConn );
308 $this->mOpened = false;
309 $this->mConn = false;
310 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
311 return true;
312 }
313
314 /**
315 * Returns slave lag.
316 * At the moment, this will only work if the DB user has the PROCESS privilege
317 * @result int
318 */
319 function getLag() {
320 if ( !is_null( $this->mFakeSlaveLag ) ) {
321 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
322 return $this->mFakeSlaveLag;
323 }
324 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
325 # Find slave SQL thread
326 while ( $row = $this->fetchObject( $res ) ) {
327 /* This should work for most situations - when default db
328 * for thread is not specified, it had no events executed,
329 * and therefore it doesn't know yet how lagged it is.
330 *
331 * Relay log I/O thread does not select databases.
332 */
333 if ( $row->User == 'system user' &&
334 $row->State != 'Waiting for master to send event' &&
335 $row->State != 'Connecting to master' &&
336 $row->State != 'Queueing master event to the relay log' &&
337 $row->State != 'Waiting for master update' &&
338 $row->State != 'Requesting binlog dump' &&
339 $row->State != 'Waiting to reconnect after a failed master event read' &&
340 $row->State != 'Reconnecting after a failed master event read' &&
341 $row->State != 'Registering slave on master'
342 ) {
343 # This is it, return the time (except -ve)
344 if ( $row->Time > 0x7fffffff ) {
345 return false;
346 } else {
347 return $row->Time;
348 }
349 }
350 }
351 return false;
352 }
353
354 /**
355 * INSERT ... ON DUPE UPDATE wrapper, inserts an array into a table, optionally updating if
356 * duplicate primary key found
357 *
358 * $a may be a single associative array, or an array of these with numeric keys, for
359 * multi-row insert.
360 *
361 * Usually aborts on failure
362 * If errors are explicitly ignored, returns success
363 *
364 * @param $table String: table name (prefix auto-added)
365 * @param $a Array: Array of rows to insert
366 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
367 * @param $options Mixed: Associative array of options
368 * @param $onDupeUpdate Array: Associative array of fields to update on duplicate
369 *
370 * @return bool
371 */
372 function insertOrUpdate( $table, $a, $fname = 'DatabaseBase::insertOnDupeUpdate', $options = array(), $onDupeUpdate = array() ) {
373 # No rows to insert, easy just return now
374 if ( !count( $a ) ) {
375 return true;
376 }
377
378 $table = $this->tableName( $table );
379 if ( !is_array( $options ) ) {
380 $options = array( $options );
381 }
382 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
383 $multi = true;
384 $keys = array_keys( $a[0] );
385 } else {
386 $multi = false;
387 $keys = array_keys( $a );
388 }
389
390 $sql = 'INSERT ' . implode( ' ', $options ) .
391 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
392
393 if ( $multi ) {
394 $first = true;
395 foreach ( $a as $row ) {
396 if ( $first ) {
397 $first = false;
398 } else {
399 $sql .= ',';
400 }
401 $sql .= '(' . $this->makeList( $row ) . ')';
402 }
403 } else {
404 $sql .= '(' . $this->makeList( $a ) . ')';
405 }
406
407 if ( count( $onDupeUpdate ) ) {
408 $sql .= ' ON DUPLICATE KEY UPDATE ' . $this->makeList( $onDupeUpdate, LIST_SET );
409 }
410
411 return (bool)$this->query( $sql, $fname );
412 }
413
414 function getServerVersion() {
415 return mysql_get_server_info( $this->mConn );
416 }
417
418 function useIndexClause( $index ) {
419 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
420 }
421
422 function lowPriorityOption() {
423 return 'LOW_PRIORITY';
424 }
425
426 public static function getSoftwareLink() {
427 return '[http://www.mysql.com/ MySQL]';
428 }
429
430 function standardSelectDistinct() {
431 return false;
432 }
433
434 public function setTimeout( $timeout ) {
435 $this->query( "SET net_read_timeout=$timeout" );
436 $this->query( "SET net_write_timeout=$timeout" );
437 }
438
439 public function lock( $lockName, $method, $timeout = 5 ) {
440 $lockName = $this->addQuotes( $lockName );
441 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
442 $row = $this->fetchObject( $result );
443
444 if( $row->lockstatus == 1 ) {
445 return true;
446 } else {
447 wfDebug( __METHOD__." failed to acquire lock\n" );
448 return false;
449 }
450 }
451
452 /**
453 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
454 */
455 public function unlock( $lockName, $method ) {
456 $lockName = $this->addQuotes( $lockName );
457 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
458 $row = $this->fetchObject( $result );
459 return $row->lockstatus;
460 }
461
462 public function lockTables( $read, $write, $method, $lowPriority = true ) {
463 $items = array();
464
465 foreach( $write as $table ) {
466 $tbl = $this->tableName( $table ) .
467 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
468 ' WRITE';
469 $items[] = $tbl;
470 }
471 foreach( $read as $table ) {
472 $items[] = $this->tableName( $table ) . ' READ';
473 }
474 $sql = "LOCK TABLES " . implode( ',', $items );
475 $this->query( $sql, $method );
476 }
477
478 public function unlockTables( $method ) {
479 $this->query( "UNLOCK TABLES", $method );
480 }
481
482 /**
483 * Get search engine class. All subclasses of this
484 * need to implement this if they wish to use searching.
485 *
486 * @return String
487 */
488 public function getSearchEngine() {
489 return 'SearchMySQL';
490 }
491
492 public function setBigSelects( $value = true ) {
493 if ( $value === 'default' ) {
494 if ( $this->mDefaultBigSelects === null ) {
495 # Function hasn't been called before so it must already be set to the default
496 return;
497 } else {
498 $value = $this->mDefaultBigSelects;
499 }
500 } elseif ( $this->mDefaultBigSelects === null ) {
501 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
502 }
503 $encValue = $value ? '1' : '0';
504 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
505 }
506
507
508 /**
509 * Determines if the last failure was due to a deadlock
510 */
511 function wasDeadlock() {
512 return $this->lastErrno() == 1213;
513 }
514
515 /**
516 * Determines if the last query error was something that should be dealt
517 * with by pinging the connection and reissuing the query
518 */
519 function wasErrorReissuable() {
520 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
521 }
522
523 /**
524 * Determines if the last failure was due to the database being read-only.
525 */
526 function wasReadOnlyError() {
527 return $this->lastErrno() == 1223 ||
528 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
529 }
530
531 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
532 $tmp = $temporary ? 'TEMPORARY ' : '';
533 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
534 # Hack for MySQL versions < 4.1, which don't support
535 # "CREATE TABLE ... LIKE". Note that
536 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
537 # would not create the indexes we need....
538 #
539 # Note that we don't bother changing around the prefixes here be-
540 # cause we know we're using MySQL anyway.
541
542 $res = $this->query( "SHOW CREATE TABLE $oldName" );
543 $row = $this->fetchRow( $res );
544 $oldQuery = $row[1];
545 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
546 "CREATE $tmp TABLE `$newName`", $oldQuery );
547 if ($oldQuery === $query) {
548 # Couldn't do replacement
549 throw new MWException( "could not create temporary table $newName" );
550 }
551 } else {
552 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
553 }
554 $this->query( $query, $fname );
555 }
556
557 }
558
559 /**
560 * Legacy support: Database == DatabaseMysql
561 */
562 class Database extends DatabaseMysql {}
563
564 class MySQLMasterPos {
565 var $file, $pos;
566
567 function __construct( $file, $pos ) {
568 $this->file = $file;
569 $this->pos = $pos;
570 }
571
572 function __toString() {
573 return "{$this->file}/{$this->pos}";
574 }
575 }