Add decodeBlob() function to complement encodeBlob()
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /** See Database::makeList() */
9 define( 'LIST_COMMA', 0 );
10 define( 'LIST_AND', 1 );
11 define( 'LIST_SET', 2 );
12 define( 'LIST_NAMES', 3);
13 define( 'LIST_OR', 4);
14
15 /** Number of times to re-try an operation in case of deadlock */
16 define( 'DEADLOCK_TRIES', 4 );
17 /** Minimum time to wait before retry, in microseconds */
18 define( 'DEADLOCK_DELAY_MIN', 500000 );
19 /** Maximum time to wait before retry */
20 define( 'DEADLOCK_DELAY_MAX', 1500000 );
21
22 /******************************************************************************
23 * Utility classes
24 *****************************************************************************/
25
26 class DBObject {
27 public $mData;
28
29 function DBObject($data) {
30 $this->mData = $data;
31 }
32
33 function isLOB() {
34 return false;
35 }
36
37 function data() {
38 return $this->mData;
39 }
40 };
41
42 /******************************************************************************
43 * Error classes
44 *****************************************************************************/
45
46 /**
47 * Database error base class
48 */
49 class DBError extends MWException {
50 public $db;
51
52 /**
53 * Construct a database error
54 * @param Database $db The database object which threw the error
55 * @param string $error A simple error message to be used for debugging
56 */
57 function __construct( Database &$db, $error ) {
58 $this->db =& $db;
59 parent::__construct( $error );
60 }
61 }
62
63 class DBConnectionError extends DBError {
64 public $error;
65
66 function __construct( Database &$db, $error = 'unknown error' ) {
67 $msg = 'DB connection error';
68 if ( trim( $error ) != '' ) {
69 $msg .= ": $error";
70 }
71 $this->error = $error;
72 parent::__construct( $db, $msg );
73 }
74
75 function useOutputPage() {
76 // Not likely to work
77 return false;
78 }
79
80 function useMessageCache() {
81 // Not likely to work
82 return false;
83 }
84
85 function getText() {
86 return $this->getMessage() . "\n";
87 }
88
89 function getPageTitle() {
90 global $wgSitename;
91 return "$wgSitename has a problem";
92 }
93
94 function getHTML() {
95 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
96 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
97
98 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
99 # Hard coding strings instead.
100
101 $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>";
102 $mainpage = 'Main Page';
103 $searchdisabled = <<<EOT
104 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
105 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
106 EOT;
107
108 $googlesearch = "
109 <!-- SiteSearch Google -->
110 <FORM method=GET action=\"http://www.google.com/search\">
111 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
112 <A HREF=\"http://www.google.com/\">
113 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
114 border=\"0\" ALT=\"Google\"></A>
115 </td>
116 <td>
117 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
118 <INPUT type=submit name=btnG VALUE=\"Google Search\">
119 <font size=-1>
120 <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 />
121 <input type='hidden' name='ie' value='$2'>
122 <input type='hidden' name='oe' value='$2'>
123 </font>
124 </td></tr></TABLE>
125 </FORM>
126 <!-- SiteSearch Google -->";
127 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
128
129 # No database access
130 if ( is_object( $wgMessageCache ) ) {
131 $wgMessageCache->disable();
132 }
133
134 if ( trim( $this->error ) == '' ) {
135 $this->error = $this->db->getProperty('mServer');
136 }
137
138 $text = str_replace( '$1', $this->error, $noconnect );
139 $text .= wfGetSiteNotice();
140
141 if($wgUseFileCache) {
142 if($wgTitle) {
143 $t =& $wgTitle;
144 } else {
145 if($title) {
146 $t = Title::newFromURL( $title );
147 } elseif (@/**/$_REQUEST['search']) {
148 $search = $_REQUEST['search'];
149 return $searchdisabled .
150 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
151 $wgInputEncoding ), $googlesearch );
152 } else {
153 $t = Title::newFromText( $mainpage );
154 }
155 }
156
157 $cache = new CacheManager( $t );
158 if( $cache->isFileCached() ) {
159 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
160 $cachederror . "</b></p>\n";
161
162 $tag = '<div id="article">';
163 $text = str_replace(
164 $tag,
165 $tag . $msg,
166 $cache->fetchPageText() );
167 }
168 }
169
170 return $text;
171 }
172 }
173
174 class DBQueryError extends DBError {
175 public $error, $errno, $sql, $fname;
176
177 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
178 $message = "A database error has occurred\n" .
179 "Query: $sql\n" .
180 "Function: $fname\n" .
181 "Error: $errno $error\n";
182
183 parent::__construct( $db, $message );
184 $this->error = $error;
185 $this->errno = $errno;
186 $this->sql = $sql;
187 $this->fname = $fname;
188 }
189
190 function getText() {
191 if ( $this->useMessageCache() ) {
192 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
193 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
194 } else {
195 return $this->getMessage();
196 }
197 }
198
199 function getSQL() {
200 global $wgShowSQLErrors;
201 if( !$wgShowSQLErrors ) {
202 return $this->msg( 'sqlhidden', 'SQL hidden' );
203 } else {
204 return $this->sql;
205 }
206 }
207
208 function getPageTitle() {
209 return $this->msg( 'databaseerror', 'Database error' );
210 }
211
212 function getHTML() {
213 if ( $this->useMessageCache() ) {
214 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
215 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
216 } else {
217 return nl2br( htmlspecialchars( $this->getMessage() ) );
218 }
219 }
220 }
221
222 class DBUnexpectedError extends DBError {}
223
224 /******************************************************************************/
225
226 /**
227 * Database abstraction object
228 * @package MediaWiki
229 */
230 class Database {
231
232 #------------------------------------------------------------------------------
233 # Variables
234 #------------------------------------------------------------------------------
235
236 protected $mLastQuery = '';
237
238 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
239 protected $mOut, $mOpened = false;
240
241 protected $mFailFunction;
242 protected $mTablePrefix;
243 protected $mFlags;
244 protected $mTrxLevel = 0;
245 protected $mErrorCount = 0;
246 protected $mLBInfo = array();
247
248 #------------------------------------------------------------------------------
249 # Accessors
250 #------------------------------------------------------------------------------
251 # These optionally set a variable and return the previous state
252
253 /**
254 * Fail function, takes a Database as a parameter
255 * Set to false for default, 1 for ignore errors
256 */
257 function failFunction( $function = NULL ) {
258 return wfSetVar( $this->mFailFunction, $function );
259 }
260
261 /**
262 * Output page, used for reporting errors
263 * FALSE means discard output
264 */
265 function setOutputPage( $out ) {
266 $this->mOut = $out;
267 }
268
269 /**
270 * Boolean, controls output of large amounts of debug information
271 */
272 function debug( $debug = NULL ) {
273 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
274 }
275
276 /**
277 * Turns buffering of SQL result sets on (true) or off (false).
278 * Default is "on" and it should not be changed without good reasons.
279 */
280 function bufferResults( $buffer = NULL ) {
281 if ( is_null( $buffer ) ) {
282 return !(bool)( $this->mFlags & DBO_NOBUFFER );
283 } else {
284 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
285 }
286 }
287
288 /**
289 * Turns on (false) or off (true) the automatic generation and sending
290 * of a "we're sorry, but there has been a database error" page on
291 * database errors. Default is on (false). When turned off, the
292 * code should use wfLastErrno() and wfLastError() to handle the
293 * situation as appropriate.
294 */
295 function ignoreErrors( $ignoreErrors = NULL ) {
296 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
297 }
298
299 /**
300 * The current depth of nested transactions
301 * @param $level Integer: , default NULL.
302 */
303 function trxLevel( $level = NULL ) {
304 return wfSetVar( $this->mTrxLevel, $level );
305 }
306
307 /**
308 * Number of errors logged, only useful when errors are ignored
309 */
310 function errorCount( $count = NULL ) {
311 return wfSetVar( $this->mErrorCount, $count );
312 }
313
314 /**
315 * Properties passed down from the server info array of the load balancer
316 */
317 function getLBInfo( $name = NULL ) {
318 if ( is_null( $name ) ) {
319 return $this->mLBInfo;
320 } else {
321 if ( array_key_exists( $name, $this->mLBInfo ) ) {
322 return $this->mLBInfo[$name];
323 } else {
324 return NULL;
325 }
326 }
327 }
328
329 function setLBInfo( $name, $value = NULL ) {
330 if ( is_null( $value ) ) {
331 $this->mLBInfo = $name;
332 } else {
333 $this->mLBInfo[$name] = $value;
334 }
335 }
336
337 /**#@+
338 * Get function
339 */
340 function lastQuery() { return $this->mLastQuery; }
341 function isOpen() { return $this->mOpened; }
342 /**#@-*/
343
344 function setFlag( $flag ) {
345 $this->mFlags |= $flag;
346 }
347
348 function clearFlag( $flag ) {
349 $this->mFlags &= ~$flag;
350 }
351
352 function getFlag( $flag ) {
353 return !!($this->mFlags & $flag);
354 }
355
356 /**
357 * General read-only accessor
358 */
359 function getProperty( $name ) {
360 return $this->$name;
361 }
362
363 #------------------------------------------------------------------------------
364 # Other functions
365 #------------------------------------------------------------------------------
366
367 /**@{{
368 * @param string $server database server host
369 * @param string $user database user name
370 * @param string $password database user password
371 * @param string $dbname database name
372 */
373
374 /**
375 * @param failFunction
376 * @param $flags
377 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
378 */
379 function __construct( $server = false, $user = false, $password = false, $dbName = false,
380 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
381
382 global $wgOut, $wgDBprefix, $wgCommandLineMode;
383 # Can't get a reference if it hasn't been set yet
384 if ( !isset( $wgOut ) ) {
385 $wgOut = NULL;
386 }
387 $this->mOut =& $wgOut;
388
389 $this->mFailFunction = $failFunction;
390 $this->mFlags = $flags;
391
392 if ( $this->mFlags & DBO_DEFAULT ) {
393 if ( $wgCommandLineMode ) {
394 $this->mFlags &= ~DBO_TRX;
395 } else {
396 $this->mFlags |= DBO_TRX;
397 }
398 }
399
400 /*
401 // Faster read-only access
402 if ( wfReadOnly() ) {
403 $this->mFlags |= DBO_PERSISTENT;
404 $this->mFlags &= ~DBO_TRX;
405 }*/
406
407 /** Get the default table prefix*/
408 if ( $tablePrefix == 'get from global' ) {
409 $this->mTablePrefix = $wgDBprefix;
410 } else {
411 $this->mTablePrefix = $tablePrefix;
412 }
413
414 if ( $server ) {
415 $this->open( $server, $user, $password, $dbName );
416 }
417 }
418
419 /**
420 * @static
421 * @param failFunction
422 * @param $flags
423 */
424 static function newFromParams( $server, $user, $password, $dbName,
425 $failFunction = false, $flags = 0 )
426 {
427 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
428 }
429
430 /**
431 * Usually aborts on failure
432 * If the failFunction is set to a non-zero integer, returns success
433 */
434 function open( $server, $user, $password, $dbName ) {
435 global $wguname;
436
437 # Test for missing mysql.so
438 # First try to load it
439 if (!@extension_loaded('mysql')) {
440 @dl('mysql.so');
441 }
442
443 # Fail now
444 # Otherwise we get a suppressed fatal error, which is very hard to track down
445 if ( !function_exists( 'mysql_connect' ) ) {
446 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
447 }
448
449 $this->close();
450 $this->mServer = $server;
451 $this->mUser = $user;
452 $this->mPassword = $password;
453 $this->mDBname = $dbName;
454
455 $success = false;
456
457 if ( $this->mFlags & DBO_PERSISTENT ) {
458 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
459 } else {
460 # Create a new connection...
461 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
462 }
463
464 if ( $dbName != '' ) {
465 if ( $this->mConn !== false ) {
466 $success = @/**/mysql_select_db( $dbName, $this->mConn );
467 if ( !$success ) {
468 $error = "Error selecting database $dbName on server {$this->mServer} " .
469 "from client host {$wguname['nodename']}\n";
470 wfDebug( $error );
471 }
472 } else {
473 wfDebug( "DB connection error\n" );
474 wfDebug( "Server: $server, User: $user, Password: " .
475 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
476 $success = false;
477 }
478 } else {
479 # Delay USE query
480 $success = (bool)$this->mConn;
481 }
482
483 if ( !$success ) {
484 $this->reportConnectionError();
485 }
486
487 global $wgDBmysql5;
488 if( $wgDBmysql5 ) {
489 // Tell the server we're communicating with it in UTF-8.
490 // This may engage various charset conversions.
491 $this->query( 'SET NAMES utf8' );
492 }
493
494 $this->mOpened = $success;
495 return $success;
496 }
497 /**@}}*/
498
499 /**
500 * Closes a database connection.
501 * if it is open : commits any open transactions
502 *
503 * @return bool operation success. true if already closed.
504 */
505 function close()
506 {
507 $this->mOpened = false;
508 if ( $this->mConn ) {
509 if ( $this->trxLevel() ) {
510 $this->immediateCommit();
511 }
512 return mysql_close( $this->mConn );
513 } else {
514 return true;
515 }
516 }
517
518 /**
519 * @param string $error fallback error message, used if none is given by MySQL
520 */
521 function reportConnectionError( $error = 'Unknown error' ) {
522 $myError = $this->lastError();
523 if ( $myError ) {
524 $error = $myError;
525 }
526
527 if ( $this->mFailFunction ) {
528 # Legacy error handling method
529 if ( !is_int( $this->mFailFunction ) ) {
530 $ff = $this->mFailFunction;
531 $ff( $this, $error );
532 }
533 } else {
534 # New method
535 wfLogDBError( "Connection error: $error\n" );
536 throw new DBConnectionError( $this, $error );
537 }
538 }
539
540 /**
541 * Usually aborts on failure
542 * If errors are explicitly ignored, returns success
543 */
544 function query( $sql, $fname = '', $tempIgnore = false ) {
545 global $wgProfiling;
546
547 if ( $wgProfiling ) {
548 # generalizeSQL will probably cut down the query to reasonable
549 # logging size most of the time. The substr is really just a sanity check.
550
551 # Who's been wasting my precious column space? -- TS
552 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
553
554 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
555 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
556 $totalProf = 'Database::query';
557 } else {
558 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
559 $totalProf = 'Database::query-master';
560 }
561 wfProfileIn( $totalProf );
562 wfProfileIn( $queryProf );
563 }
564
565 $this->mLastQuery = $sql;
566
567 # Add a comment for easy SHOW PROCESSLIST interpretation
568 if ( $fname ) {
569 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
570 } else {
571 $commentedSql = $sql;
572 }
573
574 # If DBO_TRX is set, start a transaction
575 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
576 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
577 ) {
578 $this->begin();
579 }
580
581 if ( $this->debug() ) {
582 $sqlx = substr( $commentedSql, 0, 500 );
583 $sqlx = strtr( $sqlx, "\t\n", ' ' );
584 wfDebug( "SQL: $sqlx\n" );
585 }
586
587 # Do the query and handle errors
588 $ret = $this->doQuery( $commentedSql );
589
590 # Try reconnecting if the connection was lost
591 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
592 # Transaction is gone, like it or not
593 $this->mTrxLevel = 0;
594 wfDebug( "Connection lost, reconnecting...\n" );
595 if ( $this->ping() ) {
596 wfDebug( "Reconnected\n" );
597 $ret = $this->doQuery( $commentedSql );
598 } else {
599 wfDebug( "Failed\n" );
600 }
601 }
602
603 if ( false === $ret ) {
604 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
605 }
606
607 if ( $wgProfiling ) {
608 wfProfileOut( $queryProf );
609 wfProfileOut( $totalProf );
610 }
611 return $ret;
612 }
613
614 /**
615 * The DBMS-dependent part of query()
616 * @param string $sql SQL query.
617 */
618 function doQuery( $sql ) {
619 if( $this->bufferResults() ) {
620 $ret = mysql_query( $sql, $this->mConn );
621 } else {
622 $ret = mysql_unbuffered_query( $sql, $this->mConn );
623 }
624 return $ret;
625 }
626
627 /**
628 * @param $error
629 * @param $errno
630 * @param $sql
631 * @param string $fname
632 * @param bool $tempIgnore
633 */
634 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
635 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
636 # Ignore errors during error handling to avoid infinite recursion
637 $ignore = $this->ignoreErrors( true );
638 ++$this->mErrorCount;
639
640 if( $ignore || $tempIgnore ) {
641 wfDebug("SQL ERROR (ignored): $error\n");
642 $this->ignoreErrors( $ignore );
643 } else {
644 $sql1line = str_replace( "\n", "\\n", $sql );
645 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
646 wfDebug("SQL ERROR: " . $error . "\n");
647 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
648 }
649 }
650
651
652 /**
653 * Intended to be compatible with the PEAR::DB wrapper functions.
654 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
655 *
656 * ? = scalar value, quoted as necessary
657 * ! = raw SQL bit (a function for instance)
658 * & = filename; reads the file and inserts as a blob
659 * (we don't use this though...)
660 */
661 function prepare( $sql, $func = 'Database::prepare' ) {
662 /* MySQL doesn't support prepared statements (yet), so just
663 pack up the query for reference. We'll manually replace
664 the bits later. */
665 return array( 'query' => $sql, 'func' => $func );
666 }
667
668 function freePrepared( $prepared ) {
669 /* No-op for MySQL */
670 }
671
672 /**
673 * Execute a prepared query with the various arguments
674 * @param string $prepared the prepared sql
675 * @param mixed $args Either an array here, or put scalars as varargs
676 */
677 function execute( $prepared, $args = null ) {
678 if( !is_array( $args ) ) {
679 # Pull the var args
680 $args = func_get_args();
681 array_shift( $args );
682 }
683 $sql = $this->fillPrepared( $prepared['query'], $args );
684 return $this->query( $sql, $prepared['func'] );
685 }
686
687 /**
688 * Prepare & execute an SQL statement, quoting and inserting arguments
689 * in the appropriate places.
690 * @param string $query
691 * @param string $args ...
692 */
693 function safeQuery( $query, $args = null ) {
694 $prepared = $this->prepare( $query, 'Database::safeQuery' );
695 if( !is_array( $args ) ) {
696 # Pull the var args
697 $args = func_get_args();
698 array_shift( $args );
699 }
700 $retval = $this->execute( $prepared, $args );
701 $this->freePrepared( $prepared );
702 return $retval;
703 }
704
705 /**
706 * For faking prepared SQL statements on DBs that don't support
707 * it directly.
708 * @param string $preparedSql - a 'preparable' SQL statement
709 * @param array $args - array of arguments to fill it with
710 * @return string executable SQL
711 */
712 function fillPrepared( $preparedQuery, $args ) {
713 reset( $args );
714 $this->preparedArgs =& $args;
715 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
716 array( &$this, 'fillPreparedArg' ), $preparedQuery );
717 }
718
719 /**
720 * preg_callback func for fillPrepared()
721 * The arguments should be in $this->preparedArgs and must not be touched
722 * while we're doing this.
723 *
724 * @param array $matches
725 * @return string
726 * @private
727 */
728 function fillPreparedArg( $matches ) {
729 switch( $matches[1] ) {
730 case '\\?': return '?';
731 case '\\!': return '!';
732 case '\\&': return '&';
733 }
734 list( $n, $arg ) = each( $this->preparedArgs );
735 switch( $matches[1] ) {
736 case '?': return $this->addQuotes( $arg );
737 case '!': return $arg;
738 case '&':
739 # return $this->addQuotes( file_get_contents( $arg ) );
740 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
741 default:
742 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
743 }
744 }
745
746 /**#@+
747 * @param mixed $res A SQL result
748 */
749 /**
750 * Free a result object
751 */
752 function freeResult( $res ) {
753 if ( !@/**/mysql_free_result( $res ) ) {
754 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
755 }
756 }
757
758 /**
759 * Fetch the next row from the given result object, in object form
760 */
761 function fetchObject( $res ) {
762 @/**/$row = mysql_fetch_object( $res );
763 if( mysql_errno() ) {
764 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
765 }
766 return $row;
767 }
768
769 /**
770 * Fetch the next row from the given result object
771 * Returns an array
772 */
773 function fetchRow( $res ) {
774 @/**/$row = mysql_fetch_array( $res );
775 if (mysql_errno() ) {
776 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
777 }
778 return $row;
779 }
780
781 /**
782 * Get the number of rows in a result object
783 */
784 function numRows( $res ) {
785 @/**/$n = mysql_num_rows( $res );
786 if( mysql_errno() ) {
787 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
788 }
789 return $n;
790 }
791
792 /**
793 * Get the number of fields in a result object
794 * See documentation for mysql_num_fields()
795 */
796 function numFields( $res ) { return mysql_num_fields( $res ); }
797
798 /**
799 * Get a field name in a result object
800 * See documentation for mysql_field_name():
801 * http://www.php.net/mysql_field_name
802 */
803 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
804
805 /**
806 * Get the inserted value of an auto-increment row
807 *
808 * The value inserted should be fetched from nextSequenceValue()
809 *
810 * Example:
811 * $id = $dbw->nextSequenceValue('page_page_id_seq');
812 * $dbw->insert('page',array('page_id' => $id));
813 * $id = $dbw->insertId();
814 */
815 function insertId() { return mysql_insert_id( $this->mConn ); }
816
817 /**
818 * Change the position of the cursor in a result object
819 * See mysql_data_seek()
820 */
821 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
822
823 /**
824 * Get the last error number
825 * See mysql_errno()
826 */
827 function lastErrno() {
828 if ( $this->mConn ) {
829 return mysql_errno( $this->mConn );
830 } else {
831 return mysql_errno();
832 }
833 }
834
835 /**
836 * Get a description of the last error
837 * See mysql_error() for more details
838 */
839 function lastError() {
840 if ( $this->mConn ) {
841 # Even if it's non-zero, it can still be invalid
842 wfSuppressWarnings();
843 $error = mysql_error( $this->mConn );
844 if ( !$error ) {
845 $error = mysql_error();
846 }
847 wfRestoreWarnings();
848 } else {
849 $error = mysql_error();
850 }
851 if( $error ) {
852 $error .= ' (' . $this->mServer . ')';
853 }
854 return $error;
855 }
856 /**
857 * Get the number of rows affected by the last write query
858 * See mysql_affected_rows() for more details
859 */
860 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
861 /**#@-*/ // end of template : @param $result
862
863 /**
864 * Simple UPDATE wrapper
865 * Usually aborts on failure
866 * If errors are explicitly ignored, returns success
867 *
868 * This function exists for historical reasons, Database::update() has a more standard
869 * calling convention and feature set
870 */
871 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
872 {
873 $table = $this->tableName( $table );
874 $sql = "UPDATE $table SET $var = '" .
875 $this->strencode( $value ) . "' WHERE ($cond)";
876 return (bool)$this->query( $sql, $fname );
877 }
878
879 /**
880 * Simple SELECT wrapper, returns a single field, input must be encoded
881 * Usually aborts on failure
882 * If errors are explicitly ignored, returns FALSE on failure
883 */
884 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
885 if ( !is_array( $options ) ) {
886 $options = array( $options );
887 }
888 $options['LIMIT'] = 1;
889
890 $res = $this->select( $table, $var, $cond, $fname, $options );
891 if ( $res === false || !$this->numRows( $res ) ) {
892 return false;
893 }
894 $row = $this->fetchRow( $res );
895 if ( $row !== false ) {
896 $this->freeResult( $res );
897 return $row[0];
898 } else {
899 return false;
900 }
901 }
902
903 /**
904 * Returns an optional USE INDEX clause to go after the table, and a
905 * string to go at the end of the query
906 *
907 * @private
908 *
909 * @param array $options an associative array of options to be turned into
910 * an SQL query, valid keys are listed in the function.
911 * @return array
912 */
913 function makeSelectOptions( $options ) {
914 $tailOpts = '';
915 $startOpts = '';
916
917 $noKeyOptions = array();
918 foreach ( $options as $key => $option ) {
919 if ( is_numeric( $key ) ) {
920 $noKeyOptions[$option] = true;
921 }
922 }
923
924 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
925 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
926
927 if (isset($options['LIMIT'])) {
928 $tailOpts .= $this->limitResult('', $options['LIMIT'],
929 isset($options['OFFSET']) ? $options['OFFSET'] : false);
930 }
931
932 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
933 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
934 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
935
936 # Various MySQL extensions
937 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
938 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
939 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
940 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
941 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
942 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
943 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
944
945 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
946 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
947 } else {
948 $useIndex = '';
949 }
950
951 return array( $startOpts, $useIndex, $tailOpts );
952 }
953
954 /**
955 * SELECT wrapper
956 */
957 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
958 {
959 if( is_array( $vars ) ) {
960 $vars = implode( ',', $vars );
961 }
962 if( !is_array( $options ) ) {
963 $options = array( $options );
964 }
965 if( is_array( $table ) ) {
966 if ( @is_array( $options['USE INDEX'] ) )
967 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
968 else
969 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
970 } elseif ($table!='') {
971 $from = ' FROM ' . $this->tableName( $table );
972 } else {
973 $from = '';
974 }
975
976 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
977
978 if( !empty( $conds ) ) {
979 if ( is_array( $conds ) ) {
980 $conds = $this->makeList( $conds, LIST_AND );
981 }
982 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
983 } else {
984 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
985 }
986
987 return $this->query( $sql, $fname );
988 }
989
990 /**
991 * Single row SELECT wrapper
992 * Aborts or returns FALSE on error
993 *
994 * $vars: the selected variables
995 * $conds: a condition map, terms are ANDed together.
996 * Items with numeric keys are taken to be literal conditions
997 * Takes an array of selected variables, and a condition map, which is ANDed
998 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
999 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1000 * $obj- >page_id is the ID of the Astronomy article
1001 *
1002 * @todo migrate documentation to phpdocumentor format
1003 */
1004 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1005 $options['LIMIT'] = 1;
1006 $res = $this->select( $table, $vars, $conds, $fname, $options );
1007 if ( $res === false )
1008 return false;
1009 if ( !$this->numRows($res) ) {
1010 $this->freeResult($res);
1011 return false;
1012 }
1013 $obj = $this->fetchObject( $res );
1014 $this->freeResult( $res );
1015 return $obj;
1016
1017 }
1018
1019 /**
1020 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1021 * It's only slightly flawed. Don't use for anything important.
1022 *
1023 * @param string $sql A SQL Query
1024 * @static
1025 */
1026 static function generalizeSQL( $sql ) {
1027 # This does the same as the regexp below would do, but in such a way
1028 # as to avoid crashing php on some large strings.
1029 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1030
1031 $sql = str_replace ( "\\\\", '', $sql);
1032 $sql = str_replace ( "\\'", '', $sql);
1033 $sql = str_replace ( "\\\"", '', $sql);
1034 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1035 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1036
1037 # All newlines, tabs, etc replaced by single space
1038 $sql = preg_replace ( "/\s+/", ' ', $sql);
1039
1040 # All numbers => N
1041 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1042
1043 return $sql;
1044 }
1045
1046 /**
1047 * Determines whether a field exists in a table
1048 * Usually aborts on failure
1049 * If errors are explicitly ignored, returns NULL on failure
1050 */
1051 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1052 $table = $this->tableName( $table );
1053 $res = $this->query( 'DESCRIBE '.$table, $fname );
1054 if ( !$res ) {
1055 return NULL;
1056 }
1057
1058 $found = false;
1059
1060 while ( $row = $this->fetchObject( $res ) ) {
1061 if ( $row->Field == $field ) {
1062 $found = true;
1063 break;
1064 }
1065 }
1066 return $found;
1067 }
1068
1069 /**
1070 * Determines whether an index exists
1071 * Usually aborts on failure
1072 * If errors are explicitly ignored, returns NULL on failure
1073 */
1074 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1075 $info = $this->indexInfo( $table, $index, $fname );
1076 if ( is_null( $info ) ) {
1077 return NULL;
1078 } else {
1079 return $info !== false;
1080 }
1081 }
1082
1083
1084 /**
1085 * Get information about an index into an object
1086 * Returns false if the index does not exist
1087 */
1088 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1089 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1090 # SHOW INDEX should work for 3.x and up:
1091 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1092 $table = $this->tableName( $table );
1093 $sql = 'SHOW INDEX FROM '.$table;
1094 $res = $this->query( $sql, $fname );
1095 if ( !$res ) {
1096 return NULL;
1097 }
1098
1099 while ( $row = $this->fetchObject( $res ) ) {
1100 if ( $row->Key_name == $index ) {
1101 return $row;
1102 }
1103 }
1104 return false;
1105 }
1106
1107 /**
1108 * Query whether a given table exists
1109 */
1110 function tableExists( $table ) {
1111 $table = $this->tableName( $table );
1112 $old = $this->ignoreErrors( true );
1113 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1114 $this->ignoreErrors( $old );
1115 if( $res ) {
1116 $this->freeResult( $res );
1117 return true;
1118 } else {
1119 return false;
1120 }
1121 }
1122
1123 /**
1124 * mysql_fetch_field() wrapper
1125 * Returns false if the field doesn't exist
1126 *
1127 * @param $table
1128 * @param $field
1129 */
1130 function fieldInfo( $table, $field ) {
1131 $table = $this->tableName( $table );
1132 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1133 $n = mysql_num_fields( $res );
1134 for( $i = 0; $i < $n; $i++ ) {
1135 $meta = mysql_fetch_field( $res, $i );
1136 if( $field == $meta->name ) {
1137 return $meta;
1138 }
1139 }
1140 return false;
1141 }
1142
1143 /**
1144 * mysql_field_type() wrapper
1145 */
1146 function fieldType( $res, $index ) {
1147 return mysql_field_type( $res, $index );
1148 }
1149
1150 /**
1151 * Determines if a given index is unique
1152 */
1153 function indexUnique( $table, $index ) {
1154 $indexInfo = $this->indexInfo( $table, $index );
1155 if ( !$indexInfo ) {
1156 return NULL;
1157 }
1158 return !$indexInfo->Non_unique;
1159 }
1160
1161 /**
1162 * INSERT wrapper, inserts an array into a table
1163 *
1164 * $a may be a single associative array, or an array of these with numeric keys, for
1165 * multi-row insert.
1166 *
1167 * Usually aborts on failure
1168 * If errors are explicitly ignored, returns success
1169 */
1170 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1171 # No rows to insert, easy just return now
1172 if ( !count( $a ) ) {
1173 return true;
1174 }
1175
1176 $table = $this->tableName( $table );
1177 if ( !is_array( $options ) ) {
1178 $options = array( $options );
1179 }
1180 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1181 $multi = true;
1182 $keys = array_keys( $a[0] );
1183 } else {
1184 $multi = false;
1185 $keys = array_keys( $a );
1186 }
1187
1188 $sql = 'INSERT ' . implode( ' ', $options ) .
1189 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1190
1191 if ( $multi ) {
1192 $first = true;
1193 foreach ( $a as $row ) {
1194 if ( $first ) {
1195 $first = false;
1196 } else {
1197 $sql .= ',';
1198 }
1199 $sql .= '(' . $this->makeList( $row ) . ')';
1200 }
1201 } else {
1202 $sql .= '(' . $this->makeList( $a ) . ')';
1203 }
1204 return (bool)$this->query( $sql, $fname );
1205 }
1206
1207 /**
1208 * Make UPDATE options for the Database::update function
1209 *
1210 * @private
1211 * @param array $options The options passed to Database::update
1212 * @return string
1213 */
1214 function makeUpdateOptions( $options ) {
1215 if( !is_array( $options ) ) {
1216 $options = array( $options );
1217 }
1218 $opts = array();
1219 if ( in_array( 'LOW_PRIORITY', $options ) )
1220 $opts[] = $this->lowPriorityOption();
1221 if ( in_array( 'IGNORE', $options ) )
1222 $opts[] = 'IGNORE';
1223 return implode(' ', $opts);
1224 }
1225
1226 /**
1227 * UPDATE wrapper, takes a condition array and a SET array
1228 *
1229 * @param string $table The table to UPDATE
1230 * @param array $values An array of values to SET
1231 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1232 * @param string $fname The Class::Function calling this function
1233 * (for the log)
1234 * @param array $options An array of UPDATE options, can be one or
1235 * more of IGNORE, LOW_PRIORITY
1236 */
1237 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1238 $table = $this->tableName( $table );
1239 $opts = $this->makeUpdateOptions( $options );
1240 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1241 if ( $conds != '*' ) {
1242 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1243 }
1244 $this->query( $sql, $fname );
1245 }
1246
1247 /**
1248 * Makes a wfStrencoded list from an array
1249 * $mode:
1250 * LIST_COMMA - comma separated, no field names
1251 * LIST_AND - ANDed WHERE clause (without the WHERE)
1252 * LIST_OR - ORed WHERE clause (without the WHERE)
1253 * LIST_SET - comma separated with field names, like a SET clause
1254 * LIST_NAMES - comma separated field names
1255 */
1256 function makeList( $a, $mode = LIST_COMMA ) {
1257 if ( !is_array( $a ) ) {
1258 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1259 }
1260
1261 $first = true;
1262 $list = '';
1263 foreach ( $a as $field => $value ) {
1264 if ( !$first ) {
1265 if ( $mode == LIST_AND ) {
1266 $list .= ' AND ';
1267 } elseif($mode == LIST_OR) {
1268 $list .= ' OR ';
1269 } else {
1270 $list .= ',';
1271 }
1272 } else {
1273 $first = false;
1274 }
1275 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1276 $list .= "($value)";
1277 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1278 $list .= $field." IN (".$this->makeList($value).") ";
1279 } else {
1280 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1281 $list .= "$field = ";
1282 }
1283 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1284 }
1285 }
1286 return $list;
1287 }
1288
1289 /**
1290 * Change the current database
1291 */
1292 function selectDB( $db ) {
1293 $this->mDBname = $db;
1294 return mysql_select_db( $db, $this->mConn );
1295 }
1296
1297 /**
1298 * Format a table name ready for use in constructing an SQL query
1299 *
1300 * This does two important things: it quotes table names which as necessary,
1301 * and it adds a table prefix if there is one.
1302 *
1303 * All functions of this object which require a table name call this function
1304 * themselves. Pass the canonical name to such functions. This is only needed
1305 * when calling query() directly.
1306 *
1307 * @param string $name database table name
1308 */
1309 function tableName( $name ) {
1310 global $wgSharedDB;
1311 # Skip quoted literals
1312 if ( $name{0} != '`' ) {
1313 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1314 $name = "{$this->mTablePrefix}$name";
1315 }
1316 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1317 $name = "`$wgSharedDB`.`$name`";
1318 } else {
1319 # Standard quoting
1320 $name = "`$name`";
1321 }
1322 }
1323 return $name;
1324 }
1325
1326 /**
1327 * Fetch a number of table names into an array
1328 * This is handy when you need to construct SQL for joins
1329 *
1330 * Example:
1331 * extract($dbr->tableNames('user','watchlist'));
1332 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1333 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1334 */
1335 function tableNames() {
1336 $inArray = func_get_args();
1337 $retVal = array();
1338 foreach ( $inArray as $name ) {
1339 $retVal[$name] = $this->tableName( $name );
1340 }
1341 return $retVal;
1342 }
1343
1344 /**
1345 * @private
1346 */
1347 function tableNamesWithUseIndex( $tables, $use_index ) {
1348 $ret = array();
1349
1350 foreach ( $tables as $table )
1351 if ( @$use_index[$table] !== null )
1352 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1353 else
1354 $ret[] = $this->tableName( $table );
1355
1356 return implode( ',', $ret );
1357 }
1358
1359 /**
1360 * Wrapper for addslashes()
1361 * @param string $s String to be slashed.
1362 * @return string slashed string.
1363 */
1364 function strencode( $s ) {
1365 return mysql_real_escape_string( $s, $this->mConn );
1366 }
1367
1368 /**
1369 * If it's a string, adds quotes and backslashes
1370 * Otherwise returns as-is
1371 */
1372 function addQuotes( $s ) {
1373 if ( is_null( $s ) ) {
1374 return 'NULL';
1375 } else {
1376 # This will also quote numeric values. This should be harmless,
1377 # and protects against weird problems that occur when they really
1378 # _are_ strings such as article titles and string->number->string
1379 # conversion is not 1:1.
1380 return "'" . $this->strencode( $s ) . "'";
1381 }
1382 }
1383
1384 /**
1385 * Escape string for safe LIKE usage
1386 */
1387 function escapeLike( $s ) {
1388 $s=$this->strencode( $s );
1389 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1390 return $s;
1391 }
1392
1393 /**
1394 * Returns an appropriately quoted sequence value for inserting a new row.
1395 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1396 * subclass will return an integer, and save the value for insertId()
1397 */
1398 function nextSequenceValue( $seqName ) {
1399 return NULL;
1400 }
1401
1402 /**
1403 * USE INDEX clause
1404 * PostgreSQL doesn't have them and returns ""
1405 */
1406 function useIndexClause( $index ) {
1407 return "FORCE INDEX ($index)";
1408 }
1409
1410 /**
1411 * REPLACE query wrapper
1412 * PostgreSQL simulates this with a DELETE followed by INSERT
1413 * $row is the row to insert, an associative array
1414 * $uniqueIndexes is an array of indexes. Each element may be either a
1415 * field name or an array of field names
1416 *
1417 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1418 * However if you do this, you run the risk of encountering errors which wouldn't have
1419 * occurred in MySQL
1420 *
1421 * @todo migrate comment to phodocumentor format
1422 */
1423 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1424 $table = $this->tableName( $table );
1425
1426 # Single row case
1427 if ( !is_array( reset( $rows ) ) ) {
1428 $rows = array( $rows );
1429 }
1430
1431 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1432 $first = true;
1433 foreach ( $rows as $row ) {
1434 if ( $first ) {
1435 $first = false;
1436 } else {
1437 $sql .= ',';
1438 }
1439 $sql .= '(' . $this->makeList( $row ) . ')';
1440 }
1441 return $this->query( $sql, $fname );
1442 }
1443
1444 /**
1445 * DELETE where the condition is a join
1446 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1447 *
1448 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1449 * join condition matches, set $conds='*'
1450 *
1451 * DO NOT put the join condition in $conds
1452 *
1453 * @param string $delTable The table to delete from.
1454 * @param string $joinTable The other table.
1455 * @param string $delVar The variable to join on, in the first table.
1456 * @param string $joinVar The variable to join on, in the second table.
1457 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1458 */
1459 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1460 if ( !$conds ) {
1461 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1462 }
1463
1464 $delTable = $this->tableName( $delTable );
1465 $joinTable = $this->tableName( $joinTable );
1466 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1467 if ( $conds != '*' ) {
1468 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1469 }
1470
1471 return $this->query( $sql, $fname );
1472 }
1473
1474 /**
1475 * Returns the size of a text field, or -1 for "unlimited"
1476 */
1477 function textFieldSize( $table, $field ) {
1478 $table = $this->tableName( $table );
1479 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1480 $res = $this->query( $sql, 'Database::textFieldSize' );
1481 $row = $this->fetchObject( $res );
1482 $this->freeResult( $res );
1483
1484 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1485 $size = $m[1];
1486 } else {
1487 $size = -1;
1488 }
1489 return $size;
1490 }
1491
1492 /**
1493 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1494 */
1495 function lowPriorityOption() {
1496 return 'LOW_PRIORITY';
1497 }
1498
1499 /**
1500 * DELETE query wrapper
1501 *
1502 * Use $conds == "*" to delete all rows
1503 */
1504 function delete( $table, $conds, $fname = 'Database::delete' ) {
1505 if ( !$conds ) {
1506 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1507 }
1508 $table = $this->tableName( $table );
1509 $sql = "DELETE FROM $table";
1510 if ( $conds != '*' ) {
1511 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1512 }
1513 return $this->query( $sql, $fname );
1514 }
1515
1516 /**
1517 * INSERT SELECT wrapper
1518 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1519 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1520 * $conds may be "*" to copy the whole table
1521 * srcTable may be an array of tables.
1522 */
1523 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1524 $insertOptions = array(), $selectOptions = array() )
1525 {
1526 $destTable = $this->tableName( $destTable );
1527 if ( is_array( $insertOptions ) ) {
1528 $insertOptions = implode( ' ', $insertOptions );
1529 }
1530 if( !is_array( $selectOptions ) ) {
1531 $selectOptions = array( $selectOptions );
1532 }
1533 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1534 if( is_array( $srcTable ) ) {
1535 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1536 } else {
1537 $srcTable = $this->tableName( $srcTable );
1538 }
1539 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1540 " SELECT $startOpts " . implode( ',', $varMap ) .
1541 " FROM $srcTable $useIndex ";
1542 if ( $conds != '*' ) {
1543 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1544 }
1545 $sql .= " $tailOpts";
1546 return $this->query( $sql, $fname );
1547 }
1548
1549 /**
1550 * Construct a LIMIT query with optional offset
1551 * This is used for query pages
1552 * $sql string SQL query we will append the limit too
1553 * $limit integer the SQL limit
1554 * $offset integer the SQL offset (default false)
1555 */
1556 function limitResult($sql, $limit, $offset=false) {
1557 if( !is_numeric($limit) ) {
1558 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1559 }
1560 return " $sql LIMIT "
1561 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1562 . "{$limit} ";
1563 }
1564 function limitResultForUpdate($sql, $num) {
1565 return $this->limitResult($sql, $num, 0);
1566 }
1567
1568 /**
1569 * Returns an SQL expression for a simple conditional.
1570 * Uses IF on MySQL.
1571 *
1572 * @param string $cond SQL expression which will result in a boolean value
1573 * @param string $trueVal SQL expression to return if true
1574 * @param string $falseVal SQL expression to return if false
1575 * @return string SQL fragment
1576 */
1577 function conditional( $cond, $trueVal, $falseVal ) {
1578 return " IF($cond, $trueVal, $falseVal) ";
1579 }
1580
1581 /**
1582 * Determines if the last failure was due to a deadlock
1583 */
1584 function wasDeadlock() {
1585 return $this->lastErrno() == 1213;
1586 }
1587
1588 /**
1589 * Perform a deadlock-prone transaction.
1590 *
1591 * This function invokes a callback function to perform a set of write
1592 * queries. If a deadlock occurs during the processing, the transaction
1593 * will be rolled back and the callback function will be called again.
1594 *
1595 * Usage:
1596 * $dbw->deadlockLoop( callback, ... );
1597 *
1598 * Extra arguments are passed through to the specified callback function.
1599 *
1600 * Returns whatever the callback function returned on its successful,
1601 * iteration, or false on error, for example if the retry limit was
1602 * reached.
1603 */
1604 function deadlockLoop() {
1605 $myFname = 'Database::deadlockLoop';
1606
1607 $this->begin();
1608 $args = func_get_args();
1609 $function = array_shift( $args );
1610 $oldIgnore = $this->ignoreErrors( true );
1611 $tries = DEADLOCK_TRIES;
1612 if ( is_array( $function ) ) {
1613 $fname = $function[0];
1614 } else {
1615 $fname = $function;
1616 }
1617 do {
1618 $retVal = call_user_func_array( $function, $args );
1619 $error = $this->lastError();
1620 $errno = $this->lastErrno();
1621 $sql = $this->lastQuery();
1622
1623 if ( $errno ) {
1624 if ( $this->wasDeadlock() ) {
1625 # Retry
1626 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1627 } else {
1628 $this->reportQueryError( $error, $errno, $sql, $fname );
1629 }
1630 }
1631 } while( $this->wasDeadlock() && --$tries > 0 );
1632 $this->ignoreErrors( $oldIgnore );
1633 if ( $tries <= 0 ) {
1634 $this->query( 'ROLLBACK', $myFname );
1635 $this->reportQueryError( $error, $errno, $sql, $fname );
1636 return false;
1637 } else {
1638 $this->query( 'COMMIT', $myFname );
1639 return $retVal;
1640 }
1641 }
1642
1643 /**
1644 * Do a SELECT MASTER_POS_WAIT()
1645 *
1646 * @param string $file the binlog file
1647 * @param string $pos the binlog position
1648 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1649 */
1650 function masterPosWait( $file, $pos, $timeout ) {
1651 $fname = 'Database::masterPosWait';
1652 wfProfileIn( $fname );
1653
1654
1655 # Commit any open transactions
1656 $this->immediateCommit();
1657
1658 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1659 $encFile = $this->strencode( $file );
1660 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1661 $res = $this->doQuery( $sql );
1662 if ( $res && $row = $this->fetchRow( $res ) ) {
1663 $this->freeResult( $res );
1664 wfProfileOut( $fname );
1665 return $row[0];
1666 } else {
1667 wfProfileOut( $fname );
1668 return false;
1669 }
1670 }
1671
1672 /**
1673 * Get the position of the master from SHOW SLAVE STATUS
1674 */
1675 function getSlavePos() {
1676 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1677 $row = $this->fetchObject( $res );
1678 if ( $row ) {
1679 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1680 } else {
1681 return array( false, false );
1682 }
1683 }
1684
1685 /**
1686 * Get the position of the master from SHOW MASTER STATUS
1687 */
1688 function getMasterPos() {
1689 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1690 $row = $this->fetchObject( $res );
1691 if ( $row ) {
1692 return array( $row->File, $row->Position );
1693 } else {
1694 return array( false, false );
1695 }
1696 }
1697
1698 /**
1699 * Begin a transaction, committing any previously open transaction
1700 */
1701 function begin( $fname = 'Database::begin' ) {
1702 $this->query( 'BEGIN', $fname );
1703 $this->mTrxLevel = 1;
1704 }
1705
1706 /**
1707 * End a transaction
1708 */
1709 function commit( $fname = 'Database::commit' ) {
1710 $this->query( 'COMMIT', $fname );
1711 $this->mTrxLevel = 0;
1712 }
1713
1714 /**
1715 * Rollback a transaction
1716 */
1717 function rollback( $fname = 'Database::rollback' ) {
1718 $this->query( 'ROLLBACK', $fname );
1719 $this->mTrxLevel = 0;
1720 }
1721
1722 /**
1723 * Begin a transaction, committing any previously open transaction
1724 * @deprecated use begin()
1725 */
1726 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1727 $this->begin();
1728 }
1729
1730 /**
1731 * Commit transaction, if one is open
1732 * @deprecated use commit()
1733 */
1734 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1735 $this->commit();
1736 }
1737
1738 /**
1739 * Return MW-style timestamp used for MySQL schema
1740 */
1741 function timestamp( $ts=0 ) {
1742 return wfTimestamp(TS_MW,$ts);
1743 }
1744
1745 /**
1746 * Local database timestamp format or null
1747 */
1748 function timestampOrNull( $ts = null ) {
1749 if( is_null( $ts ) ) {
1750 return null;
1751 } else {
1752 return $this->timestamp( $ts );
1753 }
1754 }
1755
1756 /**
1757 * @todo document
1758 */
1759 function resultObject( $result ) {
1760 if( empty( $result ) ) {
1761 return NULL;
1762 } else {
1763 return new ResultWrapper( $this, $result );
1764 }
1765 }
1766
1767 /**
1768 * Return aggregated value alias
1769 */
1770 function aggregateValue ($valuedata,$valuename='value') {
1771 return $valuename;
1772 }
1773
1774 /**
1775 * @return string wikitext of a link to the server software's web site
1776 */
1777 function getSoftwareLink() {
1778 return "[http://www.mysql.com/ MySQL]";
1779 }
1780
1781 /**
1782 * @return string Version information from the database
1783 */
1784 function getServerVersion() {
1785 return mysql_get_server_info();
1786 }
1787
1788 /**
1789 * Ping the server and try to reconnect if it there is no connection
1790 */
1791 function ping() {
1792 if( function_exists( 'mysql_ping' ) ) {
1793 return mysql_ping( $this->mConn );
1794 } else {
1795 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1796 return true;
1797 }
1798 }
1799
1800 /**
1801 * Get slave lag.
1802 * At the moment, this will only work if the DB user has the PROCESS privilege
1803 */
1804 function getLag() {
1805 $res = $this->query( 'SHOW PROCESSLIST' );
1806 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1807 # dubious, but unfortunately there's no easy rigorous way
1808 $slaveThreads = 0;
1809 while ( $row = $this->fetchObject( $res ) ) {
1810 /* This should work for most situations - when default db
1811 * for thread is not specified, it had no events executed,
1812 * and therefore it doesn't know yet how lagged it is.
1813 *
1814 * Relay log I/O thread does not select databases.
1815 */
1816 if ( $row->User == 'system user' &&
1817 $row->State != 'Waiting for master to send event' &&
1818 $row->State != 'Connecting to master' &&
1819 $row->State != 'Queueing master event to the relay log' &&
1820 $row->State != 'Waiting for master update' &&
1821 $row->State != 'Requesting binlog dump'
1822 ) {
1823 # This is it, return the time (except -ve)
1824 if ( $row->Time > 0x7fffffff ) {
1825 return false;
1826 } else {
1827 return $row->Time;
1828 }
1829 }
1830 }
1831 return false;
1832 }
1833
1834 /**
1835 * Get status information from SHOW STATUS in an associative array
1836 */
1837 function getStatus($which="%") {
1838 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1839 $status = array();
1840 while ( $row = $this->fetchObject( $res ) ) {
1841 $status[$row->Variable_name] = $row->Value;
1842 }
1843 return $status;
1844 }
1845
1846 /**
1847 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1848 */
1849 function maxListLen() {
1850 return 0;
1851 }
1852
1853 function encodeBlob($b) {
1854 return $b;
1855 }
1856
1857 function decodeBlob($b) {
1858 return $b;
1859 }
1860
1861 /**
1862 * Read and execute SQL commands from a file.
1863 * Returns true on success, error string on failure
1864 */
1865 function sourceFile( $filename ) {
1866 $fp = fopen( $filename, 'r' );
1867 if ( false === $fp ) {
1868 return "Could not open \"{$fname}\".\n";
1869 }
1870
1871 $cmd = "";
1872 $done = false;
1873 $dollarquote = false;
1874
1875 while ( ! feof( $fp ) ) {
1876 $line = trim( fgets( $fp, 1024 ) );
1877 $sl = strlen( $line ) - 1;
1878
1879 if ( $sl < 0 ) { continue; }
1880 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1881
1882 ## Allow dollar quoting for function declarations
1883 if (substr($line,0,4) == '$mw$') {
1884 if ($dollarquote) {
1885 $dollarquote = false;
1886 $done = true;
1887 }
1888 else {
1889 $dollarquote = true;
1890 }
1891 }
1892 else if (!$dollarquote) {
1893 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
1894 $done = true;
1895 $line = substr( $line, 0, $sl );
1896 }
1897 }
1898
1899 if ( '' != $cmd ) { $cmd .= ' '; }
1900 $cmd .= "$line\n";
1901
1902 if ( $done ) {
1903 $cmd = str_replace(';;', ";", $cmd);
1904 $cmd = $this->replaceVars( $cmd );
1905 $res = $this->query( $cmd, 'dbsource', true );
1906
1907 if ( false === $res ) {
1908 $err = $this->lastError();
1909 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1910 }
1911
1912 $cmd = '';
1913 $done = false;
1914 }
1915 }
1916 fclose( $fp );
1917 return true;
1918 }
1919
1920 /**
1921 * Replace variables in sourced SQL
1922 */
1923 protected function replaceVars( $ins ) {
1924 $varnames = array(
1925 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1926 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1927 'wgDBadminuser', 'wgDBadminpassword',
1928 );
1929
1930 // Ordinary variables
1931 foreach ( $varnames as $var ) {
1932 if( isset( $GLOBALS[$var] ) ) {
1933 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1934 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1935 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1936 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1937 }
1938 }
1939
1940 // Table prefixes
1941 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1942 array( &$this, 'tableNameCallback' ), $ins );
1943 return $ins;
1944 }
1945
1946 /**
1947 * Table name callback
1948 * @private
1949 */
1950 protected function tableNameCallback( $matches ) {
1951 return $this->tableName( $matches[1] );
1952 }
1953
1954 }
1955
1956 /**
1957 * Database abstraction object for mySQL
1958 * Inherit all methods and properties of Database::Database()
1959 *
1960 * @package MediaWiki
1961 * @see Database
1962 */
1963 class DatabaseMysql extends Database {
1964 # Inherit all
1965 }
1966
1967
1968 /**
1969 * Result wrapper for grabbing data queried by someone else
1970 *
1971 * @package MediaWiki
1972 */
1973 class ResultWrapper {
1974 var $db, $result;
1975
1976 /**
1977 * @todo document
1978 */
1979 function ResultWrapper( &$database, $result ) {
1980 $this->db =& $database;
1981 $this->result =& $result;
1982 }
1983
1984 /**
1985 * @todo document
1986 */
1987 function numRows() {
1988 return $this->db->numRows( $this->result );
1989 }
1990
1991 /**
1992 * @todo document
1993 */
1994 function fetchObject() {
1995 return $this->db->fetchObject( $this->result );
1996 }
1997
1998 /**
1999 * @todo document
2000 */
2001 function fetchRow() {
2002 return $this->db->fetchRow( $this->result );
2003 }
2004
2005 /**
2006 * @todo document
2007 */
2008 function free() {
2009 $this->db->freeResult( $this->result );
2010 unset( $this->result );
2011 unset( $this->db );
2012 }
2013
2014 function seek( $row ) {
2015 $this->db->dataSeek( $this->result, $row );
2016 }
2017
2018 }
2019
2020 ?>