* Escape backslashes before normal escaping, to not counteract the effect
[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( $value === null ) {
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 ( $s === null ) {
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=str_replace('\\','\\\\',$s);
1624 $s=$this->strencode( $s );
1625 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1626 return $s;
1627 }
1628
1629 /**
1630 * Returns an appropriately quoted sequence value for inserting a new row.
1631 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1632 * subclass will return an integer, and save the value for insertId()
1633 */
1634 function nextSequenceValue( $seqName ) {
1635 return NULL;
1636 }
1637
1638 /**
1639 * USE INDEX clause
1640 * PostgreSQL doesn't have them and returns ""
1641 */
1642 function useIndexClause( $index ) {
1643 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1644 }
1645
1646 /**
1647 * REPLACE query wrapper
1648 * PostgreSQL simulates this with a DELETE followed by INSERT
1649 * $row is the row to insert, an associative array
1650 * $uniqueIndexes is an array of indexes. Each element may be either a
1651 * field name or an array of field names
1652 *
1653 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1654 * However if you do this, you run the risk of encountering errors which wouldn't have
1655 * occurred in MySQL
1656 *
1657 * @todo migrate comment to phodocumentor format
1658 */
1659 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1660 $table = $this->tableName( $table );
1661
1662 # Single row case
1663 if ( !is_array( reset( $rows ) ) ) {
1664 $rows = array( $rows );
1665 }
1666
1667 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1668 $first = true;
1669 foreach ( $rows as $row ) {
1670 if ( $first ) {
1671 $first = false;
1672 } else {
1673 $sql .= ',';
1674 }
1675 $sql .= '(' . $this->makeList( $row ) . ')';
1676 }
1677 return $this->query( $sql, $fname );
1678 }
1679
1680 /**
1681 * DELETE where the condition is a join
1682 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1683 *
1684 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1685 * join condition matches, set $conds='*'
1686 *
1687 * DO NOT put the join condition in $conds
1688 *
1689 * @param $delTable String: The table to delete from.
1690 * @param $joinTable String: The other table.
1691 * @param $delVar String: The variable to join on, in the first table.
1692 * @param $joinVar String: The variable to join on, in the second table.
1693 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1694 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1695 */
1696 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1697 if ( !$conds ) {
1698 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1699 }
1700
1701 $delTable = $this->tableName( $delTable );
1702 $joinTable = $this->tableName( $joinTable );
1703 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1704 if ( $conds != '*' ) {
1705 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1706 }
1707
1708 return $this->query( $sql, $fname );
1709 }
1710
1711 /**
1712 * Returns the size of a text field, or -1 for "unlimited"
1713 */
1714 function textFieldSize( $table, $field ) {
1715 $table = $this->tableName( $table );
1716 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1717 $res = $this->query( $sql, 'Database::textFieldSize' );
1718 $row = $this->fetchObject( $res );
1719 $this->freeResult( $res );
1720
1721 $m = array();
1722 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1723 $size = $m[1];
1724 } else {
1725 $size = -1;
1726 }
1727 return $size;
1728 }
1729
1730 /**
1731 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1732 */
1733 function lowPriorityOption() {
1734 return 'LOW_PRIORITY';
1735 }
1736
1737 /**
1738 * DELETE query wrapper
1739 *
1740 * Use $conds == "*" to delete all rows
1741 */
1742 function delete( $table, $conds, $fname = 'Database::delete' ) {
1743 if ( !$conds ) {
1744 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1745 }
1746 $table = $this->tableName( $table );
1747 $sql = "DELETE FROM $table";
1748 if ( $conds != '*' ) {
1749 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1750 }
1751 return $this->query( $sql, $fname );
1752 }
1753
1754 /**
1755 * INSERT SELECT wrapper
1756 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1757 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1758 * $conds may be "*" to copy the whole table
1759 * srcTable may be an array of tables.
1760 */
1761 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1762 $insertOptions = array(), $selectOptions = array() )
1763 {
1764 $destTable = $this->tableName( $destTable );
1765 if ( is_array( $insertOptions ) ) {
1766 $insertOptions = implode( ' ', $insertOptions );
1767 }
1768 if( !is_array( $selectOptions ) ) {
1769 $selectOptions = array( $selectOptions );
1770 }
1771 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1772 if( is_array( $srcTable ) ) {
1773 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1774 } else {
1775 $srcTable = $this->tableName( $srcTable );
1776 }
1777 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1778 " SELECT $startOpts " . implode( ',', $varMap ) .
1779 " FROM $srcTable $useIndex ";
1780 if ( $conds != '*' ) {
1781 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1782 }
1783 $sql .= " $tailOpts";
1784 return $this->query( $sql, $fname );
1785 }
1786
1787 /**
1788 * Construct a LIMIT query with optional offset
1789 * This is used for query pages
1790 * @param $sql String: SQL query we will append the limit too
1791 * @param $limit Integer: the SQL limit
1792 * @param $offset Integer the SQL offset (default false)
1793 */
1794 function limitResult($sql, $limit, $offset=false) {
1795 if( !is_numeric($limit) ) {
1796 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1797 }
1798 return "$sql LIMIT "
1799 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1800 . "{$limit} ";
1801 }
1802 function limitResultForUpdate($sql, $num) {
1803 return $this->limitResult($sql, $num, 0);
1804 }
1805
1806 /**
1807 * Returns an SQL expression for a simple conditional.
1808 * Uses IF on MySQL.
1809 *
1810 * @param $cond String: SQL expression which will result in a boolean value
1811 * @param $trueVal String: SQL expression to return if true
1812 * @param $falseVal String: SQL expression to return if false
1813 * @return String: SQL fragment
1814 */
1815 function conditional( $cond, $trueVal, $falseVal ) {
1816 return " IF($cond, $trueVal, $falseVal) ";
1817 }
1818
1819 /**
1820 * Returns a comand for str_replace function in SQL query.
1821 * Uses REPLACE() in MySQL
1822 *
1823 * @param $orig String: column to modify
1824 * @param $old String: column to seek
1825 * @param $new String: column to replace with
1826 */
1827 function strreplace( $orig, $old, $new ) {
1828 return "REPLACE({$orig}, {$old}, {$new})";
1829 }
1830
1831 /**
1832 * Determines if the last failure was due to a deadlock
1833 */
1834 function wasDeadlock() {
1835 return $this->lastErrno() == 1213;
1836 }
1837
1838 /**
1839 * Determines if the last query error was something that should be dealt
1840 * with by pinging the connection and reissuing the query
1841 */
1842 function wasErrorReissuable() {
1843 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1844 }
1845
1846 /**
1847 * Perform a deadlock-prone transaction.
1848 *
1849 * This function invokes a callback function to perform a set of write
1850 * queries. If a deadlock occurs during the processing, the transaction
1851 * will be rolled back and the callback function will be called again.
1852 *
1853 * Usage:
1854 * $dbw->deadlockLoop( callback, ... );
1855 *
1856 * Extra arguments are passed through to the specified callback function.
1857 *
1858 * Returns whatever the callback function returned on its successful,
1859 * iteration, or false on error, for example if the retry limit was
1860 * reached.
1861 */
1862 function deadlockLoop() {
1863 $myFname = 'Database::deadlockLoop';
1864
1865 $this->begin();
1866 $args = func_get_args();
1867 $function = array_shift( $args );
1868 $oldIgnore = $this->ignoreErrors( true );
1869 $tries = DEADLOCK_TRIES;
1870 if ( is_array( $function ) ) {
1871 $fname = $function[0];
1872 } else {
1873 $fname = $function;
1874 }
1875 do {
1876 $retVal = call_user_func_array( $function, $args );
1877 $error = $this->lastError();
1878 $errno = $this->lastErrno();
1879 $sql = $this->lastQuery();
1880
1881 if ( $errno ) {
1882 if ( $this->wasDeadlock() ) {
1883 # Retry
1884 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1885 } else {
1886 $this->reportQueryError( $error, $errno, $sql, $fname );
1887 }
1888 }
1889 } while( $this->wasDeadlock() && --$tries > 0 );
1890 $this->ignoreErrors( $oldIgnore );
1891 if ( $tries <= 0 ) {
1892 $this->query( 'ROLLBACK', $myFname );
1893 $this->reportQueryError( $error, $errno, $sql, $fname );
1894 return false;
1895 } else {
1896 $this->query( 'COMMIT', $myFname );
1897 return $retVal;
1898 }
1899 }
1900
1901 /**
1902 * Do a SELECT MASTER_POS_WAIT()
1903 *
1904 * @param $pos MySQLMasterPos object
1905 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1906 */
1907 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1908 $fname = 'Database::masterPosWait';
1909 wfProfileIn( $fname );
1910
1911 # Commit any open transactions
1912 if ( $this->mTrxLevel ) {
1913 $this->immediateCommit();
1914 }
1915
1916 if ( !is_null( $this->mFakeSlaveLag ) ) {
1917 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1918 if ( $wait > $timeout * 1e6 ) {
1919 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1920 wfProfileOut( $fname );
1921 return -1;
1922 } elseif ( $wait > 0 ) {
1923 wfDebug( "Fake slave waiting $wait us\n" );
1924 usleep( $wait );
1925 wfProfileOut( $fname );
1926 return 1;
1927 } else {
1928 wfDebug( "Fake slave up to date ($wait us)\n" );
1929 wfProfileOut( $fname );
1930 return 0;
1931 }
1932 }
1933
1934 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1935 $encFile = $this->addQuotes( $pos->file );
1936 $encPos = intval( $pos->pos );
1937 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1938 $res = $this->doQuery( $sql );
1939 if ( $res && $row = $this->fetchRow( $res ) ) {
1940 $this->freeResult( $res );
1941 wfProfileOut( $fname );
1942 return $row[0];
1943 } else {
1944 wfProfileOut( $fname );
1945 return false;
1946 }
1947 }
1948
1949 /**
1950 * Get the position of the master from SHOW SLAVE STATUS
1951 */
1952 function getSlavePos() {
1953 if ( !is_null( $this->mFakeSlaveLag ) ) {
1954 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1955 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1956 return $pos;
1957 }
1958 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1959 $row = $this->fetchObject( $res );
1960 if ( $row ) {
1961 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1962 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1963 } else {
1964 return false;
1965 }
1966 }
1967
1968 /**
1969 * Get the position of the master from SHOW MASTER STATUS
1970 */
1971 function getMasterPos() {
1972 if ( $this->mFakeMaster ) {
1973 return new MySQLMasterPos( 'fake', microtime( true ) );
1974 }
1975 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1976 $row = $this->fetchObject( $res );
1977 if ( $row ) {
1978 return new MySQLMasterPos( $row->File, $row->Position );
1979 } else {
1980 return false;
1981 }
1982 }
1983
1984 /**
1985 * Begin a transaction, committing any previously open transaction
1986 */
1987 function begin( $fname = 'Database::begin' ) {
1988 $this->query( 'BEGIN', $fname );
1989 $this->mTrxLevel = 1;
1990 }
1991
1992 /**
1993 * End a transaction
1994 */
1995 function commit( $fname = 'Database::commit' ) {
1996 $this->query( 'COMMIT', $fname );
1997 $this->mTrxLevel = 0;
1998 }
1999
2000 /**
2001 * Rollback a transaction.
2002 * No-op on non-transactional databases.
2003 */
2004 function rollback( $fname = 'Database::rollback' ) {
2005 $this->query( 'ROLLBACK', $fname, true );
2006 $this->mTrxLevel = 0;
2007 }
2008
2009 /**
2010 * Begin a transaction, committing any previously open transaction
2011 * @deprecated use begin()
2012 */
2013 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2014 $this->begin();
2015 }
2016
2017 /**
2018 * Commit transaction, if one is open
2019 * @deprecated use commit()
2020 */
2021 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2022 $this->commit();
2023 }
2024
2025 /**
2026 * Return MW-style timestamp used for MySQL schema
2027 */
2028 function timestamp( $ts=0 ) {
2029 return wfTimestamp(TS_MW,$ts);
2030 }
2031
2032 /**
2033 * Local database timestamp format or null
2034 */
2035 function timestampOrNull( $ts = null ) {
2036 if( is_null( $ts ) ) {
2037 return null;
2038 } else {
2039 return $this->timestamp( $ts );
2040 }
2041 }
2042
2043 /**
2044 * @todo document
2045 */
2046 function resultObject( $result ) {
2047 if( empty( $result ) ) {
2048 return false;
2049 } elseif ( $result instanceof ResultWrapper ) {
2050 return $result;
2051 } elseif ( $result === true ) {
2052 // Successful write query
2053 return $result;
2054 } else {
2055 return new ResultWrapper( $this, $result );
2056 }
2057 }
2058
2059 /**
2060 * Return aggregated value alias
2061 */
2062 function aggregateValue ($valuedata,$valuename='value') {
2063 return $valuename;
2064 }
2065
2066 /**
2067 * @return String: wikitext of a link to the server software's web site
2068 */
2069 function getSoftwareLink() {
2070 return "[http://www.mysql.com/ MySQL]";
2071 }
2072
2073 /**
2074 * @return String: Version information from the database
2075 */
2076 function getServerVersion() {
2077 return mysql_get_server_info( $this->mConn );
2078 }
2079
2080 /**
2081 * Ping the server and try to reconnect if it there is no connection
2082 */
2083 function ping() {
2084 if( !function_exists( 'mysql_ping' ) ) {
2085 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2086 return true;
2087 }
2088 $ping = mysql_ping( $this->mConn );
2089 if ( $ping ) {
2090 return true;
2091 }
2092
2093 // Need to reconnect manually in MySQL client 5.0.13+
2094 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2095 mysql_close( $this->mConn );
2096 $this->mOpened = false;
2097 $this->mConn = false;
2098 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2099 return true;
2100 }
2101 return false;
2102 }
2103
2104 /**
2105 * Get slave lag.
2106 * At the moment, this will only work if the DB user has the PROCESS privilege
2107 */
2108 function getLag() {
2109 if ( !is_null( $this->mFakeSlaveLag ) ) {
2110 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2111 return $this->mFakeSlaveLag;
2112 }
2113 $res = $this->query( 'SHOW PROCESSLIST' );
2114 # Find slave SQL thread
2115 while ( $row = $this->fetchObject( $res ) ) {
2116 /* This should work for most situations - when default db
2117 * for thread is not specified, it had no events executed,
2118 * and therefore it doesn't know yet how lagged it is.
2119 *
2120 * Relay log I/O thread does not select databases.
2121 */
2122 if ( $row->User == 'system user' &&
2123 $row->State != 'Waiting for master to send event' &&
2124 $row->State != 'Connecting to master' &&
2125 $row->State != 'Queueing master event to the relay log' &&
2126 $row->State != 'Waiting for master update' &&
2127 $row->State != 'Requesting binlog dump'
2128 ) {
2129 # This is it, return the time (except -ve)
2130 if ( $row->Time > 0x7fffffff ) {
2131 return false;
2132 } else {
2133 return $row->Time;
2134 }
2135 }
2136 }
2137 return false;
2138 }
2139
2140 /**
2141 * Get status information from SHOW STATUS in an associative array
2142 */
2143 function getStatus($which="%") {
2144 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2145 $status = array();
2146 while ( $row = $this->fetchObject( $res ) ) {
2147 $status[$row->Variable_name] = $row->Value;
2148 }
2149 return $status;
2150 }
2151
2152 /**
2153 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2154 */
2155 function maxListLen() {
2156 return 0;
2157 }
2158
2159 function encodeBlob($b) {
2160 return $b;
2161 }
2162
2163 function decodeBlob($b) {
2164 return $b;
2165 }
2166
2167 /**
2168 * Override database's default connection timeout.
2169 * May be useful for very long batch queries such as
2170 * full-wiki dumps, where a single query reads out
2171 * over hours or days.
2172 * @param $timeout Integer in seconds
2173 */
2174 public function setTimeout( $timeout ) {
2175 $this->query( "SET net_read_timeout=$timeout" );
2176 $this->query( "SET net_write_timeout=$timeout" );
2177 }
2178
2179 /**
2180 * Read and execute SQL commands from a file.
2181 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2182 * @param $filename String: File name to open
2183 * @param $lineCallback Callback: Optional function called before reading each line
2184 * @param $resultCallback Callback: Optional function called for each MySQL result
2185 */
2186 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2187 $fp = fopen( $filename, 'r' );
2188 if ( false === $fp ) {
2189 throw new MWException( "Could not open \"{$filename}\".\n" );
2190 }
2191 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2192 fclose( $fp );
2193 return $error;
2194 }
2195
2196 /**
2197 * Read and execute commands from an open file handle
2198 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2199 * @param $fp String: File handle
2200 * @param $lineCallback Callback: Optional function called before reading each line
2201 * @param $resultCallback Callback: Optional function called for each MySQL result
2202 */
2203 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2204 $cmd = "";
2205 $done = false;
2206 $dollarquote = false;
2207
2208 while ( ! feof( $fp ) ) {
2209 if ( $lineCallback ) {
2210 call_user_func( $lineCallback );
2211 }
2212 $line = trim( fgets( $fp, 1024 ) );
2213 $sl = strlen( $line ) - 1;
2214
2215 if ( $sl < 0 ) { continue; }
2216 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2217
2218 ## Allow dollar quoting for function declarations
2219 if (substr($line,0,4) == '$mw$') {
2220 if ($dollarquote) {
2221 $dollarquote = false;
2222 $done = true;
2223 }
2224 else {
2225 $dollarquote = true;
2226 }
2227 }
2228 else if (!$dollarquote) {
2229 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2230 $done = true;
2231 $line = substr( $line, 0, $sl );
2232 }
2233 }
2234
2235 if ( '' != $cmd ) { $cmd .= ' '; }
2236 $cmd .= "$line\n";
2237
2238 if ( $done ) {
2239 $cmd = str_replace(';;', ";", $cmd);
2240 $cmd = $this->replaceVars( $cmd );
2241 $res = $this->query( $cmd, __METHOD__ );
2242 if ( $resultCallback ) {
2243 call_user_func( $resultCallback, $res, $this );
2244 }
2245
2246 if ( false === $res ) {
2247 $err = $this->lastError();
2248 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2249 }
2250
2251 $cmd = '';
2252 $done = false;
2253 }
2254 }
2255 return true;
2256 }
2257
2258
2259 /**
2260 * Replace variables in sourced SQL
2261 */
2262 protected function replaceVars( $ins ) {
2263 $varnames = array(
2264 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2265 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2266 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2267 );
2268
2269 // Ordinary variables
2270 foreach ( $varnames as $var ) {
2271 if( isset( $GLOBALS[$var] ) ) {
2272 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2273 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2274 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2275 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2276 }
2277 }
2278
2279 // Table prefixes
2280 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2281 array( $this, 'tableNameCallback' ), $ins );
2282
2283 // Index names
2284 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2285 array( $this, 'indexNameCallback' ), $ins );
2286 return $ins;
2287 }
2288
2289 /**
2290 * Table name callback
2291 * @private
2292 */
2293 protected function tableNameCallback( $matches ) {
2294 return $this->tableName( $matches[1] );
2295 }
2296
2297 /**
2298 * Index name callback
2299 */
2300 protected function indexNameCallback( $matches ) {
2301 return $this->indexName( $matches[1] );
2302 }
2303
2304 /*
2305 * Build a concatenation list to feed into a SQL query
2306 */
2307 function buildConcat( $stringList ) {
2308 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2309 }
2310
2311 /**
2312 * Acquire a lock
2313 *
2314 * Abstracted from Filestore::lock() so child classes can implement for
2315 * their own needs.
2316 *
2317 * @param $lockName String: Name of lock to aquire
2318 * @param $method String: Name of method calling us
2319 * @return bool
2320 */
2321 public function lock( $lockName, $method ) {
2322 $lockName = $this->addQuotes( $lockName );
2323 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2324 $row = $this->fetchObject( $result );
2325 $this->freeResult( $result );
2326
2327 if( $row->lockstatus == 1 ) {
2328 return true;
2329 } else {
2330 wfDebug( __METHOD__." failed to acquire lock\n" );
2331 return false;
2332 }
2333 }
2334 /**
2335 * Release a lock.
2336 *
2337 * @todo fixme - Figure out a way to return a bool
2338 * based on successful lock release.
2339 *
2340 * @param $lockName String: Name of lock to release
2341 * @param $method String: Name of method calling us
2342 */
2343 public function unlock( $lockName, $method ) {
2344 $lockName = $this->addQuotes( $lockName );
2345 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2346 $this->freeResult( $result );
2347 }
2348
2349 /**
2350 * Get search engine class. All subclasses of this
2351 * need to implement this if they wish to use searching.
2352 *
2353 * @return String
2354 */
2355 public function getSearchEngine() {
2356 return "SearchMySQL";
2357 }
2358 }
2359
2360 /**
2361 * Database abstraction object for mySQL
2362 * Inherit all methods and properties of Database::Database()
2363 *
2364 * @ingroup Database
2365 * @see Database
2366 */
2367 class DatabaseMysql extends Database {
2368 # Inherit all
2369 }
2370
2371 /******************************************************************************
2372 * Utility classes
2373 *****************************************************************************/
2374
2375 /**
2376 * Utility class.
2377 * @ingroup Database
2378 */
2379 class DBObject {
2380 public $mData;
2381
2382 function DBObject($data) {
2383 $this->mData = $data;
2384 }
2385
2386 function isLOB() {
2387 return false;
2388 }
2389
2390 function data() {
2391 return $this->mData;
2392 }
2393 }
2394
2395 /**
2396 * Utility class
2397 * @ingroup Database
2398 *
2399 * This allows us to distinguish a blob from a normal string and an array of strings
2400 */
2401 class Blob {
2402 private $mData;
2403 function __construct($data) {
2404 $this->mData = $data;
2405 }
2406 function fetch() {
2407 return $this->mData;
2408 }
2409 }
2410
2411 /**
2412 * Utility class.
2413 * @ingroup Database
2414 */
2415 class MySQLField {
2416 private $name, $tablename, $default, $max_length, $nullable,
2417 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2418 function __construct ($info) {
2419 $this->name = $info->name;
2420 $this->tablename = $info->table;
2421 $this->default = $info->def;
2422 $this->max_length = $info->max_length;
2423 $this->nullable = !$info->not_null;
2424 $this->is_pk = $info->primary_key;
2425 $this->is_unique = $info->unique_key;
2426 $this->is_multiple = $info->multiple_key;
2427 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2428 $this->type = $info->type;
2429 }
2430
2431 function name() {
2432 return $this->name;
2433 }
2434
2435 function tableName() {
2436 return $this->tableName;
2437 }
2438
2439 function defaultValue() {
2440 return $this->default;
2441 }
2442
2443 function maxLength() {
2444 return $this->max_length;
2445 }
2446
2447 function nullable() {
2448 return $this->nullable;
2449 }
2450
2451 function isKey() {
2452 return $this->is_key;
2453 }
2454
2455 function isMultipleKey() {
2456 return $this->is_multiple;
2457 }
2458
2459 function type() {
2460 return $this->type;
2461 }
2462 }
2463
2464 /******************************************************************************
2465 * Error classes
2466 *****************************************************************************/
2467
2468 /**
2469 * Database error base class
2470 * @ingroup Database
2471 */
2472 class DBError extends MWException {
2473 public $db;
2474
2475 /**
2476 * Construct a database error
2477 * @param $db Database object which threw the error
2478 * @param $error A simple error message to be used for debugging
2479 */
2480 function __construct( Database &$db, $error ) {
2481 $this->db =& $db;
2482 parent::__construct( $error );
2483 }
2484 }
2485
2486 /**
2487 * @ingroup Database
2488 */
2489 class DBConnectionError extends DBError {
2490 public $error;
2491
2492 function __construct( Database &$db, $error = 'unknown error' ) {
2493 $msg = 'DB connection error';
2494 if ( trim( $error ) != '' ) {
2495 $msg .= ": $error";
2496 }
2497 $this->error = $error;
2498 parent::__construct( $db, $msg );
2499 }
2500
2501 function useOutputPage() {
2502 // Not likely to work
2503 return false;
2504 }
2505
2506 function useMessageCache() {
2507 // Not likely to work
2508 return false;
2509 }
2510
2511 function getText() {
2512 return $this->getMessage() . "\n";
2513 }
2514
2515 function getLogMessage() {
2516 # Don't send to the exception log
2517 return false;
2518 }
2519
2520 function getPageTitle() {
2521 global $wgSitename;
2522 return "$wgSitename has a problem";
2523 }
2524
2525 function getHTML() {
2526 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2527 global $wgSitename, $wgServer, $wgMessageCache;
2528
2529 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2530 # Hard coding strings instead.
2531
2532 $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>";
2533 $mainpage = 'Main Page';
2534 $searchdisabled = <<<EOT
2535 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2536 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2537 EOT;
2538
2539 $googlesearch = "
2540 <!-- SiteSearch Google -->
2541 <FORM method=GET action=\"http://www.google.com/search\">
2542 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2543 <A HREF=\"http://www.google.com/\">
2544 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2545 border=\"0\" ALT=\"Google\"></A>
2546 </td>
2547 <td>
2548 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2549 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2550 <font size=-1>
2551 <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 />
2552 <input type='hidden' name='ie' value='$2'>
2553 <input type='hidden' name='oe' value='$2'>
2554 </font>
2555 </td></tr></TABLE>
2556 </FORM>
2557 <!-- SiteSearch Google -->";
2558 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2559
2560 # No database access
2561 if ( is_object( $wgMessageCache ) ) {
2562 $wgMessageCache->disable();
2563 }
2564
2565 if ( trim( $this->error ) == '' ) {
2566 $this->error = $this->db->getProperty('mServer');
2567 }
2568
2569 $text = str_replace( '$1', $this->error, $noconnect );
2570
2571 /*
2572 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2573 $text .= '</p><p>Backtrace:</p><p>' .
2574 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2575 "</p>\n";
2576 }*/
2577
2578 if($wgUseFileCache) {
2579 if($wgTitle) {
2580 $t =& $wgTitle;
2581 } else {
2582 if($title) {
2583 $t = Title::newFromURL( $title );
2584 } elseif (@/**/$_REQUEST['search']) {
2585 $search = $_REQUEST['search'];
2586 return $searchdisabled .
2587 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2588 $wgInputEncoding ), $googlesearch );
2589 } else {
2590 $t = Title::newFromText( $mainpage );
2591 }
2592 }
2593
2594 $cache = new HTMLFileCache( $t );
2595 if( $cache->isFileCached() ) {
2596 // @todo, FIXME: $msg is not defined on the next line.
2597 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2598 $cachederror . "</b></p>\n";
2599
2600 $tag = '<div id="article">';
2601 $text = str_replace(
2602 $tag,
2603 $tag . $text,
2604 $cache->fetchPageText() );
2605 }
2606 }
2607
2608 return $text;
2609 }
2610 }
2611
2612 /**
2613 * @ingroup Database
2614 */
2615 class DBQueryError extends DBError {
2616 public $error, $errno, $sql, $fname;
2617
2618 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
2619 $message = "A database error has occurred\n" .
2620 "Query: $sql\n" .
2621 "Function: $fname\n" .
2622 "Error: $errno $error\n";
2623
2624 parent::__construct( $db, $message );
2625 $this->error = $error;
2626 $this->errno = $errno;
2627 $this->sql = $sql;
2628 $this->fname = $fname;
2629 }
2630
2631 function getText() {
2632 if ( $this->useMessageCache() ) {
2633 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2634 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2635 } else {
2636 return $this->getMessage();
2637 }
2638 }
2639
2640 function getSQL() {
2641 global $wgShowSQLErrors;
2642 if( !$wgShowSQLErrors ) {
2643 return $this->msg( 'sqlhidden', 'SQL hidden' );
2644 } else {
2645 return $this->sql;
2646 }
2647 }
2648
2649 function getLogMessage() {
2650 # Don't send to the exception log
2651 return false;
2652 }
2653
2654 function getPageTitle() {
2655 return $this->msg( 'databaseerror', 'Database error' );
2656 }
2657
2658 function getHTML() {
2659 if ( $this->useMessageCache() ) {
2660 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2661 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2662 } else {
2663 return nl2br( htmlspecialchars( $this->getMessage() ) );
2664 }
2665 }
2666 }
2667
2668 /**
2669 * @ingroup Database
2670 */
2671 class DBUnexpectedError extends DBError {}
2672
2673
2674 /**
2675 * Result wrapper for grabbing data queried by someone else
2676 * @ingroup Database
2677 */
2678 class ResultWrapper implements Iterator {
2679 var $db, $result, $pos = 0, $currentRow = null;
2680
2681 /**
2682 * Create a new result object from a result resource and a Database object
2683 */
2684 function ResultWrapper( $database, $result ) {
2685 $this->db = $database;
2686 if ( $result instanceof ResultWrapper ) {
2687 $this->result = $result->result;
2688 } else {
2689 $this->result = $result;
2690 }
2691 }
2692
2693 /**
2694 * Get the number of rows in a result object
2695 */
2696 function numRows() {
2697 return $this->db->numRows( $this->result );
2698 }
2699
2700 /**
2701 * Fetch the next row from the given result object, in object form.
2702 * Fields can be retrieved with $row->fieldname, with fields acting like
2703 * member variables.
2704 *
2705 * @param $res SQL result object as returned from Database::query(), etc.
2706 * @return MySQL row object
2707 * @throws DBUnexpectedError Thrown if the database returns an error
2708 */
2709 function fetchObject() {
2710 return $this->db->fetchObject( $this->result );
2711 }
2712
2713 /**
2714 * Fetch the next row from the given result object, in associative array
2715 * form. Fields are retrieved with $row['fieldname'].
2716 *
2717 * @param $res SQL result object as returned from Database::query(), etc.
2718 * @return MySQL row object
2719 * @throws DBUnexpectedError Thrown if the database returns an error
2720 */
2721 function fetchRow() {
2722 return $this->db->fetchRow( $this->result );
2723 }
2724
2725 /**
2726 * Free a result object
2727 */
2728 function free() {
2729 $this->db->freeResult( $this->result );
2730 unset( $this->result );
2731 unset( $this->db );
2732 }
2733
2734 /**
2735 * Change the position of the cursor in a result object
2736 * See mysql_data_seek()
2737 */
2738 function seek( $row ) {
2739 $this->db->dataSeek( $this->result, $row );
2740 }
2741
2742 /*********************
2743 * Iterator functions
2744 * Note that using these in combination with the non-iterator functions
2745 * above may cause rows to be skipped or repeated.
2746 */
2747
2748 function rewind() {
2749 if ($this->numRows()) {
2750 $this->db->dataSeek($this->result, 0);
2751 }
2752 $this->pos = 0;
2753 $this->currentRow = null;
2754 }
2755
2756 function current() {
2757 if ( is_null( $this->currentRow ) ) {
2758 $this->next();
2759 }
2760 return $this->currentRow;
2761 }
2762
2763 function key() {
2764 return $this->pos;
2765 }
2766
2767 function next() {
2768 $this->pos++;
2769 $this->currentRow = $this->fetchObject();
2770 return $this->currentRow;
2771 }
2772
2773 function valid() {
2774 return $this->current() !== false;
2775 }
2776 }
2777
2778 class MySQLMasterPos {
2779 var $file, $pos;
2780
2781 function __construct( $file, $pos ) {
2782 $this->file = $file;
2783 $this->pos = $pos;
2784 }
2785
2786 function __toString() {
2787 return "{$this->file}/{$this->pos}";
2788 }
2789 }