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