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