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