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