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