e9e87535da77f6bcac2608e3f4811d47cb3f9b4e
[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 - not necessarily an accurate estimate across different databases,
965 * so use sparingly
966 * Takes same arguments as Database::select()
967 *
968 * @param string $table table name
969 * @param array $vars unused
970 * @param array $conds filters on the table
971 * @param string $fname function name for profiling
972 * @param array $options options for select
973 * @return int row count
974 */
975 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
976 $rows = 0;
977 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
978 if ( $res ) {
979 $row = $this->fetchRow( $res );
980 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
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 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1700 * within the UNION construct.
1701 * @return Boolean
1702 */
1703 function unionSupportsOrderAndLimit() {
1704 return true; // True for almost every DB supported
1705 }
1706
1707 /**
1708 * Construct a UNION query
1709 * This is used for providing overload point for other DB abstractions
1710 * not compatible with the MySQL syntax.
1711 * @param $sqls Array: SQL statements to combine
1712 * @param $all Boolean: use UNION ALL
1713 * @return String: SQL fragment
1714 */
1715 function unionQueries($sqls, $all) {
1716 $glue = $all ? ') UNION ALL (' : ') UNION (';
1717 return '('.implode( $glue, $sqls ) . ')';
1718 }
1719
1720 /**
1721 * Returns an SQL expression for a simple conditional. This doesn't need
1722 * to be overridden unless CASE isn't supported in your DBMS.
1723 *
1724 * @param $cond String: SQL expression which will result in a boolean value
1725 * @param $trueVal String: SQL expression to return if true
1726 * @param $falseVal String: SQL expression to return if false
1727 * @return String: SQL fragment
1728 */
1729 function conditional( $cond, $trueVal, $falseVal ) {
1730 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1731 }
1732
1733 /**
1734 * Returns a comand for str_replace function in SQL query.
1735 * Uses REPLACE() in MySQL
1736 *
1737 * @param $orig String: column to modify
1738 * @param $old String: column to seek
1739 * @param $new String: column to replace with
1740 */
1741 function strreplace( $orig, $old, $new ) {
1742 return "REPLACE({$orig}, {$old}, {$new})";
1743 }
1744
1745 /**
1746 * Determines if the last failure was due to a deadlock
1747 * STUB
1748 */
1749 function wasDeadlock() {
1750 return false;
1751 }
1752
1753 /**
1754 * Determines if the last query error was something that should be dealt
1755 * with by pinging the connection and reissuing the query.
1756 * STUB
1757 */
1758 function wasErrorReissuable() {
1759 return false;
1760 }
1761
1762 /**
1763 * Determines if the last failure was due to the database being read-only.
1764 * STUB
1765 */
1766 function wasReadOnlyError() {
1767 return false;
1768 }
1769
1770 /**
1771 * Perform a deadlock-prone transaction.
1772 *
1773 * This function invokes a callback function to perform a set of write
1774 * queries. If a deadlock occurs during the processing, the transaction
1775 * will be rolled back and the callback function will be called again.
1776 *
1777 * Usage:
1778 * $dbw->deadlockLoop( callback, ... );
1779 *
1780 * Extra arguments are passed through to the specified callback function.
1781 *
1782 * Returns whatever the callback function returned on its successful,
1783 * iteration, or false on error, for example if the retry limit was
1784 * reached.
1785 */
1786 function deadlockLoop() {
1787 $myFname = 'Database::deadlockLoop';
1788
1789 $this->begin();
1790 $args = func_get_args();
1791 $function = array_shift( $args );
1792 $oldIgnore = $this->ignoreErrors( true );
1793 $tries = DEADLOCK_TRIES;
1794 if ( is_array( $function ) ) {
1795 $fname = $function[0];
1796 } else {
1797 $fname = $function;
1798 }
1799 do {
1800 $retVal = call_user_func_array( $function, $args );
1801 $error = $this->lastError();
1802 $errno = $this->lastErrno();
1803 $sql = $this->lastQuery();
1804
1805 if ( $errno ) {
1806 if ( $this->wasDeadlock() ) {
1807 # Retry
1808 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1809 } else {
1810 $this->reportQueryError( $error, $errno, $sql, $fname );
1811 }
1812 }
1813 } while( $this->wasDeadlock() && --$tries > 0 );
1814 $this->ignoreErrors( $oldIgnore );
1815 if ( $tries <= 0 ) {
1816 $this->query( 'ROLLBACK', $myFname );
1817 $this->reportQueryError( $error, $errno, $sql, $fname );
1818 return false;
1819 } else {
1820 $this->query( 'COMMIT', $myFname );
1821 return $retVal;
1822 }
1823 }
1824
1825 /**
1826 * Do a SELECT MASTER_POS_WAIT()
1827 *
1828 * @param $pos MySQLMasterPos object
1829 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1830 */
1831 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1832 $fname = 'Database::masterPosWait';
1833 wfProfileIn( $fname );
1834
1835 # Commit any open transactions
1836 if ( $this->mTrxLevel ) {
1837 $this->immediateCommit();
1838 }
1839
1840 if ( !is_null( $this->mFakeSlaveLag ) ) {
1841 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1842 if ( $wait > $timeout * 1e6 ) {
1843 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1844 wfProfileOut( $fname );
1845 return -1;
1846 } elseif ( $wait > 0 ) {
1847 wfDebug( "Fake slave waiting $wait us\n" );
1848 usleep( $wait );
1849 wfProfileOut( $fname );
1850 return 1;
1851 } else {
1852 wfDebug( "Fake slave up to date ($wait us)\n" );
1853 wfProfileOut( $fname );
1854 return 0;
1855 }
1856 }
1857
1858 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1859 $encFile = $this->addQuotes( $pos->file );
1860 $encPos = intval( $pos->pos );
1861 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1862 $res = $this->doQuery( $sql );
1863 if ( $res && $row = $this->fetchRow( $res ) ) {
1864 $this->freeResult( $res );
1865 wfProfileOut( $fname );
1866 return $row[0];
1867 } else {
1868 wfProfileOut( $fname );
1869 return false;
1870 }
1871 }
1872
1873 /**
1874 * Get the position of the master from SHOW SLAVE STATUS
1875 */
1876 function getSlavePos() {
1877 if ( !is_null( $this->mFakeSlaveLag ) ) {
1878 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1879 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1880 return $pos;
1881 }
1882 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1883 $row = $this->fetchObject( $res );
1884 if ( $row ) {
1885 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1886 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1887 } else {
1888 return false;
1889 }
1890 }
1891
1892 /**
1893 * Get the position of the master from SHOW MASTER STATUS
1894 */
1895 function getMasterPos() {
1896 if ( $this->mFakeMaster ) {
1897 return new MySQLMasterPos( 'fake', microtime( true ) );
1898 }
1899 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1900 $row = $this->fetchObject( $res );
1901 if ( $row ) {
1902 return new MySQLMasterPos( $row->File, $row->Position );
1903 } else {
1904 return false;
1905 }
1906 }
1907
1908 /**
1909 * Begin a transaction, committing any previously open transaction
1910 */
1911 function begin( $fname = 'Database::begin' ) {
1912 $this->query( 'BEGIN', $fname );
1913 $this->mTrxLevel = 1;
1914 }
1915
1916 /**
1917 * End a transaction
1918 */
1919 function commit( $fname = 'Database::commit' ) {
1920 $this->query( 'COMMIT', $fname );
1921 $this->mTrxLevel = 0;
1922 }
1923
1924 /**
1925 * Rollback a transaction.
1926 * No-op on non-transactional databases.
1927 */
1928 function rollback( $fname = 'Database::rollback' ) {
1929 $this->query( 'ROLLBACK', $fname, true );
1930 $this->mTrxLevel = 0;
1931 }
1932
1933 /**
1934 * Begin a transaction, committing any previously open transaction
1935 * @deprecated use begin()
1936 */
1937 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1938 $this->begin();
1939 }
1940
1941 /**
1942 * Commit transaction, if one is open
1943 * @deprecated use commit()
1944 */
1945 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1946 $this->commit();
1947 }
1948
1949 /**
1950 * Return MW-style timestamp used for MySQL schema
1951 */
1952 function timestamp( $ts=0 ) {
1953 return wfTimestamp(TS_MW,$ts);
1954 }
1955
1956 /**
1957 * Local database timestamp format or null
1958 */
1959 function timestampOrNull( $ts = null ) {
1960 if( is_null( $ts ) ) {
1961 return null;
1962 } else {
1963 return $this->timestamp( $ts );
1964 }
1965 }
1966
1967 /**
1968 * @todo document
1969 */
1970 function resultObject( $result ) {
1971 if( empty( $result ) ) {
1972 return false;
1973 } elseif ( $result instanceof ResultWrapper ) {
1974 return $result;
1975 } elseif ( $result === true ) {
1976 // Successful write query
1977 return $result;
1978 } else {
1979 return new ResultWrapper( $this, $result );
1980 }
1981 }
1982
1983 /**
1984 * Return aggregated value alias
1985 */
1986 function aggregateValue ($valuedata,$valuename='value') {
1987 return $valuename;
1988 }
1989
1990 /**
1991 * Returns a wikitext link to the DB's website, e.g.,
1992 * return "[http://www.mysql.com/ MySQL]";
1993 * Should at least contain plain text, if for some reason
1994 * your database has no website.
1995 *
1996 * @return String: wikitext of a link to the server software's web site
1997 */
1998 abstract function getSoftwareLink();
1999
2000 /**
2001 * A string describing the current software version, like from
2002 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2003 *
2004 * @return String: Version information from the database
2005 */
2006 abstract function getServerVersion();
2007
2008 /**
2009 * Ping the server and try to reconnect if it there is no connection
2010 *
2011 * @return bool Success or failure
2012 */
2013 function ping() {
2014 # Stub. Not essential to override.
2015 return true;
2016 }
2017
2018 /**
2019 * Get slave lag.
2020 * At the moment, this will only work if the DB user has the PROCESS privilege
2021 */
2022 function getLag() {
2023 if ( !is_null( $this->mFakeSlaveLag ) ) {
2024 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2025 return $this->mFakeSlaveLag;
2026 }
2027 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
2028 # Find slave SQL thread
2029 while ( $row = $this->fetchObject( $res ) ) {
2030 /* This should work for most situations - when default db
2031 * for thread is not specified, it had no events executed,
2032 * and therefore it doesn't know yet how lagged it is.
2033 *
2034 * Relay log I/O thread does not select databases.
2035 */
2036 if ( $row->User == 'system user' &&
2037 $row->State != 'Waiting for master to send event' &&
2038 $row->State != 'Connecting to master' &&
2039 $row->State != 'Queueing master event to the relay log' &&
2040 $row->State != 'Waiting for master update' &&
2041 $row->State != 'Requesting binlog dump' &&
2042 $row->State != 'Waiting to reconnect after a failed master event read' &&
2043 $row->State != 'Reconnecting after a failed master event read' &&
2044 $row->State != 'Registering slave on master'
2045 ) {
2046 # This is it, return the time (except -ve)
2047 if ( $row->Time > 0x7fffffff ) {
2048 return false;
2049 } else {
2050 return $row->Time;
2051 }
2052 }
2053 }
2054 return false;
2055 }
2056
2057 /**
2058 * Get status information from SHOW STATUS in an associative array
2059 */
2060 function getStatus($which="%") {
2061 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2062 $status = array();
2063 while ( $row = $this->fetchObject( $res ) ) {
2064 $status[$row->Variable_name] = $row->Value;
2065 }
2066 return $status;
2067 }
2068
2069 /**
2070 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2071 */
2072 function maxListLen() {
2073 return 0;
2074 }
2075
2076 function encodeBlob($b) {
2077 return $b;
2078 }
2079
2080 function decodeBlob($b) {
2081 return $b;
2082 }
2083
2084 /**
2085 * Override database's default connection timeout. May be useful for very
2086 * long batch queries such as full-wiki dumps, where a single query reads
2087 * out over hours or days. May or may not be necessary for non-MySQL
2088 * databases. For most purposes, leaving it as a no-op should be fine.
2089 *
2090 * @param $timeout Integer in seconds
2091 */
2092 public function setTimeout( $timeout ) {}
2093
2094 /**
2095 * Read and execute SQL commands from a file.
2096 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2097 * @param $filename String: File name to open
2098 * @param $lineCallback Callback: Optional function called before reading each line
2099 * @param $resultCallback Callback: Optional function called for each MySQL result
2100 */
2101 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2102 $fp = fopen( $filename, 'r' );
2103 if ( false === $fp ) {
2104 throw new MWException( "Could not open \"{$filename}\".\n" );
2105 }
2106 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2107 fclose( $fp );
2108 return $error;
2109 }
2110
2111 /**
2112 * Get the full path of a patch file. Originally based on archive()
2113 * from updaters.inc. Keep in mind this always returns a patch, as
2114 * it fails back to MySQL if no DB-specific patch can be found
2115 *
2116 * @param $patch String The name of the patch, like patch-something.sql
2117 * @return String Full path to patch file
2118 */
2119 public static function patchPath( $patch ) {
2120 global $wgDBtype, $IP;
2121 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
2122 return "$IP/maintenance/$wgDBtype/archives/$name";
2123 } else {
2124 return "$IP/maintenance/archives/$name";
2125 }
2126 }
2127
2128 /**
2129 * Read and execute commands from an open file handle
2130 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2131 * @param $fp String: File handle
2132 * @param $lineCallback Callback: Optional function called before reading each line
2133 * @param $resultCallback Callback: Optional function called for each MySQL result
2134 */
2135 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2136 $cmd = "";
2137 $done = false;
2138 $dollarquote = false;
2139
2140 while ( ! feof( $fp ) ) {
2141 if ( $lineCallback ) {
2142 call_user_func( $lineCallback );
2143 }
2144 $line = trim( fgets( $fp, 1024 ) );
2145 $sl = strlen( $line ) - 1;
2146
2147 if ( $sl < 0 ) { continue; }
2148 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2149
2150 ## Allow dollar quoting for function declarations
2151 if (substr($line,0,4) == '$mw$') {
2152 if ($dollarquote) {
2153 $dollarquote = false;
2154 $done = true;
2155 }
2156 else {
2157 $dollarquote = true;
2158 }
2159 }
2160 else if (!$dollarquote) {
2161 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2162 $done = true;
2163 $line = substr( $line, 0, $sl );
2164 }
2165 }
2166
2167 if ( '' != $cmd ) { $cmd .= ' '; }
2168 $cmd .= "$line\n";
2169
2170 if ( $done ) {
2171 $cmd = str_replace(';;', ";", $cmd);
2172 $cmd = $this->replaceVars( $cmd );
2173 $res = $this->query( $cmd, __METHOD__ );
2174 if ( $resultCallback ) {
2175 call_user_func( $resultCallback, $res, $this );
2176 }
2177
2178 if ( false === $res ) {
2179 $err = $this->lastError();
2180 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2181 }
2182
2183 $cmd = '';
2184 $done = false;
2185 }
2186 }
2187 return true;
2188 }
2189
2190
2191 /**
2192 * Replace variables in sourced SQL
2193 */
2194 protected function replaceVars( $ins ) {
2195 $varnames = array(
2196 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2197 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2198 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2199 );
2200
2201 // Ordinary variables
2202 foreach ( $varnames as $var ) {
2203 if( isset( $GLOBALS[$var] ) ) {
2204 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2205 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2206 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2207 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2208 }
2209 }
2210
2211 // Table prefixes
2212 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2213 array( $this, 'tableNameCallback' ), $ins );
2214
2215 // Index names
2216 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2217 array( $this, 'indexNameCallback' ), $ins );
2218 return $ins;
2219 }
2220
2221 /**
2222 * Table name callback
2223 * @private
2224 */
2225 protected function tableNameCallback( $matches ) {
2226 return $this->tableName( $matches[1] );
2227 }
2228
2229 /**
2230 * Index name callback
2231 */
2232 protected function indexNameCallback( $matches ) {
2233 return $this->indexName( $matches[1] );
2234 }
2235
2236 /**
2237 * Build a concatenation list to feed into a SQL query
2238 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2239 * @return String
2240 */
2241 function buildConcat( $stringList ) {
2242 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2243 }
2244
2245 /**
2246 * Acquire a named lock
2247 *
2248 * Abstracted from Filestore::lock() so child classes can implement for
2249 * their own needs.
2250 *
2251 * @param $lockName String: Name of lock to aquire
2252 * @param $method String: Name of method calling us
2253 * @return bool
2254 */
2255 public function lock( $lockName, $method, $timeout = 5 ) {
2256 return true;
2257 }
2258
2259 /**
2260 * Release a lock.
2261 *
2262 * @param $lockName String: Name of lock to release
2263 * @param $method String: Name of method calling us
2264 *
2265 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2266 * @return Returns 1 if the lock was released, 0 if the lock was not established
2267 * by this thread (in which case the lock is not released), and NULL if the named
2268 * lock did not exist
2269 */
2270 public function unlock( $lockName, $method ) {
2271 return true;
2272 }
2273
2274 /**
2275 * Lock specific tables
2276 *
2277 * @param $read Array of tables to lock for read access
2278 * @param $write Array of tables to lock for write access
2279 * @param $method String name of caller
2280 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2281 */
2282 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2283 return true;
2284 }
2285
2286 /**
2287 * Unlock specific tables
2288 *
2289 * @param $method String the caller
2290 */
2291 public function unlockTables( $method ) {
2292 return true;
2293 }
2294
2295 /**
2296 * Get search engine class. All subclasses of this
2297 * need to implement this if they wish to use searching.
2298 *
2299 * @return String
2300 */
2301 public function getSearchEngine() {
2302 return "SearchMySQL";
2303 }
2304
2305 /**
2306 * Allow or deny "big selects" for this session only. This is done by setting
2307 * the sql_big_selects session variable.
2308 *
2309 * This is a MySQL-specific feature.
2310 *
2311 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2312 */
2313 public function setBigSelects( $value = true ) {
2314 // no-op
2315 }
2316 }
2317
2318
2319 /******************************************************************************
2320 * Utility classes
2321 *****************************************************************************/
2322
2323 /**
2324 * Utility class.
2325 * @ingroup Database
2326 */
2327 class DBObject {
2328 public $mData;
2329
2330 function DBObject($data) {
2331 $this->mData = $data;
2332 }
2333
2334 function isLOB() {
2335 return false;
2336 }
2337
2338 function data() {
2339 return $this->mData;
2340 }
2341 }
2342
2343 /**
2344 * Utility class
2345 * @ingroup Database
2346 *
2347 * This allows us to distinguish a blob from a normal string and an array of strings
2348 */
2349 class Blob {
2350 private $mData;
2351 function __construct($data) {
2352 $this->mData = $data;
2353 }
2354 function fetch() {
2355 return $this->mData;
2356 }
2357 }
2358
2359 /**
2360 * Utility class.
2361 * @ingroup Database
2362 */
2363 class MySQLField {
2364 private $name, $tablename, $default, $max_length, $nullable,
2365 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2366 function __construct ($info) {
2367 $this->name = $info->name;
2368 $this->tablename = $info->table;
2369 $this->default = $info->def;
2370 $this->max_length = $info->max_length;
2371 $this->nullable = !$info->not_null;
2372 $this->is_pk = $info->primary_key;
2373 $this->is_unique = $info->unique_key;
2374 $this->is_multiple = $info->multiple_key;
2375 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2376 $this->type = $info->type;
2377 }
2378
2379 function name() {
2380 return $this->name;
2381 }
2382
2383 function tableName() {
2384 return $this->tableName;
2385 }
2386
2387 function defaultValue() {
2388 return $this->default;
2389 }
2390
2391 function maxLength() {
2392 return $this->max_length;
2393 }
2394
2395 function nullable() {
2396 return $this->nullable;
2397 }
2398
2399 function isKey() {
2400 return $this->is_key;
2401 }
2402
2403 function isMultipleKey() {
2404 return $this->is_multiple;
2405 }
2406
2407 function type() {
2408 return $this->type;
2409 }
2410 }
2411
2412 /******************************************************************************
2413 * Error classes
2414 *****************************************************************************/
2415
2416 /**
2417 * Database error base class
2418 * @ingroup Database
2419 */
2420 class DBError extends MWException {
2421 public $db;
2422
2423 /**
2424 * Construct a database error
2425 * @param $db Database object which threw the error
2426 * @param $error A simple error message to be used for debugging
2427 */
2428 function __construct( DatabaseBase &$db, $error ) {
2429 $this->db =& $db;
2430 parent::__construct( $error );
2431 }
2432
2433 function getText() {
2434 global $wgShowDBErrorBacktrace;
2435 $s = $this->getMessage() . "\n";
2436 if ( $wgShowDBErrorBacktrace ) {
2437 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2438 }
2439 return $s;
2440 }
2441 }
2442
2443 /**
2444 * @ingroup Database
2445 */
2446 class DBConnectionError extends DBError {
2447 public $error;
2448
2449 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2450 $msg = 'DB connection error';
2451 if ( trim( $error ) != '' ) {
2452 $msg .= ": $error";
2453 }
2454 $this->error = $error;
2455 parent::__construct( $db, $msg );
2456 }
2457
2458 function useOutputPage() {
2459 // Not likely to work
2460 return false;
2461 }
2462
2463 function useMessageCache() {
2464 // Not likely to work
2465 return false;
2466 }
2467
2468 function getLogMessage() {
2469 # Don't send to the exception log
2470 return false;
2471 }
2472
2473 function getPageTitle() {
2474 global $wgSitename, $wgLang;
2475 $header = "$wgSitename has a problem";
2476 if ( $wgLang instanceof Language ) {
2477 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2478 }
2479
2480 return $header;
2481 }
2482
2483 function getHTML() {
2484 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2485
2486 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2487 $again = 'Try waiting a few minutes and reloading.';
2488 $info = '(Can\'t contact the database server: $1)';
2489
2490 if ( $wgLang instanceof Language ) {
2491 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2492 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2493 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2494 }
2495
2496 # No database access
2497 if ( is_object( $wgMessageCache ) ) {
2498 $wgMessageCache->disable();
2499 }
2500
2501 if ( trim( $this->error ) == '' ) {
2502 $this->error = $this->db->getProperty('mServer');
2503 }
2504
2505 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2506 $text = str_replace( '$1', $this->error, $noconnect );
2507
2508 if ( $wgShowDBErrorBacktrace ) {
2509 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2510 }
2511
2512 $extra = $this->searchForm();
2513
2514 if( $wgUseFileCache ) {
2515 try {
2516 $cache = $this->fileCachedPage();
2517 # Cached version on file system?
2518 if( $cache !== null ) {
2519 # Hack: extend the body for error messages
2520 $cache = str_replace( array('</html>','</body>'), '', $cache );
2521 # Add cache notice...
2522 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2523 # Localize it if possible...
2524 if( $wgLang instanceof Language ) {
2525 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2526 }
2527 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2528 # Output cached page with notices on bottom and re-close body
2529 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2530 }
2531 } catch( MWException $e ) {
2532 // Do nothing, just use the default page
2533 }
2534 }
2535 # Headers needed here - output is just the error message
2536 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2537 }
2538
2539 function searchForm() {
2540 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2541 $usegoogle = "You can try searching via Google in the meantime.";
2542 $outofdate = "Note that their indexes of our content may be out of date.";
2543 $googlesearch = "Search";
2544
2545 if ( $wgLang instanceof Language ) {
2546 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2547 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2548 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2549 }
2550
2551 $search = htmlspecialchars(@$_REQUEST['search']);
2552
2553 $trygoogle = <<<EOT
2554 <div style="margin: 1.5em">$usegoogle<br />
2555 <small>$outofdate</small></div>
2556 <!-- SiteSearch Google -->
2557 <form method="get" action="http://www.google.com/search" id="googlesearch">
2558 <input type="hidden" name="domains" value="$wgServer" />
2559 <input type="hidden" name="num" value="50" />
2560 <input type="hidden" name="ie" value="$wgInputEncoding" />
2561 <input type="hidden" name="oe" value="$wgInputEncoding" />
2562
2563 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2564
2565 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2566 <input type="submit" name="btnG" value="$googlesearch" />
2567 <div>
2568 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2569 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2570 </div>
2571 </form>
2572 <!-- SiteSearch Google -->
2573 EOT;
2574 return $trygoogle;
2575 }
2576
2577 function fileCachedPage() {
2578 global $wgTitle, $title, $wgLang, $wgOut;
2579 if( $wgOut->isDisabled() ) return; // Done already?
2580 $mainpage = 'Main Page';
2581 if ( $wgLang instanceof Language ) {
2582 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2583 }
2584
2585 if( $wgTitle ) {
2586 $t =& $wgTitle;
2587 } elseif( $title ) {
2588 $t = Title::newFromURL( $title );
2589 } else {
2590 $t = Title::newFromText( $mainpage );
2591 }
2592
2593 $cache = new HTMLFileCache( $t );
2594 if( $cache->isFileCached() ) {
2595 return $cache->fetchPageText();
2596 } else {
2597 return '';
2598 }
2599 }
2600
2601 function htmlBodyOnly() {
2602 return true;
2603 }
2604
2605 }
2606
2607 /**
2608 * @ingroup Database
2609 */
2610 class DBQueryError extends DBError {
2611 public $error, $errno, $sql, $fname;
2612
2613 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2614 $message = "A database error has occurred\n" .
2615 "Query: $sql\n" .
2616 "Function: $fname\n" .
2617 "Error: $errno $error\n";
2618
2619 parent::__construct( $db, $message );
2620 $this->error = $error;
2621 $this->errno = $errno;
2622 $this->sql = $sql;
2623 $this->fname = $fname;
2624 }
2625
2626 function getText() {
2627 global $wgShowDBErrorBacktrace;
2628 if ( $this->useMessageCache() ) {
2629 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2630 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2631 if ( $wgShowDBErrorBacktrace ) {
2632 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2633 }
2634 return $s;
2635 } else {
2636 return parent::getText();
2637 }
2638 }
2639
2640 function getSQL() {
2641 global $wgShowSQLErrors;
2642 if( !$wgShowSQLErrors ) {
2643 return $this->msg( 'sqlhidden', 'SQL hidden' );
2644 } else {
2645 return $this->sql;
2646 }
2647 }
2648
2649 function getLogMessage() {
2650 # Don't send to the exception log
2651 return false;
2652 }
2653
2654 function getPageTitle() {
2655 return $this->msg( 'databaseerror', 'Database error' );
2656 }
2657
2658 function getHTML() {
2659 global $wgShowDBErrorBacktrace;
2660 if ( $this->useMessageCache() ) {
2661 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2662 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2663 } else {
2664 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2665 }
2666 if ( $wgShowDBErrorBacktrace ) {
2667 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2668 }
2669 return $s;
2670 }
2671 }
2672
2673 /**
2674 * @ingroup Database
2675 */
2676 class DBUnexpectedError extends DBError {}
2677
2678
2679 /**
2680 * Result wrapper for grabbing data queried by someone else
2681 * @ingroup Database
2682 */
2683 class ResultWrapper implements Iterator {
2684 var $db, $result, $pos = 0, $currentRow = null;
2685
2686 /**
2687 * Create a new result object from a result resource and a Database object
2688 */
2689 function ResultWrapper( $database, $result ) {
2690 $this->db = $database;
2691 if ( $result instanceof ResultWrapper ) {
2692 $this->result = $result->result;
2693 } else {
2694 $this->result = $result;
2695 }
2696 }
2697
2698 /**
2699 * Get the number of rows in a result object
2700 */
2701 function numRows() {
2702 return $this->db->numRows( $this );
2703 }
2704
2705 /**
2706 * Fetch the next row from the given result object, in object form.
2707 * Fields can be retrieved with $row->fieldname, with fields acting like
2708 * member variables.
2709 *
2710 * @param $res SQL result object as returned from Database::query(), etc.
2711 * @return MySQL row object
2712 * @throws DBUnexpectedError Thrown if the database returns an error
2713 */
2714 function fetchObject() {
2715 return $this->db->fetchObject( $this );
2716 }
2717
2718 /**
2719 * Fetch the next row from the given result object, in associative array
2720 * form. Fields are retrieved with $row['fieldname'].
2721 *
2722 * @param $res SQL result object as returned from Database::query(), etc.
2723 * @return MySQL row object
2724 * @throws DBUnexpectedError Thrown if the database returns an error
2725 */
2726 function fetchRow() {
2727 return $this->db->fetchRow( $this );
2728 }
2729
2730 /**
2731 * Free a result object
2732 */
2733 function free() {
2734 $this->db->freeResult( $this );
2735 unset( $this->result );
2736 unset( $this->db );
2737 }
2738
2739 /**
2740 * Change the position of the cursor in a result object
2741 * See mysql_data_seek()
2742 */
2743 function seek( $row ) {
2744 $this->db->dataSeek( $this, $row );
2745 }
2746
2747 /*********************
2748 * Iterator functions
2749 * Note that using these in combination with the non-iterator functions
2750 * above may cause rows to be skipped or repeated.
2751 */
2752
2753 function rewind() {
2754 if ($this->numRows()) {
2755 $this->db->dataSeek($this, 0);
2756 }
2757 $this->pos = 0;
2758 $this->currentRow = null;
2759 }
2760
2761 function current() {
2762 if ( is_null( $this->currentRow ) ) {
2763 $this->next();
2764 }
2765 return $this->currentRow;
2766 }
2767
2768 function key() {
2769 return $this->pos;
2770 }
2771
2772 function next() {
2773 $this->pos++;
2774 $this->currentRow = $this->fetchObject();
2775 return $this->currentRow;
2776 }
2777
2778 function valid() {
2779 return $this->current() !== false;
2780 }
2781 }