1a046397cac7d132497e97a4540d2f656562ad49
[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 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
954 }
955
956 if ( isset( $options['HAVING'] ) ) {
957 $preLimitTail .= " HAVING {$options['HAVING']}";
958 }
959
960 if ( isset( $options['ORDER BY'] ) ) {
961 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
962 }
963
964 // if (isset($options['LIMIT'])) {
965 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
966 // isset($options['OFFSET']) ? $options['OFFSET']
967 // : false);
968 // }
969
970 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
971 $postLimitTail .= ' FOR UPDATE';
972 }
973
974 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
975 $postLimitTail .= ' LOCK IN SHARE MODE';
976 }
977
978 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
979 $startOpts .= 'DISTINCT';
980 }
981
982 # Various MySQL extensions
983 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
984 $startOpts .= ' /*! STRAIGHT_JOIN */';
985 }
986
987 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
988 $startOpts .= ' HIGH_PRIORITY';
989 }
990
991 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
992 $startOpts .= ' SQL_BIG_RESULT';
993 }
994
995 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
996 $startOpts .= ' SQL_BUFFER_RESULT';
997 }
998
999 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1000 $startOpts .= ' SQL_SMALL_RESULT';
1001 }
1002
1003 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1004 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1005 }
1006
1007 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1008 $startOpts .= ' SQL_CACHE';
1009 }
1010
1011 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1012 $startOpts .= ' SQL_NO_CACHE';
1013 }
1014
1015 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1016 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1017 } else {
1018 $useIndex = '';
1019 }
1020
1021 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1022 }
1023
1024 /**
1025 * SELECT wrapper
1026 *
1027 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1028 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1029 * @param $conds Mixed: Array or string, condition(s) for WHERE
1030 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1031 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1032 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1033 * @param $join_conds Array: Associative array of table join conditions (optional)
1034 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1035 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1036 */
1037 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1038 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1039
1040 return $this->query( $sql, $fname );
1041 }
1042
1043 /**
1044 * SELECT wrapper
1045 *
1046 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1047 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1048 * @param $conds Mixed: Array or string, condition(s) for WHERE
1049 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1050 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1051 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1052 * @param $join_conds Array: Associative array of table join conditions (optional)
1053 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1054 * @return string, the SQL text
1055 */
1056 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1057 if ( is_array( $vars ) ) {
1058 $vars = implode( ',', $vars );
1059 }
1060
1061 if ( !is_array( $options ) ) {
1062 $options = array( $options );
1063 }
1064
1065 if ( is_array( $table ) ) {
1066 if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1067 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1068 } else {
1069 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1070 }
1071 } elseif ( $table != '' ) {
1072 if ( $table { 0 } == ' ' ) {
1073 $from = ' FROM ' . $table;
1074 } else {
1075 $from = ' FROM ' . $this->tableName( $table );
1076 }
1077 } else {
1078 $from = '';
1079 }
1080
1081 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1082
1083 if ( !empty( $conds ) ) {
1084 if ( is_array( $conds ) ) {
1085 $conds = $this->makeList( $conds, LIST_AND );
1086 }
1087 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1088 } else {
1089 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1090 }
1091
1092 if ( isset( $options['LIMIT'] ) )
1093 $sql = $this->limitResult( $sql, $options['LIMIT'],
1094 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1095 $sql = "$sql $postLimitTail";
1096
1097 if ( isset( $options['EXPLAIN'] ) ) {
1098 $sql = 'EXPLAIN ' . $sql;
1099 }
1100
1101 return $sql;
1102 }
1103
1104 /**
1105 * Single row SELECT wrapper
1106 * Aborts or returns FALSE on error
1107 *
1108 * @param $table String: table name
1109 * @param $vars String: the selected variables
1110 * @param $conds Array: a condition map, terms are ANDed together.
1111 * Items with numeric keys are taken to be literal conditions
1112 * Takes an array of selected variables, and a condition map, which is ANDed
1113 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1114 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1115 * $obj- >page_id is the ID of the Astronomy article
1116 * @param $fname String: Calling function name
1117 * @param $options Array
1118 * @param $join_conds Array
1119 *
1120 * @todo migrate documentation to phpdocumentor format
1121 */
1122 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1123 $options['LIMIT'] = 1;
1124 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1125
1126 if ( $res === false ) {
1127 return false;
1128 }
1129
1130 if ( !$this->numRows( $res ) ) {
1131 return false;
1132 }
1133
1134 $obj = $this->fetchObject( $res );
1135
1136 return $obj;
1137 }
1138
1139 /**
1140 * Estimate rows in dataset
1141 * Returns estimated count - not necessarily an accurate estimate across different databases,
1142 * so use sparingly
1143 * Takes same arguments as DatabaseBase::select()
1144 *
1145 * @param $table String: table name
1146 * @param $vars Array: unused
1147 * @param $conds Array: filters on the table
1148 * @param $fname String: function name for profiling
1149 * @param $options Array: options for select
1150 * @return Integer: row count
1151 */
1152 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1153 $rows = 0;
1154 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1155
1156 if ( $res ) {
1157 $row = $this->fetchRow( $res );
1158 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1159 }
1160
1161 return $rows;
1162 }
1163
1164 /**
1165 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1166 * It's only slightly flawed. Don't use for anything important.
1167 *
1168 * @param $sql String: A SQL Query
1169 */
1170 static function generalizeSQL( $sql ) {
1171 # This does the same as the regexp below would do, but in such a way
1172 # as to avoid crashing php on some large strings.
1173 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1174
1175 $sql = str_replace ( "\\\\", '', $sql );
1176 $sql = str_replace ( "\\'", '', $sql );
1177 $sql = str_replace ( "\\\"", '', $sql );
1178 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1179 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1180
1181 # All newlines, tabs, etc replaced by single space
1182 $sql = preg_replace ( '/\s+/', ' ', $sql );
1183
1184 # All numbers => N
1185 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1186
1187 return $sql;
1188 }
1189
1190 /**
1191 * Determines whether a field exists in a table
1192 *
1193 * @param $table String: table name
1194 * @param $field String: filed to check on that table
1195 * @param $fname String: calling function name (optional)
1196 * @return Boolean: whether $table has filed $field
1197 */
1198 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1199 $info = $this->fieldInfo( $table, $field );
1200
1201 return (bool)$info;
1202 }
1203
1204 /**
1205 * Determines whether an index exists
1206 * Usually aborts on failure
1207 * If errors are explicitly ignored, returns NULL on failure
1208 */
1209 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1210 $info = $this->indexInfo( $table, $index, $fname );
1211 if ( is_null( $info ) ) {
1212 return null;
1213 } else {
1214 return $info !== false;
1215 }
1216 }
1217
1218 /**
1219 * Query whether a given table exists
1220 */
1221 function tableExists( $table ) {
1222 $table = $this->tableName( $table );
1223 $old = $this->ignoreErrors( true );
1224 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__ );
1225 $this->ignoreErrors( $old );
1226
1227 return (bool)$res;
1228 }
1229
1230 /**
1231 * mysql_field_type() wrapper
1232 */
1233 function fieldType( $res, $index ) {
1234 if ( $res instanceof ResultWrapper ) {
1235 $res = $res->result;
1236 }
1237
1238 return mysql_field_type( $res, $index );
1239 }
1240
1241 /**
1242 * Determines if a given index is unique
1243 */
1244 function indexUnique( $table, $index ) {
1245 $indexInfo = $this->indexInfo( $table, $index );
1246
1247 if ( !$indexInfo ) {
1248 return null;
1249 }
1250
1251 return !$indexInfo[0]->Non_unique;
1252 }
1253
1254 /**
1255 * INSERT wrapper, inserts an array into a table
1256 *
1257 * $a may be a single associative array, or an array of these with numeric keys, for
1258 * multi-row insert.
1259 *
1260 * Usually aborts on failure
1261 * If errors are explicitly ignored, returns success
1262 *
1263 * @param $table String: table name (prefix auto-added)
1264 * @param $a Array: Array of rows to insert
1265 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1266 * @param $options Mixed: Associative array of options
1267 *
1268 * @return bool
1269 */
1270 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1271 # No rows to insert, easy just return now
1272 if ( !count( $a ) ) {
1273 return true;
1274 }
1275
1276 $table = $this->tableName( $table );
1277
1278 if ( !is_array( $options ) ) {
1279 $options = array( $options );
1280 }
1281
1282 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1283 $multi = true;
1284 $keys = array_keys( $a[0] );
1285 } else {
1286 $multi = false;
1287 $keys = array_keys( $a );
1288 }
1289
1290 $sql = 'INSERT ' . implode( ' ', $options ) .
1291 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1292
1293 if ( $multi ) {
1294 $first = true;
1295 foreach ( $a as $row ) {
1296 if ( $first ) {
1297 $first = false;
1298 } else {
1299 $sql .= ',';
1300 }
1301 $sql .= '(' . $this->makeList( $row ) . ')';
1302 }
1303 } else {
1304 $sql .= '(' . $this->makeList( $a ) . ')';
1305 }
1306
1307 return (bool)$this->query( $sql, $fname );
1308 }
1309
1310 /**
1311 * Make UPDATE options for the DatabaseBase::update function
1312 *
1313 * @private
1314 * @param $options Array: The options passed to DatabaseBase::update
1315 * @return string
1316 */
1317 function makeUpdateOptions( $options ) {
1318 if ( !is_array( $options ) ) {
1319 $options = array( $options );
1320 }
1321
1322 $opts = array();
1323
1324 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1325 $opts[] = $this->lowPriorityOption();
1326 }
1327
1328 if ( in_array( 'IGNORE', $options ) ) {
1329 $opts[] = 'IGNORE';
1330 }
1331
1332 return implode( ' ', $opts );
1333 }
1334
1335 /**
1336 * UPDATE wrapper, takes a condition array and a SET array
1337 *
1338 * @param $table String: The table to UPDATE
1339 * @param $values Array: An array of values to SET
1340 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1341 * @param $fname String: The Class::Function calling this function
1342 * (for the log)
1343 * @param $options Array: An array of UPDATE options, can be one or
1344 * more of IGNORE, LOW_PRIORITY
1345 * @return Boolean
1346 */
1347 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1348 $table = $this->tableName( $table );
1349 $opts = $this->makeUpdateOptions( $options );
1350 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1351
1352 if ( $conds != '*' ) {
1353 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1354 }
1355
1356 return $this->query( $sql, $fname );
1357 }
1358
1359 /**
1360 * Makes an encoded list of strings from an array
1361 * $mode:
1362 * LIST_COMMA - comma separated, no field names
1363 * LIST_AND - ANDed WHERE clause (without the WHERE)
1364 * LIST_OR - ORed WHERE clause (without the WHERE)
1365 * LIST_SET - comma separated with field names, like a SET clause
1366 * LIST_NAMES - comma separated field names
1367 */
1368 function makeList( $a, $mode = LIST_COMMA ) {
1369 if ( !is_array( $a ) ) {
1370 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1371 }
1372
1373 $first = true;
1374 $list = '';
1375
1376 foreach ( $a as $field => $value ) {
1377 if ( !$first ) {
1378 if ( $mode == LIST_AND ) {
1379 $list .= ' AND ';
1380 } elseif ( $mode == LIST_OR ) {
1381 $list .= ' OR ';
1382 } else {
1383 $list .= ',';
1384 }
1385 } else {
1386 $first = false;
1387 }
1388
1389 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1390 $list .= "($value)";
1391 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1392 $list .= "$value";
1393 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1394 if ( count( $value ) == 0 ) {
1395 throw new MWException( __METHOD__ . ': empty input' );
1396 } elseif ( count( $value ) == 1 ) {
1397 // Special-case single values, as IN isn't terribly efficient
1398 // Don't necessarily assume the single key is 0; we don't
1399 // enforce linear numeric ordering on other arrays here.
1400 $value = array_values( $value );
1401 $list .= $field . " = " . $this->addQuotes( $value[0] );
1402 } else {
1403 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1404 }
1405 } elseif ( $value === null ) {
1406 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1407 $list .= "$field IS ";
1408 } elseif ( $mode == LIST_SET ) {
1409 $list .= "$field = ";
1410 }
1411 $list .= 'NULL';
1412 } else {
1413 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1414 $list .= "$field = ";
1415 }
1416 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1417 }
1418 }
1419
1420 return $list;
1421 }
1422
1423 /**
1424 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1425 * The keys on each level may be either integers or strings.
1426 *
1427 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1428 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1429 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1430 * @return Mixed: string SQL fragment, or false if no items in array.
1431 */
1432 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1433 $conds = array();
1434
1435 foreach ( $data as $base => $sub ) {
1436 if ( count( $sub ) ) {
1437 $conds[] = $this->makeList(
1438 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1439 LIST_AND );
1440 }
1441 }
1442
1443 if ( $conds ) {
1444 return $this->makeList( $conds, LIST_OR );
1445 } else {
1446 // Nothing to search for...
1447 return false;
1448 }
1449 }
1450
1451 /**
1452 * Bitwise operations
1453 */
1454
1455 function bitNot( $field ) {
1456 return "(~$field)";
1457 }
1458
1459 function bitAnd( $fieldLeft, $fieldRight ) {
1460 return "($fieldLeft & $fieldRight)";
1461 }
1462
1463 function bitOr( $fieldLeft, $fieldRight ) {
1464 return "($fieldLeft | $fieldRight)";
1465 }
1466
1467 /**
1468 * Change the current database
1469 *
1470 * @todo Explain what exactly will fail if this is not overridden.
1471 * @return bool Success or failure
1472 */
1473 function selectDB( $db ) {
1474 # Stub. Shouldn't cause serious problems if it's not overridden, but
1475 # if your database engine supports a concept similar to MySQL's
1476 # databases you may as well.
1477 $this->mDBname = $db;
1478 return true;
1479 }
1480
1481 /**
1482 * Get the current DB name
1483 */
1484 function getDBname() {
1485 return $this->mDBname;
1486 }
1487
1488 /**
1489 * Get the server hostname or IP address
1490 */
1491 function getServer() {
1492 return $this->mServer;
1493 }
1494
1495 /**
1496 * Format a table name ready for use in constructing an SQL query
1497 *
1498 * This does two important things: it quotes the table names to clean them up,
1499 * and it adds a table prefix if only given a table name with no quotes.
1500 *
1501 * All functions of this object which require a table name call this function
1502 * themselves. Pass the canonical name to such functions. This is only needed
1503 * when calling query() directly.
1504 *
1505 * @param $name String: database table name
1506 * @return String: full database name
1507 */
1508 function tableName( $name ) {
1509 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1510 # Skip the entire process when we have a string quoted on both ends.
1511 # Note that we check the end so that we will still quote any use of
1512 # use of `database`.table. But won't break things if someone wants
1513 # to query a database table with a dot in the name.
1514 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1515 return $name;
1516 }
1517
1518 # Lets test for any bits of text that should never show up in a table
1519 # name. Basically anything like JOIN or ON which are actually part of
1520 # SQL queries, but may end up inside of the table value to combine
1521 # sql. Such as how the API is doing.
1522 # Note that we use a whitespace test rather than a \b test to avoid
1523 # any remote case where a word like on may be inside of a table name
1524 # surrounded by symbols which may be considered word breaks.
1525 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1526 return $name;
1527 }
1528
1529 # Split database and table into proper variables.
1530 # We reverse the explode so that database.table and table both output
1531 # the correct table.
1532 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1533 if ( isset( $dbDetails[1] ) ) {
1534 @list( $table, $database ) = $dbDetails;
1535 } else {
1536 @list( $table ) = $dbDetails;
1537 }
1538 $prefix = $this->mTablePrefix; # Default prefix
1539
1540 # A database name has been specified in input. Quote the table name
1541 # because we don't want any prefixes added.
1542 if ( isset( $database ) ) {
1543 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1544 }
1545
1546 # Note that we use the long format because php will complain in in_array if
1547 # the input is not an array, and will complain in is_array if it is not set.
1548 if ( !isset( $database ) # Don't use shared database if pre selected.
1549 && isset( $wgSharedDB ) # We have a shared database
1550 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1551 && isset( $wgSharedTables )
1552 && is_array( $wgSharedTables )
1553 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1554 $database = $wgSharedDB;
1555 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1556 }
1557
1558 # Quote the $database and $table and apply the prefix if not quoted.
1559 if ( isset( $database ) ) {
1560 $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1561 }
1562 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1563
1564 # Merge our database and table into our final table name.
1565 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
1566
1567 return $tableName;
1568 }
1569
1570 /**
1571 * Fetch a number of table names into an array
1572 * This is handy when you need to construct SQL for joins
1573 *
1574 * Example:
1575 * extract($dbr->tableNames('user','watchlist'));
1576 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1577 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1578 */
1579 public function tableNames() {
1580 $inArray = func_get_args();
1581 $retVal = array();
1582
1583 foreach ( $inArray as $name ) {
1584 $retVal[$name] = $this->tableName( $name );
1585 }
1586
1587 return $retVal;
1588 }
1589
1590 /**
1591 * Fetch a number of table names into an zero-indexed numerical array
1592 * This is handy when you need to construct SQL for joins
1593 *
1594 * Example:
1595 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1596 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1597 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1598 */
1599 public function tableNamesN() {
1600 $inArray = func_get_args();
1601 $retVal = array();
1602
1603 foreach ( $inArray as $name ) {
1604 $retVal[] = $this->tableName( $name );
1605 }
1606
1607 return $retVal;
1608 }
1609
1610 /**
1611 * Get an aliased table name
1612 * e.g. tableName AS newTableName
1613 *
1614 * @param $name string Table name, see tableName()
1615 * @param $alias string Alias (optional)
1616 * @return string SQL name for aliased table. Will not alias a table to its own name
1617 */
1618 public function tableNameWithAlias( $name, $alias = false ) {
1619 if ( !$alias || $alias == $name ) {
1620 return $this->tableName( $name );
1621 } else {
1622 return $this->tableName( $name ) . ' `' . $alias . '`';
1623 }
1624 }
1625
1626 /**
1627 * Gets an array of aliased table names
1628 *
1629 * @param $tables array( [alias] => table )
1630 * @return array of strings, see tableNameWithAlias()
1631 */
1632 public function tableNamesWithAlias( $tables ) {
1633 $retval = array();
1634 foreach ( $tables as $alias => $table ) {
1635 if ( is_numeric( $alias ) ) {
1636 $alias = $table;
1637 }
1638 $retval[] = $this->tableNameWithAlias( $table, $alias );
1639 }
1640 return $retval;
1641 }
1642
1643 /**
1644 * @private
1645 */
1646 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1647 $ret = array();
1648 $retJOIN = array();
1649 $use_index_safe = is_array( $use_index ) ? $use_index : array();
1650 $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
1651
1652 foreach ( $tables as $alias => $table ) {
1653 if ( !is_string( $alias ) ) {
1654 // No alias? Set it equal to the table name
1655 $alias = $table;
1656 }
1657 // Is there a JOIN and INDEX clause for this table?
1658 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1659 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1660 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1661 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1662 if ( $on != '' ) {
1663 $tableClause .= ' ON (' . $on . ')';
1664 }
1665
1666 $retJOIN[] = $tableClause;
1667 // Is there an INDEX clause?
1668 } else if ( isset( $use_index_safe[$alias] ) ) {
1669 $tableClause = $this->tableNameWithAlias( $table, $alias );
1670 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1671 $ret[] = $tableClause;
1672 // Is there a JOIN clause?
1673 } else if ( isset( $join_conds_safe[$alias] ) ) {
1674 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1675 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1676 if ( $on != '' ) {
1677 $tableClause .= ' ON (' . $on . ')';
1678 }
1679
1680 $retJOIN[] = $tableClause;
1681 } else {
1682 $tableClause = $this->tableNameWithAlias( $table, $alias );
1683 $ret[] = $tableClause;
1684 }
1685 }
1686
1687 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1688 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1689 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1690
1691 // Compile our final table clause
1692 return implode( ' ', array( $straightJoins, $otherJoins ) );
1693 }
1694
1695 /**
1696 * Get the name of an index in a given table
1697 */
1698 function indexName( $index ) {
1699 // Backwards-compatibility hack
1700 $renamed = array(
1701 'ar_usertext_timestamp' => 'usertext_timestamp',
1702 'un_user_id' => 'user_id',
1703 'un_user_ip' => 'user_ip',
1704 );
1705
1706 if ( isset( $renamed[$index] ) ) {
1707 return $renamed[$index];
1708 } else {
1709 return $index;
1710 }
1711 }
1712
1713 /**
1714 * If it's a string, adds quotes and backslashes
1715 * Otherwise returns as-is
1716 */
1717 function addQuotes( $s ) {
1718 if ( $s === null ) {
1719 return 'NULL';
1720 } else {
1721 # This will also quote numeric values. This should be harmless,
1722 # and protects against weird problems that occur when they really
1723 # _are_ strings such as article titles and string->number->string
1724 # conversion is not 1:1.
1725 return "'" . $this->strencode( $s ) . "'";
1726 }
1727 }
1728
1729 /**
1730 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1731 * MySQL uses `backticks` while basically everything else uses double quotes.
1732 * Since MySQL is the odd one out here the double quotes are our generic
1733 * and we implement backticks in DatabaseMysql.
1734 */
1735 public function addIdentifierQuotes( $s ) {
1736 return '"' . str_replace( '"', '""', $s ) . '"';
1737 }
1738
1739 /**
1740 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1741 * which used quote_ident which does not follow our naming conventions
1742 * was renamed to addIdentifierQuotes.
1743 * @deprecated use addIdentifierQuotes
1744 */
1745 function quote_ident( $s ) {
1746 wfDeprecated( __METHOD__ );
1747 return $this->addIdentifierQuotes( $s );
1748 }
1749
1750 /**
1751 * Escape string for safe LIKE usage.
1752 * WARNING: you should almost never use this function directly,
1753 * instead use buildLike() that escapes everything automatically
1754 * Deprecated in 1.17, warnings in 1.17, removed in ???
1755 */
1756 public function escapeLike( $s ) {
1757 wfDeprecated( __METHOD__ );
1758 return $this->escapeLikeInternal( $s );
1759 }
1760
1761 protected function escapeLikeInternal( $s ) {
1762 $s = str_replace( '\\', '\\\\', $s );
1763 $s = $this->strencode( $s );
1764 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1765
1766 return $s;
1767 }
1768
1769 /**
1770 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1771 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1772 * Alternatively, the function could be provided with an array of aforementioned parameters.
1773 *
1774 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1775 * for subpages of 'My page title'.
1776 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1777 *
1778 * @since 1.16
1779 * @return String: fully built LIKE statement
1780 */
1781 function buildLike() {
1782 $params = func_get_args();
1783
1784 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1785 $params = $params[0];
1786 }
1787
1788 $s = '';
1789
1790 foreach ( $params as $value ) {
1791 if ( $value instanceof LikeMatch ) {
1792 $s .= $value->toString();
1793 } else {
1794 $s .= $this->escapeLikeInternal( $value );
1795 }
1796 }
1797
1798 return " LIKE '" . $s . "' ";
1799 }
1800
1801 /**
1802 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1803 */
1804 function anyChar() {
1805 return new LikeMatch( '_' );
1806 }
1807
1808 /**
1809 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1810 */
1811 function anyString() {
1812 return new LikeMatch( '%' );
1813 }
1814
1815 /**
1816 * Returns an appropriately quoted sequence value for inserting a new row.
1817 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1818 * subclass will return an integer, and save the value for insertId()
1819 */
1820 function nextSequenceValue( $seqName ) {
1821 return null;
1822 }
1823
1824 /**
1825 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1826 * is only needed because a) MySQL must be as efficient as possible due to
1827 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1828 * which index to pick. Anyway, other databases might have different
1829 * indexes on a given table. So don't bother overriding this unless you're
1830 * MySQL.
1831 */
1832 function useIndexClause( $index ) {
1833 return '';
1834 }
1835
1836 /**
1837 * REPLACE query wrapper
1838 * PostgreSQL simulates this with a DELETE followed by INSERT
1839 * $row is the row to insert, an associative array
1840 * $uniqueIndexes is an array of indexes. Each element may be either a
1841 * field name or an array of field names
1842 *
1843 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1844 * However if you do this, you run the risk of encountering errors which wouldn't have
1845 * occurred in MySQL
1846 *
1847 * @param $table String: The table to replace the row(s) in.
1848 * @param $uniqueIndexes Array: An associative array of indexes
1849 * @param $rows Array: Array of rows to replace
1850 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1851 */
1852 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1853 $table = $this->tableName( $table );
1854
1855 # Single row case
1856 if ( !is_array( reset( $rows ) ) ) {
1857 $rows = array( $rows );
1858 }
1859
1860 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1861 $first = true;
1862
1863 foreach ( $rows as $row ) {
1864 if ( $first ) {
1865 $first = false;
1866 } else {
1867 $sql .= ',';
1868 }
1869
1870 $sql .= '(' . $this->makeList( $row ) . ')';
1871 }
1872
1873 return $this->query( $sql, $fname );
1874 }
1875
1876 /**
1877 * DELETE where the condition is a join
1878 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1879 *
1880 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1881 * join condition matches, set $conds='*'
1882 *
1883 * DO NOT put the join condition in $conds
1884 *
1885 * @param $delTable String: The table to delete from.
1886 * @param $joinTable String: The other table.
1887 * @param $delVar String: The variable to join on, in the first table.
1888 * @param $joinVar String: The variable to join on, in the second table.
1889 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1890 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1891 */
1892 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1893 if ( !$conds ) {
1894 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1895 }
1896
1897 $delTable = $this->tableName( $delTable );
1898 $joinTable = $this->tableName( $joinTable );
1899 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1900
1901 if ( $conds != '*' ) {
1902 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1903 }
1904
1905 return $this->query( $sql, $fname );
1906 }
1907
1908 /**
1909 * Returns the size of a text field, or -1 for "unlimited"
1910 */
1911 function textFieldSize( $table, $field ) {
1912 $table = $this->tableName( $table );
1913 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1914 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1915 $row = $this->fetchObject( $res );
1916
1917 $m = array();
1918
1919 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1920 $size = $m[1];
1921 } else {
1922 $size = -1;
1923 }
1924
1925 return $size;
1926 }
1927
1928 /**
1929 * A string to insert into queries to show that they're low-priority, like
1930 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1931 * string and nothing bad should happen.
1932 *
1933 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1934 */
1935 function lowPriorityOption() {
1936 return '';
1937 }
1938
1939 /**
1940 * DELETE query wrapper
1941 *
1942 * Use $conds == "*" to delete all rows
1943 */
1944 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1945 if ( !$conds ) {
1946 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1947 }
1948
1949 $table = $this->tableName( $table );
1950 $sql = "DELETE FROM $table";
1951
1952 if ( $conds != '*' ) {
1953 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1954 }
1955
1956 return $this->query( $sql, $fname );
1957 }
1958
1959 /**
1960 * INSERT SELECT wrapper
1961 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1962 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1963 * $conds may be "*" to copy the whole table
1964 * srcTable may be an array of tables.
1965 */
1966 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1967 $insertOptions = array(), $selectOptions = array() )
1968 {
1969 $destTable = $this->tableName( $destTable );
1970
1971 if ( is_array( $insertOptions ) ) {
1972 $insertOptions = implode( ' ', $insertOptions );
1973 }
1974
1975 if ( !is_array( $selectOptions ) ) {
1976 $selectOptions = array( $selectOptions );
1977 }
1978
1979 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1980
1981 if ( is_array( $srcTable ) ) {
1982 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1983 } else {
1984 $srcTable = $this->tableName( $srcTable );
1985 }
1986
1987 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1988 " SELECT $startOpts " . implode( ',', $varMap ) .
1989 " FROM $srcTable $useIndex ";
1990
1991 if ( $conds != '*' ) {
1992 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1993 }
1994
1995 $sql .= " $tailOpts";
1996
1997 return $this->query( $sql, $fname );
1998 }
1999
2000 /**
2001 * Construct a LIMIT query with optional offset. This is used for query
2002 * pages. The SQL should be adjusted so that only the first $limit rows
2003 * are returned. If $offset is provided as well, then the first $offset
2004 * rows should be discarded, and the next $limit rows should be returned.
2005 * If the result of the query is not ordered, then the rows to be returned
2006 * are theoretically arbitrary.
2007 *
2008 * $sql is expected to be a SELECT, if that makes a difference. For
2009 * UPDATE, limitResultForUpdate should be used.
2010 *
2011 * The version provided by default works in MySQL and SQLite. It will very
2012 * likely need to be overridden for most other DBMSes.
2013 *
2014 * @param $sql String: SQL query we will append the limit too
2015 * @param $limit Integer: the SQL limit
2016 * @param $offset Integer the SQL offset (default false)
2017 */
2018 function limitResult( $sql, $limit, $offset = false ) {
2019 if ( !is_numeric( $limit ) ) {
2020 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2021 }
2022
2023 return "$sql LIMIT "
2024 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2025 . "{$limit} ";
2026 }
2027
2028 function limitResultForUpdate( $sql, $num ) {
2029 return $this->limitResult( $sql, $num, 0 );
2030 }
2031
2032 /**
2033 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2034 * within the UNION construct.
2035 * @return Boolean
2036 */
2037 function unionSupportsOrderAndLimit() {
2038 return true; // True for almost every DB supported
2039 }
2040
2041 /**
2042 * Construct a UNION query
2043 * This is used for providing overload point for other DB abstractions
2044 * not compatible with the MySQL syntax.
2045 * @param $sqls Array: SQL statements to combine
2046 * @param $all Boolean: use UNION ALL
2047 * @return String: SQL fragment
2048 */
2049 function unionQueries( $sqls, $all ) {
2050 $glue = $all ? ') UNION ALL (' : ') UNION (';
2051 return '(' . implode( $glue, $sqls ) . ')';
2052 }
2053
2054 /**
2055 * Returns an SQL expression for a simple conditional. This doesn't need
2056 * to be overridden unless CASE isn't supported in your DBMS.
2057 *
2058 * @param $cond String: SQL expression which will result in a boolean value
2059 * @param $trueVal String: SQL expression to return if true
2060 * @param $falseVal String: SQL expression to return if false
2061 * @return String: SQL fragment
2062 */
2063 function conditional( $cond, $trueVal, $falseVal ) {
2064 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2065 }
2066
2067 /**
2068 * Returns a comand for str_replace function in SQL query.
2069 * Uses REPLACE() in MySQL
2070 *
2071 * @param $orig String: column to modify
2072 * @param $old String: column to seek
2073 * @param $new String: column to replace with
2074 */
2075 function strreplace( $orig, $old, $new ) {
2076 return "REPLACE({$orig}, {$old}, {$new})";
2077 }
2078
2079 /**
2080 * Determines if the last failure was due to a deadlock
2081 * STUB
2082 */
2083 function wasDeadlock() {
2084 return false;
2085 }
2086
2087 /**
2088 * Determines if the last query error was something that should be dealt
2089 * with by pinging the connection and reissuing the query.
2090 * STUB
2091 */
2092 function wasErrorReissuable() {
2093 return false;
2094 }
2095
2096 /**
2097 * Determines if the last failure was due to the database being read-only.
2098 * STUB
2099 */
2100 function wasReadOnlyError() {
2101 return false;
2102 }
2103
2104 /**
2105 * Perform a deadlock-prone transaction.
2106 *
2107 * This function invokes a callback function to perform a set of write
2108 * queries. If a deadlock occurs during the processing, the transaction
2109 * will be rolled back and the callback function will be called again.
2110 *
2111 * Usage:
2112 * $dbw->deadlockLoop( callback, ... );
2113 *
2114 * Extra arguments are passed through to the specified callback function.
2115 *
2116 * Returns whatever the callback function returned on its successful,
2117 * iteration, or false on error, for example if the retry limit was
2118 * reached.
2119 */
2120 function deadlockLoop() {
2121 $myFname = 'DatabaseBase::deadlockLoop';
2122
2123 $this->begin();
2124 $args = func_get_args();
2125 $function = array_shift( $args );
2126 $oldIgnore = $this->ignoreErrors( true );
2127 $tries = DEADLOCK_TRIES;
2128
2129 if ( is_array( $function ) ) {
2130 $fname = $function[0];
2131 } else {
2132 $fname = $function;
2133 }
2134
2135 do {
2136 $retVal = call_user_func_array( $function, $args );
2137 $error = $this->lastError();
2138 $errno = $this->lastErrno();
2139 $sql = $this->lastQuery();
2140
2141 if ( $errno ) {
2142 if ( $this->wasDeadlock() ) {
2143 # Retry
2144 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2145 } else {
2146 $this->reportQueryError( $error, $errno, $sql, $fname );
2147 }
2148 }
2149 } while ( $this->wasDeadlock() && --$tries > 0 );
2150
2151 $this->ignoreErrors( $oldIgnore );
2152
2153 if ( $tries <= 0 ) {
2154 $this->rollback( $myFname );
2155 $this->reportQueryError( $error, $errno, $sql, $fname );
2156 return false;
2157 } else {
2158 $this->commit( $myFname );
2159 return $retVal;
2160 }
2161 }
2162
2163 /**
2164 * Do a SELECT MASTER_POS_WAIT()
2165 *
2166 * @param $pos MySQLMasterPos object
2167 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2168 */
2169 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
2170 $fname = 'DatabaseBase::masterPosWait';
2171 wfProfileIn( $fname );
2172
2173 # Commit any open transactions
2174 if ( $this->mTrxLevel ) {
2175 $this->commit();
2176 }
2177
2178 if ( !is_null( $this->mFakeSlaveLag ) ) {
2179 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2180
2181 if ( $wait > $timeout * 1e6 ) {
2182 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2183 wfProfileOut( $fname );
2184 return -1;
2185 } elseif ( $wait > 0 ) {
2186 wfDebug( "Fake slave waiting $wait us\n" );
2187 usleep( $wait );
2188 wfProfileOut( $fname );
2189 return 1;
2190 } else {
2191 wfDebug( "Fake slave up to date ($wait us)\n" );
2192 wfProfileOut( $fname );
2193 return 0;
2194 }
2195 }
2196
2197 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2198 $encFile = $this->addQuotes( $pos->file );
2199 $encPos = intval( $pos->pos );
2200 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2201 $res = $this->doQuery( $sql );
2202
2203 if ( $res && $row = $this->fetchRow( $res ) ) {
2204 wfProfileOut( $fname );
2205 return $row[0];
2206 } else {
2207 wfProfileOut( $fname );
2208 return false;
2209 }
2210 }
2211
2212 /**
2213 * Get the position of the master from SHOW SLAVE STATUS
2214 */
2215 function getSlavePos() {
2216 if ( !is_null( $this->mFakeSlaveLag ) ) {
2217 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2218 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2219 return $pos;
2220 }
2221
2222 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2223 $row = $this->fetchObject( $res );
2224
2225 if ( $row ) {
2226 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
2227 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
2228 } else {
2229 return false;
2230 }
2231 }
2232
2233 /**
2234 * Get the position of the master from SHOW MASTER STATUS
2235 */
2236 function getMasterPos() {
2237 if ( $this->mFakeMaster ) {
2238 return new MySQLMasterPos( 'fake', microtime( true ) );
2239 }
2240
2241 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2242 $row = $this->fetchObject( $res );
2243
2244 if ( $row ) {
2245 return new MySQLMasterPos( $row->File, $row->Position );
2246 } else {
2247 return false;
2248 }
2249 }
2250
2251 /**
2252 * Begin a transaction, committing any previously open transaction
2253 */
2254 function begin( $fname = 'DatabaseBase::begin' ) {
2255 $this->query( 'BEGIN', $fname );
2256 $this->mTrxLevel = 1;
2257 }
2258
2259 /**
2260 * End a transaction
2261 */
2262 function commit( $fname = 'DatabaseBase::commit' ) {
2263 if ( $this->mTrxLevel ) {
2264 $this->query( 'COMMIT', $fname );
2265 $this->mTrxLevel = 0;
2266 }
2267 }
2268
2269 /**
2270 * Rollback a transaction.
2271 * No-op on non-transactional databases.
2272 */
2273 function rollback( $fname = 'DatabaseBase::rollback' ) {
2274 if ( $this->mTrxLevel ) {
2275 $this->query( 'ROLLBACK', $fname, true );
2276 $this->mTrxLevel = 0;
2277 }
2278 }
2279
2280 /**
2281 * Begin a transaction, committing any previously open transaction
2282 * @deprecated use begin()
2283 */
2284 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2285 wfDeprecated( __METHOD__ );
2286 $this->begin();
2287 }
2288
2289 /**
2290 * Commit transaction, if one is open
2291 * @deprecated use commit()
2292 */
2293 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2294 wfDeprecated( __METHOD__ );
2295 $this->commit();
2296 }
2297
2298 /**
2299 * Creates a new table with structure copied from existing table
2300 * Note that unlike most database abstraction functions, this function does not
2301 * automatically append database prefix, because it works at a lower
2302 * abstraction level.
2303 *
2304 * @param $oldName String: name of table whose structure should be copied
2305 * @param $newName String: name of table to be created
2306 * @param $temporary Boolean: whether the new table should be temporary
2307 * @param $fname String: calling function name
2308 * @return Boolean: true if operation was successful
2309 */
2310 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2311 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2312 }
2313
2314 /**
2315 * List all tables on the database
2316 *
2317 * @param $prefix Only show tables with this prefix, e.g. mw_
2318 * @param $fname String: calling function name
2319 */
2320 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2321 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2322 }
2323
2324 /**
2325 * Return MW-style timestamp used for MySQL schema
2326 */
2327 function timestamp( $ts = 0 ) {
2328 return wfTimestamp( TS_MW, $ts );
2329 }
2330
2331 /**
2332 * Local database timestamp format or null
2333 */
2334 function timestampOrNull( $ts = null ) {
2335 if ( is_null( $ts ) ) {
2336 return null;
2337 } else {
2338 return $this->timestamp( $ts );
2339 }
2340 }
2341
2342 /**
2343 * @todo document
2344 */
2345 function resultObject( $result ) {
2346 if ( empty( $result ) ) {
2347 return false;
2348 } elseif ( $result instanceof ResultWrapper ) {
2349 return $result;
2350 } elseif ( $result === true ) {
2351 // Successful write query
2352 return $result;
2353 } else {
2354 return new ResultWrapper( $this, $result );
2355 }
2356 }
2357
2358 /**
2359 * Return aggregated value alias
2360 */
2361 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2362 return $valuename;
2363 }
2364
2365 /**
2366 * Ping the server and try to reconnect if it there is no connection
2367 *
2368 * @return bool Success or failure
2369 */
2370 function ping() {
2371 # Stub. Not essential to override.
2372 return true;
2373 }
2374
2375 /**
2376 * Get slave lag.
2377 * Currently supported only by MySQL
2378 * @return Database replication lag in seconds
2379 */
2380 function getLag() {
2381 return intval( $this->mFakeSlaveLag );
2382 }
2383
2384 /**
2385 * Get status information from SHOW STATUS in an associative array
2386 */
2387 function getStatus( $which = "%" ) {
2388 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2389 $status = array();
2390
2391 foreach ( $res as $row ) {
2392 $status[$row->Variable_name] = $row->Value;
2393 }
2394
2395 return $status;
2396 }
2397
2398 /**
2399 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2400 */
2401 function maxListLen() {
2402 return 0;
2403 }
2404
2405 function encodeBlob( $b ) {
2406 return $b;
2407 }
2408
2409 function decodeBlob( $b ) {
2410 return $b;
2411 }
2412
2413 /**
2414 * Override database's default connection timeout. May be useful for very
2415 * long batch queries such as full-wiki dumps, where a single query reads
2416 * out over hours or days. May or may not be necessary for non-MySQL
2417 * databases. For most purposes, leaving it as a no-op should be fine.
2418 *
2419 * @param $timeout Integer in seconds
2420 */
2421 public function setTimeout( $timeout ) {}
2422
2423 /**
2424 * Read and execute SQL commands from a file.
2425 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2426 * @param $filename String: File name to open
2427 * @param $lineCallback Callback: Optional function called before reading each line
2428 * @param $resultCallback Callback: Optional function called for each MySQL result
2429 * @param $fname String: Calling function name or false if name should be generated dynamically
2430 * using $filename
2431 */
2432 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2433 wfSuppressWarnings();
2434 $fp = fopen( $filename, 'r' );
2435 wfRestoreWarnings();
2436
2437 if ( false === $fp ) {
2438 throw new MWException( "Could not open \"{$filename}\".\n" );
2439 }
2440
2441 if ( !$fname ) {
2442 $fname = __METHOD__ . "( $filename )";
2443 }
2444
2445 try {
2446 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2447 }
2448 catch ( MWException $e ) {
2449 fclose( $fp );
2450 throw $e;
2451 }
2452
2453 fclose( $fp );
2454
2455 return $error;
2456 }
2457
2458 /**
2459 * Get the full path of a patch file. Originally based on archive()
2460 * from updaters.inc. Keep in mind this always returns a patch, as
2461 * it fails back to MySQL if no DB-specific patch can be found
2462 *
2463 * @param $patch String The name of the patch, like patch-something.sql
2464 * @return String Full path to patch file
2465 */
2466 public function patchPath( $patch ) {
2467 global $IP;
2468
2469 $dbType = $this->getType();
2470 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2471 return "$IP/maintenance/$dbType/archives/$patch";
2472 } else {
2473 return "$IP/maintenance/archives/$patch";
2474 }
2475 }
2476
2477 /**
2478 * Set variables to be used in sourceFile/sourceStream, in preference to the
2479 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2480 * all. If it's set to false, $GLOBALS will be used.
2481 *
2482 * @param $vars False, or array mapping variable name to value.
2483 */
2484 function setSchemaVars( $vars ) {
2485 $this->mSchemaVars = $vars;
2486 }
2487
2488 /**
2489 * Read and execute commands from an open file handle
2490 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2491 * @param $fp String: File handle
2492 * @param $lineCallback Callback: Optional function called before reading each line
2493 * @param $resultCallback Callback: Optional function called for each MySQL result
2494 * @param $fname String: Calling function name
2495 */
2496 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2497 $cmd = "";
2498 $done = false;
2499 $dollarquote = false;
2500
2501 while ( ! feof( $fp ) ) {
2502 if ( $lineCallback ) {
2503 call_user_func( $lineCallback );
2504 }
2505
2506 $line = trim( fgets( $fp, 1024 ) );
2507 $sl = strlen( $line ) - 1;
2508
2509 if ( $sl < 0 ) {
2510 continue;
2511 }
2512
2513 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2514 continue;
2515 }
2516
2517 # # Allow dollar quoting for function declarations
2518 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2519 if ( $dollarquote ) {
2520 $dollarquote = false;
2521 $done = true;
2522 }
2523 else {
2524 $dollarquote = true;
2525 }
2526 }
2527 else if ( !$dollarquote ) {
2528 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
2529 $done = true;
2530 $line = substr( $line, 0, $sl );
2531 }
2532 }
2533
2534 if ( $cmd != '' ) {
2535 $cmd .= ' ';
2536 }
2537
2538 $cmd .= "$line\n";
2539
2540 if ( $done ) {
2541 $cmd = str_replace( ';;', ";", $cmd );
2542 $cmd = $this->replaceVars( $cmd );
2543 $res = $this->query( $cmd, $fname );
2544
2545 if ( $resultCallback ) {
2546 call_user_func( $resultCallback, $res, $this );
2547 }
2548
2549 if ( false === $res ) {
2550 $err = $this->lastError();
2551 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2552 }
2553
2554 $cmd = '';
2555 $done = false;
2556 }
2557 }
2558
2559 return true;
2560 }
2561
2562 /**
2563 * Database independent variable replacement, replaces a set of variables
2564 * in a sql statement with their contents as given by $this->getSchemaVars().
2565 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2566 *
2567 * '{$var}' should be used for text and is passed through the database's addQuotes method
2568 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2569 * the database's addIdentifierQuotes method which can be overridden if the database
2570 * uses something other than backticks.
2571 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2572 *
2573 * @param $ins String: SQL statement to replace variables in
2574 * @return String The new SQL statement with variables replaced
2575 */
2576 protected function replaceSchemaVars( $ins ) {
2577 $vars = $this->getSchemaVars();
2578 foreach ( $vars as $var => $value ) {
2579 // replace '{$var}'
2580 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2581 // replace `{$var}`
2582 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2583 // replace /*$var*/
2584 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2585 }
2586 return $ins;
2587 }
2588
2589 /**
2590 * Replace variables in sourced SQL
2591 */
2592 protected function replaceVars( $ins ) {
2593 $ins = $this->replaceSchemaVars( $ins );
2594
2595 // Table prefixes
2596 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2597 array( $this, 'tableNameCallback' ), $ins );
2598
2599 // Index names
2600 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2601 array( $this, 'indexNameCallback' ), $ins );
2602
2603 return $ins;
2604 }
2605
2606 /**
2607 * Get schema variables. If none have been set via setSchemaVars(), then
2608 * use some defaults from the current object.
2609 */
2610 protected function getSchemaVars() {
2611 if ( $this->mSchemaVars ) {
2612 return $this->mSchemaVars;
2613 } else {
2614 return $this->getDefaultSchemaVars();
2615 }
2616 }
2617
2618 /**
2619 * Get schema variables to use if none have been set via setSchemaVars().
2620 * Override this in derived classes to provide variables for tables.sql
2621 * and SQL patch files.
2622 */
2623 protected function getDefaultSchemaVars() {
2624 return array();
2625 }
2626
2627 /**
2628 * Table name callback
2629 * @private
2630 */
2631 protected function tableNameCallback( $matches ) {
2632 return $this->tableName( $matches[1] );
2633 }
2634
2635 /**
2636 * Index name callback
2637 */
2638 protected function indexNameCallback( $matches ) {
2639 return $this->indexName( $matches[1] );
2640 }
2641
2642 /**
2643 * Build a concatenation list to feed into a SQL query
2644 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2645 * @return String
2646 */
2647 function buildConcat( $stringList ) {
2648 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2649 }
2650
2651 /**
2652 * Acquire a named lock
2653 *
2654 * Abstracted from Filestore::lock() so child classes can implement for
2655 * their own needs.
2656 *
2657 * @param $lockName String: name of lock to aquire
2658 * @param $method String: name of method calling us
2659 * @param $timeout Integer: timeout
2660 * @return Boolean
2661 */
2662 public function lock( $lockName, $method, $timeout = 5 ) {
2663 return true;
2664 }
2665
2666 /**
2667 * Release a lock.
2668 *
2669 * @param $lockName String: Name of lock to release
2670 * @param $method String: Name of method calling us
2671 *
2672 * @return Returns 1 if the lock was released, 0 if the lock was not established
2673 * by this thread (in which case the lock is not released), and NULL if the named
2674 * lock did not exist
2675 */
2676 public function unlock( $lockName, $method ) {
2677 return true;
2678 }
2679
2680 /**
2681 * Lock specific tables
2682 *
2683 * @param $read Array of tables to lock for read access
2684 * @param $write Array of tables to lock for write access
2685 * @param $method String name of caller
2686 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2687 */
2688 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2689 return true;
2690 }
2691
2692 /**
2693 * Unlock specific tables
2694 *
2695 * @param $method String the caller
2696 */
2697 public function unlockTables( $method ) {
2698 return true;
2699 }
2700
2701 /**
2702 * Delete a table
2703 */
2704 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2705 if( !$this->tableExists( $tableName ) ) {
2706 return false;
2707 }
2708 $sql = "DROP TABLE " . $this->tableName( $tableName );
2709 if( $this->cascadingDeletes() ) {
2710 $sql .= " CASCADE";
2711 }
2712 return $this->query( $sql, $fName );
2713 }
2714
2715 /**
2716 * Get search engine class. All subclasses of this need to implement this
2717 * if they wish to use searching.
2718 *
2719 * @return String
2720 */
2721 public function getSearchEngine() {
2722 return 'SearchEngineDummy';
2723 }
2724
2725 /**
2726 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2727 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2728 * because "i" sorts after all numbers.
2729 *
2730 * @return String
2731 */
2732 public function getInfinity() {
2733 return 'infinity';
2734 }
2735
2736 /**
2737 * Allow or deny "big selects" for this session only. This is done by setting
2738 * the sql_big_selects session variable.
2739 *
2740 * This is a MySQL-specific feature.
2741 *
2742 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2743 */
2744 public function setBigSelects( $value = true ) {
2745 // no-op
2746 }
2747 }
2748
2749 /******************************************************************************
2750 * Utility classes
2751 *****************************************************************************/
2752
2753 /**
2754 * Utility class.
2755 * @ingroup Database
2756 */
2757 class DBObject {
2758 public $mData;
2759
2760 function __construct( $data ) {
2761 $this->mData = $data;
2762 }
2763
2764 function isLOB() {
2765 return false;
2766 }
2767
2768 function data() {
2769 return $this->mData;
2770 }
2771 }
2772
2773 /**
2774 * Utility class
2775 * @ingroup Database
2776 *
2777 * This allows us to distinguish a blob from a normal string and an array of strings
2778 */
2779 class Blob {
2780 private $mData;
2781
2782 function __construct( $data ) {
2783 $this->mData = $data;
2784 }
2785
2786 function fetch() {
2787 return $this->mData;
2788 }
2789 }
2790
2791 /**
2792 * Base for all database-specific classes representing information about database fields
2793 * @ingroup Database
2794 */
2795 interface Field {
2796 /**
2797 * Field name
2798 * @return string
2799 */
2800 function name();
2801
2802 /**
2803 * Name of table this field belongs to
2804 * @return string
2805 */
2806 function tableName();
2807
2808 /**
2809 * Database type
2810 * @return string
2811 */
2812 function type();
2813
2814 /**
2815 * Whether this field can store NULL values
2816 * @return bool
2817 */
2818 function isNullable();
2819 }
2820
2821 /******************************************************************************
2822 * Error classes
2823 *****************************************************************************/
2824
2825 /**
2826 * Database error base class
2827 * @ingroup Database
2828 */
2829 class DBError extends MWException {
2830 public $db;
2831
2832 /**
2833 * Construct a database error
2834 * @param $db Database object which threw the error
2835 * @param $error A simple error message to be used for debugging
2836 */
2837 function __construct( DatabaseBase &$db, $error ) {
2838 $this->db =& $db;
2839 parent::__construct( $error );
2840 }
2841
2842 function getText() {
2843 global $wgShowDBErrorBacktrace;
2844
2845 $s = $this->getMessage() . "\n";
2846
2847 if ( $wgShowDBErrorBacktrace ) {
2848 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2849 }
2850
2851 return $s;
2852 }
2853 }
2854
2855 /**
2856 * @ingroup Database
2857 */
2858 class DBConnectionError extends DBError {
2859 public $error;
2860
2861 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2862 $msg = 'DB connection error';
2863
2864 if ( trim( $error ) != '' ) {
2865 $msg .= ": $error";
2866 }
2867
2868 $this->error = $error;
2869
2870 parent::__construct( $db, $msg );
2871 }
2872
2873 function useOutputPage() {
2874 // Not likely to work
2875 return false;
2876 }
2877
2878 function useMessageCache() {
2879 // Not likely to work
2880 return false;
2881 }
2882
2883 function getLogMessage() {
2884 # Don't send to the exception log
2885 return false;
2886 }
2887
2888 function getPageTitle() {
2889 global $wgSitename, $wgLang;
2890
2891 $header = "$wgSitename has a problem";
2892
2893 if ( $wgLang instanceof Language ) {
2894 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2895 }
2896
2897 return $header;
2898 }
2899
2900 function getHTML() {
2901 global $wgLang, $wgUseFileCache, $wgShowDBErrorBacktrace;
2902
2903 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2904 $again = 'Try waiting a few minutes and reloading.';
2905 $info = '(Can\'t contact the database server: $1)';
2906
2907 if ( $wgLang instanceof Language ) {
2908 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2909 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2910 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2911 }
2912
2913 # No database access
2914 MessageCache::singleton()->disable();
2915
2916 if ( trim( $this->error ) == '' ) {
2917 $this->error = $this->db->getProperty( 'mServer' );
2918 }
2919
2920 $this->error = Html::element( 'span', array( 'dir' => 'ltr' ), $this->error );
2921
2922 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2923 $text = str_replace( '$1', $this->error, $noconnect );
2924
2925 if ( $wgShowDBErrorBacktrace ) {
2926 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2927 }
2928
2929 $extra = $this->searchForm();
2930
2931 if ( $wgUseFileCache ) {
2932 try {
2933 $cache = $this->fileCachedPage();
2934 # Cached version on file system?
2935 if ( $cache !== null ) {
2936 # Hack: extend the body for error messages
2937 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2938 # Add cache notice...
2939 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2940
2941 # Localize it if possible...
2942 if ( $wgLang instanceof Language ) {
2943 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2944 }
2945
2946 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2947
2948 # Output cached page with notices on bottom and re-close body
2949 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2950 }
2951 } catch ( MWException $e ) {
2952 // Do nothing, just use the default page
2953 }
2954 }
2955
2956 # Headers needed here - output is just the error message
2957 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2958 }
2959
2960 function searchForm() {
2961 global $wgSitename, $wgServer, $wgLang;
2962
2963 $usegoogle = "You can try searching via Google in the meantime.";
2964 $outofdate = "Note that their indexes of our content may be out of date.";
2965 $googlesearch = "Search";
2966
2967 if ( $wgLang instanceof Language ) {
2968 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2969 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2970 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2971 }
2972
2973 $search = htmlspecialchars( @$_REQUEST['search'] );
2974
2975 $server = htmlspecialchars( $wgServer );
2976 $sitename = htmlspecialchars( $wgSitename );
2977
2978 $trygoogle = <<<EOT
2979 <div style="margin: 1.5em">$usegoogle<br />
2980 <small>$outofdate</small></div>
2981 <!-- SiteSearch Google -->
2982 <form method="get" action="http://www.google.com/search" id="googlesearch">
2983 <input type="hidden" name="domains" value="$server" />
2984 <input type="hidden" name="num" value="50" />
2985 <input type="hidden" name="ie" value="UTF-8" />
2986 <input type="hidden" name="oe" value="UTF-8" />
2987
2988 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2989 <input type="submit" name="btnG" value="$googlesearch" />
2990 <div>
2991 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
2992 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2993 </div>
2994 </form>
2995 <!-- SiteSearch Google -->
2996 EOT;
2997 return $trygoogle;
2998 }
2999
3000 private function fileCachedPage() {
3001 global $wgTitle, $wgLang, $wgOut;
3002
3003 if ( $wgOut->isDisabled() ) {
3004 return; // Done already?
3005 }
3006
3007 $mainpage = 'Main Page';
3008
3009 if ( $wgLang instanceof Language ) {
3010 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
3011 }
3012
3013 if ( $wgTitle ) {
3014 $t =& $wgTitle;
3015 } else {
3016 $t = Title::newFromText( $mainpage );
3017 }
3018
3019 $cache = new HTMLFileCache( $t );
3020 if ( $cache->isFileCached() ) {
3021 return $cache->fetchPageText();
3022 } else {
3023 return '';
3024 }
3025 }
3026
3027 function htmlBodyOnly() {
3028 return true;
3029 }
3030 }
3031
3032 /**
3033 * @ingroup Database
3034 */
3035 class DBQueryError extends DBError {
3036 public $error, $errno, $sql, $fname;
3037
3038 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
3039 $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" .
3040 "Query: $sql\n" .
3041 "Function: $fname\n" .
3042 "Error: $errno $error\n";
3043
3044 parent::__construct( $db, $message );
3045
3046 $this->error = $error;
3047 $this->errno = $errno;
3048 $this->sql = $sql;
3049 $this->fname = $fname;
3050 }
3051
3052 function getText() {
3053 global $wgShowDBErrorBacktrace;
3054
3055 if ( $this->useMessageCache() ) {
3056 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
3057 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
3058
3059 if ( $wgShowDBErrorBacktrace ) {
3060 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
3061 }
3062
3063 return $s;
3064 } else {
3065 return parent::getText();
3066 }
3067 }
3068
3069 function getSQL() {
3070 global $wgShowSQLErrors;
3071
3072 if ( !$wgShowSQLErrors ) {
3073 return $this->msg( 'sqlhidden', 'SQL hidden' );
3074 } else {
3075 return $this->sql;
3076 }
3077 }
3078
3079 function getLogMessage() {
3080 # Don't send to the exception log
3081 return false;
3082 }
3083
3084 function getPageTitle() {
3085 return $this->msg( 'databaseerror', 'Database error' );
3086 }
3087
3088 function getHTML() {
3089 global $wgShowDBErrorBacktrace;
3090
3091 if ( $this->useMessageCache() ) {
3092 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
3093 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
3094 } else {
3095 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
3096 }
3097
3098 if ( $wgShowDBErrorBacktrace ) {
3099 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3100 }
3101
3102 return $s;
3103 }
3104 }
3105
3106 /**
3107 * @ingroup Database
3108 */
3109 class DBUnexpectedError extends DBError {}
3110
3111
3112 /**
3113 * Result wrapper for grabbing data queried by someone else
3114 * @ingroup Database
3115 */
3116 class ResultWrapper implements Iterator {
3117 var $db, $result, $pos = 0, $currentRow = null;
3118
3119 /**
3120 * Create a new result object from a result resource and a Database object
3121 */
3122 function __construct( $database, $result ) {
3123 $this->db = $database;
3124
3125 if ( $result instanceof ResultWrapper ) {
3126 $this->result = $result->result;
3127 } else {
3128 $this->result = $result;
3129 }
3130 }
3131
3132 /**
3133 * Get the number of rows in a result object
3134 */
3135 function numRows() {
3136 return $this->db->numRows( $this );
3137 }
3138
3139 /**
3140 * Fetch the next row from the given result object, in object form.
3141 * Fields can be retrieved with $row->fieldname, with fields acting like
3142 * member variables.
3143 *
3144 * @return MySQL row object
3145 * @throws DBUnexpectedError Thrown if the database returns an error
3146 */
3147 function fetchObject() {
3148 return $this->db->fetchObject( $this );
3149 }
3150
3151 /**
3152 * Fetch the next row from the given result object, in associative array
3153 * form. Fields are retrieved with $row['fieldname'].
3154 *
3155 * @return MySQL row object
3156 * @throws DBUnexpectedError Thrown if the database returns an error
3157 */
3158 function fetchRow() {
3159 return $this->db->fetchRow( $this );
3160 }
3161
3162 /**
3163 * Free a result object
3164 */
3165 function free() {
3166 $this->db->freeResult( $this );
3167 unset( $this->result );
3168 unset( $this->db );
3169 }
3170
3171 /**
3172 * Change the position of the cursor in a result object
3173 * See mysql_data_seek()
3174 */
3175 function seek( $row ) {
3176 $this->db->dataSeek( $this, $row );
3177 }
3178
3179 /*********************
3180 * Iterator functions
3181 * Note that using these in combination with the non-iterator functions
3182 * above may cause rows to be skipped or repeated.
3183 */
3184
3185 function rewind() {
3186 if ( $this->numRows() ) {
3187 $this->db->dataSeek( $this, 0 );
3188 }
3189 $this->pos = 0;
3190 $this->currentRow = null;
3191 }
3192
3193 function current() {
3194 if ( is_null( $this->currentRow ) ) {
3195 $this->next();
3196 }
3197 return $this->currentRow;
3198 }
3199
3200 function key() {
3201 return $this->pos;
3202 }
3203
3204 function next() {
3205 $this->pos++;
3206 $this->currentRow = $this->fetchObject();
3207 return $this->currentRow;
3208 }
3209
3210 function valid() {
3211 return $this->current() !== false;
3212 }
3213 }
3214
3215 /**
3216 * Overloads the relevant methods of the real ResultsWrapper so it
3217 * doesn't go anywhere near an actual database.
3218 */
3219 class FakeResultWrapper extends ResultWrapper {
3220 var $result = array();
3221 var $db = null; // And it's going to stay that way :D
3222 var $pos = 0;
3223 var $currentRow = null;
3224
3225 function __construct( $array ) {
3226 $this->result = $array;
3227 }
3228
3229 function numRows() {
3230 return count( $this->result );
3231 }
3232
3233 function fetchRow() {
3234 $this->currentRow = $this->result[$this->pos++];
3235 return $this->currentRow;
3236 }
3237
3238 function seek( $row ) {
3239 $this->pos = $row;
3240 }
3241
3242 function free() {}
3243
3244 // Callers want to be able to access fields with $this->fieldName
3245 function fetchObject() {
3246 $this->currentRow = $this->result[$this->pos++];
3247 return (object)$this->currentRow;
3248 }
3249
3250 function rewind() {
3251 $this->pos = 0;
3252 $this->currentRow = null;
3253 }
3254 }
3255
3256 /**
3257 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3258 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3259 */
3260 class LikeMatch {
3261 private $str;
3262
3263 public function __construct( $s ) {
3264 $this->str = $s;
3265 }
3266
3267 public function toString() {
3268 return $this->str;
3269 }
3270 }