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