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