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