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