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