(bug 12586) Use wfHostname() everywhere, remove $wguname and $wgNodeName. Use getenv...
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * @file
6 * @ingroup Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
9 */
10
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
17
18 /**
19 * Database abstraction object
20 * @ingroup Database
21 */
22 class Database {
23
24 #------------------------------------------------------------------------------
25 # Variables
26 #------------------------------------------------------------------------------
27
28 protected $mLastQuery = '';
29 protected $mPHPError = false;
30
31 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
32 protected $mOpened = false;
33
34 protected $mFailFunction;
35 protected $mTablePrefix;
36 protected $mFlags;
37 protected $mTrxLevel = 0;
38 protected $mErrorCount = 0;
39 protected $mLBInfo = array();
40 protected $mFakeSlaveLag = null, $mFakeMaster = false;
41
42 #------------------------------------------------------------------------------
43 # Accessors
44 #------------------------------------------------------------------------------
45 # These optionally set a variable and return the previous state
46
47 /**
48 * Fail function, takes a Database as a parameter
49 * Set to false for default, 1 for ignore errors
50 */
51 function failFunction( $function = NULL ) {
52 return wfSetVar( $this->mFailFunction, $function );
53 }
54
55 /**
56 * Output page, used for reporting errors
57 * FALSE means discard output
58 */
59 function setOutputPage( $out ) {
60 wfDeprecated( __METHOD__ );
61 }
62
63 /**
64 * Boolean, controls output of large amounts of debug information
65 */
66 function debug( $debug = NULL ) {
67 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
68 }
69
70 /**
71 * Turns buffering of SQL result sets on (true) or off (false).
72 * Default is "on" and it should not be changed without good reasons.
73 */
74 function bufferResults( $buffer = NULL ) {
75 if ( is_null( $buffer ) ) {
76 return !(bool)( $this->mFlags & DBO_NOBUFFER );
77 } else {
78 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
79 }
80 }
81
82 /**
83 * Turns on (false) or off (true) the automatic generation and sending
84 * of a "we're sorry, but there has been a database error" page on
85 * database errors. Default is on (false). When turned off, the
86 * code should use lastErrno() and lastError() to handle the
87 * situation as appropriate.
88 */
89 function ignoreErrors( $ignoreErrors = NULL ) {
90 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
91 }
92
93 /**
94 * The current depth of nested transactions
95 * @param $level Integer: , default NULL.
96 */
97 function trxLevel( $level = NULL ) {
98 return wfSetVar( $this->mTrxLevel, $level );
99 }
100
101 /**
102 * Number of errors logged, only useful when errors are ignored
103 */
104 function errorCount( $count = NULL ) {
105 return wfSetVar( $this->mErrorCount, $count );
106 }
107
108 function tablePrefix( $prefix = null ) {
109 return wfSetVar( $this->mTablePrefix, $prefix );
110 }
111
112 /**
113 * Properties passed down from the server info array of the load balancer
114 */
115 function getLBInfo( $name = NULL ) {
116 if ( is_null( $name ) ) {
117 return $this->mLBInfo;
118 } else {
119 if ( array_key_exists( $name, $this->mLBInfo ) ) {
120 return $this->mLBInfo[$name];
121 } else {
122 return NULL;
123 }
124 }
125 }
126
127 function setLBInfo( $name, $value = NULL ) {
128 if ( is_null( $value ) ) {
129 $this->mLBInfo = $name;
130 } else {
131 $this->mLBInfo[$name] = $value;
132 }
133 }
134
135 /**
136 * Set lag time in seconds for a fake slave
137 */
138 function setFakeSlaveLag( $lag ) {
139 $this->mFakeSlaveLag = $lag;
140 }
141
142 /**
143 * Make this connection a fake master
144 */
145 function setFakeMaster( $enabled = true ) {
146 $this->mFakeMaster = $enabled;
147 }
148
149 /**
150 * Returns true if this database supports (and uses) cascading deletes
151 */
152 function cascadingDeletes() {
153 return false;
154 }
155
156 /**
157 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
158 */
159 function cleanupTriggers() {
160 return false;
161 }
162
163 /**
164 * Returns true if this database is strict about what can be put into an IP field.
165 * Specifically, it uses a NULL value instead of an empty string.
166 */
167 function strictIPs() {
168 return false;
169 }
170
171 /**
172 * Returns true if this database uses timestamps rather than integers
173 */
174 function realTimestamps() {
175 return false;
176 }
177
178 /**
179 * Returns true if this database does an implicit sort when doing GROUP BY
180 */
181 function implicitGroupby() {
182 return true;
183 }
184
185 /**
186 * Returns true if this database does an implicit order by when the column has an index
187 * For example: SELECT page_title FROM page LIMIT 1
188 */
189 function implicitOrderby() {
190 return true;
191 }
192
193 /**
194 * Returns true if this database can do a native search on IP columns
195 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
196 */
197 function searchableIPs() {
198 return false;
199 }
200
201 /**
202 * Returns true if this database can use functional indexes
203 */
204 function functionalIndexes() {
205 return false;
206 }
207
208 /**
209 * Return the last query that went through Database::query()
210 * @return string
211 */
212 function lastQuery() { return $this->mLastQuery; }
213
214 /**
215 * Is a connection to the database open?
216 * @return bool
217 */
218 function isOpen() { return $this->mOpened; }
219
220 function setFlag( $flag ) {
221 $this->mFlags |= $flag;
222 }
223
224 function clearFlag( $flag ) {
225 $this->mFlags &= ~$flag;
226 }
227
228 function getFlag( $flag ) {
229 return !!($this->mFlags & $flag);
230 }
231
232 /**
233 * General read-only accessor
234 */
235 function getProperty( $name ) {
236 return $this->$name;
237 }
238
239 function getWikiID() {
240 if( $this->mTablePrefix ) {
241 return "{$this->mDBname}-{$this->mTablePrefix}";
242 } else {
243 return $this->mDBname;
244 }
245 }
246
247 #------------------------------------------------------------------------------
248 # Other functions
249 #------------------------------------------------------------------------------
250
251 /**@{{
252 * Constructor.
253 * @param string $server database server host
254 * @param string $user database user name
255 * @param string $password database user password
256 * @param string $dbname database name
257 * @param failFunction
258 * @param $flags
259 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
260 */
261 function __construct( $server = false, $user = false, $password = false, $dbName = false,
262 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
263
264 global $wgOut, $wgDBprefix, $wgCommandLineMode;
265 # Can't get a reference if it hasn't been set yet
266 if ( !isset( $wgOut ) ) {
267 $wgOut = NULL;
268 }
269
270 $this->mFailFunction = $failFunction;
271 $this->mFlags = $flags;
272
273 if ( $this->mFlags & DBO_DEFAULT ) {
274 if ( $wgCommandLineMode ) {
275 $this->mFlags &= ~DBO_TRX;
276 } else {
277 $this->mFlags |= DBO_TRX;
278 }
279 }
280
281 /*
282 // Faster read-only access
283 if ( wfReadOnly() ) {
284 $this->mFlags |= DBO_PERSISTENT;
285 $this->mFlags &= ~DBO_TRX;
286 }*/
287
288 /** Get the default table prefix*/
289 if ( $tablePrefix == 'get from global' ) {
290 $this->mTablePrefix = $wgDBprefix;
291 } else {
292 $this->mTablePrefix = $tablePrefix;
293 }
294
295 if ( $server ) {
296 $this->open( $server, $user, $password, $dbName );
297 }
298 }
299
300 /**
301 * @static
302 * @param failFunction
303 * @param $flags
304 */
305 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
306 {
307 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
308 }
309
310 /**
311 * Usually aborts on failure
312 * If the failFunction is set to a non-zero integer, returns success
313 */
314 function open( $server, $user, $password, $dbName ) {
315 global $wgAllDBsAreLocalhost;
316 wfProfileIn( __METHOD__ );
317
318 # Test for missing mysql.so
319 # First try to load it
320 if (!@extension_loaded('mysql')) {
321 @dl('mysql.so');
322 }
323
324 # Fail now
325 # Otherwise we get a suppressed fatal error, which is very hard to track down
326 if ( !function_exists( 'mysql_connect' ) ) {
327 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
328 }
329
330 # Debugging hack -- fake cluster
331 if ( $wgAllDBsAreLocalhost ) {
332 $realServer = 'localhost';
333 } else {
334 $realServer = $server;
335 }
336 $this->close();
337 $this->mServer = $server;
338 $this->mUser = $user;
339 $this->mPassword = $password;
340 $this->mDBname = $dbName;
341
342 $success = false;
343
344 wfProfileIn("dbconnect-$server");
345
346 # The kernel's default SYN retransmission period is far too slow for us,
347 # so we use a short timeout plus a manual retry. Retrying means that a small
348 # but finite rate of SYN packet loss won't cause user-visible errors.
349 $this->mConn = false;
350 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
351 $numAttempts = 2;
352 } else {
353 $numAttempts = 1;
354 }
355 $this->installErrorHandler();
356 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
357 if ( $i > 1 ) {
358 usleep( 1000 );
359 }
360 if ( $this->mFlags & DBO_PERSISTENT ) {
361 $this->mConn = mysql_pconnect( $realServer, $user, $password );
362 } else {
363 # Create a new connection...
364 $this->mConn = mysql_connect( $realServer, $user, $password, true );
365 }
366 if ($this->mConn === false) {
367 #$iplus = $i + 1;
368 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
369 }
370 }
371 $phpError = $this->restoreErrorHandler();
372 # Always log connection errors
373 if ( !$this->mConn ) {
374 $error = $this->lastError();
375 if ( !$error ) {
376 $error = $phpError;
377 }
378 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
379 wfDebug( "DB connection error\n" );
380 wfDebug( "Server: $server, User: $user, Password: " .
381 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
382 $success = false;
383 }
384
385 wfProfileOut("dbconnect-$server");
386
387 if ( $dbName != '' && $this->mConn !== false ) {
388 $success = @/**/mysql_select_db( $dbName, $this->mConn );
389 if ( !$success ) {
390 $error = "Error selecting database $dbName on server {$this->mServer} " .
391 "from client host " . wfHostname() . "\n";
392 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
393 wfDebug( $error );
394 }
395 } else {
396 # Delay USE query
397 $success = (bool)$this->mConn;
398 }
399
400 if ( $success ) {
401 $version = $this->getServerVersion();
402 if ( version_compare( $version, '4.1' ) >= 0 ) {
403 // Tell the server we're communicating with it in UTF-8.
404 // This may engage various charset conversions.
405 global $wgDBmysql5;
406 if( $wgDBmysql5 ) {
407 $this->query( 'SET NAMES utf8', __METHOD__ );
408 }
409 // Turn off strict mode
410 $this->query( "SET sql_mode = ''", __METHOD__ );
411 }
412
413 // Turn off strict mode if it is on
414 } else {
415 $this->reportConnectionError( $phpError );
416 }
417
418 $this->mOpened = $success;
419 wfProfileOut( __METHOD__ );
420 return $success;
421 }
422 /**@}}*/
423
424 protected function installErrorHandler() {
425 $this->mPHPError = false;
426 $this->htmlErrors = ini_set( 'html_errors', '0' );
427 set_error_handler( array( $this, 'connectionErrorHandler' ) );
428 }
429
430 protected function restoreErrorHandler() {
431 restore_error_handler();
432 if ( $this->htmlErrors !== false ) {
433 ini_set( 'html_errors', $this->htmlErrors );
434 }
435 if ( $this->mPHPError ) {
436 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
437 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
438 return $error;
439 } else {
440 return false;
441 }
442 }
443
444 protected function connectionErrorHandler( $errno, $errstr ) {
445 $this->mPHPError = $errstr;
446 }
447
448 /**
449 * Closes a database connection.
450 * if it is open : commits any open transactions
451 *
452 * @return bool operation success. true if already closed.
453 */
454 function close()
455 {
456 $this->mOpened = false;
457 if ( $this->mConn ) {
458 if ( $this->trxLevel() ) {
459 $this->immediateCommit();
460 }
461 return mysql_close( $this->mConn );
462 } else {
463 return true;
464 }
465 }
466
467 /**
468 * @param string $error fallback error message, used if none is given by MySQL
469 */
470 function reportConnectionError( $error = 'Unknown error' ) {
471 $myError = $this->lastError();
472 if ( $myError ) {
473 $error = $myError;
474 }
475
476 if ( $this->mFailFunction ) {
477 # Legacy error handling method
478 if ( !is_int( $this->mFailFunction ) ) {
479 $ff = $this->mFailFunction;
480 $ff( $this, $error );
481 }
482 } else {
483 # New method
484 throw new DBConnectionError( $this, $error );
485 }
486 }
487
488 /**
489 * Usually aborts on failure. If errors are explicitly ignored, returns success.
490 *
491 * @param $sql String: SQL query
492 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
493 * comment (you can use __METHOD__ or add some extra info)
494 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
495 * maybe best to catch the exception instead?
496 * @return true for a successful write query, ResultWrapper object for a successful read query,
497 * or false on failure if $tempIgnore set
498 * @throws DBQueryError Thrown when the database returns an error of any kind
499 */
500 public function query( $sql, $fname = '', $tempIgnore = false ) {
501 global $wgProfiler;
502
503 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
504 if ( isset( $wgProfiler ) ) {
505 # generalizeSQL will probably cut down the query to reasonable
506 # logging size most of the time. The substr is really just a sanity check.
507
508 # Who's been wasting my precious column space? -- TS
509 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
510
511 if ( $isMaster ) {
512 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
513 $totalProf = 'Database::query-master';
514 } else {
515 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
516 $totalProf = 'Database::query';
517 }
518 wfProfileIn( $totalProf );
519 wfProfileIn( $queryProf );
520 }
521
522 $this->mLastQuery = $sql;
523
524 # Add a comment for easy SHOW PROCESSLIST interpretation
525 #if ( $fname ) {
526 global $wgUser;
527 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
528 $userName = $wgUser->getName();
529 if ( mb_strlen( $userName ) > 15 ) {
530 $userName = mb_substr( $userName, 0, 15 ) . '...';
531 }
532 $userName = str_replace( '/', '', $userName );
533 } else {
534 $userName = '';
535 }
536 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
537 #} else {
538 # $commentedSql = $sql;
539 #}
540
541 # If DBO_TRX is set, start a transaction
542 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
543 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
544 // avoid establishing transactions for SHOW and SET statements too -
545 // that would delay transaction initializations to once connection
546 // is really used by application
547 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
548 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
549 $this->begin();
550 }
551
552 if ( $this->debug() ) {
553 $sqlx = substr( $commentedSql, 0, 500 );
554 $sqlx = strtr( $sqlx, "\t\n", ' ' );
555 if ( $isMaster ) {
556 wfDebug( "SQL-master: $sqlx\n" );
557 } else {
558 wfDebug( "SQL: $sqlx\n" );
559 }
560 }
561
562 # Do the query and handle errors
563 $ret = $this->doQuery( $commentedSql );
564
565 # Try reconnecting if the connection was lost
566 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
567 # Transaction is gone, like it or not
568 $this->mTrxLevel = 0;
569 wfDebug( "Connection lost, reconnecting...\n" );
570 if ( $this->ping() ) {
571 wfDebug( "Reconnected\n" );
572 $sqlx = substr( $commentedSql, 0, 500 );
573 $sqlx = strtr( $sqlx, "\t\n", ' ' );
574 global $wgRequestTime;
575 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
576 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
577 $ret = $this->doQuery( $commentedSql );
578 } else {
579 wfDebug( "Failed\n" );
580 }
581 }
582
583 if ( false === $ret ) {
584 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
585 }
586
587 if ( isset( $wgProfiler ) ) {
588 wfProfileOut( $queryProf );
589 wfProfileOut( $totalProf );
590 }
591 return $this->resultObject( $ret );
592 }
593
594 /**
595 * The DBMS-dependent part of query()
596 * @param $sql String: SQL query.
597 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
598 * @access private
599 */
600 /*private*/ function doQuery( $sql ) {
601 if( $this->bufferResults() ) {
602 $ret = mysql_query( $sql, $this->mConn );
603 } else {
604 $ret = mysql_unbuffered_query( $sql, $this->mConn );
605 }
606 return $ret;
607 }
608
609 /**
610 * @param $error
611 * @param $errno
612 * @param $sql
613 * @param string $fname
614 * @param bool $tempIgnore
615 */
616 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
617 global $wgCommandLineMode;
618 # Ignore errors during error handling to avoid infinite recursion
619 $ignore = $this->ignoreErrors( true );
620 ++$this->mErrorCount;
621
622 if( $ignore || $tempIgnore ) {
623 wfDebug("SQL ERROR (ignored): $error\n");
624 $this->ignoreErrors( $ignore );
625 } else {
626 $sql1line = str_replace( "\n", "\\n", $sql );
627 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
628 wfDebug("SQL ERROR: " . $error . "\n");
629 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
630 }
631 }
632
633
634 /**
635 * Intended to be compatible with the PEAR::DB wrapper functions.
636 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
637 *
638 * ? = scalar value, quoted as necessary
639 * ! = raw SQL bit (a function for instance)
640 * & = filename; reads the file and inserts as a blob
641 * (we don't use this though...)
642 */
643 function prepare( $sql, $func = 'Database::prepare' ) {
644 /* MySQL doesn't support prepared statements (yet), so just
645 pack up the query for reference. We'll manually replace
646 the bits later. */
647 return array( 'query' => $sql, 'func' => $func );
648 }
649
650 function freePrepared( $prepared ) {
651 /* No-op for MySQL */
652 }
653
654 /**
655 * Execute a prepared query with the various arguments
656 * @param string $prepared the prepared sql
657 * @param mixed $args Either an array here, or put scalars as varargs
658 */
659 function execute( $prepared, $args = null ) {
660 if( !is_array( $args ) ) {
661 # Pull the var args
662 $args = func_get_args();
663 array_shift( $args );
664 }
665 $sql = $this->fillPrepared( $prepared['query'], $args );
666 return $this->query( $sql, $prepared['func'] );
667 }
668
669 /**
670 * Prepare & execute an SQL statement, quoting and inserting arguments
671 * in the appropriate places.
672 * @param string $query
673 * @param string $args ...
674 */
675 function safeQuery( $query, $args = null ) {
676 $prepared = $this->prepare( $query, 'Database::safeQuery' );
677 if( !is_array( $args ) ) {
678 # Pull the var args
679 $args = func_get_args();
680 array_shift( $args );
681 }
682 $retval = $this->execute( $prepared, $args );
683 $this->freePrepared( $prepared );
684 return $retval;
685 }
686
687 /**
688 * For faking prepared SQL statements on DBs that don't support
689 * it directly.
690 * @param string $preparedSql - a 'preparable' SQL statement
691 * @param array $args - array of arguments to fill it with
692 * @return string executable SQL
693 */
694 function fillPrepared( $preparedQuery, $args ) {
695 reset( $args );
696 $this->preparedArgs =& $args;
697 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
698 array( &$this, 'fillPreparedArg' ), $preparedQuery );
699 }
700
701 /**
702 * preg_callback func for fillPrepared()
703 * The arguments should be in $this->preparedArgs and must not be touched
704 * while we're doing this.
705 *
706 * @param array $matches
707 * @return string
708 * @private
709 */
710 function fillPreparedArg( $matches ) {
711 switch( $matches[1] ) {
712 case '\\?': return '?';
713 case '\\!': return '!';
714 case '\\&': return '&';
715 }
716 list( /* $n */ , $arg ) = each( $this->preparedArgs );
717 switch( $matches[1] ) {
718 case '?': return $this->addQuotes( $arg );
719 case '!': return $arg;
720 case '&':
721 # return $this->addQuotes( file_get_contents( $arg ) );
722 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
723 default:
724 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
725 }
726 }
727
728 /**#@+
729 * @param mixed $res A SQL result
730 */
731 /**
732 * Free a result object
733 */
734 function freeResult( $res ) {
735 if ( $res instanceof ResultWrapper ) {
736 $res = $res->result;
737 }
738 if ( !@/**/mysql_free_result( $res ) ) {
739 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
740 }
741 }
742
743 /**
744 * Fetch the next row from the given result object, in object form.
745 * Fields can be retrieved with $row->fieldname, with fields acting like
746 * member variables.
747 *
748 * @param $res SQL result object as returned from Database::query(), etc.
749 * @return MySQL row object
750 * @throws DBUnexpectedError Thrown if the database returns an error
751 */
752 function fetchObject( $res ) {
753 if ( $res instanceof ResultWrapper ) {
754 $res = $res->result;
755 }
756 @/**/$row = mysql_fetch_object( $res );
757 if( $this->lastErrno() ) {
758 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
759 }
760 return $row;
761 }
762
763 /**
764 * Fetch the next row from the given result object, in associative array
765 * form. Fields are retrieved with $row['fieldname'].
766 *
767 * @param $res SQL result object as returned from Database::query(), etc.
768 * @return MySQL row object
769 * @throws DBUnexpectedError Thrown if the database returns an error
770 */
771 function fetchRow( $res ) {
772 if ( $res instanceof ResultWrapper ) {
773 $res = $res->result;
774 }
775 @/**/$row = mysql_fetch_array( $res );
776 if ( $this->lastErrno() ) {
777 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
778 }
779 return $row;
780 }
781
782 /**
783 * Get the number of rows in a result object
784 */
785 function numRows( $res ) {
786 if ( $res instanceof ResultWrapper ) {
787 $res = $res->result;
788 }
789 @/**/$n = mysql_num_rows( $res );
790 if( $this->lastErrno() ) {
791 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
792 }
793 return $n;
794 }
795
796 /**
797 * Get the number of fields in a result object
798 * See documentation for mysql_num_fields()
799 */
800 function numFields( $res ) {
801 if ( $res instanceof ResultWrapper ) {
802 $res = $res->result;
803 }
804 return mysql_num_fields( $res );
805 }
806
807 /**
808 * Get a field name in a result object
809 * See documentation for mysql_field_name():
810 * http://www.php.net/mysql_field_name
811 */
812 function fieldName( $res, $n ) {
813 if ( $res instanceof ResultWrapper ) {
814 $res = $res->result;
815 }
816 return mysql_field_name( $res, $n );
817 }
818
819 /**
820 * Get the inserted value of an auto-increment row
821 *
822 * The value inserted should be fetched from nextSequenceValue()
823 *
824 * Example:
825 * $id = $dbw->nextSequenceValue('page_page_id_seq');
826 * $dbw->insert('page',array('page_id' => $id));
827 * $id = $dbw->insertId();
828 */
829 function insertId() { return mysql_insert_id( $this->mConn ); }
830
831 /**
832 * Change the position of the cursor in a result object
833 * See mysql_data_seek()
834 */
835 function dataSeek( $res, $row ) {
836 if ( $res instanceof ResultWrapper ) {
837 $res = $res->result;
838 }
839 return mysql_data_seek( $res, $row );
840 }
841
842 /**
843 * Get the last error number
844 * See mysql_errno()
845 */
846 function lastErrno() {
847 if ( $this->mConn ) {
848 return mysql_errno( $this->mConn );
849 } else {
850 return mysql_errno();
851 }
852 }
853
854 /**
855 * Get a description of the last error
856 * See mysql_error() for more details
857 */
858 function lastError() {
859 if ( $this->mConn ) {
860 # Even if it's non-zero, it can still be invalid
861 wfSuppressWarnings();
862 $error = mysql_error( $this->mConn );
863 if ( !$error ) {
864 $error = mysql_error();
865 }
866 wfRestoreWarnings();
867 } else {
868 $error = mysql_error();
869 }
870 if( $error ) {
871 $error .= ' (' . $this->mServer . ')';
872 }
873 return $error;
874 }
875 /**
876 * Get the number of rows affected by the last write query
877 * See mysql_affected_rows() for more details
878 */
879 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
880 /**#@-*/ // end of template : @param $result
881
882 /**
883 * Simple UPDATE wrapper
884 * Usually aborts on failure
885 * If errors are explicitly ignored, returns success
886 *
887 * This function exists for historical reasons, Database::update() has a more standard
888 * calling convention and feature set
889 */
890 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
891 {
892 $table = $this->tableName( $table );
893 $sql = "UPDATE $table SET $var = '" .
894 $this->strencode( $value ) . "' WHERE ($cond)";
895 return (bool)$this->query( $sql, $fname );
896 }
897
898 /**
899 * Simple SELECT wrapper, returns a single field, input must be encoded
900 * Usually aborts on failure
901 * If errors are explicitly ignored, returns FALSE on failure
902 */
903 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
904 if ( !is_array( $options ) ) {
905 $options = array( $options );
906 }
907 $options['LIMIT'] = 1;
908
909 $res = $this->select( $table, $var, $cond, $fname, $options );
910 if ( $res === false || !$this->numRows( $res ) ) {
911 return false;
912 }
913 $row = $this->fetchRow( $res );
914 if ( $row !== false ) {
915 $this->freeResult( $res );
916 return $row[0];
917 } else {
918 return false;
919 }
920 }
921
922 /**
923 * Returns an optional USE INDEX clause to go after the table, and a
924 * string to go at the end of the query
925 *
926 * @private
927 *
928 * @param array $options an associative array of options to be turned into
929 * an SQL query, valid keys are listed in the function.
930 * @return array
931 */
932 function makeSelectOptions( $options ) {
933 $preLimitTail = $postLimitTail = '';
934 $startOpts = '';
935
936 $noKeyOptions = array();
937 foreach ( $options as $key => $option ) {
938 if ( is_numeric( $key ) ) {
939 $noKeyOptions[$option] = true;
940 }
941 }
942
943 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
944 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
945 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
946
947 //if (isset($options['LIMIT'])) {
948 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
949 // isset($options['OFFSET']) ? $options['OFFSET']
950 // : false);
951 //}
952
953 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
954 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
955 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
956
957 # Various MySQL extensions
958 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
959 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
960 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
961 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
962 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
963 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
964 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
965 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
966
967 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
968 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
969 } else {
970 $useIndex = '';
971 }
972
973 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
974 }
975
976 /**
977 * SELECT wrapper
978 *
979 * @param mixed $table Array or string, table name(s) (prefix auto-added)
980 * @param mixed $vars Array or string, field name(s) to be retrieved
981 * @param mixed $conds Array or string, condition(s) for WHERE
982 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
983 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
984 * see Database::makeSelectOptions code for list of supported stuff
985 * @param array $join_conds Associative array of table join conditions (optional)
986 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
987 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
988 */
989 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
990 {
991 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
992 return $this->query( $sql, $fname );
993 }
994
995 /**
996 * SELECT wrapper
997 *
998 * @param mixed $table Array or string, table name(s) (prefix auto-added)
999 * @param mixed $vars Array or string, field name(s) to be retrieved
1000 * @param mixed $conds Array or string, condition(s) for WHERE
1001 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1002 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1003 * see Database::makeSelectOptions code for list of supported stuff
1004 * @param array $join_conds Associative array of table join conditions (optional)
1005 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1006 * @return string, the SQL text
1007 */
1008 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1009 if( is_array( $vars ) ) {
1010 $vars = implode( ',', $vars );
1011 }
1012 if( !is_array( $options ) ) {
1013 $options = array( $options );
1014 }
1015 if( is_array( $table ) ) {
1016 if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1017 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1018 else
1019 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1020 } elseif ($table!='') {
1021 if ($table{0}==' ') {
1022 $from = ' FROM ' . $table;
1023 } else {
1024 $from = ' FROM ' . $this->tableName( $table );
1025 }
1026 } else {
1027 $from = '';
1028 }
1029
1030 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1031
1032 if( !empty( $conds ) ) {
1033 if ( is_array( $conds ) ) {
1034 $conds = $this->makeList( $conds, LIST_AND );
1035 }
1036 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1037 } else {
1038 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1039 }
1040
1041 if (isset($options['LIMIT']))
1042 $sql = $this->limitResult($sql, $options['LIMIT'],
1043 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1044 $sql = "$sql $postLimitTail";
1045
1046 if (isset($options['EXPLAIN'])) {
1047 $sql = 'EXPLAIN ' . $sql;
1048 }
1049 return $sql;
1050 }
1051
1052 /**
1053 * Single row SELECT wrapper
1054 * Aborts or returns FALSE on error
1055 *
1056 * $vars: the selected variables
1057 * $conds: a condition map, terms are ANDed together.
1058 * Items with numeric keys are taken to be literal conditions
1059 * Takes an array of selected variables, and a condition map, which is ANDed
1060 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1061 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1062 * $obj- >page_id is the ID of the Astronomy article
1063 *
1064 * @todo migrate documentation to phpdocumentor format
1065 */
1066 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1067 $options['LIMIT'] = 1;
1068 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1069 if ( $res === false )
1070 return false;
1071 if ( !$this->numRows($res) ) {
1072 $this->freeResult($res);
1073 return false;
1074 }
1075 $obj = $this->fetchObject( $res );
1076 $this->freeResult( $res );
1077 return $obj;
1078
1079 }
1080
1081 /**
1082 * Estimate rows in dataset
1083 * Returns estimated count, based on EXPLAIN output
1084 * Takes same arguments as Database::select()
1085 */
1086
1087 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1088 $options['EXPLAIN']=true;
1089 $res = $this->select ($table, $vars, $conds, $fname, $options );
1090 if ( $res === false )
1091 return false;
1092 if (!$this->numRows($res)) {
1093 $this->freeResult($res);
1094 return 0;
1095 }
1096
1097 $rows=1;
1098
1099 while( $plan = $this->fetchObject( $res ) ) {
1100 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1101 }
1102
1103 $this->freeResult($res);
1104 return $rows;
1105 }
1106
1107
1108 /**
1109 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1110 * It's only slightly flawed. Don't use for anything important.
1111 *
1112 * @param string $sql A SQL Query
1113 * @static
1114 */
1115 static function generalizeSQL( $sql ) {
1116 # This does the same as the regexp below would do, but in such a way
1117 # as to avoid crashing php on some large strings.
1118 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1119
1120 $sql = str_replace ( "\\\\", '', $sql);
1121 $sql = str_replace ( "\\'", '', $sql);
1122 $sql = str_replace ( "\\\"", '', $sql);
1123 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1124 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1125
1126 # All newlines, tabs, etc replaced by single space
1127 $sql = preg_replace ( '/\s+/', ' ', $sql);
1128
1129 # All numbers => N
1130 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1131
1132 return $sql;
1133 }
1134
1135 /**
1136 * Determines whether a field exists in a table
1137 * Usually aborts on failure
1138 * If errors are explicitly ignored, returns NULL on failure
1139 */
1140 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1141 $table = $this->tableName( $table );
1142 $res = $this->query( 'DESCRIBE '.$table, $fname );
1143 if ( !$res ) {
1144 return NULL;
1145 }
1146
1147 $found = false;
1148
1149 while ( $row = $this->fetchObject( $res ) ) {
1150 if ( $row->Field == $field ) {
1151 $found = true;
1152 break;
1153 }
1154 }
1155 return $found;
1156 }
1157
1158 /**
1159 * Determines whether an index exists
1160 * Usually aborts on failure
1161 * If errors are explicitly ignored, returns NULL on failure
1162 */
1163 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1164 $info = $this->indexInfo( $table, $index, $fname );
1165 if ( is_null( $info ) ) {
1166 return NULL;
1167 } else {
1168 return $info !== false;
1169 }
1170 }
1171
1172
1173 /**
1174 * Get information about an index into an object
1175 * Returns false if the index does not exist
1176 */
1177 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1178 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1179 # SHOW INDEX should work for 3.x and up:
1180 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1181 $table = $this->tableName( $table );
1182 $sql = 'SHOW INDEX FROM '.$table;
1183 $res = $this->query( $sql, $fname );
1184 if ( !$res ) {
1185 return NULL;
1186 }
1187
1188 $result = array();
1189 while ( $row = $this->fetchObject( $res ) ) {
1190 if ( $row->Key_name == $index ) {
1191 $result[] = $row;
1192 }
1193 }
1194 $this->freeResult($res);
1195
1196 return empty($result) ? false : $result;
1197 }
1198
1199 /**
1200 * Query whether a given table exists
1201 */
1202 function tableExists( $table ) {
1203 $table = $this->tableName( $table );
1204 $old = $this->ignoreErrors( true );
1205 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1206 $this->ignoreErrors( $old );
1207 if( $res ) {
1208 $this->freeResult( $res );
1209 return true;
1210 } else {
1211 return false;
1212 }
1213 }
1214
1215 /**
1216 * mysql_fetch_field() wrapper
1217 * Returns false if the field doesn't exist
1218 *
1219 * @param $table
1220 * @param $field
1221 */
1222 function fieldInfo( $table, $field ) {
1223 $table = $this->tableName( $table );
1224 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1225 $n = mysql_num_fields( $res->result );
1226 for( $i = 0; $i < $n; $i++ ) {
1227 $meta = mysql_fetch_field( $res->result, $i );
1228 if( $field == $meta->name ) {
1229 return new MySQLField($meta);
1230 }
1231 }
1232 return false;
1233 }
1234
1235 /**
1236 * mysql_field_type() wrapper
1237 */
1238 function fieldType( $res, $index ) {
1239 if ( $res instanceof ResultWrapper ) {
1240 $res = $res->result;
1241 }
1242 return mysql_field_type( $res, $index );
1243 }
1244
1245 /**
1246 * Determines if a given index is unique
1247 */
1248 function indexUnique( $table, $index ) {
1249 $indexInfo = $this->indexInfo( $table, $index );
1250 if ( !$indexInfo ) {
1251 return NULL;
1252 }
1253 return !$indexInfo[0]->Non_unique;
1254 }
1255
1256 /**
1257 * INSERT wrapper, inserts an array into a table
1258 *
1259 * $a may be a single associative array, or an array of these with numeric keys, for
1260 * multi-row insert.
1261 *
1262 * Usually aborts on failure
1263 * If errors are explicitly ignored, returns success
1264 */
1265 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1266 # No rows to insert, easy just return now
1267 if ( !count( $a ) ) {
1268 return true;
1269 }
1270
1271 $table = $this->tableName( $table );
1272 if ( !is_array( $options ) ) {
1273 $options = array( $options );
1274 }
1275 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1276 $multi = true;
1277 $keys = array_keys( $a[0] );
1278 } else {
1279 $multi = false;
1280 $keys = array_keys( $a );
1281 }
1282
1283 $sql = 'INSERT ' . implode( ' ', $options ) .
1284 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1285
1286 if ( $multi ) {
1287 $first = true;
1288 foreach ( $a as $row ) {
1289 if ( $first ) {
1290 $first = false;
1291 } else {
1292 $sql .= ',';
1293 }
1294 $sql .= '(' . $this->makeList( $row ) . ')';
1295 }
1296 } else {
1297 $sql .= '(' . $this->makeList( $a ) . ')';
1298 }
1299 return (bool)$this->query( $sql, $fname );
1300 }
1301
1302 /**
1303 * Make UPDATE options for the Database::update function
1304 *
1305 * @private
1306 * @param array $options The options passed to Database::update
1307 * @return string
1308 */
1309 function makeUpdateOptions( $options ) {
1310 if( !is_array( $options ) ) {
1311 $options = array( $options );
1312 }
1313 $opts = array();
1314 if ( in_array( 'LOW_PRIORITY', $options ) )
1315 $opts[] = $this->lowPriorityOption();
1316 if ( in_array( 'IGNORE', $options ) )
1317 $opts[] = 'IGNORE';
1318 return implode(' ', $opts);
1319 }
1320
1321 /**
1322 * UPDATE wrapper, takes a condition array and a SET array
1323 *
1324 * @param string $table The table to UPDATE
1325 * @param array $values An array of values to SET
1326 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1327 * @param string $fname The Class::Function calling this function
1328 * (for the log)
1329 * @param array $options An array of UPDATE options, can be one or
1330 * more of IGNORE, LOW_PRIORITY
1331 * @return bool
1332 */
1333 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1334 $table = $this->tableName( $table );
1335 $opts = $this->makeUpdateOptions( $options );
1336 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1337 if ( $conds != '*' ) {
1338 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1339 }
1340 return $this->query( $sql, $fname );
1341 }
1342
1343 /**
1344 * Makes an encoded list of strings from an array
1345 * $mode:
1346 * LIST_COMMA - comma separated, no field names
1347 * LIST_AND - ANDed WHERE clause (without the WHERE)
1348 * LIST_OR - ORed WHERE clause (without the WHERE)
1349 * LIST_SET - comma separated with field names, like a SET clause
1350 * LIST_NAMES - comma separated field names
1351 */
1352 function makeList( $a, $mode = LIST_COMMA ) {
1353 if ( !is_array( $a ) ) {
1354 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1355 }
1356
1357 $first = true;
1358 $list = '';
1359 foreach ( $a as $field => $value ) {
1360 if ( !$first ) {
1361 if ( $mode == LIST_AND ) {
1362 $list .= ' AND ';
1363 } elseif($mode == LIST_OR) {
1364 $list .= ' OR ';
1365 } else {
1366 $list .= ',';
1367 }
1368 } else {
1369 $first = false;
1370 }
1371 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1372 $list .= "($value)";
1373 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1374 $list .= "$value";
1375 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1376 if( count( $value ) == 0 ) {
1377 throw new MWException( __METHOD__.': empty input' );
1378 } elseif( count( $value ) == 1 ) {
1379 // Special-case single values, as IN isn't terribly efficient
1380 // Don't necessarily assume the single key is 0; we don't
1381 // enforce linear numeric ordering on other arrays here.
1382 $value = array_values( $value );
1383 $list .= $field." = ".$this->addQuotes( $value[0] );
1384 } else {
1385 $list .= $field." IN (".$this->makeList($value).") ";
1386 }
1387 } elseif( is_null($value) ) {
1388 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1389 $list .= "$field IS ";
1390 } elseif ( $mode == LIST_SET ) {
1391 $list .= "$field = ";
1392 }
1393 $list .= 'NULL';
1394 } else {
1395 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1396 $list .= "$field = ";
1397 }
1398 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1399 }
1400 }
1401 return $list;
1402 }
1403
1404 /**
1405 * Change the current database
1406 */
1407 function selectDB( $db ) {
1408 $this->mDBname = $db;
1409 return mysql_select_db( $db, $this->mConn );
1410 }
1411
1412 /**
1413 * Get the current DB name
1414 */
1415 function getDBname() {
1416 return $this->mDBname;
1417 }
1418
1419 /**
1420 * Get the server hostname or IP address
1421 */
1422 function getServer() {
1423 return $this->mServer;
1424 }
1425
1426 /**
1427 * Format a table name ready for use in constructing an SQL query
1428 *
1429 * This does two important things: it quotes the table names to clean them up,
1430 * and it adds a table prefix if only given a table name with no quotes.
1431 *
1432 * All functions of this object which require a table name call this function
1433 * themselves. Pass the canonical name to such functions. This is only needed
1434 * when calling query() directly.
1435 *
1436 * @param string $name database table name
1437 * @return string full database name
1438 */
1439 function tableName( $name ) {
1440 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1441 # Skip the entire process when we have a string quoted on both ends.
1442 # Note that we check the end so that we will still quote any use of
1443 # use of `database`.table. But won't break things if someone wants
1444 # to query a database table with a dot in the name.
1445 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1446
1447 # Lets test for any bits of text that should never show up in a table
1448 # name. Basically anything like JOIN or ON which are actually part of
1449 # SQL queries, but may end up inside of the table value to combine
1450 # sql. Such as how the API is doing.
1451 # Note that we use a whitespace test rather than a \b test to avoid
1452 # any remote case where a word like on may be inside of a table name
1453 # surrounded by symbols which may be considered word breaks.
1454 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1455
1456 # Split database and table into proper variables.
1457 # We reverse the explode so that database.table and table both output
1458 # the correct table.
1459 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1460 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1461 else @list( $table ) = $dbDetails;
1462 $prefix = $this->mTablePrefix; # Default prefix
1463
1464 # A database name has been specified in input. Quote the table name
1465 # because we don't want any prefixes added.
1466 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1467
1468 # Note that we use the long format because php will complain in in_array if
1469 # the input is not an array, and will complain in is_array if it is not set.
1470 if( !isset( $database ) # Don't use shared database if pre selected.
1471 && isset( $wgSharedDB ) # We have a shared database
1472 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1473 && isset( $wgSharedTables )
1474 && is_array( $wgSharedTables )
1475 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1476 $database = $wgSharedDB;
1477 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1478 }
1479
1480 # Quote the $database and $table and apply the prefix if not quoted.
1481 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1482 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1483
1484 # Merge our database and table into our final table name.
1485 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1486
1487 # We're finished, return.
1488 return $tableName;
1489 }
1490
1491 /**
1492 * Fetch a number of table names into an array
1493 * This is handy when you need to construct SQL for joins
1494 *
1495 * Example:
1496 * extract($dbr->tableNames('user','watchlist'));
1497 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1498 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1499 */
1500 public function tableNames() {
1501 $inArray = func_get_args();
1502 $retVal = array();
1503 foreach ( $inArray as $name ) {
1504 $retVal[$name] = $this->tableName( $name );
1505 }
1506 return $retVal;
1507 }
1508
1509 /**
1510 * Fetch a number of table names into an zero-indexed numerical array
1511 * This is handy when you need to construct SQL for joins
1512 *
1513 * Example:
1514 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1515 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1516 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1517 */
1518 public function tableNamesN() {
1519 $inArray = func_get_args();
1520 $retVal = array();
1521 foreach ( $inArray as $name ) {
1522 $retVal[] = $this->tableName( $name );
1523 }
1524 return $retVal;
1525 }
1526
1527 /**
1528 * @private
1529 */
1530 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1531 $ret = array();
1532 $retJOIN = array();
1533 $use_index_safe = is_array($use_index) ? $use_index : array();
1534 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1535 foreach ( $tables as $table ) {
1536 // Is there a JOIN and INDEX clause for this table?
1537 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1538 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1539 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1540 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1541 $retJOIN[] = $tableClause;
1542 // Is there an INDEX clause?
1543 } else if ( isset($use_index_safe[$table]) ) {
1544 $tableClause = $this->tableName( $table );
1545 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1546 $ret[] = $tableClause;
1547 // Is there a JOIN clause?
1548 } else if ( isset($join_conds_safe[$table]) ) {
1549 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1550 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1551 $retJOIN[] = $tableClause;
1552 } else {
1553 $tableClause = $this->tableName( $table );
1554 $ret[] = $tableClause;
1555 }
1556 }
1557 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1558 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1559 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1560 // Compile our final table clause
1561 return implode(' ',array($straightJoins,$otherJoins) );
1562 }
1563
1564 /**
1565 * Wrapper for addslashes()
1566 * @param string $s String to be slashed.
1567 * @return string slashed string.
1568 */
1569 function strencode( $s ) {
1570 return mysql_real_escape_string( $s, $this->mConn );
1571 }
1572
1573 /**
1574 * If it's a string, adds quotes and backslashes
1575 * Otherwise returns as-is
1576 */
1577 function addQuotes( $s ) {
1578 if ( is_null( $s ) ) {
1579 return 'NULL';
1580 } else {
1581 # This will also quote numeric values. This should be harmless,
1582 # and protects against weird problems that occur when they really
1583 # _are_ strings such as article titles and string->number->string
1584 # conversion is not 1:1.
1585 return "'" . $this->strencode( $s ) . "'";
1586 }
1587 }
1588
1589 /**
1590 * Escape string for safe LIKE usage
1591 */
1592 function escapeLike( $s ) {
1593 $s=$this->strencode( $s );
1594 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1595 return $s;
1596 }
1597
1598 /**
1599 * Returns an appropriately quoted sequence value for inserting a new row.
1600 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1601 * subclass will return an integer, and save the value for insertId()
1602 */
1603 function nextSequenceValue( $seqName ) {
1604 return NULL;
1605 }
1606
1607 /**
1608 * USE INDEX clause
1609 * PostgreSQL doesn't have them and returns ""
1610 */
1611 function useIndexClause( $index ) {
1612 return "FORCE INDEX ($index)";
1613 }
1614
1615 /**
1616 * REPLACE query wrapper
1617 * PostgreSQL simulates this with a DELETE followed by INSERT
1618 * $row is the row to insert, an associative array
1619 * $uniqueIndexes is an array of indexes. Each element may be either a
1620 * field name or an array of field names
1621 *
1622 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1623 * However if you do this, you run the risk of encountering errors which wouldn't have
1624 * occurred in MySQL
1625 *
1626 * @todo migrate comment to phodocumentor format
1627 */
1628 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1629 $table = $this->tableName( $table );
1630
1631 # Single row case
1632 if ( !is_array( reset( $rows ) ) ) {
1633 $rows = array( $rows );
1634 }
1635
1636 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1637 $first = true;
1638 foreach ( $rows as $row ) {
1639 if ( $first ) {
1640 $first = false;
1641 } else {
1642 $sql .= ',';
1643 }
1644 $sql .= '(' . $this->makeList( $row ) . ')';
1645 }
1646 return $this->query( $sql, $fname );
1647 }
1648
1649 /**
1650 * DELETE where the condition is a join
1651 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1652 *
1653 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1654 * join condition matches, set $conds='*'
1655 *
1656 * DO NOT put the join condition in $conds
1657 *
1658 * @param string $delTable The table to delete from.
1659 * @param string $joinTable The other table.
1660 * @param string $delVar The variable to join on, in the first table.
1661 * @param string $joinVar The variable to join on, in the second table.
1662 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1663 */
1664 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1665 if ( !$conds ) {
1666 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1667 }
1668
1669 $delTable = $this->tableName( $delTable );
1670 $joinTable = $this->tableName( $joinTable );
1671 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1672 if ( $conds != '*' ) {
1673 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1674 }
1675
1676 return $this->query( $sql, $fname );
1677 }
1678
1679 /**
1680 * Returns the size of a text field, or -1 for "unlimited"
1681 */
1682 function textFieldSize( $table, $field ) {
1683 $table = $this->tableName( $table );
1684 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1685 $res = $this->query( $sql, 'Database::textFieldSize' );
1686 $row = $this->fetchObject( $res );
1687 $this->freeResult( $res );
1688
1689 $m = array();
1690 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1691 $size = $m[1];
1692 } else {
1693 $size = -1;
1694 }
1695 return $size;
1696 }
1697
1698 /**
1699 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1700 */
1701 function lowPriorityOption() {
1702 return 'LOW_PRIORITY';
1703 }
1704
1705 /**
1706 * DELETE query wrapper
1707 *
1708 * Use $conds == "*" to delete all rows
1709 */
1710 function delete( $table, $conds, $fname = 'Database::delete' ) {
1711 if ( !$conds ) {
1712 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1713 }
1714 $table = $this->tableName( $table );
1715 $sql = "DELETE FROM $table";
1716 if ( $conds != '*' ) {
1717 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1718 }
1719 return $this->query( $sql, $fname );
1720 }
1721
1722 /**
1723 * INSERT SELECT wrapper
1724 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1725 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1726 * $conds may be "*" to copy the whole table
1727 * srcTable may be an array of tables.
1728 */
1729 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1730 $insertOptions = array(), $selectOptions = array() )
1731 {
1732 $destTable = $this->tableName( $destTable );
1733 if ( is_array( $insertOptions ) ) {
1734 $insertOptions = implode( ' ', $insertOptions );
1735 }
1736 if( !is_array( $selectOptions ) ) {
1737 $selectOptions = array( $selectOptions );
1738 }
1739 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1740 if( is_array( $srcTable ) ) {
1741 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1742 } else {
1743 $srcTable = $this->tableName( $srcTable );
1744 }
1745 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1746 " SELECT $startOpts " . implode( ',', $varMap ) .
1747 " FROM $srcTable $useIndex ";
1748 if ( $conds != '*' ) {
1749 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1750 }
1751 $sql .= " $tailOpts";
1752 return $this->query( $sql, $fname );
1753 }
1754
1755 /**
1756 * Construct a LIMIT query with optional offset
1757 * This is used for query pages
1758 * $sql string SQL query we will append the limit too
1759 * $limit integer the SQL limit
1760 * $offset integer the SQL offset (default false)
1761 */
1762 function limitResult($sql, $limit, $offset=false) {
1763 if( !is_numeric($limit) ) {
1764 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1765 }
1766 return "$sql LIMIT "
1767 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1768 . "{$limit} ";
1769 }
1770 function limitResultForUpdate($sql, $num) {
1771 return $this->limitResult($sql, $num, 0);
1772 }
1773
1774 /**
1775 * Returns an SQL expression for a simple conditional.
1776 * Uses IF on MySQL.
1777 *
1778 * @param string $cond SQL expression which will result in a boolean value
1779 * @param string $trueVal SQL expression to return if true
1780 * @param string $falseVal SQL expression to return if false
1781 * @return string SQL fragment
1782 */
1783 function conditional( $cond, $trueVal, $falseVal ) {
1784 return " IF($cond, $trueVal, $falseVal) ";
1785 }
1786
1787 /**
1788 * Returns a comand for str_replace function in SQL query.
1789 * Uses REPLACE() in MySQL
1790 *
1791 * @param string $orig String or column to modify
1792 * @param string $old String or column to seek
1793 * @param string $new String or column to replace with
1794 */
1795 function strreplace( $orig, $old, $new ) {
1796 return "REPLACE({$orig}, {$old}, {$new})";
1797 }
1798
1799 /**
1800 * Determines if the last failure was due to a deadlock
1801 */
1802 function wasDeadlock() {
1803 return $this->lastErrno() == 1213;
1804 }
1805
1806 /**
1807 * Perform a deadlock-prone transaction.
1808 *
1809 * This function invokes a callback function to perform a set of write
1810 * queries. If a deadlock occurs during the processing, the transaction
1811 * will be rolled back and the callback function will be called again.
1812 *
1813 * Usage:
1814 * $dbw->deadlockLoop( callback, ... );
1815 *
1816 * Extra arguments are passed through to the specified callback function.
1817 *
1818 * Returns whatever the callback function returned on its successful,
1819 * iteration, or false on error, for example if the retry limit was
1820 * reached.
1821 */
1822 function deadlockLoop() {
1823 $myFname = 'Database::deadlockLoop';
1824
1825 $this->begin();
1826 $args = func_get_args();
1827 $function = array_shift( $args );
1828 $oldIgnore = $this->ignoreErrors( true );
1829 $tries = DEADLOCK_TRIES;
1830 if ( is_array( $function ) ) {
1831 $fname = $function[0];
1832 } else {
1833 $fname = $function;
1834 }
1835 do {
1836 $retVal = call_user_func_array( $function, $args );
1837 $error = $this->lastError();
1838 $errno = $this->lastErrno();
1839 $sql = $this->lastQuery();
1840
1841 if ( $errno ) {
1842 if ( $this->wasDeadlock() ) {
1843 # Retry
1844 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1845 } else {
1846 $this->reportQueryError( $error, $errno, $sql, $fname );
1847 }
1848 }
1849 } while( $this->wasDeadlock() && --$tries > 0 );
1850 $this->ignoreErrors( $oldIgnore );
1851 if ( $tries <= 0 ) {
1852 $this->query( 'ROLLBACK', $myFname );
1853 $this->reportQueryError( $error, $errno, $sql, $fname );
1854 return false;
1855 } else {
1856 $this->query( 'COMMIT', $myFname );
1857 return $retVal;
1858 }
1859 }
1860
1861 /**
1862 * Do a SELECT MASTER_POS_WAIT()
1863 *
1864 * @param string $file the binlog file
1865 * @param string $pos the binlog position
1866 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1867 */
1868 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1869 $fname = 'Database::masterPosWait';
1870 wfProfileIn( $fname );
1871
1872 # Commit any open transactions
1873 if ( $this->mTrxLevel ) {
1874 $this->immediateCommit();
1875 }
1876
1877 if ( !is_null( $this->mFakeSlaveLag ) ) {
1878 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1879 if ( $wait > $timeout * 1e6 ) {
1880 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1881 wfProfileOut( $fname );
1882 return -1;
1883 } elseif ( $wait > 0 ) {
1884 wfDebug( "Fake slave waiting $wait us\n" );
1885 usleep( $wait );
1886 wfProfileOut( $fname );
1887 return 1;
1888 } else {
1889 wfDebug( "Fake slave up to date ($wait us)\n" );
1890 wfProfileOut( $fname );
1891 return 0;
1892 }
1893 }
1894
1895 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1896 $encFile = $this->addQuotes( $pos->file );
1897 $encPos = intval( $pos->pos );
1898 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1899 $res = $this->doQuery( $sql );
1900 if ( $res && $row = $this->fetchRow( $res ) ) {
1901 $this->freeResult( $res );
1902 wfProfileOut( $fname );
1903 return $row[0];
1904 } else {
1905 wfProfileOut( $fname );
1906 return false;
1907 }
1908 }
1909
1910 /**
1911 * Get the position of the master from SHOW SLAVE STATUS
1912 */
1913 function getSlavePos() {
1914 if ( !is_null( $this->mFakeSlaveLag ) ) {
1915 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1916 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1917 return $pos;
1918 }
1919 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1920 $row = $this->fetchObject( $res );
1921 if ( $row ) {
1922 return new MySQLMasterPos( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1923 } else {
1924 return false;
1925 }
1926 }
1927
1928 /**
1929 * Get the position of the master from SHOW MASTER STATUS
1930 */
1931 function getMasterPos() {
1932 if ( $this->mFakeMaster ) {
1933 return new MySQLMasterPos( 'fake', microtime( true ) );
1934 }
1935 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1936 $row = $this->fetchObject( $res );
1937 if ( $row ) {
1938 return new MySQLMasterPos( $row->File, $row->Position );
1939 } else {
1940 return false;
1941 }
1942 }
1943
1944 /**
1945 * Begin a transaction, committing any previously open transaction
1946 */
1947 function begin( $fname = 'Database::begin' ) {
1948 $this->query( 'BEGIN', $fname );
1949 $this->mTrxLevel = 1;
1950 }
1951
1952 /**
1953 * End a transaction
1954 */
1955 function commit( $fname = 'Database::commit' ) {
1956 $this->query( 'COMMIT', $fname );
1957 $this->mTrxLevel = 0;
1958 }
1959
1960 /**
1961 * Rollback a transaction.
1962 * No-op on non-transactional databases.
1963 */
1964 function rollback( $fname = 'Database::rollback' ) {
1965 $this->query( 'ROLLBACK', $fname, true );
1966 $this->mTrxLevel = 0;
1967 }
1968
1969 /**
1970 * Begin a transaction, committing any previously open transaction
1971 * @deprecated use begin()
1972 */
1973 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1974 $this->begin();
1975 }
1976
1977 /**
1978 * Commit transaction, if one is open
1979 * @deprecated use commit()
1980 */
1981 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1982 $this->commit();
1983 }
1984
1985 /**
1986 * Return MW-style timestamp used for MySQL schema
1987 */
1988 function timestamp( $ts=0 ) {
1989 return wfTimestamp(TS_MW,$ts);
1990 }
1991
1992 /**
1993 * Local database timestamp format or null
1994 */
1995 function timestampOrNull( $ts = null ) {
1996 if( is_null( $ts ) ) {
1997 return null;
1998 } else {
1999 return $this->timestamp( $ts );
2000 }
2001 }
2002
2003 /**
2004 * @todo document
2005 */
2006 function resultObject( $result ) {
2007 if( empty( $result ) ) {
2008 return false;
2009 } elseif ( $result instanceof ResultWrapper ) {
2010 return $result;
2011 } elseif ( $result === true ) {
2012 // Successful write query
2013 return $result;
2014 } else {
2015 return new ResultWrapper( $this, $result );
2016 }
2017 }
2018
2019 /**
2020 * Return aggregated value alias
2021 */
2022 function aggregateValue ($valuedata,$valuename='value') {
2023 return $valuename;
2024 }
2025
2026 /**
2027 * @return string wikitext of a link to the server software's web site
2028 */
2029 function getSoftwareLink() {
2030 return "[http://www.mysql.com/ MySQL]";
2031 }
2032
2033 /**
2034 * @return string Version information from the database
2035 */
2036 function getServerVersion() {
2037 return mysql_get_server_info( $this->mConn );
2038 }
2039
2040 /**
2041 * Ping the server and try to reconnect if it there is no connection
2042 */
2043 function ping() {
2044 if( !function_exists( 'mysql_ping' ) ) {
2045 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2046 return true;
2047 }
2048 $ping = mysql_ping( $this->mConn );
2049 if ( $ping ) {
2050 return true;
2051 }
2052
2053 // Need to reconnect manually in MySQL client 5.0.13+
2054 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2055 mysql_close( $this->mConn );
2056 $this->mOpened = false;
2057 $this->mConn = false;
2058 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2059 return true;
2060 }
2061 return false;
2062 }
2063
2064 /**
2065 * Get slave lag.
2066 * At the moment, this will only work if the DB user has the PROCESS privilege
2067 */
2068 function getLag() {
2069 if ( !is_null( $this->mFakeSlaveLag ) ) {
2070 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2071 return $this->mFakeSlaveLag;
2072 }
2073 $res = $this->query( 'SHOW PROCESSLIST' );
2074 # Find slave SQL thread
2075 while ( $row = $this->fetchObject( $res ) ) {
2076 /* This should work for most situations - when default db
2077 * for thread is not specified, it had no events executed,
2078 * and therefore it doesn't know yet how lagged it is.
2079 *
2080 * Relay log I/O thread does not select databases.
2081 */
2082 if ( $row->User == 'system user' &&
2083 $row->State != 'Waiting for master to send event' &&
2084 $row->State != 'Connecting to master' &&
2085 $row->State != 'Queueing master event to the relay log' &&
2086 $row->State != 'Waiting for master update' &&
2087 $row->State != 'Requesting binlog dump'
2088 ) {
2089 # This is it, return the time (except -ve)
2090 if ( $row->Time > 0x7fffffff ) {
2091 return false;
2092 } else {
2093 return $row->Time;
2094 }
2095 }
2096 }
2097 return false;
2098 }
2099
2100 /**
2101 * Get status information from SHOW STATUS in an associative array
2102 */
2103 function getStatus($which="%") {
2104 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2105 $status = array();
2106 while ( $row = $this->fetchObject( $res ) ) {
2107 $status[$row->Variable_name] = $row->Value;
2108 }
2109 return $status;
2110 }
2111
2112 /**
2113 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2114 */
2115 function maxListLen() {
2116 return 0;
2117 }
2118
2119 function encodeBlob($b) {
2120 return $b;
2121 }
2122
2123 function decodeBlob($b) {
2124 return $b;
2125 }
2126
2127 /**
2128 * Override database's default connection timeout.
2129 * May be useful for very long batch queries such as
2130 * full-wiki dumps, where a single query reads out
2131 * over hours or days.
2132 * @param int $timeout in seconds
2133 */
2134 public function setTimeout( $timeout ) {
2135 $this->query( "SET net_read_timeout=$timeout" );
2136 $this->query( "SET net_write_timeout=$timeout" );
2137 }
2138
2139 /**
2140 * Read and execute SQL commands from a file.
2141 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2142 * @param string $filename File name to open
2143 * @param callback $lineCallback Optional function called before reading each line
2144 * @param callback $resultCallback Optional function called for each MySQL result
2145 */
2146 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2147 $fp = fopen( $filename, 'r' );
2148 if ( false === $fp ) {
2149 throw new MWException( "Could not open \"{$filename}\".\n" );
2150 }
2151 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2152 fclose( $fp );
2153 return $error;
2154 }
2155
2156 /**
2157 * Read and execute commands from an open file handle
2158 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2159 * @param string $fp File handle
2160 * @param callback $lineCallback Optional function called before reading each line
2161 * @param callback $resultCallback Optional function called for each MySQL result
2162 */
2163 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2164 $cmd = "";
2165 $done = false;
2166 $dollarquote = false;
2167
2168 while ( ! feof( $fp ) ) {
2169 if ( $lineCallback ) {
2170 call_user_func( $lineCallback );
2171 }
2172 $line = trim( fgets( $fp, 1024 ) );
2173 $sl = strlen( $line ) - 1;
2174
2175 if ( $sl < 0 ) { continue; }
2176 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2177
2178 ## Allow dollar quoting for function declarations
2179 if (substr($line,0,4) == '$mw$') {
2180 if ($dollarquote) {
2181 $dollarquote = false;
2182 $done = true;
2183 }
2184 else {
2185 $dollarquote = true;
2186 }
2187 }
2188 else if (!$dollarquote) {
2189 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2190 $done = true;
2191 $line = substr( $line, 0, $sl );
2192 }
2193 }
2194
2195 if ( '' != $cmd ) { $cmd .= ' '; }
2196 $cmd .= "$line\n";
2197
2198 if ( $done ) {
2199 $cmd = str_replace(';;', ";", $cmd);
2200 $cmd = $this->replaceVars( $cmd );
2201 $res = $this->query( $cmd, __METHOD__ );
2202 if ( $resultCallback ) {
2203 call_user_func( $resultCallback, $res, $this );
2204 }
2205
2206 if ( false === $res ) {
2207 $err = $this->lastError();
2208 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2209 }
2210
2211 $cmd = '';
2212 $done = false;
2213 }
2214 }
2215 return true;
2216 }
2217
2218
2219 /**
2220 * Replace variables in sourced SQL
2221 */
2222 protected function replaceVars( $ins ) {
2223 $varnames = array(
2224 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2225 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2226 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2227 );
2228
2229 // Ordinary variables
2230 foreach ( $varnames as $var ) {
2231 if( isset( $GLOBALS[$var] ) ) {
2232 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2233 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2234 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2235 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2236 }
2237 }
2238
2239 // Table prefixes
2240 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2241 array( &$this, 'tableNameCallback' ), $ins );
2242 return $ins;
2243 }
2244
2245 /**
2246 * Table name callback
2247 * @private
2248 */
2249 protected function tableNameCallback( $matches ) {
2250 return $this->tableName( $matches[1] );
2251 }
2252
2253 /*
2254 * Build a concatenation list to feed into a SQL query
2255 */
2256 function buildConcat( $stringList ) {
2257 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2258 }
2259
2260 /**
2261 * Acquire a lock
2262 *
2263 * Abstracted from Filestore::lock() so child classes can implement for
2264 * their own needs.
2265 *
2266 * @param string $lockName Name of lock to aquire
2267 * @param string $method Name of method calling us
2268 * @return bool
2269 */
2270 public function lock( $lockName, $method ) {
2271 $lockName = $this->addQuotes( $lockName );
2272 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2273 $row = $this->fetchObject( $result );
2274 $this->freeResult( $result );
2275
2276 if( $row->lockstatus == 1 ) {
2277 return true;
2278 } else {
2279 wfDebug( __METHOD__." failed to acquire lock\n" );
2280 return false;
2281 }
2282 }
2283 /**
2284 * Release a lock.
2285 *
2286 * @todo fixme - Figure out a way to return a bool
2287 * based on successful lock release.
2288 *
2289 * @param string $lockName Name of lock to release
2290 * @param string $method Name of method calling us
2291 */
2292 public function unlock( $lockName, $method ) {
2293 $lockName = $this->addQuotes( $lockName );
2294 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2295 $this->freeResult( $result );
2296 }
2297
2298 /**
2299 * Get search engine class. All subclasses of this
2300 * need to implement this if they wish to use searching.
2301 *
2302 * @return string
2303 */
2304 public function getSearchEngine() {
2305 return "SearchMySQL";
2306 }
2307 }
2308
2309 /**
2310 * Database abstraction object for mySQL
2311 * Inherit all methods and properties of Database::Database()
2312 *
2313 * @ingroup Database
2314 * @see Database
2315 */
2316 class DatabaseMysql extends Database {
2317 # Inherit all
2318 }
2319
2320 /******************************************************************************
2321 * Utility classes
2322 *****************************************************************************/
2323
2324 /**
2325 * Utility class.
2326 * @ingroup Database
2327 */
2328 class DBObject {
2329 public $mData;
2330
2331 function DBObject($data) {
2332 $this->mData = $data;
2333 }
2334
2335 function isLOB() {
2336 return false;
2337 }
2338
2339 function data() {
2340 return $this->mData;
2341 }
2342 }
2343
2344 /**
2345 * Utility class
2346 * @ingroup Database
2347 *
2348 * This allows us to distinguish a blob from a normal string and an array of strings
2349 */
2350 class Blob {
2351 private $mData;
2352 function __construct($data) {
2353 $this->mData = $data;
2354 }
2355 function fetch() {
2356 return $this->mData;
2357 }
2358 }
2359
2360 /**
2361 * Utility class.
2362 * @ingroup Database
2363 */
2364 class MySQLField {
2365 private $name, $tablename, $default, $max_length, $nullable,
2366 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2367 function __construct ($info) {
2368 $this->name = $info->name;
2369 $this->tablename = $info->table;
2370 $this->default = $info->def;
2371 $this->max_length = $info->max_length;
2372 $this->nullable = !$info->not_null;
2373 $this->is_pk = $info->primary_key;
2374 $this->is_unique = $info->unique_key;
2375 $this->is_multiple = $info->multiple_key;
2376 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2377 $this->type = $info->type;
2378 }
2379
2380 function name() {
2381 return $this->name;
2382 }
2383
2384 function tableName() {
2385 return $this->tableName;
2386 }
2387
2388 function defaultValue() {
2389 return $this->default;
2390 }
2391
2392 function maxLength() {
2393 return $this->max_length;
2394 }
2395
2396 function nullable() {
2397 return $this->nullable;
2398 }
2399
2400 function isKey() {
2401 return $this->is_key;
2402 }
2403
2404 function isMultipleKey() {
2405 return $this->is_multiple;
2406 }
2407
2408 function type() {
2409 return $this->type;
2410 }
2411 }
2412
2413 /******************************************************************************
2414 * Error classes
2415 *****************************************************************************/
2416
2417 /**
2418 * Database error base class
2419 * @ingroup Database
2420 */
2421 class DBError extends MWException {
2422 public $db;
2423
2424 /**
2425 * Construct a database error
2426 * @param Database $db The database object which threw the error
2427 * @param string $error A simple error message to be used for debugging
2428 */
2429 function __construct( Database &$db, $error ) {
2430 $this->db =& $db;
2431 parent::__construct( $error );
2432 }
2433 }
2434
2435 /**
2436 * @ingroup Database
2437 */
2438 class DBConnectionError extends DBError {
2439 public $error;
2440
2441 function __construct( Database &$db, $error = 'unknown error' ) {
2442 $msg = 'DB connection error';
2443 if ( trim( $error ) != '' ) {
2444 $msg .= ": $error";
2445 }
2446 $this->error = $error;
2447 parent::__construct( $db, $msg );
2448 }
2449
2450 function useOutputPage() {
2451 // Not likely to work
2452 return false;
2453 }
2454
2455 function useMessageCache() {
2456 // Not likely to work
2457 return false;
2458 }
2459
2460 function getText() {
2461 return $this->getMessage() . "\n";
2462 }
2463
2464 function getLogMessage() {
2465 # Don't send to the exception log
2466 return false;
2467 }
2468
2469 function getPageTitle() {
2470 global $wgSitename;
2471 return "$wgSitename has a problem";
2472 }
2473
2474 function getHTML() {
2475 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2476 global $wgSitename, $wgServer, $wgMessageCache;
2477
2478 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2479 # Hard coding strings instead.
2480
2481 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2482 $mainpage = 'Main Page';
2483 $searchdisabled = <<<EOT
2484 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2485 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2486 EOT;
2487
2488 $googlesearch = "
2489 <!-- SiteSearch Google -->
2490 <FORM method=GET action=\"http://www.google.com/search\">
2491 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2492 <A HREF=\"http://www.google.com/\">
2493 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2494 border=\"0\" ALT=\"Google\"></A>
2495 </td>
2496 <td>
2497 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2498 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2499 <font size=-1>
2500 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
2501 <input type='hidden' name='ie' value='$2'>
2502 <input type='hidden' name='oe' value='$2'>
2503 </font>
2504 </td></tr></TABLE>
2505 </FORM>
2506 <!-- SiteSearch Google -->";
2507 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2508
2509 # No database access
2510 if ( is_object( $wgMessageCache ) ) {
2511 $wgMessageCache->disable();
2512 }
2513
2514 if ( trim( $this->error ) == '' ) {
2515 $this->error = $this->db->getProperty('mServer');
2516 }
2517
2518 $text = str_replace( '$1', $this->error, $noconnect );
2519
2520 /*
2521 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2522 $text .= '</p><p>Backtrace:</p><p>' .
2523 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2524 "</p>\n";
2525 }*/
2526
2527 if($wgUseFileCache) {
2528 if($wgTitle) {
2529 $t =& $wgTitle;
2530 } else {
2531 if($title) {
2532 $t = Title::newFromURL( $title );
2533 } elseif (@/**/$_REQUEST['search']) {
2534 $search = $_REQUEST['search'];
2535 return $searchdisabled .
2536 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2537 $wgInputEncoding ), $googlesearch );
2538 } else {
2539 $t = Title::newFromText( $mainpage );
2540 }
2541 }
2542
2543 $cache = new HTMLFileCache( $t );
2544 if( $cache->isFileCached() ) {
2545 // @todo, FIXME: $msg is not defined on the next line.
2546 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2547 $cachederror . "</b></p>\n";
2548
2549 $tag = '<div id="article">';
2550 $text = str_replace(
2551 $tag,
2552 $tag . $text,
2553 $cache->fetchPageText() );
2554 }
2555 }
2556
2557 return $text;
2558 }
2559 }
2560
2561 /**
2562 * @ingroup Database
2563 */
2564 class DBQueryError extends DBError {
2565 public $error, $errno, $sql, $fname;
2566
2567 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
2568 $message = "A database error has occurred\n" .
2569 "Query: $sql\n" .
2570 "Function: $fname\n" .
2571 "Error: $errno $error\n";
2572
2573 parent::__construct( $db, $message );
2574 $this->error = $error;
2575 $this->errno = $errno;
2576 $this->sql = $sql;
2577 $this->fname = $fname;
2578 }
2579
2580 function getText() {
2581 if ( $this->useMessageCache() ) {
2582 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2583 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2584 } else {
2585 return $this->getMessage();
2586 }
2587 }
2588
2589 function getSQL() {
2590 global $wgShowSQLErrors;
2591 if( !$wgShowSQLErrors ) {
2592 return $this->msg( 'sqlhidden', 'SQL hidden' );
2593 } else {
2594 return $this->sql;
2595 }
2596 }
2597
2598 function getLogMessage() {
2599 # Don't send to the exception log
2600 return false;
2601 }
2602
2603 function getPageTitle() {
2604 return $this->msg( 'databaseerror', 'Database error' );
2605 }
2606
2607 function getHTML() {
2608 if ( $this->useMessageCache() ) {
2609 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2610 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2611 } else {
2612 return nl2br( htmlspecialchars( $this->getMessage() ) );
2613 }
2614 }
2615 }
2616
2617 /**
2618 * @ingroup Database
2619 */
2620 class DBUnexpectedError extends DBError {}
2621
2622
2623 /**
2624 * Result wrapper for grabbing data queried by someone else
2625 * @ingroup Database
2626 */
2627 class ResultWrapper implements Iterator {
2628 var $db, $result, $pos = 0, $currentRow = null;
2629
2630 /**
2631 * Create a new result object from a result resource and a Database object
2632 */
2633 function ResultWrapper( $database, $result ) {
2634 $this->db = $database;
2635 if ( $result instanceof ResultWrapper ) {
2636 $this->result = $result->result;
2637 } else {
2638 $this->result = $result;
2639 }
2640 }
2641
2642 /**
2643 * Get the number of rows in a result object
2644 */
2645 function numRows() {
2646 return $this->db->numRows( $this->result );
2647 }
2648
2649 /**
2650 * Fetch the next row from the given result object, in object form.
2651 * Fields can be retrieved with $row->fieldname, with fields acting like
2652 * member variables.
2653 *
2654 * @param $res SQL result object as returned from Database::query(), etc.
2655 * @return MySQL row object
2656 * @throws DBUnexpectedError Thrown if the database returns an error
2657 */
2658 function fetchObject() {
2659 return $this->db->fetchObject( $this->result );
2660 }
2661
2662 /**
2663 * Fetch the next row from the given result object, in associative array
2664 * form. Fields are retrieved with $row['fieldname'].
2665 *
2666 * @param $res SQL result object as returned from Database::query(), etc.
2667 * @return MySQL row object
2668 * @throws DBUnexpectedError Thrown if the database returns an error
2669 */
2670 function fetchRow() {
2671 return $this->db->fetchRow( $this->result );
2672 }
2673
2674 /**
2675 * Free a result object
2676 */
2677 function free() {
2678 $this->db->freeResult( $this->result );
2679 unset( $this->result );
2680 unset( $this->db );
2681 }
2682
2683 /**
2684 * Change the position of the cursor in a result object
2685 * See mysql_data_seek()
2686 */
2687 function seek( $row ) {
2688 $this->db->dataSeek( $this->result, $row );
2689 }
2690
2691 /*********************
2692 * Iterator functions
2693 * Note that using these in combination with the non-iterator functions
2694 * above may cause rows to be skipped or repeated.
2695 */
2696
2697 function rewind() {
2698 if ($this->numRows()) {
2699 $this->db->dataSeek($this->result, 0);
2700 }
2701 $this->pos = 0;
2702 $this->currentRow = null;
2703 }
2704
2705 function current() {
2706 if ( is_null( $this->currentRow ) ) {
2707 $this->next();
2708 }
2709 return $this->currentRow;
2710 }
2711
2712 function key() {
2713 return $this->pos;
2714 }
2715
2716 function next() {
2717 $this->pos++;
2718 $this->currentRow = $this->fetchObject();
2719 return $this->currentRow;
2720 }
2721
2722 function valid() {
2723 return $this->current() !== false;
2724 }
2725 }
2726
2727 class MySQLMasterPos {
2728 var $file, $pos;
2729
2730 function __construct( $file, $pos ) {
2731 $this->file = $file;
2732 $this->pos = $pos;
2733 }
2734
2735 function __toString() {
2736 return "{$this->file}/{$this->pos}";
2737 }
2738 }