PHPDocumentor [http://en.wikipedia.org/wiki/PhpDocumentor] documentation tweaking...
[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 * Closes a database connection.
617 * if it is open : commits any open transactions
618 *
619 * @return bool operation success. true if already closed.
620 */
621 function close()
622 {
623 $this->mOpened = false;
624 if ( $this->mConn ) {
625 if ( $this->trxLevel() ) {
626 $this->immediateCommit();
627 }
628 return mysql_close( $this->mConn );
629 } else {
630 return true;
631 }
632 }
633
634 /**
635 * @param string $error fallback error message, used if none is given by MySQL
636 */
637 function reportConnectionError( $error = 'Unknown error' ) {
638 $myError = $this->lastError();
639 if ( $myError ) {
640 $error = $myError;
641 }
642
643 if ( $this->mFailFunction ) {
644 # Legacy error handling method
645 if ( !is_int( $this->mFailFunction ) ) {
646 $ff = $this->mFailFunction;
647 $ff( $this, $error );
648 }
649 } else {
650 # New method
651 wfLogDBError( "Connection error: $error\n" );
652 throw new DBConnectionError( $this, $error );
653 }
654 }
655
656 /**
657 * Usually aborts on failure
658 * If errors are explicitly ignored, returns success
659 */
660 function query( $sql, $fname = '', $tempIgnore = false ) {
661 global $wgProfiling;
662
663 if ( $wgProfiling ) {
664 # generalizeSQL will probably cut down the query to reasonable
665 # logging size most of the time. The substr is really just a sanity check.
666
667 # Who's been wasting my precious column space? -- TS
668 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
669
670 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
671 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
672 $totalProf = 'Database::query';
673 } else {
674 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
675 $totalProf = 'Database::query-master';
676 }
677 wfProfileIn( $totalProf );
678 wfProfileIn( $queryProf );
679 }
680
681 $this->mLastQuery = $sql;
682
683 # Add a comment for easy SHOW PROCESSLIST interpretation
684 if ( $fname ) {
685 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
686 } else {
687 $commentedSql = $sql;
688 }
689
690 # If DBO_TRX is set, start a transaction
691 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
692 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
693 ) {
694 $this->begin();
695 }
696
697 if ( $this->debug() ) {
698 $sqlx = substr( $commentedSql, 0, 500 );
699 $sqlx = strtr( $sqlx, "\t\n", ' ' );
700 wfDebug( "SQL: $sqlx\n" );
701 }
702
703 # Do the query and handle errors
704 $ret = $this->doQuery( $commentedSql );
705
706 # Try reconnecting if the connection was lost
707 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
708 # Transaction is gone, like it or not
709 $this->mTrxLevel = 0;
710 wfDebug( "Connection lost, reconnecting...\n" );
711 if ( $this->ping() ) {
712 wfDebug( "Reconnected\n" );
713 $sqlx = substr( $commentedSql, 0, 500 );
714 $sqlx = strtr( $sqlx, "\t\n", ' ' );
715 global $wgRequestTime;
716 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
717 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
718 $ret = $this->doQuery( $commentedSql );
719 } else {
720 wfDebug( "Failed\n" );
721 }
722 }
723
724 if ( false === $ret ) {
725 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
726 }
727
728 if ( $wgProfiling ) {
729 wfProfileOut( $queryProf );
730 wfProfileOut( $totalProf );
731 }
732 return $ret;
733 }
734
735 /**
736 * The DBMS-dependent part of query()
737 * @param string $sql SQL query.
738 */
739 function doQuery( $sql ) {
740 if( $this->bufferResults() ) {
741 $ret = mysql_query( $sql, $this->mConn );
742 } else {
743 $ret = mysql_unbuffered_query( $sql, $this->mConn );
744 }
745 return $ret;
746 }
747
748 /**
749 * @param $error
750 * @param $errno
751 * @param $sql
752 * @param string $fname
753 * @param bool $tempIgnore
754 */
755 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
756 global $wgCommandLineMode;
757 # Ignore errors during error handling to avoid infinite recursion
758 $ignore = $this->ignoreErrors( true );
759 ++$this->mErrorCount;
760
761 if( $ignore || $tempIgnore ) {
762 wfDebug("SQL ERROR (ignored): $error\n");
763 $this->ignoreErrors( $ignore );
764 } else {
765 $sql1line = str_replace( "\n", "\\n", $sql );
766 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
767 wfDebug("SQL ERROR: " . $error . "\n");
768 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
769 }
770 }
771
772
773 /**
774 * Intended to be compatible with the PEAR::DB wrapper functions.
775 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
776 *
777 * ? = scalar value, quoted as necessary
778 * ! = raw SQL bit (a function for instance)
779 * & = filename; reads the file and inserts as a blob
780 * (we don't use this though...)
781 */
782 function prepare( $sql, $func = 'Database::prepare' ) {
783 /* MySQL doesn't support prepared statements (yet), so just
784 pack up the query for reference. We'll manually replace
785 the bits later. */
786 return array( 'query' => $sql, 'func' => $func );
787 }
788
789 function freePrepared( $prepared ) {
790 /* No-op for MySQL */
791 }
792
793 /**
794 * Execute a prepared query with the various arguments
795 * @param string $prepared the prepared sql
796 * @param mixed $args Either an array here, or put scalars as varargs
797 */
798 function execute( $prepared, $args = null ) {
799 if( !is_array( $args ) ) {
800 # Pull the var args
801 $args = func_get_args();
802 array_shift( $args );
803 }
804 $sql = $this->fillPrepared( $prepared['query'], $args );
805 return $this->query( $sql, $prepared['func'] );
806 }
807
808 /**
809 * Prepare & execute an SQL statement, quoting and inserting arguments
810 * in the appropriate places.
811 * @param string $query
812 * @param string $args ...
813 */
814 function safeQuery( $query, $args = null ) {
815 $prepared = $this->prepare( $query, 'Database::safeQuery' );
816 if( !is_array( $args ) ) {
817 # Pull the var args
818 $args = func_get_args();
819 array_shift( $args );
820 }
821 $retval = $this->execute( $prepared, $args );
822 $this->freePrepared( $prepared );
823 return $retval;
824 }
825
826 /**
827 * For faking prepared SQL statements on DBs that don't support
828 * it directly.
829 * @param string $preparedSql - a 'preparable' SQL statement
830 * @param array $args - array of arguments to fill it with
831 * @return string executable SQL
832 */
833 function fillPrepared( $preparedQuery, $args ) {
834 reset( $args );
835 $this->preparedArgs =& $args;
836 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
837 array( &$this, 'fillPreparedArg' ), $preparedQuery );
838 }
839
840 /**
841 * preg_callback func for fillPrepared()
842 * The arguments should be in $this->preparedArgs and must not be touched
843 * while we're doing this.
844 *
845 * @param array $matches
846 * @return string
847 * @private
848 */
849 function fillPreparedArg( $matches ) {
850 switch( $matches[1] ) {
851 case '\\?': return '?';
852 case '\\!': return '!';
853 case '\\&': return '&';
854 }
855 list( /* $n */ , $arg ) = each( $this->preparedArgs );
856 switch( $matches[1] ) {
857 case '?': return $this->addQuotes( $arg );
858 case '!': return $arg;
859 case '&':
860 # return $this->addQuotes( file_get_contents( $arg ) );
861 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
862 default:
863 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
864 }
865 }
866
867 /**#@+
868 * @param mixed $res A SQL result
869 */
870 /**
871 * Free a result object
872 */
873 function freeResult( $res ) {
874 if ( !@/**/mysql_free_result( $res ) ) {
875 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
876 }
877 }
878
879 /**
880 * Fetch the next row from the given result object, in object form
881 */
882 function fetchObject( $res ) {
883 @/**/$row = mysql_fetch_object( $res );
884 if( $this->lastErrno() ) {
885 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
886 }
887 return $row;
888 }
889
890 /**
891 * Fetch the next row from the given result object
892 * Returns an array
893 */
894 function fetchRow( $res ) {
895 @/**/$row = mysql_fetch_array( $res );
896 if ( $this->lastErrno() ) {
897 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
898 }
899 return $row;
900 }
901
902 /**
903 * Get the number of rows in a result object
904 */
905 function numRows( $res ) {
906 @/**/$n = mysql_num_rows( $res );
907 if( $this->lastErrno() ) {
908 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
909 }
910 return $n;
911 }
912
913 /**
914 * Get the number of fields in a result object
915 * See documentation for mysql_num_fields()
916 */
917 function numFields( $res ) { return mysql_num_fields( $res ); }
918
919 /**
920 * Get a field name in a result object
921 * See documentation for mysql_field_name():
922 * http://www.php.net/mysql_field_name
923 */
924 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
925
926 /**
927 * Get the inserted value of an auto-increment row
928 *
929 * The value inserted should be fetched from nextSequenceValue()
930 *
931 * Example:
932 * $id = $dbw->nextSequenceValue('page_page_id_seq');
933 * $dbw->insert('page',array('page_id' => $id));
934 * $id = $dbw->insertId();
935 */
936 function insertId() { return mysql_insert_id( $this->mConn ); }
937
938 /**
939 * Change the position of the cursor in a result object
940 * See mysql_data_seek()
941 */
942 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
943
944 /**
945 * Get the last error number
946 * See mysql_errno()
947 */
948 function lastErrno() {
949 if ( $this->mConn ) {
950 return mysql_errno( $this->mConn );
951 } else {
952 return mysql_errno();
953 }
954 }
955
956 /**
957 * Get a description of the last error
958 * See mysql_error() for more details
959 */
960 function lastError() {
961 if ( $this->mConn ) {
962 # Even if it's non-zero, it can still be invalid
963 wfSuppressWarnings();
964 $error = mysql_error( $this->mConn );
965 if ( !$error ) {
966 $error = mysql_error();
967 }
968 wfRestoreWarnings();
969 } else {
970 $error = mysql_error();
971 }
972 if( $error ) {
973 $error .= ' (' . $this->mServer . ')';
974 }
975 return $error;
976 }
977 /**
978 * Get the number of rows affected by the last write query
979 * See mysql_affected_rows() for more details
980 */
981 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
982 /**#@-*/ // end of template : @param $result
983
984 /**
985 * Simple UPDATE wrapper
986 * Usually aborts on failure
987 * If errors are explicitly ignored, returns success
988 *
989 * This function exists for historical reasons, Database::update() has a more standard
990 * calling convention and feature set
991 */
992 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
993 {
994 $table = $this->tableName( $table );
995 $sql = "UPDATE $table SET $var = '" .
996 $this->strencode( $value ) . "' WHERE ($cond)";
997 return (bool)$this->query( $sql, $fname );
998 }
999
1000 /**
1001 * Simple SELECT wrapper, returns a single field, input must be encoded
1002 * Usually aborts on failure
1003 * If errors are explicitly ignored, returns FALSE on failure
1004 */
1005 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1006 if ( !is_array( $options ) ) {
1007 $options = array( $options );
1008 }
1009 $options['LIMIT'] = 1;
1010
1011 $res = $this->select( $table, $var, $cond, $fname, $options );
1012 if ( $res === false || !$this->numRows( $res ) ) {
1013 return false;
1014 }
1015 $row = $this->fetchRow( $res );
1016 if ( $row !== false ) {
1017 $this->freeResult( $res );
1018 return $row[0];
1019 } else {
1020 return false;
1021 }
1022 }
1023
1024 /**
1025 * Returns an optional USE INDEX clause to go after the table, and a
1026 * string to go at the end of the query
1027 *
1028 * @private
1029 *
1030 * @param array $options an associative array of options to be turned into
1031 * an SQL query, valid keys are listed in the function.
1032 * @return array
1033 */
1034 function makeSelectOptions( $options ) {
1035 $preLimitTail = $postLimitTail = '';
1036 $startOpts = '';
1037
1038 $noKeyOptions = array();
1039 foreach ( $options as $key => $option ) {
1040 if ( is_numeric( $key ) ) {
1041 $noKeyOptions[$option] = true;
1042 }
1043 }
1044
1045 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1046 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1047
1048 //if (isset($options['LIMIT'])) {
1049 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1050 // isset($options['OFFSET']) ? $options['OFFSET']
1051 // : false);
1052 //}
1053
1054 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1055 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1056 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1057
1058 # Various MySQL extensions
1059 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1060 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1061 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1062 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1063 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1064 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1065 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1066 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1067
1068 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1069 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1070 } else {
1071 $useIndex = '';
1072 }
1073
1074 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1075 }
1076
1077 /**
1078 * SELECT wrapper
1079 *
1080 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1081 * @param mixed $vars Array or string, field name(s) to be retrieved
1082 * @param mixed $conds Array or string, condition(s) for WHERE
1083 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1084 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1085 * see Database::makeSelectOptions code for list of supported stuff
1086 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1087 */
1088 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1089 {
1090 if( is_array( $vars ) ) {
1091 $vars = implode( ',', $vars );
1092 }
1093 if( !is_array( $options ) ) {
1094 $options = array( $options );
1095 }
1096 if( is_array( $table ) ) {
1097 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1098 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1099 else
1100 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1101 } elseif ($table!='') {
1102 if ($table{0}==' ') {
1103 $from = ' FROM ' . $table;
1104 } else {
1105 $from = ' FROM ' . $this->tableName( $table );
1106 }
1107 } else {
1108 $from = '';
1109 }
1110
1111 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1112
1113 if( !empty( $conds ) ) {
1114 if ( is_array( $conds ) ) {
1115 $conds = $this->makeList( $conds, LIST_AND );
1116 }
1117 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1118 } else {
1119 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1120 }
1121
1122 if (isset($options['LIMIT']))
1123 $sql = $this->limitResult($sql, $options['LIMIT'],
1124 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1125 $sql = "$sql $postLimitTail";
1126
1127 return $this->query( $sql, $fname );
1128 }
1129
1130 /**
1131 * Single row SELECT wrapper
1132 * Aborts or returns FALSE on error
1133 *
1134 * $vars: the selected variables
1135 * $conds: a condition map, terms are ANDed together.
1136 * Items with numeric keys are taken to be literal conditions
1137 * Takes an array of selected variables, and a condition map, which is ANDed
1138 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1139 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1140 * $obj- >page_id is the ID of the Astronomy article
1141 *
1142 * @todo migrate documentation to phpdocumentor format
1143 */
1144 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1145 $options['LIMIT'] = 1;
1146 $res = $this->select( $table, $vars, $conds, $fname, $options );
1147 if ( $res === false )
1148 return false;
1149 if ( !$this->numRows($res) ) {
1150 $this->freeResult($res);
1151 return false;
1152 }
1153 $obj = $this->fetchObject( $res );
1154 $this->freeResult( $res );
1155 return $obj;
1156
1157 }
1158
1159 /**
1160 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1161 * It's only slightly flawed. Don't use for anything important.
1162 *
1163 * @param string $sql A SQL Query
1164 * @static
1165 */
1166 static function generalizeSQL( $sql ) {
1167 # This does the same as the regexp below would do, but in such a way
1168 # as to avoid crashing php on some large strings.
1169 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1170
1171 $sql = str_replace ( "\\\\", '', $sql);
1172 $sql = str_replace ( "\\'", '', $sql);
1173 $sql = str_replace ( "\\\"", '', $sql);
1174 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1175 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1176
1177 # All newlines, tabs, etc replaced by single space
1178 $sql = preg_replace ( '/\s+/', ' ', $sql);
1179
1180 # All numbers => N
1181 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1182
1183 return $sql;
1184 }
1185
1186 /**
1187 * Determines whether a field exists in a table
1188 * Usually aborts on failure
1189 * If errors are explicitly ignored, returns NULL on failure
1190 */
1191 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1192 $table = $this->tableName( $table );
1193 $res = $this->query( 'DESCRIBE '.$table, $fname );
1194 if ( !$res ) {
1195 return NULL;
1196 }
1197
1198 $found = false;
1199
1200 while ( $row = $this->fetchObject( $res ) ) {
1201 if ( $row->Field == $field ) {
1202 $found = true;
1203 break;
1204 }
1205 }
1206 return $found;
1207 }
1208
1209 /**
1210 * Determines whether an index exists
1211 * Usually aborts on failure
1212 * If errors are explicitly ignored, returns NULL on failure
1213 */
1214 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1215 $info = $this->indexInfo( $table, $index, $fname );
1216 if ( is_null( $info ) ) {
1217 return NULL;
1218 } else {
1219 return $info !== false;
1220 }
1221 }
1222
1223
1224 /**
1225 * Get information about an index into an object
1226 * Returns false if the index does not exist
1227 */
1228 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1229 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1230 # SHOW INDEX should work for 3.x and up:
1231 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1232 $table = $this->tableName( $table );
1233 $sql = 'SHOW INDEX FROM '.$table;
1234 $res = $this->query( $sql, $fname );
1235 if ( !$res ) {
1236 return NULL;
1237 }
1238
1239 $result = array();
1240 while ( $row = $this->fetchObject( $res ) ) {
1241 if ( $row->Key_name == $index ) {
1242 $result[] = $row;
1243 }
1244 }
1245 $this->freeResult($res);
1246
1247 return empty($result) ? false : $result;
1248 }
1249
1250 /**
1251 * Query whether a given table exists
1252 */
1253 function tableExists( $table ) {
1254 $table = $this->tableName( $table );
1255 $old = $this->ignoreErrors( true );
1256 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1257 $this->ignoreErrors( $old );
1258 if( $res ) {
1259 $this->freeResult( $res );
1260 return true;
1261 } else {
1262 return false;
1263 }
1264 }
1265
1266 /**
1267 * mysql_fetch_field() wrapper
1268 * Returns false if the field doesn't exist
1269 *
1270 * @param $table
1271 * @param $field
1272 */
1273 function fieldInfo( $table, $field ) {
1274 $table = $this->tableName( $table );
1275 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1276 $n = mysql_num_fields( $res );
1277 for( $i = 0; $i < $n; $i++ ) {
1278 $meta = mysql_fetch_field( $res, $i );
1279 if( $field == $meta->name ) {
1280 return new MySQLField($meta);
1281 }
1282 }
1283 return false;
1284 }
1285
1286 /**
1287 * mysql_field_type() wrapper
1288 */
1289 function fieldType( $res, $index ) {
1290 return mysql_field_type( $res, $index );
1291 }
1292
1293 /**
1294 * Determines if a given index is unique
1295 */
1296 function indexUnique( $table, $index ) {
1297 $indexInfo = $this->indexInfo( $table, $index );
1298 if ( !$indexInfo ) {
1299 return NULL;
1300 }
1301 return !$indexInfo[0]->Non_unique;
1302 }
1303
1304 /**
1305 * INSERT wrapper, inserts an array into a table
1306 *
1307 * $a may be a single associative array, or an array of these with numeric keys, for
1308 * multi-row insert.
1309 *
1310 * Usually aborts on failure
1311 * If errors are explicitly ignored, returns success
1312 */
1313 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1314 # No rows to insert, easy just return now
1315 if ( !count( $a ) ) {
1316 return true;
1317 }
1318
1319 $table = $this->tableName( $table );
1320 if ( !is_array( $options ) ) {
1321 $options = array( $options );
1322 }
1323 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1324 $multi = true;
1325 $keys = array_keys( $a[0] );
1326 } else {
1327 $multi = false;
1328 $keys = array_keys( $a );
1329 }
1330
1331 $sql = 'INSERT ' . implode( ' ', $options ) .
1332 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1333
1334 if ( $multi ) {
1335 $first = true;
1336 foreach ( $a as $row ) {
1337 if ( $first ) {
1338 $first = false;
1339 } else {
1340 $sql .= ',';
1341 }
1342 $sql .= '(' . $this->makeList( $row ) . ')';
1343 }
1344 } else {
1345 $sql .= '(' . $this->makeList( $a ) . ')';
1346 }
1347 return (bool)$this->query( $sql, $fname );
1348 }
1349
1350 /**
1351 * Make UPDATE options for the Database::update function
1352 *
1353 * @private
1354 * @param array $options The options passed to Database::update
1355 * @return string
1356 */
1357 function makeUpdateOptions( $options ) {
1358 if( !is_array( $options ) ) {
1359 $options = array( $options );
1360 }
1361 $opts = array();
1362 if ( in_array( 'LOW_PRIORITY', $options ) )
1363 $opts[] = $this->lowPriorityOption();
1364 if ( in_array( 'IGNORE', $options ) )
1365 $opts[] = 'IGNORE';
1366 return implode(' ', $opts);
1367 }
1368
1369 /**
1370 * UPDATE wrapper, takes a condition array and a SET array
1371 *
1372 * @param string $table The table to UPDATE
1373 * @param array $values An array of values to SET
1374 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1375 * @param string $fname The Class::Function calling this function
1376 * (for the log)
1377 * @param array $options An array of UPDATE options, can be one or
1378 * more of IGNORE, LOW_PRIORITY
1379 */
1380 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1381 $table = $this->tableName( $table );
1382 $opts = $this->makeUpdateOptions( $options );
1383 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1384 if ( $conds != '*' ) {
1385 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1386 }
1387 $this->query( $sql, $fname );
1388 }
1389
1390 /**
1391 * Makes an encoded list of strings from an array
1392 * $mode:
1393 * LIST_COMMA - comma separated, no field names
1394 * LIST_AND - ANDed WHERE clause (without the WHERE)
1395 * LIST_OR - ORed WHERE clause (without the WHERE)
1396 * LIST_SET - comma separated with field names, like a SET clause
1397 * LIST_NAMES - comma separated field names
1398 */
1399 function makeList( $a, $mode = LIST_COMMA ) {
1400 if ( !is_array( $a ) ) {
1401 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1402 }
1403
1404 $first = true;
1405 $list = '';
1406 foreach ( $a as $field => $value ) {
1407 if ( !$first ) {
1408 if ( $mode == LIST_AND ) {
1409 $list .= ' AND ';
1410 } elseif($mode == LIST_OR) {
1411 $list .= ' OR ';
1412 } else {
1413 $list .= ',';
1414 }
1415 } else {
1416 $first = false;
1417 }
1418 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1419 $list .= "($value)";
1420 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1421 $list .= "$value";
1422 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1423 $list .= $field." IN (".$this->makeList($value).") ";
1424 } else {
1425 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1426 $list .= "$field = ";
1427 }
1428 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1429 }
1430 }
1431 return $list;
1432 }
1433
1434 /**
1435 * Change the current database
1436 */
1437 function selectDB( $db ) {
1438 $this->mDBname = $db;
1439 return mysql_select_db( $db, $this->mConn );
1440 }
1441
1442 /**
1443 * Format a table name ready for use in constructing an SQL query
1444 *
1445 * This does two important things: it quotes table names which as necessary,
1446 * and it adds a table prefix if there is one.
1447 *
1448 * All functions of this object which require a table name call this function
1449 * themselves. Pass the canonical name to such functions. This is only needed
1450 * when calling query() directly.
1451 *
1452 * @param string $name database table name
1453 */
1454 function tableName( $name ) {
1455 global $wgSharedDB;
1456 # Skip quoted literals
1457 if ( $name{0} != '`' ) {
1458 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1459 $name = "{$this->mTablePrefix}$name";
1460 }
1461 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1462 $name = "`$wgSharedDB`.`$name`";
1463 } else {
1464 # Standard quoting
1465 $name = "`$name`";
1466 }
1467 }
1468 return $name;
1469 }
1470
1471 /**
1472 * Fetch a number of table names into an array
1473 * This is handy when you need to construct SQL for joins
1474 *
1475 * Example:
1476 * extract($dbr->tableNames('user','watchlist'));
1477 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1478 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1479 */
1480 public function tableNames() {
1481 $inArray = func_get_args();
1482 $retVal = array();
1483 foreach ( $inArray as $name ) {
1484 $retVal[$name] = $this->tableName( $name );
1485 }
1486 return $retVal;
1487 }
1488
1489 /**
1490 * Fetch a number of table names into an zero-indexed numerical array
1491 * This is handy when you need to construct SQL for joins
1492 *
1493 * Example:
1494 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1495 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1496 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1497 */
1498 public function tableNamesN() {
1499 $inArray = func_get_args();
1500 $retVal = array();
1501 foreach ( $inArray as $name ) {
1502 $retVal[] = $this->tableName( $name );
1503 }
1504 return $retVal;
1505 }
1506
1507 /**
1508 * @private
1509 */
1510 function tableNamesWithUseIndex( $tables, $use_index ) {
1511 $ret = array();
1512
1513 foreach ( $tables as $table )
1514 if ( @$use_index[$table] !== null )
1515 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1516 else
1517 $ret[] = $this->tableName( $table );
1518
1519 return implode( ',', $ret );
1520 }
1521
1522 /**
1523 * Wrapper for addslashes()
1524 * @param string $s String to be slashed.
1525 * @return string slashed string.
1526 */
1527 function strencode( $s ) {
1528 return mysql_real_escape_string( $s, $this->mConn );
1529 }
1530
1531 /**
1532 * If it's a string, adds quotes and backslashes
1533 * Otherwise returns as-is
1534 */
1535 function addQuotes( $s ) {
1536 if ( is_null( $s ) ) {
1537 return 'NULL';
1538 } else {
1539 # This will also quote numeric values. This should be harmless,
1540 # and protects against weird problems that occur when they really
1541 # _are_ strings such as article titles and string->number->string
1542 # conversion is not 1:1.
1543 return "'" . $this->strencode( $s ) . "'";
1544 }
1545 }
1546
1547 /**
1548 * Escape string for safe LIKE usage
1549 */
1550 function escapeLike( $s ) {
1551 $s=$this->strencode( $s );
1552 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1553 return $s;
1554 }
1555
1556 /**
1557 * Returns an appropriately quoted sequence value for inserting a new row.
1558 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1559 * subclass will return an integer, and save the value for insertId()
1560 */
1561 function nextSequenceValue( $seqName ) {
1562 return NULL;
1563 }
1564
1565 /**
1566 * USE INDEX clause
1567 * PostgreSQL doesn't have them and returns ""
1568 */
1569 function useIndexClause( $index ) {
1570 return "FORCE INDEX ($index)";
1571 }
1572
1573 /**
1574 * REPLACE query wrapper
1575 * PostgreSQL simulates this with a DELETE followed by INSERT
1576 * $row is the row to insert, an associative array
1577 * $uniqueIndexes is an array of indexes. Each element may be either a
1578 * field name or an array of field names
1579 *
1580 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1581 * However if you do this, you run the risk of encountering errors which wouldn't have
1582 * occurred in MySQL
1583 *
1584 * @todo migrate comment to phodocumentor format
1585 */
1586 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1587 $table = $this->tableName( $table );
1588
1589 # Single row case
1590 if ( !is_array( reset( $rows ) ) ) {
1591 $rows = array( $rows );
1592 }
1593
1594 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1595 $first = true;
1596 foreach ( $rows as $row ) {
1597 if ( $first ) {
1598 $first = false;
1599 } else {
1600 $sql .= ',';
1601 }
1602 $sql .= '(' . $this->makeList( $row ) . ')';
1603 }
1604 return $this->query( $sql, $fname );
1605 }
1606
1607 /**
1608 * DELETE where the condition is a join
1609 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1610 *
1611 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1612 * join condition matches, set $conds='*'
1613 *
1614 * DO NOT put the join condition in $conds
1615 *
1616 * @param string $delTable The table to delete from.
1617 * @param string $joinTable The other table.
1618 * @param string $delVar The variable to join on, in the first table.
1619 * @param string $joinVar The variable to join on, in the second table.
1620 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1621 */
1622 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1623 if ( !$conds ) {
1624 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1625 }
1626
1627 $delTable = $this->tableName( $delTable );
1628 $joinTable = $this->tableName( $joinTable );
1629 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1630 if ( $conds != '*' ) {
1631 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1632 }
1633
1634 return $this->query( $sql, $fname );
1635 }
1636
1637 /**
1638 * Returns the size of a text field, or -1 for "unlimited"
1639 */
1640 function textFieldSize( $table, $field ) {
1641 $table = $this->tableName( $table );
1642 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1643 $res = $this->query( $sql, 'Database::textFieldSize' );
1644 $row = $this->fetchObject( $res );
1645 $this->freeResult( $res );
1646
1647 $m = array();
1648 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1649 $size = $m[1];
1650 } else {
1651 $size = -1;
1652 }
1653 return $size;
1654 }
1655
1656 /**
1657 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1658 */
1659 function lowPriorityOption() {
1660 return 'LOW_PRIORITY';
1661 }
1662
1663 /**
1664 * DELETE query wrapper
1665 *
1666 * Use $conds == "*" to delete all rows
1667 */
1668 function delete( $table, $conds, $fname = 'Database::delete' ) {
1669 if ( !$conds ) {
1670 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1671 }
1672 $table = $this->tableName( $table );
1673 $sql = "DELETE FROM $table";
1674 if ( $conds != '*' ) {
1675 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1676 }
1677 return $this->query( $sql, $fname );
1678 }
1679
1680 /**
1681 * INSERT SELECT wrapper
1682 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1683 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1684 * $conds may be "*" to copy the whole table
1685 * srcTable may be an array of tables.
1686 */
1687 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1688 $insertOptions = array(), $selectOptions = array() )
1689 {
1690 $destTable = $this->tableName( $destTable );
1691 if ( is_array( $insertOptions ) ) {
1692 $insertOptions = implode( ' ', $insertOptions );
1693 }
1694 if( !is_array( $selectOptions ) ) {
1695 $selectOptions = array( $selectOptions );
1696 }
1697 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1698 if( is_array( $srcTable ) ) {
1699 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1700 } else {
1701 $srcTable = $this->tableName( $srcTable );
1702 }
1703 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1704 " SELECT $startOpts " . implode( ',', $varMap ) .
1705 " FROM $srcTable $useIndex ";
1706 if ( $conds != '*' ) {
1707 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1708 }
1709 $sql .= " $tailOpts";
1710 return $this->query( $sql, $fname );
1711 }
1712
1713 /**
1714 * Construct a LIMIT query with optional offset
1715 * This is used for query pages
1716 * $sql string SQL query we will append the limit too
1717 * $limit integer the SQL limit
1718 * $offset integer the SQL offset (default false)
1719 */
1720 function limitResult($sql, $limit, $offset=false) {
1721 if( !is_numeric($limit) ) {
1722 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1723 }
1724 return " $sql LIMIT "
1725 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1726 . "{$limit} ";
1727 }
1728 function limitResultForUpdate($sql, $num) {
1729 return $this->limitResult($sql, $num, 0);
1730 }
1731
1732 /**
1733 * Returns an SQL expression for a simple conditional.
1734 * Uses IF on MySQL.
1735 *
1736 * @param string $cond SQL expression which will result in a boolean value
1737 * @param string $trueVal SQL expression to return if true
1738 * @param string $falseVal SQL expression to return if false
1739 * @return string SQL fragment
1740 */
1741 function conditional( $cond, $trueVal, $falseVal ) {
1742 return " IF($cond, $trueVal, $falseVal) ";
1743 }
1744
1745 /**
1746 * Determines if the last failure was due to a deadlock
1747 */
1748 function wasDeadlock() {
1749 return $this->lastErrno() == 1213;
1750 }
1751
1752 /**
1753 * Perform a deadlock-prone transaction.
1754 *
1755 * This function invokes a callback function to perform a set of write
1756 * queries. If a deadlock occurs during the processing, the transaction
1757 * will be rolled back and the callback function will be called again.
1758 *
1759 * Usage:
1760 * $dbw->deadlockLoop( callback, ... );
1761 *
1762 * Extra arguments are passed through to the specified callback function.
1763 *
1764 * Returns whatever the callback function returned on its successful,
1765 * iteration, or false on error, for example if the retry limit was
1766 * reached.
1767 */
1768 function deadlockLoop() {
1769 $myFname = 'Database::deadlockLoop';
1770
1771 $this->begin();
1772 $args = func_get_args();
1773 $function = array_shift( $args );
1774 $oldIgnore = $this->ignoreErrors( true );
1775 $tries = DEADLOCK_TRIES;
1776 if ( is_array( $function ) ) {
1777 $fname = $function[0];
1778 } else {
1779 $fname = $function;
1780 }
1781 do {
1782 $retVal = call_user_func_array( $function, $args );
1783 $error = $this->lastError();
1784 $errno = $this->lastErrno();
1785 $sql = $this->lastQuery();
1786
1787 if ( $errno ) {
1788 if ( $this->wasDeadlock() ) {
1789 # Retry
1790 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1791 } else {
1792 $this->reportQueryError( $error, $errno, $sql, $fname );
1793 }
1794 }
1795 } while( $this->wasDeadlock() && --$tries > 0 );
1796 $this->ignoreErrors( $oldIgnore );
1797 if ( $tries <= 0 ) {
1798 $this->query( 'ROLLBACK', $myFname );
1799 $this->reportQueryError( $error, $errno, $sql, $fname );
1800 return false;
1801 } else {
1802 $this->query( 'COMMIT', $myFname );
1803 return $retVal;
1804 }
1805 }
1806
1807 /**
1808 * Do a SELECT MASTER_POS_WAIT()
1809 *
1810 * @param string $file the binlog file
1811 * @param string $pos the binlog position
1812 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1813 */
1814 function masterPosWait( $file, $pos, $timeout ) {
1815 $fname = 'Database::masterPosWait';
1816 wfProfileIn( $fname );
1817
1818
1819 # Commit any open transactions
1820 $this->immediateCommit();
1821
1822 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1823 $encFile = $this->strencode( $file );
1824 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1825 $res = $this->doQuery( $sql );
1826 if ( $res && $row = $this->fetchRow( $res ) ) {
1827 $this->freeResult( $res );
1828 wfProfileOut( $fname );
1829 return $row[0];
1830 } else {
1831 wfProfileOut( $fname );
1832 return false;
1833 }
1834 }
1835
1836 /**
1837 * Get the position of the master from SHOW SLAVE STATUS
1838 */
1839 function getSlavePos() {
1840 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1841 $row = $this->fetchObject( $res );
1842 if ( $row ) {
1843 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1844 } else {
1845 return array( false, false );
1846 }
1847 }
1848
1849 /**
1850 * Get the position of the master from SHOW MASTER STATUS
1851 */
1852 function getMasterPos() {
1853 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1854 $row = $this->fetchObject( $res );
1855 if ( $row ) {
1856 return array( $row->File, $row->Position );
1857 } else {
1858 return array( false, false );
1859 }
1860 }
1861
1862 /**
1863 * Begin a transaction, committing any previously open transaction
1864 */
1865 function begin( $fname = 'Database::begin' ) {
1866 $this->query( 'BEGIN', $fname );
1867 $this->mTrxLevel = 1;
1868 }
1869
1870 /**
1871 * End a transaction
1872 */
1873 function commit( $fname = 'Database::commit' ) {
1874 $this->query( 'COMMIT', $fname );
1875 $this->mTrxLevel = 0;
1876 }
1877
1878 /**
1879 * Rollback a transaction
1880 */
1881 function rollback( $fname = 'Database::rollback' ) {
1882 $this->query( 'ROLLBACK', $fname );
1883 $this->mTrxLevel = 0;
1884 }
1885
1886 /**
1887 * Begin a transaction, committing any previously open transaction
1888 * @deprecated use begin()
1889 */
1890 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1891 $this->begin();
1892 }
1893
1894 /**
1895 * Commit transaction, if one is open
1896 * @deprecated use commit()
1897 */
1898 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1899 $this->commit();
1900 }
1901
1902 /**
1903 * Return MW-style timestamp used for MySQL schema
1904 */
1905 function timestamp( $ts=0 ) {
1906 return wfTimestamp(TS_MW,$ts);
1907 }
1908
1909 /**
1910 * Local database timestamp format or null
1911 */
1912 function timestampOrNull( $ts = null ) {
1913 if( is_null( $ts ) ) {
1914 return null;
1915 } else {
1916 return $this->timestamp( $ts );
1917 }
1918 }
1919
1920 /**
1921 * @todo document
1922 */
1923 function resultObject( $result ) {
1924 if( empty( $result ) ) {
1925 return NULL;
1926 } else {
1927 return new ResultWrapper( $this, $result );
1928 }
1929 }
1930
1931 /**
1932 * Return aggregated value alias
1933 */
1934 function aggregateValue ($valuedata,$valuename='value') {
1935 return $valuename;
1936 }
1937
1938 /**
1939 * @return string wikitext of a link to the server software's web site
1940 */
1941 function getSoftwareLink() {
1942 return "[http://www.mysql.com/ MySQL]";
1943 }
1944
1945 /**
1946 * @return string Version information from the database
1947 */
1948 function getServerVersion() {
1949 return mysql_get_server_info( $this->mConn );
1950 }
1951
1952 /**
1953 * Ping the server and try to reconnect if it there is no connection
1954 */
1955 function ping() {
1956 if( function_exists( 'mysql_ping' ) ) {
1957 return mysql_ping( $this->mConn );
1958 } else {
1959 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1960 return true;
1961 }
1962 }
1963
1964 /**
1965 * Get slave lag.
1966 * At the moment, this will only work if the DB user has the PROCESS privilege
1967 */
1968 function getLag() {
1969 $res = $this->query( 'SHOW PROCESSLIST' );
1970 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1971 # dubious, but unfortunately there's no easy rigorous way
1972 while ( $row = $this->fetchObject( $res ) ) {
1973 /* This should work for most situations - when default db
1974 * for thread is not specified, it had no events executed,
1975 * and therefore it doesn't know yet how lagged it is.
1976 *
1977 * Relay log I/O thread does not select databases.
1978 */
1979 if ( $row->User == 'system user' &&
1980 $row->State != 'Waiting for master to send event' &&
1981 $row->State != 'Connecting to master' &&
1982 $row->State != 'Queueing master event to the relay log' &&
1983 $row->State != 'Waiting for master update' &&
1984 $row->State != 'Requesting binlog dump'
1985 ) {
1986 # This is it, return the time (except -ve)
1987 if ( $row->Time > 0x7fffffff ) {
1988 return false;
1989 } else {
1990 return $row->Time;
1991 }
1992 }
1993 }
1994 return false;
1995 }
1996
1997 /**
1998 * Get status information from SHOW STATUS in an associative array
1999 */
2000 function getStatus($which="%") {
2001 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2002 $status = array();
2003 while ( $row = $this->fetchObject( $res ) ) {
2004 $status[$row->Variable_name] = $row->Value;
2005 }
2006 return $status;
2007 }
2008
2009 /**
2010 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2011 */
2012 function maxListLen() {
2013 return 0;
2014 }
2015
2016 function encodeBlob($b) {
2017 return $b;
2018 }
2019
2020 function decodeBlob($b) {
2021 return $b;
2022 }
2023
2024 /**
2025 * Override database's default connection timeout.
2026 * May be useful for very long batch queries such as
2027 * full-wiki dumps, where a single query reads out
2028 * over hours or days.
2029 * @param int $timeout in seconds
2030 */
2031 public function setTimeout( $timeout ) {
2032 $this->query( "SET net_read_timeout=$timeout" );
2033 $this->query( "SET net_write_timeout=$timeout" );
2034 }
2035
2036 /**
2037 * Read and execute SQL commands from a file.
2038 * Returns true on success, error string on failure
2039 */
2040 function sourceFile( $filename ) {
2041 $fp = fopen( $filename, 'r' );
2042 if ( false === $fp ) {
2043 return "Could not open \"{$filename}\".\n";
2044 }
2045
2046 $cmd = "";
2047 $done = false;
2048 $dollarquote = false;
2049
2050 while ( ! feof( $fp ) ) {
2051 $line = trim( fgets( $fp, 1024 ) );
2052 $sl = strlen( $line ) - 1;
2053
2054 if ( $sl < 0 ) { continue; }
2055 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2056
2057 ## Allow dollar quoting for function declarations
2058 if (substr($line,0,4) == '$mw$') {
2059 if ($dollarquote) {
2060 $dollarquote = false;
2061 $done = true;
2062 }
2063 else {
2064 $dollarquote = true;
2065 }
2066 }
2067 else if (!$dollarquote) {
2068 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2069 $done = true;
2070 $line = substr( $line, 0, $sl );
2071 }
2072 }
2073
2074 if ( '' != $cmd ) { $cmd .= ' '; }
2075 $cmd .= "$line\n";
2076
2077 if ( $done ) {
2078 $cmd = str_replace(';;', ";", $cmd);
2079 $cmd = $this->replaceVars( $cmd );
2080 $res = $this->query( $cmd, 'dbsource', true );
2081
2082 if ( false === $res ) {
2083 $err = $this->lastError();
2084 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2085 }
2086
2087 $cmd = '';
2088 $done = false;
2089 }
2090 }
2091 fclose( $fp );
2092 return true;
2093 }
2094
2095 /**
2096 * Replace variables in sourced SQL
2097 */
2098 protected function replaceVars( $ins ) {
2099 $varnames = array(
2100 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2101 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2102 'wgDBadminuser', 'wgDBadminpassword',
2103 );
2104
2105 // Ordinary variables
2106 foreach ( $varnames as $var ) {
2107 if( isset( $GLOBALS[$var] ) ) {
2108 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2109 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2110 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2111 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2112 }
2113 }
2114
2115 // Table prefixes
2116 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2117 array( &$this, 'tableNameCallback' ), $ins );
2118 return $ins;
2119 }
2120
2121 /**
2122 * Table name callback
2123 * @private
2124 */
2125 protected function tableNameCallback( $matches ) {
2126 return $this->tableName( $matches[1] );
2127 }
2128
2129 }
2130
2131 /**
2132 * Database abstraction object for mySQL
2133 * Inherit all methods and properties of Database::Database()
2134 *
2135 * @see Database
2136 */
2137 class DatabaseMysql extends Database {
2138 # Inherit all
2139 }
2140
2141
2142 /**
2143 * Result wrapper for grabbing data queried by someone else
2144 *
2145 */
2146 class ResultWrapper {
2147 var $db, $result;
2148
2149 /**
2150 * @todo document
2151 */
2152 function ResultWrapper( &$database, $result ) {
2153 $this->db =& $database;
2154 $this->result =& $result;
2155 }
2156
2157 /**
2158 * @todo document
2159 */
2160 function numRows() {
2161 return $this->db->numRows( $this->result );
2162 }
2163
2164 /**
2165 * @todo document
2166 */
2167 function fetchObject() {
2168 return $this->db->fetchObject( $this->result );
2169 }
2170
2171 /**
2172 * @todo document
2173 */
2174 function fetchRow() {
2175 return $this->db->fetchRow( $this->result );
2176 }
2177
2178 /**
2179 * @todo document
2180 */
2181 function free() {
2182 $this->db->freeResult( $this->result );
2183 unset( $this->result );
2184 unset( $this->db );
2185 }
2186
2187 function seek( $row ) {
2188 $this->db->dataSeek( $this->result, $row );
2189 }
2190
2191 function rewind() {
2192 if ($this->numRows()) {
2193 $this->db->dataSeek($this->result, 0);
2194 }
2195 }
2196
2197 }
2198
2199 ?>