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