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