Revert Special:Log to r20745 with non-ugly form
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 */
6
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
13
14 /******************************************************************************
15 * Utility classes
16 *****************************************************************************/
17
18 /**
19 * Utility class.
20 */
21 class DBObject {
22 public $mData;
23
24 function DBObject($data) {
25 $this->mData = $data;
26 }
27
28 function isLOB() {
29 return false;
30 }
31
32 function data() {
33 return $this->mData;
34 }
35 };
36
37 /**
38 * Utility class.
39 */
40 class MySQLField {
41 private $name, $tablename, $default, $max_length, $nullable,
42 $is_pk, $is_unique, $is_key, $type;
43 function __construct ($info) {
44 $this->name = $info->name;
45 $this->tablename = $info->table;
46 $this->default = $info->def;
47 $this->max_length = $info->max_length;
48 $this->nullable = !$info->not_null;
49 $this->is_pk = $info->primary_key;
50 $this->is_unique = $info->unique_key;
51 $this->is_multiple = $info->multiple_key;
52 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
53 $this->type = $info->type;
54 }
55
56 function name() {
57 return $this->name;
58 }
59
60 function tableName() {
61 return $this->tableName;
62 }
63
64 function defaultValue() {
65 return $this->default;
66 }
67
68 function maxLength() {
69 return $this->max_length;
70 }
71
72 function nullable() {
73 return $this->nullable;
74 }
75
76 function isKey() {
77 return $this->is_key;
78 }
79
80 function isMultipleKey() {
81 return $this->is_multiple;
82 }
83
84 function type() {
85 return $this->type;
86 }
87 }
88
89 /******************************************************************************
90 * Error classes
91 *****************************************************************************/
92
93 /**
94 * Database error base class
95 */
96 class DBError extends MWException {
97 public $db;
98
99 /**
100 * Construct a database error
101 * @param Database $db The database object which threw the error
102 * @param string $error A simple error message to be used for debugging
103 */
104 function __construct( Database &$db, $error ) {
105 $this->db =& $db;
106 parent::__construct( $error );
107 }
108 }
109
110 class DBConnectionError extends DBError {
111 public $error;
112
113 function __construct( Database &$db, $error = 'unknown error' ) {
114 $msg = 'DB connection error';
115 if ( trim( $error ) != '' ) {
116 $msg .= ": $error";
117 }
118 $this->error = $error;
119 parent::__construct( $db, $msg );
120 }
121
122 function useOutputPage() {
123 // Not likely to work
124 return false;
125 }
126
127 function useMessageCache() {
128 // Not likely to work
129 return false;
130 }
131
132 function getText() {
133 return $this->getMessage() . "\n";
134 }
135
136 function getLogMessage() {
137 # Don't send to the exception log
138 return false;
139 }
140
141 function getPageTitle() {
142 global $wgSitename;
143 return "$wgSitename has a problem";
144 }
145
146 function getHTML() {
147 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
148 global $wgSitename, $wgServer, $wgMessageCache;
149
150 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
151 # Hard coding strings instead.
152
153 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
154 $mainpage = 'Main Page';
155 $searchdisabled = <<<EOT
156 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
157 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
158 EOT;
159
160 $googlesearch = "
161 <!-- SiteSearch Google -->
162 <FORM method=GET action=\"http://www.google.com/search\">
163 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
164 <A HREF=\"http://www.google.com/\">
165 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
166 border=\"0\" ALT=\"Google\"></A>
167 </td>
168 <td>
169 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
170 <INPUT type=submit name=btnG VALUE=\"Google Search\">
171 <font size=-1>
172 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
173 <input type='hidden' name='ie' value='$2'>
174 <input type='hidden' name='oe' value='$2'>
175 </font>
176 </td></tr></TABLE>
177 </FORM>
178 <!-- SiteSearch Google -->";
179 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
180
181 # No database access
182 if ( is_object( $wgMessageCache ) ) {
183 $wgMessageCache->disable();
184 }
185
186 if ( trim( $this->error ) == '' ) {
187 $this->error = $this->db->getProperty('mServer');
188 }
189
190 $text = str_replace( '$1', $this->error, $noconnect );
191 $text .= wfGetSiteNotice();
192
193 if($wgUseFileCache) {
194 if($wgTitle) {
195 $t =& $wgTitle;
196 } else {
197 if($title) {
198 $t = Title::newFromURL( $title );
199 } elseif (@/**/$_REQUEST['search']) {
200 $search = $_REQUEST['search'];
201 return $searchdisabled .
202 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
203 $wgInputEncoding ), $googlesearch );
204 } else {
205 $t = Title::newFromText( $mainpage );
206 }
207 }
208
209 $cache = new HTMLFileCache( $t );
210 if( $cache->isFileCached() ) {
211 // FIXME: $msg is not defined on the next line.
212 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
213 $cachederror . "</b></p>\n";
214
215 $tag = '<div id="article">';
216 $text = str_replace(
217 $tag,
218 $tag . $msg,
219 $cache->fetchPageText() );
220 }
221 }
222
223 return $text;
224 }
225 }
226
227 class DBQueryError extends DBError {
228 public $error, $errno, $sql, $fname;
229
230 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
231 $message = "A database error has occurred\n" .
232 "Query: $sql\n" .
233 "Function: $fname\n" .
234 "Error: $errno $error\n";
235
236 parent::__construct( $db, $message );
237 $this->error = $error;
238 $this->errno = $errno;
239 $this->sql = $sql;
240 $this->fname = $fname;
241 }
242
243 function getText() {
244 if ( $this->useMessageCache() ) {
245 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
246 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
247 } else {
248 return $this->getMessage();
249 }
250 }
251
252 function getSQL() {
253 global $wgShowSQLErrors;
254 if( !$wgShowSQLErrors ) {
255 return $this->msg( 'sqlhidden', 'SQL hidden' );
256 } else {
257 return $this->sql;
258 }
259 }
260
261 function getLogMessage() {
262 # Don't send to the exception log
263 return false;
264 }
265
266 function getPageTitle() {
267 return $this->msg( 'databaseerror', 'Database error' );
268 }
269
270 function getHTML() {
271 if ( $this->useMessageCache() ) {
272 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
273 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
274 } else {
275 return nl2br( htmlspecialchars( $this->getMessage() ) );
276 }
277 }
278 }
279
280 class DBUnexpectedError extends DBError {}
281
282 /******************************************************************************/
283
284 /**
285 * Database abstraction object
286 */
287 class Database {
288
289 #------------------------------------------------------------------------------
290 # Variables
291 #------------------------------------------------------------------------------
292
293 protected $mLastQuery = '';
294
295 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
296 protected $mOut, $mOpened = false;
297
298 protected $mFailFunction;
299 protected $mTablePrefix;
300 protected $mFlags;
301 protected $mTrxLevel = 0;
302 protected $mErrorCount = 0;
303 protected $mLBInfo = array();
304
305 #------------------------------------------------------------------------------
306 # Accessors
307 #------------------------------------------------------------------------------
308 # These optionally set a variable and return the previous state
309
310 /**
311 * Fail function, takes a Database as a parameter
312 * Set to false for default, 1 for ignore errors
313 */
314 function failFunction( $function = NULL ) {
315 return wfSetVar( $this->mFailFunction, $function );
316 }
317
318 /**
319 * Output page, used for reporting errors
320 * FALSE means discard output
321 */
322 function setOutputPage( $out ) {
323 $this->mOut = $out;
324 }
325
326 /**
327 * Boolean, controls output of large amounts of debug information
328 */
329 function debug( $debug = NULL ) {
330 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
331 }
332
333 /**
334 * Turns buffering of SQL result sets on (true) or off (false).
335 * Default is "on" and it should not be changed without good reasons.
336 */
337 function bufferResults( $buffer = NULL ) {
338 if ( is_null( $buffer ) ) {
339 return !(bool)( $this->mFlags & DBO_NOBUFFER );
340 } else {
341 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
342 }
343 }
344
345 /**
346 * Turns on (false) or off (true) the automatic generation and sending
347 * of a "we're sorry, but there has been a database error" page on
348 * database errors. Default is on (false). When turned off, the
349 * code should use lastErrno() and lastError() to handle the
350 * situation as appropriate.
351 */
352 function ignoreErrors( $ignoreErrors = NULL ) {
353 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
354 }
355
356 /**
357 * The current depth of nested transactions
358 * @param $level Integer: , default NULL.
359 */
360 function trxLevel( $level = NULL ) {
361 return wfSetVar( $this->mTrxLevel, $level );
362 }
363
364 /**
365 * Number of errors logged, only useful when errors are ignored
366 */
367 function errorCount( $count = NULL ) {
368 return wfSetVar( $this->mErrorCount, $count );
369 }
370
371 /**
372 * Properties passed down from the server info array of the load balancer
373 */
374 function getLBInfo( $name = NULL ) {
375 if ( is_null( $name ) ) {
376 return $this->mLBInfo;
377 } else {
378 if ( array_key_exists( $name, $this->mLBInfo ) ) {
379 return $this->mLBInfo[$name];
380 } else {
381 return NULL;
382 }
383 }
384 }
385
386 function setLBInfo( $name, $value = NULL ) {
387 if ( is_null( $value ) ) {
388 $this->mLBInfo = $name;
389 } else {
390 $this->mLBInfo[$name] = $value;
391 }
392 }
393
394 /**
395 * Returns true if this database supports (and uses) cascading deletes
396 */
397 function cascadingDeletes() {
398 return false;
399 }
400
401 /**
402 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
403 */
404 function cleanupTriggers() {
405 return false;
406 }
407
408 /**
409 * Returns true if this database is strict about what can be put into an IP field.
410 * Specifically, it uses a NULL value instead of an empty string.
411 */
412 function strictIPs() {
413 return false;
414 }
415
416 /**
417 * Returns true if this database uses timestamps rather than integers
418 */
419 function realTimestamps() {
420 return false;
421 }
422
423 /**
424 * Returns true if this database does an implicit sort when doing GROUP BY
425 */
426 function implicitGroupby() {
427 return true;
428 }
429
430 /**
431 * Returns true if this database can do a native search on IP columns
432 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
433 */
434 function searchableIPs() {
435 return false;
436 }
437
438 /**#@+
439 * Get function
440 */
441 function lastQuery() { return $this->mLastQuery; }
442 function isOpen() { return $this->mOpened; }
443 /**#@-*/
444
445 function setFlag( $flag ) {
446 $this->mFlags |= $flag;
447 }
448
449 function clearFlag( $flag ) {
450 $this->mFlags &= ~$flag;
451 }
452
453 function getFlag( $flag ) {
454 return !!($this->mFlags & $flag);
455 }
456
457 /**
458 * General read-only accessor
459 */
460 function getProperty( $name ) {
461 return $this->$name;
462 }
463
464 #------------------------------------------------------------------------------
465 # Other functions
466 #------------------------------------------------------------------------------
467
468 /**@{{
469 * Constructor.
470 * @param string $server database server host
471 * @param string $user database user name
472 * @param string $password database user password
473 * @param string $dbname database name
474 * @param failFunction
475 * @param $flags
476 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
477 */
478 function __construct( $server = false, $user = false, $password = false, $dbName = false,
479 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
480
481 global $wgOut, $wgDBprefix, $wgCommandLineMode;
482 # Can't get a reference if it hasn't been set yet
483 if ( !isset( $wgOut ) ) {
484 $wgOut = NULL;
485 }
486 $this->mOut =& $wgOut;
487
488 $this->mFailFunction = $failFunction;
489 $this->mFlags = $flags;
490
491 if ( $this->mFlags & DBO_DEFAULT ) {
492 if ( $wgCommandLineMode ) {
493 $this->mFlags &= ~DBO_TRX;
494 } else {
495 $this->mFlags |= DBO_TRX;
496 }
497 }
498
499 /*
500 // Faster read-only access
501 if ( wfReadOnly() ) {
502 $this->mFlags |= DBO_PERSISTENT;
503 $this->mFlags &= ~DBO_TRX;
504 }*/
505
506 /** Get the default table prefix*/
507 if ( $tablePrefix == 'get from global' ) {
508 $this->mTablePrefix = $wgDBprefix;
509 } else {
510 $this->mTablePrefix = $tablePrefix;
511 }
512
513 if ( $server ) {
514 $this->open( $server, $user, $password, $dbName );
515 }
516 }
517
518 /**
519 * @static
520 * @param failFunction
521 * @param $flags
522 */
523 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
524 {
525 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
526 }
527
528 /**
529 * Usually aborts on failure
530 * If the failFunction is set to a non-zero integer, returns success
531 */
532 function open( $server, $user, $password, $dbName ) {
533 global $wguname;
534 wfProfileIn( __METHOD__ );
535
536 # Test for missing mysql.so
537 # First try to load it
538 if (!@extension_loaded('mysql')) {
539 @dl('mysql.so');
540 }
541
542 # Fail now
543 # Otherwise we get a suppressed fatal error, which is very hard to track down
544 if ( !function_exists( 'mysql_connect' ) ) {
545 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
546 }
547
548 $this->close();
549 $this->mServer = $server;
550 $this->mUser = $user;
551 $this->mPassword = $password;
552 $this->mDBname = $dbName;
553
554 $success = false;
555
556 wfProfileIn("dbconnect-$server");
557
558 # LIVE PATCH by Tim, ask Domas for why: retry loop
559 $this->mConn = false;
560 $max = 3;
561 for ( $i = 0; $i < $max && !$this->mConn; $i++ ) {
562 if ( $i > 1 ) {
563 usleep( 1000 );
564 }
565 if ( $this->mFlags & DBO_PERSISTENT ) {
566 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
567 } else {
568 # Create a new connection...
569 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
570 }
571 if ($this->mConn === false) {
572 $iplus = $i + 1;
573 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
574 }
575 }
576
577 wfProfileOut("dbconnect-$server");
578
579 if ( $dbName != '' ) {
580 if ( $this->mConn !== false ) {
581 $success = @/**/mysql_select_db( $dbName, $this->mConn );
582 if ( !$success ) {
583 $error = "Error selecting database $dbName on server {$this->mServer} " .
584 "from client host {$wguname['nodename']}\n";
585 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
586 wfDebug( $error );
587 }
588 } else {
589 wfDebug( "DB connection error\n" );
590 wfDebug( "Server: $server, User: $user, Password: " .
591 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
592 $success = false;
593 }
594 } else {
595 # Delay USE query
596 $success = (bool)$this->mConn;
597 }
598
599 if ( $success ) {
600 global $wgDBmysql5;
601 if( $wgDBmysql5 ) {
602 // Tell the server we're communicating with it in UTF-8.
603 // This may engage various charset conversions.
604 $this->query( 'SET NAMES utf8' );
605 }
606 } else {
607 $this->reportConnectionError();
608 }
609
610 $this->mOpened = $success;
611 wfProfileOut( __METHOD__ );
612 return $success;
613 }
614 /**@}}*/
615
616 /**
617 * Closes a database connection.
618 * if it is open : commits any open transactions
619 *
620 * @return bool operation success. true if already closed.
621 */
622 function close()
623 {
624 $this->mOpened = false;
625 if ( $this->mConn ) {
626 if ( $this->trxLevel() ) {
627 $this->immediateCommit();
628 }
629 return mysql_close( $this->mConn );
630 } else {
631 return true;
632 }
633 }
634
635 /**
636 * @param string $error fallback error message, used if none is given by MySQL
637 */
638 function reportConnectionError( $error = 'Unknown error' ) {
639 $myError = $this->lastError();
640 if ( $myError ) {
641 $error = $myError;
642 }
643
644 if ( $this->mFailFunction ) {
645 # Legacy error handling method
646 if ( !is_int( $this->mFailFunction ) ) {
647 $ff = $this->mFailFunction;
648 $ff( $this, $error );
649 }
650 } else {
651 # New method
652 wfLogDBError( "Connection error: $error\n" );
653 throw new DBConnectionError( $this, $error );
654 }
655 }
656
657 /**
658 * Usually aborts on failure. If errors are explicitly ignored, returns success.
659 *
660 * @param $sql String: SQL query
661 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST comment (you can use __METHOD__ or add some extra info)
662 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors... maybe best to catch the exception instead?
663 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure if $tempIgnore set
664 * @throws DBQueryError Thrown when the database returns an error of any kind
665 */
666 public function query( $sql, $fname = '', $tempIgnore = false ) {
667 global $wgProfiling;
668
669 if ( $wgProfiling ) {
670 # generalizeSQL will probably cut down the query to reasonable
671 # logging size most of the time. The substr is really just a sanity check.
672
673 # Who's been wasting my precious column space? -- TS
674 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
675
676 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
677 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
678 $totalProf = 'Database::query';
679 } else {
680 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
681 $totalProf = 'Database::query-master';
682 }
683 wfProfileIn( $totalProf );
684 wfProfileIn( $queryProf );
685 }
686
687 $this->mLastQuery = $sql;
688
689 # Add a comment for easy SHOW PROCESSLIST interpretation
690 if ( $fname ) {
691 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
692 } else {
693 $commentedSql = $sql;
694 }
695
696 # If DBO_TRX is set, start a transaction
697 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
698 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
699 ) {
700 $this->begin();
701 }
702
703 if ( $this->debug() ) {
704 $sqlx = substr( $commentedSql, 0, 500 );
705 $sqlx = strtr( $sqlx, "\t\n", ' ' );
706 wfDebug( "SQL: $sqlx\n" );
707 }
708
709 # Do the query and handle errors
710 $ret = $this->doQuery( $commentedSql );
711
712 # Try reconnecting if the connection was lost
713 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
714 # Transaction is gone, like it or not
715 $this->mTrxLevel = 0;
716 wfDebug( "Connection lost, reconnecting...\n" );
717 if ( $this->ping() ) {
718 wfDebug( "Reconnected\n" );
719 $sqlx = substr( $commentedSql, 0, 500 );
720 $sqlx = strtr( $sqlx, "\t\n", ' ' );
721 global $wgRequestTime;
722 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
723 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
724 $ret = $this->doQuery( $commentedSql );
725 } else {
726 wfDebug( "Failed\n" );
727 }
728 }
729
730 if ( false === $ret ) {
731 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
732 }
733
734 if ( $wgProfiling ) {
735 wfProfileOut( $queryProf );
736 wfProfileOut( $totalProf );
737 }
738 return $ret;
739 }
740
741 /**
742 * The DBMS-dependent part of query()
743 * @param $sql String: SQL query.
744 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
745 * @access private
746 */
747 /*private*/ function doQuery( $sql ) {
748 if( $this->bufferResults() ) {
749 $ret = mysql_query( $sql, $this->mConn );
750 } else {
751 $ret = mysql_unbuffered_query( $sql, $this->mConn );
752 }
753 return $ret;
754 }
755
756 /**
757 * @param $error
758 * @param $errno
759 * @param $sql
760 * @param string $fname
761 * @param bool $tempIgnore
762 */
763 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
764 global $wgCommandLineMode;
765 # Ignore errors during error handling to avoid infinite recursion
766 $ignore = $this->ignoreErrors( true );
767 ++$this->mErrorCount;
768
769 if( $ignore || $tempIgnore ) {
770 wfDebug("SQL ERROR (ignored): $error\n");
771 $this->ignoreErrors( $ignore );
772 } else {
773 $sql1line = str_replace( "\n", "\\n", $sql );
774 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
775 wfDebug("SQL ERROR: " . $error . "\n");
776 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
777 }
778 }
779
780
781 /**
782 * Intended to be compatible with the PEAR::DB wrapper functions.
783 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
784 *
785 * ? = scalar value, quoted as necessary
786 * ! = raw SQL bit (a function for instance)
787 * & = filename; reads the file and inserts as a blob
788 * (we don't use this though...)
789 */
790 function prepare( $sql, $func = 'Database::prepare' ) {
791 /* MySQL doesn't support prepared statements (yet), so just
792 pack up the query for reference. We'll manually replace
793 the bits later. */
794 return array( 'query' => $sql, 'func' => $func );
795 }
796
797 function freePrepared( $prepared ) {
798 /* No-op for MySQL */
799 }
800
801 /**
802 * Execute a prepared query with the various arguments
803 * @param string $prepared the prepared sql
804 * @param mixed $args Either an array here, or put scalars as varargs
805 */
806 function execute( $prepared, $args = null ) {
807 if( !is_array( $args ) ) {
808 # Pull the var args
809 $args = func_get_args();
810 array_shift( $args );
811 }
812 $sql = $this->fillPrepared( $prepared['query'], $args );
813 return $this->query( $sql, $prepared['func'] );
814 }
815
816 /**
817 * Prepare & execute an SQL statement, quoting and inserting arguments
818 * in the appropriate places.
819 * @param string $query
820 * @param string $args ...
821 */
822 function safeQuery( $query, $args = null ) {
823 $prepared = $this->prepare( $query, 'Database::safeQuery' );
824 if( !is_array( $args ) ) {
825 # Pull the var args
826 $args = func_get_args();
827 array_shift( $args );
828 }
829 $retval = $this->execute( $prepared, $args );
830 $this->freePrepared( $prepared );
831 return $retval;
832 }
833
834 /**
835 * For faking prepared SQL statements on DBs that don't support
836 * it directly.
837 * @param string $preparedSql - a 'preparable' SQL statement
838 * @param array $args - array of arguments to fill it with
839 * @return string executable SQL
840 */
841 function fillPrepared( $preparedQuery, $args ) {
842 reset( $args );
843 $this->preparedArgs =& $args;
844 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
845 array( &$this, 'fillPreparedArg' ), $preparedQuery );
846 }
847
848 /**
849 * preg_callback func for fillPrepared()
850 * The arguments should be in $this->preparedArgs and must not be touched
851 * while we're doing this.
852 *
853 * @param array $matches
854 * @return string
855 * @private
856 */
857 function fillPreparedArg( $matches ) {
858 switch( $matches[1] ) {
859 case '\\?': return '?';
860 case '\\!': return '!';
861 case '\\&': return '&';
862 }
863 list( /* $n */ , $arg ) = each( $this->preparedArgs );
864 switch( $matches[1] ) {
865 case '?': return $this->addQuotes( $arg );
866 case '!': return $arg;
867 case '&':
868 # return $this->addQuotes( file_get_contents( $arg ) );
869 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
870 default:
871 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
872 }
873 }
874
875 /**#@+
876 * @param mixed $res A SQL result
877 */
878 /**
879 * Free a result object
880 */
881 function freeResult( $res ) {
882 if ( !@/**/mysql_free_result( $res ) ) {
883 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
884 }
885 }
886
887 /**
888 * Fetch the next row from the given result object, in object form.
889 * Fields can be retrieved with $row->fieldname, with fields acting like
890 * member variables.
891 *
892 * @param $res SQL result object as returned from Database::query(), etc.
893 * @return MySQL row object
894 * @throws DBUnexpectedError Thrown if the database returns an error
895 */
896 function fetchObject( $res ) {
897 @/**/$row = mysql_fetch_object( $res );
898 if( $this->lastErrno() ) {
899 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
900 }
901 return $row;
902 }
903
904 /**
905 * Fetch the next row from the given result object, in associative array
906 * form. Fields are retrieved with $row['fieldname'].
907 *
908 * @param $res SQL result object as returned from Database::query(), etc.
909 * @return MySQL row object
910 * @throws DBUnexpectedError Thrown if the database returns an error
911 */
912 function fetchRow( $res ) {
913 @/**/$row = mysql_fetch_array( $res );
914 if ( $this->lastErrno() ) {
915 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
916 }
917 return $row;
918 }
919
920 /**
921 * Get the number of rows in a result object
922 */
923 function numRows( $res ) {
924 @/**/$n = mysql_num_rows( $res );
925 if( $this->lastErrno() ) {
926 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
927 }
928 return $n;
929 }
930
931 /**
932 * Get the number of fields in a result object
933 * See documentation for mysql_num_fields()
934 */
935 function numFields( $res ) { return mysql_num_fields( $res ); }
936
937 /**
938 * Get a field name in a result object
939 * See documentation for mysql_field_name():
940 * http://www.php.net/mysql_field_name
941 */
942 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
943
944 /**
945 * Get the inserted value of an auto-increment row
946 *
947 * The value inserted should be fetched from nextSequenceValue()
948 *
949 * Example:
950 * $id = $dbw->nextSequenceValue('page_page_id_seq');
951 * $dbw->insert('page',array('page_id' => $id));
952 * $id = $dbw->insertId();
953 */
954 function insertId() { return mysql_insert_id( $this->mConn ); }
955
956 /**
957 * Change the position of the cursor in a result object
958 * See mysql_data_seek()
959 */
960 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
961
962 /**
963 * Get the last error number
964 * See mysql_errno()
965 */
966 function lastErrno() {
967 if ( $this->mConn ) {
968 return mysql_errno( $this->mConn );
969 } else {
970 return mysql_errno();
971 }
972 }
973
974 /**
975 * Get a description of the last error
976 * See mysql_error() for more details
977 */
978 function lastError() {
979 if ( $this->mConn ) {
980 # Even if it's non-zero, it can still be invalid
981 wfSuppressWarnings();
982 $error = mysql_error( $this->mConn );
983 if ( !$error ) {
984 $error = mysql_error();
985 }
986 wfRestoreWarnings();
987 } else {
988 $error = mysql_error();
989 }
990 if( $error ) {
991 $error .= ' (' . $this->mServer . ')';
992 }
993 return $error;
994 }
995 /**
996 * Get the number of rows affected by the last write query
997 * See mysql_affected_rows() for more details
998 */
999 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
1000 /**#@-*/ // end of template : @param $result
1001
1002 /**
1003 * Simple UPDATE wrapper
1004 * Usually aborts on failure
1005 * If errors are explicitly ignored, returns success
1006 *
1007 * This function exists for historical reasons, Database::update() has a more standard
1008 * calling convention and feature set
1009 */
1010 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1011 {
1012 $table = $this->tableName( $table );
1013 $sql = "UPDATE $table SET $var = '" .
1014 $this->strencode( $value ) . "' WHERE ($cond)";
1015 return (bool)$this->query( $sql, $fname );
1016 }
1017
1018 /**
1019 * Simple SELECT wrapper, returns a single field, input must be encoded
1020 * Usually aborts on failure
1021 * If errors are explicitly ignored, returns FALSE on failure
1022 */
1023 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1024 if ( !is_array( $options ) ) {
1025 $options = array( $options );
1026 }
1027 $options['LIMIT'] = 1;
1028
1029 $res = $this->select( $table, $var, $cond, $fname, $options );
1030 if ( $res === false || !$this->numRows( $res ) ) {
1031 return false;
1032 }
1033 $row = $this->fetchRow( $res );
1034 if ( $row !== false ) {
1035 $this->freeResult( $res );
1036 return $row[0];
1037 } else {
1038 return false;
1039 }
1040 }
1041
1042 /**
1043 * Returns an optional USE INDEX clause to go after the table, and a
1044 * string to go at the end of the query
1045 *
1046 * @private
1047 *
1048 * @param array $options an associative array of options to be turned into
1049 * an SQL query, valid keys are listed in the function.
1050 * @return array
1051 */
1052 function makeSelectOptions( $options ) {
1053 $preLimitTail = $postLimitTail = '';
1054 $startOpts = '';
1055
1056 $noKeyOptions = array();
1057 foreach ( $options as $key => $option ) {
1058 if ( is_numeric( $key ) ) {
1059 $noKeyOptions[$option] = true;
1060 }
1061 }
1062
1063 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1064 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1065
1066 //if (isset($options['LIMIT'])) {
1067 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1068 // isset($options['OFFSET']) ? $options['OFFSET']
1069 // : false);
1070 //}
1071
1072 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1073 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1074 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1075
1076 # Various MySQL extensions
1077 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1078 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1079 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1080 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1081 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1082 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1083 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1084 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1085
1086 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1087 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1088 } else {
1089 $useIndex = '';
1090 }
1091
1092 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1093 }
1094
1095 /**
1096 * SELECT wrapper
1097 *
1098 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1099 * @param mixed $vars Array or string, field name(s) to be retrieved
1100 * @param mixed $conds Array or string, condition(s) for WHERE
1101 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1102 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1103 * see Database::makeSelectOptions code for list of supported stuff
1104 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1105 */
1106 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1107 {
1108 if( is_array( $vars ) ) {
1109 $vars = implode( ',', $vars );
1110 }
1111 if( !is_array( $options ) ) {
1112 $options = array( $options );
1113 }
1114 if( is_array( $table ) ) {
1115 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1116 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1117 else
1118 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1119 } elseif ($table!='') {
1120 if ($table{0}==' ') {
1121 $from = ' FROM ' . $table;
1122 } else {
1123 $from = ' FROM ' . $this->tableName( $table );
1124 }
1125 } else {
1126 $from = '';
1127 }
1128
1129 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1130
1131 if( !empty( $conds ) ) {
1132 if ( is_array( $conds ) ) {
1133 $conds = $this->makeList( $conds, LIST_AND );
1134 }
1135 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1136 } else {
1137 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1138 }
1139
1140 if (isset($options['LIMIT']))
1141 $sql = $this->limitResult($sql, $options['LIMIT'],
1142 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1143 $sql = "$sql $postLimitTail";
1144
1145 if (isset($options['EXPLAIN'])) {
1146 $sql = 'EXPLAIN ' . $sql;
1147 }
1148
1149 return $this->query( $sql, $fname );
1150 }
1151
1152 /**
1153 * Single row SELECT wrapper
1154 * Aborts or returns FALSE on error
1155 *
1156 * $vars: the selected variables
1157 * $conds: a condition map, terms are ANDed together.
1158 * Items with numeric keys are taken to be literal conditions
1159 * Takes an array of selected variables, and a condition map, which is ANDed
1160 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1161 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1162 * $obj- >page_id is the ID of the Astronomy article
1163 *
1164 * @todo migrate documentation to phpdocumentor format
1165 */
1166 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1167 $options['LIMIT'] = 1;
1168 $res = $this->select( $table, $vars, $conds, $fname, $options );
1169 if ( $res === false )
1170 return false;
1171 if ( !$this->numRows($res) ) {
1172 $this->freeResult($res);
1173 return false;
1174 }
1175 $obj = $this->fetchObject( $res );
1176 $this->freeResult( $res );
1177 return $obj;
1178
1179 }
1180
1181 /**
1182 * Estimate rows in dataset
1183 * Returns estimated count, based on EXPLAIN output
1184 * Takes same arguments as Database::select()
1185 */
1186
1187 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1188 $options['EXPLAIN']=true;
1189 $res = $this->select ($table, $vars, $conds, $fname, $options );
1190 if ( $res === false )
1191 return false;
1192 if (!$this->numRows($res)) {
1193 $this->freeResult($res);
1194 return 0;
1195 }
1196
1197 $rows=1;
1198
1199 while( $plan = $this->fetchObject( $res ) ) {
1200 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1201 }
1202
1203 $this->freeResult($res);
1204 return $rows;
1205 }
1206
1207
1208 /**
1209 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1210 * It's only slightly flawed. Don't use for anything important.
1211 *
1212 * @param string $sql A SQL Query
1213 * @static
1214 */
1215 static function generalizeSQL( $sql ) {
1216 # This does the same as the regexp below would do, but in such a way
1217 # as to avoid crashing php on some large strings.
1218 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1219
1220 $sql = str_replace ( "\\\\", '', $sql);
1221 $sql = str_replace ( "\\'", '', $sql);
1222 $sql = str_replace ( "\\\"", '', $sql);
1223 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1224 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1225
1226 # All newlines, tabs, etc replaced by single space
1227 $sql = preg_replace ( '/\s+/', ' ', $sql);
1228
1229 # All numbers => N
1230 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1231
1232 return $sql;
1233 }
1234
1235 /**
1236 * Determines whether a field exists in a table
1237 * Usually aborts on failure
1238 * If errors are explicitly ignored, returns NULL on failure
1239 */
1240 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1241 $table = $this->tableName( $table );
1242 $res = $this->query( 'DESCRIBE '.$table, $fname );
1243 if ( !$res ) {
1244 return NULL;
1245 }
1246
1247 $found = false;
1248
1249 while ( $row = $this->fetchObject( $res ) ) {
1250 if ( $row->Field == $field ) {
1251 $found = true;
1252 break;
1253 }
1254 }
1255 return $found;
1256 }
1257
1258 /**
1259 * Determines whether an index exists
1260 * Usually aborts on failure
1261 * If errors are explicitly ignored, returns NULL on failure
1262 */
1263 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1264 $info = $this->indexInfo( $table, $index, $fname );
1265 if ( is_null( $info ) ) {
1266 return NULL;
1267 } else {
1268 return $info !== false;
1269 }
1270 }
1271
1272
1273 /**
1274 * Get information about an index into an object
1275 * Returns false if the index does not exist
1276 */
1277 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1278 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1279 # SHOW INDEX should work for 3.x and up:
1280 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1281 $table = $this->tableName( $table );
1282 $sql = 'SHOW INDEX FROM '.$table;
1283 $res = $this->query( $sql, $fname );
1284 if ( !$res ) {
1285 return NULL;
1286 }
1287
1288 $result = array();
1289 while ( $row = $this->fetchObject( $res ) ) {
1290 if ( $row->Key_name == $index ) {
1291 $result[] = $row;
1292 }
1293 }
1294 $this->freeResult($res);
1295
1296 return empty($result) ? false : $result;
1297 }
1298
1299 /**
1300 * Query whether a given table exists
1301 */
1302 function tableExists( $table ) {
1303 $table = $this->tableName( $table );
1304 $old = $this->ignoreErrors( true );
1305 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1306 $this->ignoreErrors( $old );
1307 if( $res ) {
1308 $this->freeResult( $res );
1309 return true;
1310 } else {
1311 return false;
1312 }
1313 }
1314
1315 /**
1316 * mysql_fetch_field() wrapper
1317 * Returns false if the field doesn't exist
1318 *
1319 * @param $table
1320 * @param $field
1321 */
1322 function fieldInfo( $table, $field ) {
1323 $table = $this->tableName( $table );
1324 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1325 $n = mysql_num_fields( $res );
1326 for( $i = 0; $i < $n; $i++ ) {
1327 $meta = mysql_fetch_field( $res, $i );
1328 if( $field == $meta->name ) {
1329 return new MySQLField($meta);
1330 }
1331 }
1332 return false;
1333 }
1334
1335 /**
1336 * mysql_field_type() wrapper
1337 */
1338 function fieldType( $res, $index ) {
1339 return mysql_field_type( $res, $index );
1340 }
1341
1342 /**
1343 * Determines if a given index is unique
1344 */
1345 function indexUnique( $table, $index ) {
1346 $indexInfo = $this->indexInfo( $table, $index );
1347 if ( !$indexInfo ) {
1348 return NULL;
1349 }
1350 return !$indexInfo[0]->Non_unique;
1351 }
1352
1353 /**
1354 * INSERT wrapper, inserts an array into a table
1355 *
1356 * $a may be a single associative array, or an array of these with numeric keys, for
1357 * multi-row insert.
1358 *
1359 * Usually aborts on failure
1360 * If errors are explicitly ignored, returns success
1361 */
1362 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1363 # No rows to insert, easy just return now
1364 if ( !count( $a ) ) {
1365 return true;
1366 }
1367
1368 $table = $this->tableName( $table );
1369 if ( !is_array( $options ) ) {
1370 $options = array( $options );
1371 }
1372 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1373 $multi = true;
1374 $keys = array_keys( $a[0] );
1375 } else {
1376 $multi = false;
1377 $keys = array_keys( $a );
1378 }
1379
1380 $sql = 'INSERT ' . implode( ' ', $options ) .
1381 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1382
1383 if ( $multi ) {
1384 $first = true;
1385 foreach ( $a as $row ) {
1386 if ( $first ) {
1387 $first = false;
1388 } else {
1389 $sql .= ',';
1390 }
1391 $sql .= '(' . $this->makeList( $row ) . ')';
1392 }
1393 } else {
1394 $sql .= '(' . $this->makeList( $a ) . ')';
1395 }
1396 return (bool)$this->query( $sql, $fname );
1397 }
1398
1399 /**
1400 * Make UPDATE options for the Database::update function
1401 *
1402 * @private
1403 * @param array $options The options passed to Database::update
1404 * @return string
1405 */
1406 function makeUpdateOptions( $options ) {
1407 if( !is_array( $options ) ) {
1408 $options = array( $options );
1409 }
1410 $opts = array();
1411 if ( in_array( 'LOW_PRIORITY', $options ) )
1412 $opts[] = $this->lowPriorityOption();
1413 if ( in_array( 'IGNORE', $options ) )
1414 $opts[] = 'IGNORE';
1415 return implode(' ', $opts);
1416 }
1417
1418 /**
1419 * UPDATE wrapper, takes a condition array and a SET array
1420 *
1421 * @param string $table The table to UPDATE
1422 * @param array $values An array of values to SET
1423 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1424 * @param string $fname The Class::Function calling this function
1425 * (for the log)
1426 * @param array $options An array of UPDATE options, can be one or
1427 * more of IGNORE, LOW_PRIORITY
1428 */
1429 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1430 $table = $this->tableName( $table );
1431 $opts = $this->makeUpdateOptions( $options );
1432 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1433 if ( $conds != '*' ) {
1434 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1435 }
1436 $this->query( $sql, $fname );
1437 }
1438
1439 /**
1440 * Makes an encoded list of strings from an array
1441 * $mode:
1442 * LIST_COMMA - comma separated, no field names
1443 * LIST_AND - ANDed WHERE clause (without the WHERE)
1444 * LIST_OR - ORed WHERE clause (without the WHERE)
1445 * LIST_SET - comma separated with field names, like a SET clause
1446 * LIST_NAMES - comma separated field names
1447 */
1448 function makeList( $a, $mode = LIST_COMMA ) {
1449 if ( !is_array( $a ) ) {
1450 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1451 }
1452
1453 $first = true;
1454 $list = '';
1455 foreach ( $a as $field => $value ) {
1456 if ( !$first ) {
1457 if ( $mode == LIST_AND ) {
1458 $list .= ' AND ';
1459 } elseif($mode == LIST_OR) {
1460 $list .= ' OR ';
1461 } else {
1462 $list .= ',';
1463 }
1464 } else {
1465 $first = false;
1466 }
1467 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1468 $list .= "($value)";
1469 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1470 $list .= "$value";
1471 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1472 $list .= $field." IN (".$this->makeList($value).") ";
1473 } else {
1474 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1475 $list .= "$field = ";
1476 }
1477 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1478 }
1479 }
1480 return $list;
1481 }
1482
1483 /**
1484 * Change the current database
1485 */
1486 function selectDB( $db ) {
1487 $this->mDBname = $db;
1488 return mysql_select_db( $db, $this->mConn );
1489 }
1490
1491 /**
1492 * Format a table name ready for use in constructing an SQL query
1493 *
1494 * This does two important things: it quotes table names which as necessary,
1495 * and it adds a table prefix if there is one.
1496 *
1497 * All functions of this object which require a table name call this function
1498 * themselves. Pass the canonical name to such functions. This is only needed
1499 * when calling query() directly.
1500 *
1501 * @param string $name database table name
1502 */
1503 function tableName( $name ) {
1504 global $wgSharedDB;
1505 # Skip quoted literals
1506 if ( $name{0} != '`' ) {
1507 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1508 $name = "{$this->mTablePrefix}$name";
1509 }
1510 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1511 $name = "`$wgSharedDB`.`$name`";
1512 } else {
1513 # Standard quoting
1514 $name = "`$name`";
1515 }
1516 }
1517 return $name;
1518 }
1519
1520 /**
1521 * Fetch a number of table names into an array
1522 * This is handy when you need to construct SQL for joins
1523 *
1524 * Example:
1525 * extract($dbr->tableNames('user','watchlist'));
1526 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1527 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1528 */
1529 public function tableNames() {
1530 $inArray = func_get_args();
1531 $retVal = array();
1532 foreach ( $inArray as $name ) {
1533 $retVal[$name] = $this->tableName( $name );
1534 }
1535 return $retVal;
1536 }
1537
1538 /**
1539 * Fetch a number of table names into an zero-indexed numerical array
1540 * This is handy when you need to construct SQL for joins
1541 *
1542 * Example:
1543 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1544 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1545 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1546 */
1547 public function tableNamesN() {
1548 $inArray = func_get_args();
1549 $retVal = array();
1550 foreach ( $inArray as $name ) {
1551 $retVal[] = $this->tableName( $name );
1552 }
1553 return $retVal;
1554 }
1555
1556 /**
1557 * @private
1558 */
1559 function tableNamesWithUseIndex( $tables, $use_index ) {
1560 $ret = array();
1561
1562 foreach ( $tables as $table )
1563 if ( @$use_index[$table] !== null )
1564 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1565 else
1566 $ret[] = $this->tableName( $table );
1567
1568 return implode( ',', $ret );
1569 }
1570
1571 /**
1572 * Wrapper for addslashes()
1573 * @param string $s String to be slashed.
1574 * @return string slashed string.
1575 */
1576 function strencode( $s ) {
1577 return mysql_real_escape_string( $s, $this->mConn );
1578 }
1579
1580 /**
1581 * If it's a string, adds quotes and backslashes
1582 * Otherwise returns as-is
1583 */
1584 function addQuotes( $s ) {
1585 if ( is_null( $s ) ) {
1586 return 'NULL';
1587 } else {
1588 # This will also quote numeric values. This should be harmless,
1589 # and protects against weird problems that occur when they really
1590 # _are_ strings such as article titles and string->number->string
1591 # conversion is not 1:1.
1592 return "'" . $this->strencode( $s ) . "'";
1593 }
1594 }
1595
1596 /**
1597 * Escape string for safe LIKE usage
1598 */
1599 function escapeLike( $s ) {
1600 $s=$this->strencode( $s );
1601 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1602 return $s;
1603 }
1604
1605 /**
1606 * Returns an appropriately quoted sequence value for inserting a new row.
1607 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1608 * subclass will return an integer, and save the value for insertId()
1609 */
1610 function nextSequenceValue( $seqName ) {
1611 return NULL;
1612 }
1613
1614 /**
1615 * USE INDEX clause
1616 * PostgreSQL doesn't have them and returns ""
1617 */
1618 function useIndexClause( $index ) {
1619 return "FORCE INDEX ($index)";
1620 }
1621
1622 /**
1623 * REPLACE query wrapper
1624 * PostgreSQL simulates this with a DELETE followed by INSERT
1625 * $row is the row to insert, an associative array
1626 * $uniqueIndexes is an array of indexes. Each element may be either a
1627 * field name or an array of field names
1628 *
1629 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1630 * However if you do this, you run the risk of encountering errors which wouldn't have
1631 * occurred in MySQL
1632 *
1633 * @todo migrate comment to phodocumentor format
1634 */
1635 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1636 $table = $this->tableName( $table );
1637
1638 # Single row case
1639 if ( !is_array( reset( $rows ) ) ) {
1640 $rows = array( $rows );
1641 }
1642
1643 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1644 $first = true;
1645 foreach ( $rows as $row ) {
1646 if ( $first ) {
1647 $first = false;
1648 } else {
1649 $sql .= ',';
1650 }
1651 $sql .= '(' . $this->makeList( $row ) . ')';
1652 }
1653 return $this->query( $sql, $fname );
1654 }
1655
1656 /**
1657 * DELETE where the condition is a join
1658 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1659 *
1660 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1661 * join condition matches, set $conds='*'
1662 *
1663 * DO NOT put the join condition in $conds
1664 *
1665 * @param string $delTable The table to delete from.
1666 * @param string $joinTable The other table.
1667 * @param string $delVar The variable to join on, in the first table.
1668 * @param string $joinVar The variable to join on, in the second table.
1669 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1670 */
1671 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1672 if ( !$conds ) {
1673 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1674 }
1675
1676 $delTable = $this->tableName( $delTable );
1677 $joinTable = $this->tableName( $joinTable );
1678 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1679 if ( $conds != '*' ) {
1680 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1681 }
1682
1683 return $this->query( $sql, $fname );
1684 }
1685
1686 /**
1687 * Returns the size of a text field, or -1 for "unlimited"
1688 */
1689 function textFieldSize( $table, $field ) {
1690 $table = $this->tableName( $table );
1691 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1692 $res = $this->query( $sql, 'Database::textFieldSize' );
1693 $row = $this->fetchObject( $res );
1694 $this->freeResult( $res );
1695
1696 $m = array();
1697 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1698 $size = $m[1];
1699 } else {
1700 $size = -1;
1701 }
1702 return $size;
1703 }
1704
1705 /**
1706 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1707 */
1708 function lowPriorityOption() {
1709 return 'LOW_PRIORITY';
1710 }
1711
1712 /**
1713 * DELETE query wrapper
1714 *
1715 * Use $conds == "*" to delete all rows
1716 */
1717 function delete( $table, $conds, $fname = 'Database::delete' ) {
1718 if ( !$conds ) {
1719 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1720 }
1721 $table = $this->tableName( $table );
1722 $sql = "DELETE FROM $table";
1723 if ( $conds != '*' ) {
1724 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1725 }
1726 return $this->query( $sql, $fname );
1727 }
1728
1729 /**
1730 * INSERT SELECT wrapper
1731 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1732 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1733 * $conds may be "*" to copy the whole table
1734 * srcTable may be an array of tables.
1735 */
1736 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1737 $insertOptions = array(), $selectOptions = array() )
1738 {
1739 $destTable = $this->tableName( $destTable );
1740 if ( is_array( $insertOptions ) ) {
1741 $insertOptions = implode( ' ', $insertOptions );
1742 }
1743 if( !is_array( $selectOptions ) ) {
1744 $selectOptions = array( $selectOptions );
1745 }
1746 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1747 if( is_array( $srcTable ) ) {
1748 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1749 } else {
1750 $srcTable = $this->tableName( $srcTable );
1751 }
1752 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1753 " SELECT $startOpts " . implode( ',', $varMap ) .
1754 " FROM $srcTable $useIndex ";
1755 if ( $conds != '*' ) {
1756 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1757 }
1758 $sql .= " $tailOpts";
1759 return $this->query( $sql, $fname );
1760 }
1761
1762 /**
1763 * Construct a LIMIT query with optional offset
1764 * This is used for query pages
1765 * $sql string SQL query we will append the limit too
1766 * $limit integer the SQL limit
1767 * $offset integer the SQL offset (default false)
1768 */
1769 function limitResult($sql, $limit, $offset=false) {
1770 if( !is_numeric($limit) ) {
1771 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1772 }
1773 return " $sql LIMIT "
1774 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1775 . "{$limit} ";
1776 }
1777 function limitResultForUpdate($sql, $num) {
1778 return $this->limitResult($sql, $num, 0);
1779 }
1780
1781 /**
1782 * Returns an SQL expression for a simple conditional.
1783 * Uses IF on MySQL.
1784 *
1785 * @param string $cond SQL expression which will result in a boolean value
1786 * @param string $trueVal SQL expression to return if true
1787 * @param string $falseVal SQL expression to return if false
1788 * @return string SQL fragment
1789 */
1790 function conditional( $cond, $trueVal, $falseVal ) {
1791 return " IF($cond, $trueVal, $falseVal) ";
1792 }
1793
1794 /**
1795 * Determines if the last failure was due to a deadlock
1796 */
1797 function wasDeadlock() {
1798 return $this->lastErrno() == 1213;
1799 }
1800
1801 /**
1802 * Perform a deadlock-prone transaction.
1803 *
1804 * This function invokes a callback function to perform a set of write
1805 * queries. If a deadlock occurs during the processing, the transaction
1806 * will be rolled back and the callback function will be called again.
1807 *
1808 * Usage:
1809 * $dbw->deadlockLoop( callback, ... );
1810 *
1811 * Extra arguments are passed through to the specified callback function.
1812 *
1813 * Returns whatever the callback function returned on its successful,
1814 * iteration, or false on error, for example if the retry limit was
1815 * reached.
1816 */
1817 function deadlockLoop() {
1818 $myFname = 'Database::deadlockLoop';
1819
1820 $this->begin();
1821 $args = func_get_args();
1822 $function = array_shift( $args );
1823 $oldIgnore = $this->ignoreErrors( true );
1824 $tries = DEADLOCK_TRIES;
1825 if ( is_array( $function ) ) {
1826 $fname = $function[0];
1827 } else {
1828 $fname = $function;
1829 }
1830 do {
1831 $retVal = call_user_func_array( $function, $args );
1832 $error = $this->lastError();
1833 $errno = $this->lastErrno();
1834 $sql = $this->lastQuery();
1835
1836 if ( $errno ) {
1837 if ( $this->wasDeadlock() ) {
1838 # Retry
1839 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1840 } else {
1841 $this->reportQueryError( $error, $errno, $sql, $fname );
1842 }
1843 }
1844 } while( $this->wasDeadlock() && --$tries > 0 );
1845 $this->ignoreErrors( $oldIgnore );
1846 if ( $tries <= 0 ) {
1847 $this->query( 'ROLLBACK', $myFname );
1848 $this->reportQueryError( $error, $errno, $sql, $fname );
1849 return false;
1850 } else {
1851 $this->query( 'COMMIT', $myFname );
1852 return $retVal;
1853 }
1854 }
1855
1856 /**
1857 * Do a SELECT MASTER_POS_WAIT()
1858 *
1859 * @param string $file the binlog file
1860 * @param string $pos the binlog position
1861 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1862 */
1863 function masterPosWait( $file, $pos, $timeout ) {
1864 $fname = 'Database::masterPosWait';
1865 wfProfileIn( $fname );
1866
1867
1868 # Commit any open transactions
1869 $this->immediateCommit();
1870
1871 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1872 $encFile = $this->strencode( $file );
1873 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1874 $res = $this->doQuery( $sql );
1875 if ( $res && $row = $this->fetchRow( $res ) ) {
1876 $this->freeResult( $res );
1877 wfProfileOut( $fname );
1878 return $row[0];
1879 } else {
1880 wfProfileOut( $fname );
1881 return false;
1882 }
1883 }
1884
1885 /**
1886 * Get the position of the master from SHOW SLAVE STATUS
1887 */
1888 function getSlavePos() {
1889 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1890 $row = $this->fetchObject( $res );
1891 if ( $row ) {
1892 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1893 } else {
1894 return array( false, false );
1895 }
1896 }
1897
1898 /**
1899 * Get the position of the master from SHOW MASTER STATUS
1900 */
1901 function getMasterPos() {
1902 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1903 $row = $this->fetchObject( $res );
1904 if ( $row ) {
1905 return array( $row->File, $row->Position );
1906 } else {
1907 return array( false, false );
1908 }
1909 }
1910
1911 /**
1912 * Begin a transaction, committing any previously open transaction
1913 */
1914 function begin( $fname = 'Database::begin' ) {
1915 $this->query( 'BEGIN', $fname );
1916 $this->mTrxLevel = 1;
1917 }
1918
1919 /**
1920 * End a transaction
1921 */
1922 function commit( $fname = 'Database::commit' ) {
1923 $this->query( 'COMMIT', $fname );
1924 $this->mTrxLevel = 0;
1925 }
1926
1927 /**
1928 * Rollback a transaction
1929 */
1930 function rollback( $fname = 'Database::rollback' ) {
1931 $this->query( 'ROLLBACK', $fname );
1932 $this->mTrxLevel = 0;
1933 }
1934
1935 /**
1936 * Begin a transaction, committing any previously open transaction
1937 * @deprecated use begin()
1938 */
1939 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1940 $this->begin();
1941 }
1942
1943 /**
1944 * Commit transaction, if one is open
1945 * @deprecated use commit()
1946 */
1947 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1948 $this->commit();
1949 }
1950
1951 /**
1952 * Return MW-style timestamp used for MySQL schema
1953 */
1954 function timestamp( $ts=0 ) {
1955 return wfTimestamp(TS_MW,$ts);
1956 }
1957
1958 /**
1959 * Local database timestamp format or null
1960 */
1961 function timestampOrNull( $ts = null ) {
1962 if( is_null( $ts ) ) {
1963 return null;
1964 } else {
1965 return $this->timestamp( $ts );
1966 }
1967 }
1968
1969 /**
1970 * @todo document
1971 */
1972 function resultObject( $result ) {
1973 if( empty( $result ) ) {
1974 return NULL;
1975 } else {
1976 return new ResultWrapper( $this, $result );
1977 }
1978 }
1979
1980 /**
1981 * Return aggregated value alias
1982 */
1983 function aggregateValue ($valuedata,$valuename='value') {
1984 return $valuename;
1985 }
1986
1987 /**
1988 * @return string wikitext of a link to the server software's web site
1989 */
1990 function getSoftwareLink() {
1991 return "[http://www.mysql.com/ MySQL]";
1992 }
1993
1994 /**
1995 * @return string Version information from the database
1996 */
1997 function getServerVersion() {
1998 return mysql_get_server_info( $this->mConn );
1999 }
2000
2001 /**
2002 * Ping the server and try to reconnect if it there is no connection
2003 */
2004 function ping() {
2005 if( function_exists( 'mysql_ping' ) ) {
2006 return mysql_ping( $this->mConn );
2007 } else {
2008 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2009 return true;
2010 }
2011 }
2012
2013 /**
2014 * Get slave lag.
2015 * At the moment, this will only work if the DB user has the PROCESS privilege
2016 */
2017 function getLag() {
2018 $res = $this->query( 'SHOW PROCESSLIST' );
2019 # Find slave SQL thread. Assumed to be the second one running, which is a bit
2020 # dubious, but unfortunately there's no easy rigorous way
2021 while ( $row = $this->fetchObject( $res ) ) {
2022 /* This should work for most situations - when default db
2023 * for thread is not specified, it had no events executed,
2024 * and therefore it doesn't know yet how lagged it is.
2025 *
2026 * Relay log I/O thread does not select databases.
2027 */
2028 if ( $row->User == 'system user' &&
2029 $row->State != 'Waiting for master to send event' &&
2030 $row->State != 'Connecting to master' &&
2031 $row->State != 'Queueing master event to the relay log' &&
2032 $row->State != 'Waiting for master update' &&
2033 $row->State != 'Requesting binlog dump'
2034 ) {
2035 # This is it, return the time (except -ve)
2036 if ( $row->Time > 0x7fffffff ) {
2037 return false;
2038 } else {
2039 return $row->Time;
2040 }
2041 }
2042 }
2043 return false;
2044 }
2045
2046 /**
2047 * Get status information from SHOW STATUS in an associative array
2048 */
2049 function getStatus($which="%") {
2050 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2051 $status = array();
2052 while ( $row = $this->fetchObject( $res ) ) {
2053 $status[$row->Variable_name] = $row->Value;
2054 }
2055 return $status;
2056 }
2057
2058 /**
2059 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2060 */
2061 function maxListLen() {
2062 return 0;
2063 }
2064
2065 function encodeBlob($b) {
2066 return $b;
2067 }
2068
2069 function decodeBlob($b) {
2070 return $b;
2071 }
2072
2073 /**
2074 * Override database's default connection timeout.
2075 * May be useful for very long batch queries such as
2076 * full-wiki dumps, where a single query reads out
2077 * over hours or days.
2078 * @param int $timeout in seconds
2079 */
2080 public function setTimeout( $timeout ) {
2081 $this->query( "SET net_read_timeout=$timeout" );
2082 $this->query( "SET net_write_timeout=$timeout" );
2083 }
2084
2085 /**
2086 * Read and execute SQL commands from a file.
2087 * Returns true on success, error string on failure
2088 */
2089 function sourceFile( $filename ) {
2090 $fp = fopen( $filename, 'r' );
2091 if ( false === $fp ) {
2092 return "Could not open \"{$filename}\".\n";
2093 }
2094
2095 $cmd = "";
2096 $done = false;
2097 $dollarquote = false;
2098
2099 while ( ! feof( $fp ) ) {
2100 $line = trim( fgets( $fp, 1024 ) );
2101 $sl = strlen( $line ) - 1;
2102
2103 if ( $sl < 0 ) { continue; }
2104 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2105
2106 ## Allow dollar quoting for function declarations
2107 if (substr($line,0,4) == '$mw$') {
2108 if ($dollarquote) {
2109 $dollarquote = false;
2110 $done = true;
2111 }
2112 else {
2113 $dollarquote = true;
2114 }
2115 }
2116 else if (!$dollarquote) {
2117 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2118 $done = true;
2119 $line = substr( $line, 0, $sl );
2120 }
2121 }
2122
2123 if ( '' != $cmd ) { $cmd .= ' '; }
2124 $cmd .= "$line\n";
2125
2126 if ( $done ) {
2127 $cmd = str_replace(';;', ";", $cmd);
2128 $cmd = $this->replaceVars( $cmd );
2129 $res = $this->query( $cmd, 'dbsource', true );
2130
2131 if ( false === $res ) {
2132 $err = $this->lastError();
2133 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2134 }
2135
2136 $cmd = '';
2137 $done = false;
2138 }
2139 }
2140 fclose( $fp );
2141 return true;
2142 }
2143
2144 /**
2145 * Replace variables in sourced SQL
2146 */
2147 protected function replaceVars( $ins ) {
2148 $varnames = array(
2149 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2150 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2151 'wgDBadminuser', 'wgDBadminpassword',
2152 );
2153
2154 // Ordinary variables
2155 foreach ( $varnames as $var ) {
2156 if( isset( $GLOBALS[$var] ) ) {
2157 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2158 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2159 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2160 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2161 }
2162 }
2163
2164 // Table prefixes
2165 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2166 array( &$this, 'tableNameCallback' ), $ins );
2167 return $ins;
2168 }
2169
2170 /**
2171 * Table name callback
2172 * @private
2173 */
2174 protected function tableNameCallback( $matches ) {
2175 return $this->tableName( $matches[1] );
2176 }
2177
2178 }
2179
2180 /**
2181 * Database abstraction object for mySQL
2182 * Inherit all methods and properties of Database::Database()
2183 *
2184 * @see Database
2185 */
2186 class DatabaseMysql extends Database {
2187 # Inherit all
2188 }
2189
2190
2191 /**
2192 * Result wrapper for grabbing data queried by someone else
2193 *
2194 */
2195 class ResultWrapper {
2196 var $db, $result;
2197
2198 /**
2199 * @todo document
2200 */
2201 function ResultWrapper( &$database, $result ) {
2202 $this->db =& $database;
2203 $this->result =& $result;
2204 }
2205
2206 /**
2207 * @todo document
2208 */
2209 function numRows() {
2210 return $this->db->numRows( $this->result );
2211 }
2212
2213 /**
2214 * @todo document
2215 */
2216 function fetchObject() {
2217 return $this->db->fetchObject( $this->result );
2218 }
2219
2220 /**
2221 * @todo document
2222 */
2223 function fetchRow() {
2224 return $this->db->fetchRow( $this->result );
2225 }
2226
2227 /**
2228 * @todo document
2229 */
2230 function free() {
2231 $this->db->freeResult( $this->result );
2232 unset( $this->result );
2233 unset( $this->db );
2234 }
2235
2236 function seek( $row ) {
2237 $this->db->dataSeek( $this->result, $row );
2238 }
2239
2240 function rewind() {
2241 if ($this->numRows()) {
2242 $this->db->dataSeek($this->result, 0);
2243 }
2244 }
2245
2246 }
2247
2248 ?>