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