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