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