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