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