0fd4ea374eb472e7319802b06452c8fb7ab7cb21
[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 DUPE UPDATE wrapper, inserts an array into a table, optionally updating if
1043 * duplicate primary key found
1044 *
1045 * $a may be a single associative array, or an array of these with numeric keys, for
1046 * multi-row insert.
1047 *
1048 * Usually aborts on failure
1049 * If errors are explicitly ignored, returns success
1050 *
1051 * @param $table String: table name (prefix auto-added)
1052 * @param $a Array: Array of rows to insert
1053 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1054 * @param $onDupeUpdate Array: Associative array of fields to update on duplicate
1055 *
1056 * @return bool
1057 */
1058 function insertOrUpdate( $table, $a, $fname = 'DatabaseBase::insertOrUpdate', $onDupeUpdate = array() ) {
1059
1060 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1061 $keys = array_keys( $a[0] );
1062 } else {
1063 $keys = array_keys( $a );
1064 }
1065
1066 //Get what is only to be set if inserted
1067 $where = array_diff( $a, $onDupeUpdate );
1068
1069 $res = $this->select(
1070 $table,
1071 $keys,
1072 $where,
1073 __METHOD__
1074 );
1075
1076 if ( $res ) {
1077 // Where there is a different value to set if this is being "updated", use the $onDupeUpdate value for that to
1078 // replace the original option (if it was an insert), and replace the column name with the value read from
1079 // the existing row
1080 foreach( $where as $k => $v ) {
1081 if ( isset( $onDupeUpdate[$k] ) ) {
1082 $options[$k] = str_replace( $k, $res[0]->{$k}, $onDupeUpdate[$k] );
1083 }
1084 }
1085 } else {
1086 // No results, it's just an insert
1087 $update = $where;
1088 }
1089
1090 return (bool)$this->replace(
1091 $table,
1092 $update,
1093 array(),
1094 __METHOD__
1095 );
1096 }
1097
1098 /**
1099 * Make UPDATE options for the DatabaseBase::update function
1100 *
1101 * @private
1102 * @param $options Array: The options passed to DatabaseBase::update
1103 * @return string
1104 */
1105 function makeUpdateOptions( $options ) {
1106 if( !is_array( $options ) ) {
1107 $options = array( $options );
1108 }
1109 $opts = array();
1110 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1111 $opts[] = $this->lowPriorityOption();
1112 }
1113 if ( in_array( 'IGNORE', $options ) ) {
1114 $opts[] = 'IGNORE';
1115 }
1116 return implode(' ', $opts);
1117 }
1118
1119 /**
1120 * UPDATE wrapper, takes a condition array and a SET array
1121 *
1122 * @param $table String: The table to UPDATE
1123 * @param $values Array: An array of values to SET
1124 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1125 * @param $fname String: The Class::Function calling this function
1126 * (for the log)
1127 * @param $options Array: An array of UPDATE options, can be one or
1128 * more of IGNORE, LOW_PRIORITY
1129 * @return Boolean
1130 */
1131 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1132 $table = $this->tableName( $table );
1133 $opts = $this->makeUpdateOptions( $options );
1134 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1135 if ( $conds != '*' ) {
1136 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1137 }
1138 return $this->query( $sql, $fname );
1139 }
1140
1141 /**
1142 * Makes an encoded list of strings from an array
1143 * $mode:
1144 * LIST_COMMA - comma separated, no field names
1145 * LIST_AND - ANDed WHERE clause (without the WHERE)
1146 * LIST_OR - ORed WHERE clause (without the WHERE)
1147 * LIST_SET - comma separated with field names, like a SET clause
1148 * LIST_NAMES - comma separated field names
1149 */
1150 function makeList( $a, $mode = LIST_COMMA ) {
1151 if ( !is_array( $a ) ) {
1152 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1153 }
1154
1155 $first = true;
1156 $list = '';
1157 foreach ( $a as $field => $value ) {
1158 if ( !$first ) {
1159 if ( $mode == LIST_AND ) {
1160 $list .= ' AND ';
1161 } elseif($mode == LIST_OR) {
1162 $list .= ' OR ';
1163 } else {
1164 $list .= ',';
1165 }
1166 } else {
1167 $first = false;
1168 }
1169 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1170 $list .= "($value)";
1171 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1172 $list .= "$value";
1173 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1174 if( count( $value ) == 0 ) {
1175 throw new MWException( __METHOD__.': empty input' );
1176 } elseif( count( $value ) == 1 ) {
1177 // Special-case single values, as IN isn't terribly efficient
1178 // Don't necessarily assume the single key is 0; we don't
1179 // enforce linear numeric ordering on other arrays here.
1180 $value = array_values( $value );
1181 $list .= $field." = ".$this->addQuotes( $value[0] );
1182 } else {
1183 $list .= $field." IN (".$this->makeList($value).") ";
1184 }
1185 } elseif( $value === null ) {
1186 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1187 $list .= "$field IS ";
1188 } elseif ( $mode == LIST_SET ) {
1189 $list .= "$field = ";
1190 }
1191 $list .= 'NULL';
1192 } else {
1193 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1194 $list .= "$field = ";
1195 }
1196 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1197 }
1198 }
1199 return $list;
1200 }
1201
1202 /**
1203 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1204 * The keys on each level may be either integers or strings.
1205 *
1206 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1207 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1208 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1209 * @return Mixed: string SQL fragment, or false if no items in array.
1210 */
1211 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1212 $conds = array();
1213 foreach ( $data as $base => $sub ) {
1214 if ( count( $sub ) ) {
1215 $conds[] = $this->makeList(
1216 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1217 LIST_AND);
1218 }
1219 }
1220
1221 if ( $conds ) {
1222 return $this->makeList( $conds, LIST_OR );
1223 } else {
1224 // Nothing to search for...
1225 return false;
1226 }
1227 }
1228
1229 /**
1230 * Bitwise operations
1231 */
1232
1233 function bitNot($field) {
1234 return "(~$field)";
1235 }
1236
1237 function bitAnd($fieldLeft, $fieldRight) {
1238 return "($fieldLeft & $fieldRight)";
1239 }
1240
1241 function bitOr($fieldLeft, $fieldRight) {
1242 return "($fieldLeft | $fieldRight)";
1243 }
1244
1245 /**
1246 * Change the current database
1247 *
1248 * @return bool Success or failure
1249 */
1250 function selectDB( $db ) {
1251 # Stub. Shouldn't cause serious problems if it's not overridden, but
1252 # if your database engine supports a concept similar to MySQL's
1253 # databases you may as well. TODO: explain what exactly will fail if
1254 # this is not overridden.
1255 return true;
1256 }
1257
1258 /**
1259 * Get the current DB name
1260 */
1261 function getDBname() {
1262 return $this->mDBname;
1263 }
1264
1265 /**
1266 * Get the server hostname or IP address
1267 */
1268 function getServer() {
1269 return $this->mServer;
1270 }
1271
1272 /**
1273 * Format a table name ready for use in constructing an SQL query
1274 *
1275 * This does two important things: it quotes the table names to clean them up,
1276 * and it adds a table prefix if only given a table name with no quotes.
1277 *
1278 * All functions of this object which require a table name call this function
1279 * themselves. Pass the canonical name to such functions. This is only needed
1280 * when calling query() directly.
1281 *
1282 * @param $name String: database table name
1283 * @return String: full database name
1284 */
1285 function tableName( $name ) {
1286 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1287 # Skip the entire process when we have a string quoted on both ends.
1288 # Note that we check the end so that we will still quote any use of
1289 # use of `database`.table. But won't break things if someone wants
1290 # to query a database table with a dot in the name.
1291 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1292 return $name;
1293 }
1294
1295 # Lets test for any bits of text that should never show up in a table
1296 # name. Basically anything like JOIN or ON which are actually part of
1297 # SQL queries, but may end up inside of the table value to combine
1298 # sql. Such as how the API is doing.
1299 # Note that we use a whitespace test rather than a \b test to avoid
1300 # any remote case where a word like on may be inside of a table name
1301 # surrounded by symbols which may be considered word breaks.
1302 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1303 return $name;
1304 }
1305
1306 # Split database and table into proper variables.
1307 # We reverse the explode so that database.table and table both output
1308 # the correct table.
1309 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1310 if( isset( $dbDetails[1] ) ) {
1311 @list( $table, $database ) = $dbDetails;
1312 } else {
1313 @list( $table ) = $dbDetails;
1314 }
1315 $prefix = $this->mTablePrefix; # Default prefix
1316
1317 # A database name has been specified in input. Quote the table name
1318 # because we don't want any prefixes added.
1319 if( isset($database) ) {
1320 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1321 }
1322
1323 # Note that we use the long format because php will complain in in_array if
1324 # the input is not an array, and will complain in is_array if it is not set.
1325 if( !isset( $database ) # Don't use shared database if pre selected.
1326 && isset( $wgSharedDB ) # We have a shared database
1327 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1328 && isset( $wgSharedTables )
1329 && is_array( $wgSharedTables )
1330 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1331 $database = $wgSharedDB;
1332 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1333 }
1334
1335 # Quote the $database and $table and apply the prefix if not quoted.
1336 if( isset($database) ) {
1337 $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1338 }
1339 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1340
1341 # Merge our database and table into our final table name.
1342 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1343
1344 # We're finished, return.
1345 return $tableName;
1346 }
1347
1348 /**
1349 * Fetch a number of table names into an array
1350 * This is handy when you need to construct SQL for joins
1351 *
1352 * Example:
1353 * extract($dbr->tableNames('user','watchlist'));
1354 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1355 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1356 */
1357 public function tableNames() {
1358 $inArray = func_get_args();
1359 $retVal = array();
1360 foreach ( $inArray as $name ) {
1361 $retVal[$name] = $this->tableName( $name );
1362 }
1363 return $retVal;
1364 }
1365
1366 /**
1367 * Fetch a number of table names into an zero-indexed numerical array
1368 * This is handy when you need to construct SQL for joins
1369 *
1370 * Example:
1371 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1372 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1373 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1374 */
1375 public function tableNamesN() {
1376 $inArray = func_get_args();
1377 $retVal = array();
1378 foreach ( $inArray as $name ) {
1379 $retVal[] = $this->tableName( $name );
1380 }
1381 return $retVal;
1382 }
1383
1384 /**
1385 * @private
1386 */
1387 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1388 $ret = array();
1389 $retJOIN = array();
1390 $use_index_safe = is_array($use_index) ? $use_index : array();
1391 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1392 foreach ( $tables as $table ) {
1393 // Is there a JOIN and INDEX clause for this table?
1394 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1395 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1396 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1397 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND);
1398 if ( $on != '' ) {
1399 $tableClause .= ' ON (' . $on . ')';
1400 }
1401 $retJOIN[] = $tableClause;
1402 // Is there an INDEX clause?
1403 } else if ( isset($use_index_safe[$table]) ) {
1404 $tableClause = $this->tableName( $table );
1405 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1406 $ret[] = $tableClause;
1407 // Is there a JOIN clause?
1408 } else if ( isset($join_conds_safe[$table]) ) {
1409 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1410 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND);
1411 if ( $on != '' ) {
1412 $tableClause .= ' ON (' . $on . ')';
1413 }
1414 $retJOIN[] = $tableClause;
1415 } else {
1416 $tableClause = $this->tableName( $table );
1417 $ret[] = $tableClause;
1418 }
1419 }
1420 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1421 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1422 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1423 // Compile our final table clause
1424 return implode(' ',array($straightJoins,$otherJoins) );
1425 }
1426
1427 /**
1428 * Get the name of an index in a given table
1429 */
1430 function indexName( $index ) {
1431 // Backwards-compatibility hack
1432 $renamed = array(
1433 'ar_usertext_timestamp' => 'usertext_timestamp',
1434 'un_user_id' => 'user_id',
1435 'un_user_ip' => 'user_ip',
1436 );
1437 if( isset( $renamed[$index] ) ) {
1438 return $renamed[$index];
1439 } else {
1440 return $index;
1441 }
1442 }
1443
1444 /**
1445 * If it's a string, adds quotes and backslashes
1446 * Otherwise returns as-is
1447 */
1448 function addQuotes( $s ) {
1449 if ( $s === null ) {
1450 return 'NULL';
1451 } else {
1452 # This will also quote numeric values. This should be harmless,
1453 # and protects against weird problems that occur when they really
1454 # _are_ strings such as article titles and string->number->string
1455 # conversion is not 1:1.
1456 return "'" . $this->strencode( $s ) . "'";
1457 }
1458 }
1459
1460 /**
1461 * Escape string for safe LIKE usage.
1462 * WARNING: you should almost never use this function directly,
1463 * instead use buildLike() that escapes everything automatically
1464 * Deprecated in 1.17, warnings in 1.17, removed in ???
1465 */
1466 public function escapeLike( $s ) {
1467 wfDeprecated( __METHOD__ );
1468 return $this->escapeLikeInternal( $s );
1469 }
1470
1471 protected function escapeLikeInternal( $s ) {
1472 $s = str_replace( '\\', '\\\\', $s );
1473 $s = $this->strencode( $s );
1474 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1475 return $s;
1476 }
1477
1478 /**
1479 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1480 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1481 * Alternatively, the function could be provided with an array of aforementioned parameters.
1482 *
1483 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1484 * for subpages of 'My page title'.
1485 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1486 *
1487 * @since 1.16
1488 * @return String: fully built LIKE statement
1489 */
1490 function buildLike() {
1491 $params = func_get_args();
1492 if (count($params) > 0 && is_array($params[0])) {
1493 $params = $params[0];
1494 }
1495
1496 $s = '';
1497 foreach( $params as $value) {
1498 if( $value instanceof LikeMatch ) {
1499 $s .= $value->toString();
1500 } else {
1501 $s .= $this->escapeLikeInternal( $value );
1502 }
1503 }
1504 return " LIKE '" . $s . "' ";
1505 }
1506
1507 /**
1508 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1509 */
1510 function anyChar() {
1511 return new LikeMatch( '_' );
1512 }
1513
1514 /**
1515 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1516 */
1517 function anyString() {
1518 return new LikeMatch( '%' );
1519 }
1520
1521 /**
1522 * Returns an appropriately quoted sequence value for inserting a new row.
1523 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1524 * subclass will return an integer, and save the value for insertId()
1525 */
1526 function nextSequenceValue( $seqName ) {
1527 return null;
1528 }
1529
1530 /**
1531 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1532 * is only needed because a) MySQL must be as efficient as possible due to
1533 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1534 * which index to pick. Anyway, other databases might have different
1535 * indexes on a given table. So don't bother overriding this unless you're
1536 * MySQL.
1537 */
1538 function useIndexClause( $index ) {
1539 return '';
1540 }
1541
1542 /**
1543 * REPLACE query wrapper
1544 * PostgreSQL simulates this with a DELETE followed by INSERT
1545 * $row is the row to insert, an associative array
1546 * $uniqueIndexes is an array of indexes. Each element may be either a
1547 * field name or an array of field names
1548 *
1549 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1550 * However if you do this, you run the risk of encountering errors which wouldn't have
1551 * occurred in MySQL
1552 *
1553 * @param $table String: The table to replace the row(s) in.
1554 * @param $uniqueIndexes Array: An associative array of indexes
1555 * @param $rows Array: Array of rows to replace
1556 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1557 */
1558 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1559 $table = $this->tableName( $table );
1560
1561 # Single row case
1562 if ( !is_array( reset( $rows ) ) ) {
1563 $rows = array( $rows );
1564 }
1565
1566 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1567 $first = true;
1568 foreach ( $rows as $row ) {
1569 if ( $first ) {
1570 $first = false;
1571 } else {
1572 $sql .= ',';
1573 }
1574 $sql .= '(' . $this->makeList( $row ) . ')';
1575 }
1576 return $this->query( $sql, $fname );
1577 }
1578
1579 /**
1580 * DELETE where the condition is a join
1581 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1582 *
1583 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1584 * join condition matches, set $conds='*'
1585 *
1586 * DO NOT put the join condition in $conds
1587 *
1588 * @param $delTable String: The table to delete from.
1589 * @param $joinTable String: The other table.
1590 * @param $delVar String: The variable to join on, in the first table.
1591 * @param $joinVar String: The variable to join on, in the second table.
1592 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1593 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1594 */
1595 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1596 if ( !$conds ) {
1597 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1598 }
1599
1600 $delTable = $this->tableName( $delTable );
1601 $joinTable = $this->tableName( $joinTable );
1602 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1603 if ( $conds != '*' ) {
1604 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1605 }
1606
1607 return $this->query( $sql, $fname );
1608 }
1609
1610 /**
1611 * Returns the size of a text field, or -1 for "unlimited"
1612 */
1613 function textFieldSize( $table, $field ) {
1614 $table = $this->tableName( $table );
1615 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1616 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1617 $row = $this->fetchObject( $res );
1618
1619 $m = array();
1620 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1621 $size = $m[1];
1622 } else {
1623 $size = -1;
1624 }
1625 return $size;
1626 }
1627
1628 /**
1629 * A string to insert into queries to show that they're low-priority, like
1630 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1631 * string and nothing bad should happen.
1632 *
1633 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1634 */
1635 function lowPriorityOption() {
1636 return '';
1637 }
1638
1639 /**
1640 * DELETE query wrapper
1641 *
1642 * Use $conds == "*" to delete all rows
1643 */
1644 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1645 if ( !$conds ) {
1646 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1647 }
1648 $table = $this->tableName( $table );
1649 $sql = "DELETE FROM $table";
1650 if ( $conds != '*' ) {
1651 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1652 }
1653 return $this->query( $sql, $fname );
1654 }
1655
1656 /**
1657 * INSERT SELECT wrapper
1658 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1659 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1660 * $conds may be "*" to copy the whole table
1661 * srcTable may be an array of tables.
1662 */
1663 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1664 $insertOptions = array(), $selectOptions = array() )
1665 {
1666 $destTable = $this->tableName( $destTable );
1667 if ( is_array( $insertOptions ) ) {
1668 $insertOptions = implode( ' ', $insertOptions );
1669 }
1670 if( !is_array( $selectOptions ) ) {
1671 $selectOptions = array( $selectOptions );
1672 }
1673 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1674 if( is_array( $srcTable ) ) {
1675 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1676 } else {
1677 $srcTable = $this->tableName( $srcTable );
1678 }
1679 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1680 " SELECT $startOpts " . implode( ',', $varMap ) .
1681 " FROM $srcTable $useIndex ";
1682 if ( $conds != '*' ) {
1683 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1684 }
1685 $sql .= " $tailOpts";
1686 return $this->query( $sql, $fname );
1687 }
1688
1689 /**
1690 * Construct a LIMIT query with optional offset. This is used for query
1691 * pages. The SQL should be adjusted so that only the first $limit rows
1692 * are returned. If $offset is provided as well, then the first $offset
1693 * rows should be discarded, and the next $limit rows should be returned.
1694 * If the result of the query is not ordered, then the rows to be returned
1695 * are theoretically arbitrary.
1696 *
1697 * $sql is expected to be a SELECT, if that makes a difference. For
1698 * UPDATE, limitResultForUpdate should be used.
1699 *
1700 * The version provided by default works in MySQL and SQLite. It will very
1701 * likely need to be overridden for most other DBMSes.
1702 *
1703 * @param $sql String: SQL query we will append the limit too
1704 * @param $limit Integer: the SQL limit
1705 * @param $offset Integer the SQL offset (default false)
1706 */
1707 function limitResult( $sql, $limit, $offset=false ) {
1708 if( !is_numeric( $limit ) ) {
1709 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1710 }
1711 return "$sql LIMIT "
1712 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1713 . "{$limit} ";
1714 }
1715 function limitResultForUpdate( $sql, $num ) {
1716 return $this->limitResult( $sql, $num, 0 );
1717 }
1718
1719 /**
1720 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1721 * within the UNION construct.
1722 * @return Boolean
1723 */
1724 function unionSupportsOrderAndLimit() {
1725 return true; // True for almost every DB supported
1726 }
1727
1728 /**
1729 * Construct a UNION query
1730 * This is used for providing overload point for other DB abstractions
1731 * not compatible with the MySQL syntax.
1732 * @param $sqls Array: SQL statements to combine
1733 * @param $all Boolean: use UNION ALL
1734 * @return String: SQL fragment
1735 */
1736 function unionQueries($sqls, $all) {
1737 $glue = $all ? ') UNION ALL (' : ') UNION (';
1738 return '('.implode( $glue, $sqls ) . ')';
1739 }
1740
1741 /**
1742 * Returns an SQL expression for a simple conditional. This doesn't need
1743 * to be overridden unless CASE isn't supported in your DBMS.
1744 *
1745 * @param $cond String: SQL expression which will result in a boolean value
1746 * @param $trueVal String: SQL expression to return if true
1747 * @param $falseVal String: SQL expression to return if false
1748 * @return String: SQL fragment
1749 */
1750 function conditional( $cond, $trueVal, $falseVal ) {
1751 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1752 }
1753
1754 /**
1755 * Returns a comand for str_replace function in SQL query.
1756 * Uses REPLACE() in MySQL
1757 *
1758 * @param $orig String: column to modify
1759 * @param $old String: column to seek
1760 * @param $new String: column to replace with
1761 */
1762 function strreplace( $orig, $old, $new ) {
1763 return "REPLACE({$orig}, {$old}, {$new})";
1764 }
1765
1766 /**
1767 * Determines if the last failure was due to a deadlock
1768 * STUB
1769 */
1770 function wasDeadlock() {
1771 return false;
1772 }
1773
1774 /**
1775 * Determines if the last query error was something that should be dealt
1776 * with by pinging the connection and reissuing the query.
1777 * STUB
1778 */
1779 function wasErrorReissuable() {
1780 return false;
1781 }
1782
1783 /**
1784 * Determines if the last failure was due to the database being read-only.
1785 * STUB
1786 */
1787 function wasReadOnlyError() {
1788 return false;
1789 }
1790
1791 /**
1792 * Perform a deadlock-prone transaction.
1793 *
1794 * This function invokes a callback function to perform a set of write
1795 * queries. If a deadlock occurs during the processing, the transaction
1796 * will be rolled back and the callback function will be called again.
1797 *
1798 * Usage:
1799 * $dbw->deadlockLoop( callback, ... );
1800 *
1801 * Extra arguments are passed through to the specified callback function.
1802 *
1803 * Returns whatever the callback function returned on its successful,
1804 * iteration, or false on error, for example if the retry limit was
1805 * reached.
1806 */
1807 function deadlockLoop() {
1808 $myFname = 'DatabaseBase::deadlockLoop';
1809
1810 $this->begin();
1811 $args = func_get_args();
1812 $function = array_shift( $args );
1813 $oldIgnore = $this->ignoreErrors( true );
1814 $tries = DEADLOCK_TRIES;
1815 if ( is_array( $function ) ) {
1816 $fname = $function[0];
1817 } else {
1818 $fname = $function;
1819 }
1820 do {
1821 $retVal = call_user_func_array( $function, $args );
1822 $error = $this->lastError();
1823 $errno = $this->lastErrno();
1824 $sql = $this->lastQuery();
1825
1826 if ( $errno ) {
1827 if ( $this->wasDeadlock() ) {
1828 # Retry
1829 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1830 } else {
1831 $this->reportQueryError( $error, $errno, $sql, $fname );
1832 }
1833 }
1834 } while( $this->wasDeadlock() && --$tries > 0 );
1835 $this->ignoreErrors( $oldIgnore );
1836 if ( $tries <= 0 ) {
1837 $this->rollback( $myFname );
1838 $this->reportQueryError( $error, $errno, $sql, $fname );
1839 return false;
1840 } else {
1841 $this->commit( $myFname );
1842 return $retVal;
1843 }
1844 }
1845
1846 /**
1847 * Do a SELECT MASTER_POS_WAIT()
1848 *
1849 * @param $pos MySQLMasterPos object
1850 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1851 */
1852 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1853 $fname = 'DatabaseBase::masterPosWait';
1854 wfProfileIn( $fname );
1855
1856 # Commit any open transactions
1857 if ( $this->mTrxLevel ) {
1858 $this->commit();
1859 }
1860
1861 if ( !is_null( $this->mFakeSlaveLag ) ) {
1862 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1863 if ( $wait > $timeout * 1e6 ) {
1864 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1865 wfProfileOut( $fname );
1866 return -1;
1867 } elseif ( $wait > 0 ) {
1868 wfDebug( "Fake slave waiting $wait us\n" );
1869 usleep( $wait );
1870 wfProfileOut( $fname );
1871 return 1;
1872 } else {
1873 wfDebug( "Fake slave up to date ($wait us)\n" );
1874 wfProfileOut( $fname );
1875 return 0;
1876 }
1877 }
1878
1879 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1880 $encFile = $this->addQuotes( $pos->file );
1881 $encPos = intval( $pos->pos );
1882 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1883 $res = $this->doQuery( $sql );
1884 if ( $res && $row = $this->fetchRow( $res ) ) {
1885 wfProfileOut( $fname );
1886 return $row[0];
1887 } else {
1888 wfProfileOut( $fname );
1889 return false;
1890 }
1891 }
1892
1893 /**
1894 * Get the position of the master from SHOW SLAVE STATUS
1895 */
1896 function getSlavePos() {
1897 if ( !is_null( $this->mFakeSlaveLag ) ) {
1898 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1899 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1900 return $pos;
1901 }
1902 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
1903 $row = $this->fetchObject( $res );
1904 if ( $row ) {
1905 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1906 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1907 } else {
1908 return false;
1909 }
1910 }
1911
1912 /**
1913 * Get the position of the master from SHOW MASTER STATUS
1914 */
1915 function getMasterPos() {
1916 if ( $this->mFakeMaster ) {
1917 return new MySQLMasterPos( 'fake', microtime( true ) );
1918 }
1919 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
1920 $row = $this->fetchObject( $res );
1921 if ( $row ) {
1922 return new MySQLMasterPos( $row->File, $row->Position );
1923 } else {
1924 return false;
1925 }
1926 }
1927
1928 /**
1929 * Begin a transaction, committing any previously open transaction
1930 */
1931 function begin( $fname = 'DatabaseBase::begin' ) {
1932 $this->query( 'BEGIN', $fname );
1933 $this->mTrxLevel = 1;
1934 }
1935
1936 /**
1937 * End a transaction
1938 */
1939 function commit( $fname = 'DatabaseBase::commit' ) {
1940 if( $this->mTrxLevel ) {
1941 $this->query( 'COMMIT', $fname );
1942 $this->mTrxLevel = 0;
1943 }
1944 }
1945
1946 /**
1947 * Rollback a transaction.
1948 * No-op on non-transactional databases.
1949 */
1950 function rollback( $fname = 'DatabaseBase::rollback' ) {
1951 if( $this->mTrxLevel ) {
1952 $this->query( 'ROLLBACK', $fname, true );
1953 $this->mTrxLevel = 0;
1954 }
1955 }
1956
1957 /**
1958 * Begin a transaction, committing any previously open transaction
1959 * @deprecated use begin()
1960 */
1961 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
1962 wfDeprecated( __METHOD__ );
1963 $this->begin();
1964 }
1965
1966 /**
1967 * Commit transaction, if one is open
1968 * @deprecated use commit()
1969 */
1970 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
1971 wfDeprecated( __METHOD__ );
1972 $this->commit();
1973 }
1974
1975 /**
1976 * Creates a new table with structure copied from existing table
1977 * Note that unlike most database abstraction functions, this function does not
1978 * automatically append database prefix, because it works at a lower
1979 * abstraction level.
1980 *
1981 * @param $oldName String: name of table whose structure should be copied
1982 * @param $newName String: name of table to be created
1983 * @param $temporary Boolean: whether the new table should be temporary
1984 * @param $fname String: calling function name
1985 * @return Boolean: true if operation was successful
1986 */
1987 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
1988 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
1989 }
1990
1991 /**
1992 * Return MW-style timestamp used for MySQL schema
1993 */
1994 function timestamp( $ts=0 ) {
1995 return wfTimestamp(TS_MW,$ts);
1996 }
1997
1998 /**
1999 * Local database timestamp format or null
2000 */
2001 function timestampOrNull( $ts = null ) {
2002 if( is_null( $ts ) ) {
2003 return null;
2004 } else {
2005 return $this->timestamp( $ts );
2006 }
2007 }
2008
2009 /**
2010 * @todo document
2011 */
2012 function resultObject( $result ) {
2013 if( empty( $result ) ) {
2014 return false;
2015 } elseif ( $result instanceof ResultWrapper ) {
2016 return $result;
2017 } elseif ( $result === true ) {
2018 // Successful write query
2019 return $result;
2020 } else {
2021 return new ResultWrapper( $this, $result );
2022 }
2023 }
2024
2025 /**
2026 * Return aggregated value alias
2027 */
2028 function aggregateValue ($valuedata,$valuename='value') {
2029 return $valuename;
2030 }
2031
2032 /**
2033 * Ping the server and try to reconnect if it there is no connection
2034 *
2035 * @return bool Success or failure
2036 */
2037 function ping() {
2038 # Stub. Not essential to override.
2039 return true;
2040 }
2041
2042 /**
2043 * Get slave lag.
2044 * Currently supported only by MySQL
2045 * @return Database replication lag in seconds
2046 */
2047 function getLag() {
2048 return $this->mFakeSlaveLag;
2049 }
2050
2051 /**
2052 * Get status information from SHOW STATUS in an associative array
2053 */
2054 function getStatus($which="%") {
2055 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2056 $status = array();
2057 while ( $row = $this->fetchObject( $res ) ) {
2058 $status[$row->Variable_name] = $row->Value;
2059 }
2060 return $status;
2061 }
2062
2063 /**
2064 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2065 */
2066 function maxListLen() {
2067 return 0;
2068 }
2069
2070 function encodeBlob($b) {
2071 return $b;
2072 }
2073
2074 function decodeBlob($b) {
2075 return $b;
2076 }
2077
2078 /**
2079 * Override database's default connection timeout. May be useful for very
2080 * long batch queries such as full-wiki dumps, where a single query reads
2081 * out over hours or days. May or may not be necessary for non-MySQL
2082 * databases. For most purposes, leaving it as a no-op should be fine.
2083 *
2084 * @param $timeout Integer in seconds
2085 */
2086 public function setTimeout( $timeout ) {}
2087
2088 /**
2089 * Read and execute SQL commands from a file.
2090 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2091 * @param $filename String: File name to open
2092 * @param $lineCallback Callback: Optional function called before reading each line
2093 * @param $resultCallback Callback: Optional function called for each MySQL result
2094 */
2095 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2096 $fp = fopen( $filename, 'r' );
2097 if ( false === $fp ) {
2098 if (!defined("MEDIAWIKI_INSTALL"))
2099 throw new MWException( "Could not open \"{$filename}\".\n" );
2100 else
2101 return "Could not open \"{$filename}\".\n";
2102 }
2103 try {
2104 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2105 }
2106 catch( MWException $e ) {
2107 if ( defined("MEDIAWIKI_INSTALL") ) {
2108 $error = $e->getMessage();
2109 } else {
2110 fclose( $fp );
2111 throw $e;
2112 }
2113 }
2114
2115 fclose( $fp );
2116 return $error;
2117 }
2118
2119 /**
2120 * Get the full path of a patch file. Originally based on archive()
2121 * from updaters.inc. Keep in mind this always returns a patch, as
2122 * it fails back to MySQL if no DB-specific patch can be found
2123 *
2124 * @param $patch String The name of the patch, like patch-something.sql
2125 * @return String Full path to patch file
2126 */
2127 public static function patchPath( $patch ) {
2128 global $wgDBtype, $IP;
2129 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2130 return "$IP/maintenance/$wgDBtype/archives/$patch";
2131 } else {
2132 return "$IP/maintenance/archives/$patch";
2133 }
2134 }
2135
2136 /**
2137 * Read and execute commands from an open file handle
2138 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2139 * @param $fp String: File handle
2140 * @param $lineCallback Callback: Optional function called before reading each line
2141 * @param $resultCallback Callback: Optional function called for each MySQL result
2142 */
2143 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2144 $cmd = "";
2145 $done = false;
2146 $dollarquote = false;
2147
2148 while ( ! feof( $fp ) ) {
2149 if ( $lineCallback ) {
2150 call_user_func( $lineCallback );
2151 }
2152 $line = trim( fgets( $fp, 1024 ) );
2153 $sl = strlen( $line ) - 1;
2154
2155 if ( $sl < 0 ) { continue; }
2156 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2157
2158 ## Allow dollar quoting for function declarations
2159 if (substr($line,0,4) == '$mw$') {
2160 if ($dollarquote) {
2161 $dollarquote = false;
2162 $done = true;
2163 }
2164 else {
2165 $dollarquote = true;
2166 }
2167 }
2168 else if (!$dollarquote) {
2169 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2170 $done = true;
2171 $line = substr( $line, 0, $sl );
2172 }
2173 }
2174
2175 if ( $cmd != '' ) { $cmd .= ' '; }
2176 $cmd .= "$line\n";
2177
2178 if ( $done ) {
2179 $cmd = str_replace(';;', ";", $cmd);
2180 $cmd = $this->replaceVars( $cmd );
2181 $res = $this->query( $cmd, __METHOD__ );
2182 if ( $resultCallback ) {
2183 call_user_func( $resultCallback, $res, $this );
2184 }
2185
2186 if ( false === $res ) {
2187 $err = $this->lastError();
2188 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2189 }
2190
2191 $cmd = '';
2192 $done = false;
2193 }
2194 }
2195 return true;
2196 }
2197
2198
2199 /**
2200 * Replace variables in sourced SQL
2201 */
2202 protected function replaceVars( $ins ) {
2203 $varnames = array(
2204 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2205 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2206 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2207 );
2208
2209 // Ordinary variables
2210 foreach ( $varnames as $var ) {
2211 if( isset( $GLOBALS[$var] ) ) {
2212 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2213 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2214 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2215 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2216 }
2217 }
2218
2219 // Table prefixes
2220 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2221 array( $this, 'tableNameCallback' ), $ins );
2222
2223 // Index names
2224 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2225 array( $this, 'indexNameCallback' ), $ins );
2226 return $ins;
2227 }
2228
2229 /**
2230 * Table name callback
2231 * @private
2232 */
2233 protected function tableNameCallback( $matches ) {
2234 return $this->tableName( $matches[1] );
2235 }
2236
2237 /**
2238 * Index name callback
2239 */
2240 protected function indexNameCallback( $matches ) {
2241 return $this->indexName( $matches[1] );
2242 }
2243
2244 /**
2245 * Build a concatenation list to feed into a SQL query
2246 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2247 * @return String
2248 */
2249 function buildConcat( $stringList ) {
2250 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2251 }
2252
2253 /**
2254 * Acquire a named lock
2255 *
2256 * Abstracted from Filestore::lock() so child classes can implement for
2257 * their own needs.
2258 *
2259 * @param $lockName String: name of lock to aquire
2260 * @param $method String: name of method calling us
2261 * @param $timeout Integer: timeout
2262 * @return Boolean
2263 */
2264 public function lock( $lockName, $method, $timeout = 5 ) {
2265 return true;
2266 }
2267
2268 /**
2269 * Release a lock.
2270 *
2271 * @param $lockName String: Name of lock to release
2272 * @param $method String: Name of method calling us
2273 *
2274 * @return Returns 1 if the lock was released, 0 if the lock was not established
2275 * by this thread (in which case the lock is not released), and NULL if the named
2276 * lock did not exist
2277 */
2278 public function unlock( $lockName, $method ) {
2279 return true;
2280 }
2281
2282 /**
2283 * Lock specific tables
2284 *
2285 * @param $read Array of tables to lock for read access
2286 * @param $write Array of tables to lock for write access
2287 * @param $method String name of caller
2288 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2289 */
2290 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2291 return true;
2292 }
2293
2294 /**
2295 * Unlock specific tables
2296 *
2297 * @param $method String the caller
2298 */
2299 public function unlockTables( $method ) {
2300 return true;
2301 }
2302
2303 /**
2304 * Get search engine class. All subclasses of this need to implement this
2305 * if they wish to use searching.
2306 *
2307 * @return String
2308 */
2309 public function getSearchEngine() {
2310 return 'SearchEngineDummy';
2311 }
2312
2313 /**
2314 * Allow or deny "big selects" for this session only. This is done by setting
2315 * the sql_big_selects session variable.
2316 *
2317 * This is a MySQL-specific feature.
2318 *
2319 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2320 */
2321 public function setBigSelects( $value = true ) {
2322 // no-op
2323 }
2324 }
2325
2326
2327 /******************************************************************************
2328 * Utility classes
2329 *****************************************************************************/
2330
2331 /**
2332 * Utility class.
2333 * @ingroup Database
2334 */
2335 class DBObject {
2336 public $mData;
2337
2338 function DBObject($data) {
2339 $this->mData = $data;
2340 }
2341
2342 function isLOB() {
2343 return false;
2344 }
2345
2346 function data() {
2347 return $this->mData;
2348 }
2349 }
2350
2351 /**
2352 * Utility class
2353 * @ingroup Database
2354 *
2355 * This allows us to distinguish a blob from a normal string and an array of strings
2356 */
2357 class Blob {
2358 private $mData;
2359 function __construct($data) {
2360 $this->mData = $data;
2361 }
2362 function fetch() {
2363 return $this->mData;
2364 }
2365 }
2366
2367 /**
2368 * Utility class.
2369 * @ingroup Database
2370 */
2371 class MySQLField {
2372 private $name, $tablename, $default, $max_length, $nullable,
2373 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2374 function __construct ($info) {
2375 $this->name = $info->name;
2376 $this->tablename = $info->table;
2377 $this->default = $info->def;
2378 $this->max_length = $info->max_length;
2379 $this->nullable = !$info->not_null;
2380 $this->is_pk = $info->primary_key;
2381 $this->is_unique = $info->unique_key;
2382 $this->is_multiple = $info->multiple_key;
2383 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2384 $this->type = $info->type;
2385 }
2386
2387 function name() {
2388 return $this->name;
2389 }
2390
2391 function tableName() {
2392 return $this->tableName;
2393 }
2394
2395 function defaultValue() {
2396 return $this->default;
2397 }
2398
2399 function maxLength() {
2400 return $this->max_length;
2401 }
2402
2403 function nullable() {
2404 return $this->nullable;
2405 }
2406
2407 function isKey() {
2408 return $this->is_key;
2409 }
2410
2411 function isMultipleKey() {
2412 return $this->is_multiple;
2413 }
2414
2415 function type() {
2416 return $this->type;
2417 }
2418 }
2419
2420 /******************************************************************************
2421 * Error classes
2422 *****************************************************************************/
2423
2424 /**
2425 * Database error base class
2426 * @ingroup Database
2427 */
2428 class DBError extends MWException {
2429 public $db;
2430
2431 /**
2432 * Construct a database error
2433 * @param $db Database object which threw the error
2434 * @param $error A simple error message to be used for debugging
2435 */
2436 function __construct( DatabaseBase &$db, $error ) {
2437 $this->db =& $db;
2438 parent::__construct( $error );
2439 }
2440
2441 function getText() {
2442 global $wgShowDBErrorBacktrace;
2443 $s = $this->getMessage() . "\n";
2444 if ( $wgShowDBErrorBacktrace ) {
2445 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2446 }
2447 return $s;
2448 }
2449 }
2450
2451 /**
2452 * @ingroup Database
2453 */
2454 class DBConnectionError extends DBError {
2455 public $error;
2456
2457 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2458 $msg = 'DB connection error';
2459 if ( trim( $error ) != '' ) {
2460 $msg .= ": $error";
2461 }
2462 $this->error = $error;
2463 parent::__construct( $db, $msg );
2464 }
2465
2466 function useOutputPage() {
2467 // Not likely to work
2468 return false;
2469 }
2470
2471 function useMessageCache() {
2472 // Not likely to work
2473 return false;
2474 }
2475
2476 function getLogMessage() {
2477 # Don't send to the exception log
2478 return false;
2479 }
2480
2481 function getPageTitle() {
2482 global $wgSitename, $wgLang;
2483 $header = "$wgSitename has a problem";
2484 if ( $wgLang instanceof Language ) {
2485 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2486 }
2487
2488 return $header;
2489 }
2490
2491 function getHTML() {
2492 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2493
2494 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2495 $again = 'Try waiting a few minutes and reloading.';
2496 $info = '(Can\'t contact the database server: $1)';
2497
2498 if ( $wgLang instanceof Language ) {
2499 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2500 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2501 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2502 }
2503
2504 # No database access
2505 if ( is_object( $wgMessageCache ) ) {
2506 $wgMessageCache->disable();
2507 }
2508
2509 if ( trim( $this->error ) == '' ) {
2510 $this->error = $this->db->getProperty('mServer');
2511 }
2512
2513 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2514 $text = str_replace( '$1', $this->error, $noconnect );
2515
2516 if ( $wgShowDBErrorBacktrace ) {
2517 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2518 }
2519
2520 $extra = $this->searchForm();
2521
2522 if( $wgUseFileCache ) {
2523 try {
2524 $cache = $this->fileCachedPage();
2525 # Cached version on file system?
2526 if( $cache !== null ) {
2527 # Hack: extend the body for error messages
2528 $cache = str_replace( array('</html>','</body>'), '', $cache );
2529 # Add cache notice...
2530 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2531 # Localize it if possible...
2532 if( $wgLang instanceof Language ) {
2533 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2534 }
2535 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2536 # Output cached page with notices on bottom and re-close body
2537 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2538 }
2539 } catch( MWException $e ) {
2540 // Do nothing, just use the default page
2541 }
2542 }
2543 # Headers needed here - output is just the error message
2544 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2545 }
2546
2547 function searchForm() {
2548 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2549 $usegoogle = "You can try searching via Google in the meantime.";
2550 $outofdate = "Note that their indexes of our content may be out of date.";
2551 $googlesearch = "Search";
2552
2553 if ( $wgLang instanceof Language ) {
2554 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2555 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2556 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2557 }
2558
2559 $search = htmlspecialchars(@$_REQUEST['search']);
2560
2561 $trygoogle = <<<EOT
2562 <div style="margin: 1.5em">$usegoogle<br />
2563 <small>$outofdate</small></div>
2564 <!-- SiteSearch Google -->
2565 <form method="get" action="http://www.google.com/search" id="googlesearch">
2566 <input type="hidden" name="domains" value="$wgServer" />
2567 <input type="hidden" name="num" value="50" />
2568 <input type="hidden" name="ie" value="$wgInputEncoding" />
2569 <input type="hidden" name="oe" value="$wgInputEncoding" />
2570
2571 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2572 <input type="submit" name="btnG" value="$googlesearch" />
2573 <div>
2574 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2575 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2576 </div>
2577 </form>
2578 <!-- SiteSearch Google -->
2579 EOT;
2580 return $trygoogle;
2581 }
2582
2583 function fileCachedPage() {
2584 global $wgTitle, $title, $wgLang, $wgOut;
2585 if( $wgOut->isDisabled() ) return; // Done already?
2586 $mainpage = 'Main Page';
2587 if ( $wgLang instanceof Language ) {
2588 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2589 }
2590
2591 if( $wgTitle ) {
2592 $t =& $wgTitle;
2593 } elseif( $title ) {
2594 $t = Title::newFromURL( $title );
2595 } else {
2596 $t = Title::newFromText( $mainpage );
2597 }
2598
2599 $cache = new HTMLFileCache( $t );
2600 if( $cache->isFileCached() ) {
2601 return $cache->fetchPageText();
2602 } else {
2603 return '';
2604 }
2605 }
2606
2607 function htmlBodyOnly() {
2608 return true;
2609 }
2610
2611 }
2612
2613 /**
2614 * @ingroup Database
2615 */
2616 class DBQueryError extends DBError {
2617 public $error, $errno, $sql, $fname;
2618
2619 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2620 $message = "A database error has occurred\n" .
2621 "Query: $sql\n" .
2622 "Function: $fname\n" .
2623 "Error: $errno $error\n";
2624
2625 parent::__construct( $db, $message );
2626 $this->error = $error;
2627 $this->errno = $errno;
2628 $this->sql = $sql;
2629 $this->fname = $fname;
2630 }
2631
2632 function getText() {
2633 global $wgShowDBErrorBacktrace;
2634 if ( $this->useMessageCache() ) {
2635 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2636 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2637 if ( $wgShowDBErrorBacktrace ) {
2638 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2639 }
2640 return $s;
2641 } else {
2642 return parent::getText();
2643 }
2644 }
2645
2646 function getSQL() {
2647 global $wgShowSQLErrors;
2648 if( !$wgShowSQLErrors ) {
2649 return $this->msg( 'sqlhidden', 'SQL hidden' );
2650 } else {
2651 return $this->sql;
2652 }
2653 }
2654
2655 function getLogMessage() {
2656 # Don't send to the exception log
2657 return false;
2658 }
2659
2660 function getPageTitle() {
2661 return $this->msg( 'databaseerror', 'Database error' );
2662 }
2663
2664 function getHTML() {
2665 global $wgShowDBErrorBacktrace;
2666 if ( $this->useMessageCache() ) {
2667 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2668 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2669 } else {
2670 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2671 }
2672 if ( $wgShowDBErrorBacktrace ) {
2673 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2674 }
2675 return $s;
2676 }
2677 }
2678
2679 /**
2680 * @ingroup Database
2681 */
2682 class DBUnexpectedError extends DBError {}
2683
2684
2685 /**
2686 * Result wrapper for grabbing data queried by someone else
2687 * @ingroup Database
2688 */
2689 class ResultWrapper implements Iterator {
2690 var $db, $result, $pos = 0, $currentRow = null;
2691
2692 /**
2693 * Create a new result object from a result resource and a Database object
2694 */
2695 function ResultWrapper( $database, $result ) {
2696 $this->db = $database;
2697 if ( $result instanceof ResultWrapper ) {
2698 $this->result = $result->result;
2699 } else {
2700 $this->result = $result;
2701 }
2702 }
2703
2704 /**
2705 * Get the number of rows in a result object
2706 */
2707 function numRows() {
2708 return $this->db->numRows( $this );
2709 }
2710
2711 /**
2712 * Fetch the next row from the given result object, in object form.
2713 * Fields can be retrieved with $row->fieldname, with fields acting like
2714 * member variables.
2715 *
2716 * @return MySQL row object
2717 * @throws DBUnexpectedError Thrown if the database returns an error
2718 */
2719 function fetchObject() {
2720 return $this->db->fetchObject( $this );
2721 }
2722
2723 /**
2724 * Fetch the next row from the given result object, in associative array
2725 * form. Fields are retrieved with $row['fieldname'].
2726 *
2727 * @return MySQL row object
2728 * @throws DBUnexpectedError Thrown if the database returns an error
2729 */
2730 function fetchRow() {
2731 return $this->db->fetchRow( $this );
2732 }
2733
2734 /**
2735 * Free a result object
2736 */
2737 function free() {
2738 $this->db->freeResult( $this );
2739 unset( $this->result );
2740 unset( $this->db );
2741 }
2742
2743 /**
2744 * Change the position of the cursor in a result object
2745 * See mysql_data_seek()
2746 */
2747 function seek( $row ) {
2748 $this->db->dataSeek( $this, $row );
2749 }
2750
2751 /*********************
2752 * Iterator functions
2753 * Note that using these in combination with the non-iterator functions
2754 * above may cause rows to be skipped or repeated.
2755 */
2756
2757 function rewind() {
2758 if ($this->numRows()) {
2759 $this->db->dataSeek($this, 0);
2760 }
2761 $this->pos = 0;
2762 $this->currentRow = null;
2763 }
2764
2765 function current() {
2766 if ( is_null( $this->currentRow ) ) {
2767 $this->next();
2768 }
2769 return $this->currentRow;
2770 }
2771
2772 function key() {
2773 return $this->pos;
2774 }
2775
2776 function next() {
2777 $this->pos++;
2778 $this->currentRow = $this->fetchObject();
2779 return $this->currentRow;
2780 }
2781
2782 function valid() {
2783 return $this->current() !== false;
2784 }
2785 }
2786
2787 /* Overloads the relevant methods of the real ResultsWrapper so it
2788 * doesn't go anywhere near an actual database.
2789 */
2790 class FakeResultWrapper extends ResultWrapper {
2791
2792 var $result = array();
2793 var $db = null; // And it's going to stay that way :D
2794 var $pos = 0;
2795 var $currentRow = null;
2796
2797 function __construct( $array ){
2798 $this->result = $array;
2799 }
2800
2801 function numRows() {
2802 return count( $this->result );
2803 }
2804
2805 function fetchRow() {
2806 $this->currentRow = $this->result[$this->pos++];
2807 return $this->currentRow;
2808 }
2809
2810 function seek( $row ) {
2811 $this->pos = $row;
2812 }
2813
2814 function free() {}
2815
2816 // Callers want to be able to access fields with $this->fieldName
2817 function fetchObject(){
2818 $this->currentRow = $this->result[$this->pos++];
2819 return (object)$this->currentRow;
2820 }
2821
2822 function rewind() {
2823 $this->pos = 0;
2824 $this->currentRow = null;
2825 }
2826 }
2827
2828 /**
2829 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2830 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
2831 */
2832 class LikeMatch {
2833 private $str;
2834
2835 public function __construct( $s ) {
2836 $this->str = $s;
2837 }
2838
2839 public function toString() {
2840 return $this->str;
2841 }
2842 }