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