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