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