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