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