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