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