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