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