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