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