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