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