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