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