3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
15 * Database abstraction object
16 * @addtogroup Database
20 #------------------------------------------------------------------------------
22 #------------------------------------------------------------------------------
24 protected $mLastQuery = '';
26 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
27 protected $mOut, $mOpened = false;
29 protected $mFailFunction;
30 protected $mTablePrefix;
32 protected $mTrxLevel = 0;
33 protected $mErrorCount = 0;
34 protected $mLBInfo = array();
35 protected $mFakeSlaveLag = null, $mFakeMaster = false;
37 #------------------------------------------------------------------------------
39 #------------------------------------------------------------------------------
40 # These optionally set a variable and return the previous state
43 * Fail function, takes a Database as a parameter
44 * Set to false for default, 1 for ignore errors
46 function failFunction( $function = NULL ) {
47 return wfSetVar( $this->mFailFunction
, $function );
51 * Output page, used for reporting errors
52 * FALSE means discard output
54 function setOutputPage( $out ) {
59 * Boolean, controls output of large amounts of debug information
61 function debug( $debug = NULL ) {
62 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
66 * Turns buffering of SQL result sets on (true) or off (false).
67 * Default is "on" and it should not be changed without good reasons.
69 function bufferResults( $buffer = NULL ) {
70 if ( is_null( $buffer ) ) {
71 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
73 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
78 * Turns on (false) or off (true) the automatic generation and sending
79 * of a "we're sorry, but there has been a database error" page on
80 * database errors. Default is on (false). When turned off, the
81 * code should use lastErrno() and lastError() to handle the
82 * situation as appropriate.
84 function ignoreErrors( $ignoreErrors = NULL ) {
85 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
89 * The current depth of nested transactions
90 * @param $level Integer: , default NULL.
92 function trxLevel( $level = NULL ) {
93 return wfSetVar( $this->mTrxLevel
, $level );
97 * Number of errors logged, only useful when errors are ignored
99 function errorCount( $count = NULL ) {
100 return wfSetVar( $this->mErrorCount
, $count );
103 function tablePrefix( $prefix = null ) {
104 return wfSetVar( $this->mTablePrefix
, $prefix );
108 * Properties passed down from the server info array of the load balancer
110 function getLBInfo( $name = NULL ) {
111 if ( is_null( $name ) ) {
112 return $this->mLBInfo
;
114 if ( array_key_exists( $name, $this->mLBInfo
) ) {
115 return $this->mLBInfo
[$name];
122 function setLBInfo( $name, $value = NULL ) {
123 if ( is_null( $value ) ) {
124 $this->mLBInfo
= $name;
126 $this->mLBInfo
[$name] = $value;
131 * Set lag time in seconds for a fake slave
133 function setFakeSlaveLag( $lag ) {
134 $this->mFakeSlaveLag
= $lag;
138 * Make this connection a fake master
140 function setFakeMaster( $enabled = true ) {
141 $this->mFakeMaster
= $enabled;
145 * Returns true if this database supports (and uses) cascading deletes
147 function cascadingDeletes() {
152 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
154 function cleanupTriggers() {
159 * Returns true if this database is strict about what can be put into an IP field.
160 * Specifically, it uses a NULL value instead of an empty string.
162 function strictIPs() {
167 * Returns true if this database uses timestamps rather than integers
169 function realTimestamps() {
174 * Returns true if this database does an implicit sort when doing GROUP BY
176 function implicitGroupby() {
181 * Returns true if this database does an implicit order by when the column has an index
182 * For example: SELECT page_title FROM page LIMIT 1
184 function implicitOrderby() {
189 * Returns true if this database can do a native search on IP columns
190 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
192 function searchableIPs() {
197 * Returns true if this database can use functional indexes
199 function functionalIndexes() {
206 function lastQuery() { return $this->mLastQuery
; }
207 function isOpen() { return $this->mOpened
; }
210 function setFlag( $flag ) {
211 $this->mFlags |
= $flag;
214 function clearFlag( $flag ) {
215 $this->mFlags
&= ~
$flag;
218 function getFlag( $flag ) {
219 return !!($this->mFlags
& $flag);
223 * General read-only accessor
225 function getProperty( $name ) {
229 function getWikiID() {
230 if( $this->mTablePrefix
) {
231 return "{$this->mDBname}-{$this->mTablePrefix}";
233 return $this->mDBname
;
237 #------------------------------------------------------------------------------
239 #------------------------------------------------------------------------------
243 * @param string $server database server host
244 * @param string $user database user name
245 * @param string $password database user password
246 * @param string $dbname database name
247 * @param failFunction
249 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
251 function __construct( $server = false, $user = false, $password = false, $dbName = false,
252 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
254 global $wgOut, $wgDBprefix, $wgCommandLineMode;
255 # Can't get a reference if it hasn't been set yet
256 if ( !isset( $wgOut ) ) {
259 $this->mOut
=& $wgOut;
261 $this->mFailFunction
= $failFunction;
262 $this->mFlags
= $flags;
264 if ( $this->mFlags
& DBO_DEFAULT
) {
265 if ( $wgCommandLineMode ) {
266 $this->mFlags
&= ~DBO_TRX
;
268 $this->mFlags |
= DBO_TRX
;
273 // Faster read-only access
274 if ( wfReadOnly() ) {
275 $this->mFlags |= DBO_PERSISTENT;
276 $this->mFlags &= ~DBO_TRX;
279 /** Get the default table prefix*/
280 if ( $tablePrefix == 'get from global' ) {
281 $this->mTablePrefix
= $wgDBprefix;
283 $this->mTablePrefix
= $tablePrefix;
287 $this->open( $server, $user, $password, $dbName );
293 * @param failFunction
296 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
298 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
302 * Usually aborts on failure
303 * If the failFunction is set to a non-zero integer, returns success
305 function open( $server, $user, $password, $dbName ) {
306 global $wguname, $wgAllDBsAreLocalhost;
307 wfProfileIn( __METHOD__
);
309 # Test for missing mysql.so
310 # First try to load it
311 if (!@extension_loaded
('mysql')) {
316 # Otherwise we get a suppressed fatal error, which is very hard to track down
317 if ( !function_exists( 'mysql_connect' ) ) {
318 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
321 # Debugging hack -- fake cluster
322 if ( $wgAllDBsAreLocalhost ) {
323 $realServer = 'localhost';
325 $realServer = $server;
328 $this->mServer
= $server;
329 $this->mUser
= $user;
330 $this->mPassword
= $password;
331 $this->mDBname
= $dbName;
335 wfProfileIn("dbconnect-$server");
337 # Try to connect up to three times
338 # The kernel's default SYN retransmission period is far too slow for us,
339 # so we use a short timeout plus a manual retry.
340 $this->mConn
= false;
342 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
346 if ( $this->mFlags
& DBO_PERSISTENT
) {
347 @/**/$this->mConn
= mysql_pconnect( $realServer, $user, $password );
349 # Create a new connection...
350 @/**/$this->mConn
= mysql_connect( $realServer, $user, $password, true );
352 if ($this->mConn
=== false) {
354 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
358 wfProfileOut("dbconnect-$server");
360 if ( $dbName != '' ) {
361 if ( $this->mConn
!== false ) {
362 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
364 $error = "Error selecting database $dbName on server {$this->mServer} " .
365 "from client host {$wguname['nodename']}\n";
366 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
370 wfDebug( "DB connection error\n" );
371 wfDebug( "Server: $server, User: $user, Password: " .
372 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
377 $success = (bool)$this->mConn
;
381 $version = $this->getServerVersion();
382 if ( version_compare( $version, '4.1' ) >= 0 ) {
383 // Tell the server we're communicating with it in UTF-8.
384 // This may engage various charset conversions.
387 $this->query( 'SET NAMES utf8', __METHOD__
);
389 // Turn off strict mode
390 $this->query( "SET sql_mode = ''", __METHOD__
);
393 // Turn off strict mode if it is on
395 $this->reportConnectionError();
398 $this->mOpened
= $success;
399 wfProfileOut( __METHOD__
);
405 * Closes a database connection.
406 * if it is open : commits any open transactions
408 * @return bool operation success. true if already closed.
412 $this->mOpened
= false;
413 if ( $this->mConn
) {
414 if ( $this->trxLevel() ) {
415 $this->immediateCommit();
417 return mysql_close( $this->mConn
);
424 * @param string $error fallback error message, used if none is given by MySQL
426 function reportConnectionError( $error = 'Unknown error' ) {
427 $myError = $this->lastError();
432 if ( $this->mFailFunction
) {
433 # Legacy error handling method
434 if ( !is_int( $this->mFailFunction
) ) {
435 $ff = $this->mFailFunction
;
436 $ff( $this, $error );
440 wfLogDBError( "Connection error: $error\n" );
441 throw new DBConnectionError( $this, $error );
446 * Usually aborts on failure. If errors are explicitly ignored, returns success.
448 * @param $sql String: SQL query
449 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
450 * comment (you can use __METHOD__ or add some extra info)
451 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
452 * maybe best to catch the exception instead?
453 * @return true for a successful write query, ResultWrapper object for a successful read query,
454 * or false on failure if $tempIgnore set
455 * @throws DBQueryError Thrown when the database returns an error of any kind
457 public function query( $sql, $fname = '', $tempIgnore = false ) {
460 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
461 if ( isset( $wgProfiler ) ) {
462 # generalizeSQL will probably cut down the query to reasonable
463 # logging size most of the time. The substr is really just a sanity check.
465 # Who's been wasting my precious column space? -- TS
466 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
469 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
470 $totalProf = 'Database::query-master';
472 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
473 $totalProf = 'Database::query';
475 wfProfileIn( $totalProf );
476 wfProfileIn( $queryProf );
479 $this->mLastQuery
= $sql;
481 # Add a comment for easy SHOW PROCESSLIST interpretation
484 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
485 $userName = $wgUser->getName();
486 if ( mb_strlen( $userName ) > 15 ) {
487 $userName = mb_substr( $userName, 0, 15 ) . '...';
489 $userName = str_replace( '/', '', $userName );
493 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
495 # $commentedSql = $sql;
498 # If DBO_TRX is set, start a transaction
499 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
500 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
501 // avoid establishing transactions for SHOW and SET statements too -
502 // that would delay transaction initializations to once connection
503 // is really used by application
504 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
505 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
509 if ( $this->debug() ) {
510 $sqlx = substr( $commentedSql, 0, 500 );
511 $sqlx = strtr( $sqlx, "\t\n", ' ' );
513 wfDebug( "SQL-master: $sqlx\n" );
515 wfDebug( "SQL: $sqlx\n" );
519 # Do the query and handle errors
520 $ret = $this->doQuery( $commentedSql );
522 # Try reconnecting if the connection was lost
523 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
524 # Transaction is gone, like it or not
525 $this->mTrxLevel
= 0;
526 wfDebug( "Connection lost, reconnecting...\n" );
527 if ( $this->ping() ) {
528 wfDebug( "Reconnected\n" );
529 $sqlx = substr( $commentedSql, 0, 500 );
530 $sqlx = strtr( $sqlx, "\t\n", ' ' );
531 global $wgRequestTime;
532 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
533 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
534 $ret = $this->doQuery( $commentedSql );
536 wfDebug( "Failed\n" );
540 if ( false === $ret ) {
541 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
544 if ( isset( $wgProfiler ) ) {
545 wfProfileOut( $queryProf );
546 wfProfileOut( $totalProf );
548 return $this->resultObject( $ret );
552 * The DBMS-dependent part of query()
553 * @param $sql String: SQL query.
554 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
557 /*private*/ function doQuery( $sql ) {
558 if( $this->bufferResults() ) {
559 $ret = mysql_query( $sql, $this->mConn
);
561 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
570 * @param string $fname
571 * @param bool $tempIgnore
573 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
574 global $wgCommandLineMode;
575 # Ignore errors during error handling to avoid infinite recursion
576 $ignore = $this->ignoreErrors( true );
577 ++
$this->mErrorCount
;
579 if( $ignore ||
$tempIgnore ) {
580 wfDebug("SQL ERROR (ignored): $error\n");
581 $this->ignoreErrors( $ignore );
583 $sql1line = str_replace( "\n", "\\n", $sql );
584 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
585 wfDebug("SQL ERROR: " . $error . "\n");
586 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
592 * Intended to be compatible with the PEAR::DB wrapper functions.
593 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
595 * ? = scalar value, quoted as necessary
596 * ! = raw SQL bit (a function for instance)
597 * & = filename; reads the file and inserts as a blob
598 * (we don't use this though...)
600 function prepare( $sql, $func = 'Database::prepare' ) {
601 /* MySQL doesn't support prepared statements (yet), so just
602 pack up the query for reference. We'll manually replace
604 return array( 'query' => $sql, 'func' => $func );
607 function freePrepared( $prepared ) {
608 /* No-op for MySQL */
612 * Execute a prepared query with the various arguments
613 * @param string $prepared the prepared sql
614 * @param mixed $args Either an array here, or put scalars as varargs
616 function execute( $prepared, $args = null ) {
617 if( !is_array( $args ) ) {
619 $args = func_get_args();
620 array_shift( $args );
622 $sql = $this->fillPrepared( $prepared['query'], $args );
623 return $this->query( $sql, $prepared['func'] );
627 * Prepare & execute an SQL statement, quoting and inserting arguments
628 * in the appropriate places.
629 * @param string $query
630 * @param string $args ...
632 function safeQuery( $query, $args = null ) {
633 $prepared = $this->prepare( $query, 'Database::safeQuery' );
634 if( !is_array( $args ) ) {
636 $args = func_get_args();
637 array_shift( $args );
639 $retval = $this->execute( $prepared, $args );
640 $this->freePrepared( $prepared );
645 * For faking prepared SQL statements on DBs that don't support
647 * @param string $preparedSql - a 'preparable' SQL statement
648 * @param array $args - array of arguments to fill it with
649 * @return string executable SQL
651 function fillPrepared( $preparedQuery, $args ) {
653 $this->preparedArgs
=& $args;
654 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
655 array( &$this, 'fillPreparedArg' ), $preparedQuery );
659 * preg_callback func for fillPrepared()
660 * The arguments should be in $this->preparedArgs and must not be touched
661 * while we're doing this.
663 * @param array $matches
667 function fillPreparedArg( $matches ) {
668 switch( $matches[1] ) {
669 case '\\?': return '?';
670 case '\\!': return '!';
671 case '\\&': return '&';
673 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
674 switch( $matches[1] ) {
675 case '?': return $this->addQuotes( $arg );
676 case '!': return $arg;
678 # return $this->addQuotes( file_get_contents( $arg ) );
679 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
681 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
686 * @param mixed $res A SQL result
689 * Free a result object
691 function freeResult( $res ) {
692 if ( $res instanceof ResultWrapper
) {
695 if ( !@/**/mysql_free_result( $res ) ) {
696 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
701 * Fetch the next row from the given result object, in object form.
702 * Fields can be retrieved with $row->fieldname, with fields acting like
705 * @param $res SQL result object as returned from Database::query(), etc.
706 * @return MySQL row object
707 * @throws DBUnexpectedError Thrown if the database returns an error
709 function fetchObject( $res ) {
710 if ( $res instanceof ResultWrapper
) {
713 @/**/$row = mysql_fetch_object( $res );
714 if( $this->lastErrno() ) {
715 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
721 * Fetch the next row from the given result object, in associative array
722 * form. Fields are retrieved with $row['fieldname'].
724 * @param $res SQL result object as returned from Database::query(), etc.
725 * @return MySQL row object
726 * @throws DBUnexpectedError Thrown if the database returns an error
728 function fetchRow( $res ) {
729 if ( $res instanceof ResultWrapper
) {
732 @/**/$row = mysql_fetch_array( $res );
733 if ( $this->lastErrno() ) {
734 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
740 * Get the number of rows in a result object
742 function numRows( $res ) {
743 if ( $res instanceof ResultWrapper
) {
746 @/**/$n = mysql_num_rows( $res );
747 if( $this->lastErrno() ) {
748 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
754 * Get the number of fields in a result object
755 * See documentation for mysql_num_fields()
757 function numFields( $res ) {
758 if ( $res instanceof ResultWrapper
) {
761 return mysql_num_fields( $res );
765 * Get a field name in a result object
766 * See documentation for mysql_field_name():
767 * http://www.php.net/mysql_field_name
769 function fieldName( $res, $n ) {
770 if ( $res instanceof ResultWrapper
) {
773 return mysql_field_name( $res, $n );
777 * Get the inserted value of an auto-increment row
779 * The value inserted should be fetched from nextSequenceValue()
782 * $id = $dbw->nextSequenceValue('page_page_id_seq');
783 * $dbw->insert('page',array('page_id' => $id));
784 * $id = $dbw->insertId();
786 function insertId() { return mysql_insert_id( $this->mConn
); }
789 * Change the position of the cursor in a result object
790 * See mysql_data_seek()
792 function dataSeek( $res, $row ) {
793 if ( $res instanceof ResultWrapper
) {
796 return mysql_data_seek( $res, $row );
800 * Get the last error number
803 function lastErrno() {
804 if ( $this->mConn
) {
805 return mysql_errno( $this->mConn
);
807 return mysql_errno();
812 * Get a description of the last error
813 * See mysql_error() for more details
815 function lastError() {
816 if ( $this->mConn
) {
817 # Even if it's non-zero, it can still be invalid
818 wfSuppressWarnings();
819 $error = mysql_error( $this->mConn
);
821 $error = mysql_error();
825 $error = mysql_error();
828 $error .= ' (' . $this->mServer
. ')';
833 * Get the number of rows affected by the last write query
834 * See mysql_affected_rows() for more details
836 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
837 /**#@-*/ // end of template : @param $result
840 * Simple UPDATE wrapper
841 * Usually aborts on failure
842 * If errors are explicitly ignored, returns success
844 * This function exists for historical reasons, Database::update() has a more standard
845 * calling convention and feature set
847 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
849 $table = $this->tableName( $table );
850 $sql = "UPDATE $table SET $var = '" .
851 $this->strencode( $value ) . "' WHERE ($cond)";
852 return (bool)$this->query( $sql, $fname );
856 * Simple SELECT wrapper, returns a single field, input must be encoded
857 * Usually aborts on failure
858 * If errors are explicitly ignored, returns FALSE on failure
860 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
861 if ( !is_array( $options ) ) {
862 $options = array( $options );
864 $options['LIMIT'] = 1;
866 $res = $this->select( $table, $var, $cond, $fname, $options );
867 if ( $res === false ||
!$this->numRows( $res ) ) {
870 $row = $this->fetchRow( $res );
871 if ( $row !== false ) {
872 $this->freeResult( $res );
880 * Returns an optional USE INDEX clause to go after the table, and a
881 * string to go at the end of the query
885 * @param array $options an associative array of options to be turned into
886 * an SQL query, valid keys are listed in the function.
889 function makeSelectOptions( $options ) {
890 $preLimitTail = $postLimitTail = '';
893 $noKeyOptions = array();
894 foreach ( $options as $key => $option ) {
895 if ( is_numeric( $key ) ) {
896 $noKeyOptions[$option] = true;
900 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
901 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
902 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
904 //if (isset($options['LIMIT'])) {
905 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
906 // isset($options['OFFSET']) ? $options['OFFSET']
910 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
911 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
912 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
914 # Various MySQL extensions
915 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
916 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
917 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
918 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
919 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
920 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
921 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
922 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
924 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
925 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
930 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
936 * @param mixed $table Array or string, table name(s) (prefix auto-added)
937 * @param mixed $vars Array or string, field name(s) to be retrieved
938 * @param mixed $conds Array or string, condition(s) for WHERE
939 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
940 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
941 * see Database::makeSelectOptions code for list of supported stuff
942 * @param array $join_conds Associative array of table join conditions (optional)
943 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
944 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
946 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
948 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
949 return $this->query( $sql, $fname );
955 * @param mixed $table Array or string, table name(s) (prefix auto-added)
956 * @param mixed $vars Array or string, field name(s) to be retrieved
957 * @param mixed $conds Array or string, condition(s) for WHERE
958 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
959 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
960 * see Database::makeSelectOptions code for list of supported stuff
961 * @param array $join_conds Associative array of table join conditions (optional)
962 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
963 * @return string, the SQL text
965 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
966 if( is_array( $vars ) ) {
967 $vars = implode( ',', $vars );
969 if( !is_array( $options ) ) {
970 $options = array( $options );
972 if( is_array( $table ) ) {
973 if ( !empty($join_conds) ||
is_array( @$options['USE INDEX'] ) )
974 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
976 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
977 } elseif ($table!='') {
978 if ($table{0}==' ') {
979 $from = ' FROM ' . $table;
981 $from = ' FROM ' . $this->tableName( $table );
987 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
989 if( !empty( $conds ) ) {
990 if ( is_array( $conds ) ) {
991 $conds = $this->makeList( $conds, LIST_AND
);
993 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
995 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
998 if (isset($options['LIMIT']))
999 $sql = $this->limitResult($sql, $options['LIMIT'],
1000 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1001 $sql = "$sql $postLimitTail";
1003 if (isset($options['EXPLAIN'])) {
1004 $sql = 'EXPLAIN ' . $sql;
1010 * Single row SELECT wrapper
1011 * Aborts or returns FALSE on error
1013 * $vars: the selected variables
1014 * $conds: a condition map, terms are ANDed together.
1015 * Items with numeric keys are taken to be literal conditions
1016 * Takes an array of selected variables, and a condition map, which is ANDed
1017 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1018 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1019 * $obj- >page_id is the ID of the Astronomy article
1021 * @todo migrate documentation to phpdocumentor format
1023 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1024 $options['LIMIT'] = 1;
1025 $res = $this->select( $table, $vars, $conds, $fname, $options );
1026 if ( $res === false )
1028 if ( !$this->numRows($res) ) {
1029 $this->freeResult($res);
1032 $obj = $this->fetchObject( $res );
1033 $this->freeResult( $res );
1039 * Estimate rows in dataset
1040 * Returns estimated count, based on EXPLAIN output
1041 * Takes same arguments as Database::select()
1044 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1045 $options['EXPLAIN']=true;
1046 $res = $this->select ($table, $vars, $conds, $fname, $options );
1047 if ( $res === false )
1049 if (!$this->numRows($res)) {
1050 $this->freeResult($res);
1056 while( $plan = $this->fetchObject( $res ) ) {
1057 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1060 $this->freeResult($res);
1066 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1067 * It's only slightly flawed. Don't use for anything important.
1069 * @param string $sql A SQL Query
1072 static function generalizeSQL( $sql ) {
1073 # This does the same as the regexp below would do, but in such a way
1074 # as to avoid crashing php on some large strings.
1075 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1077 $sql = str_replace ( "\\\\", '', $sql);
1078 $sql = str_replace ( "\\'", '', $sql);
1079 $sql = str_replace ( "\\\"", '', $sql);
1080 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1081 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1083 # All newlines, tabs, etc replaced by single space
1084 $sql = preg_replace ( '/\s+/', ' ', $sql);
1087 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1093 * Determines whether a field exists in a table
1094 * Usually aborts on failure
1095 * If errors are explicitly ignored, returns NULL on failure
1097 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1098 $table = $this->tableName( $table );
1099 $res = $this->query( 'DESCRIBE '.$table, $fname );
1106 while ( $row = $this->fetchObject( $res ) ) {
1107 if ( $row->Field
== $field ) {
1116 * Determines whether an index exists
1117 * Usually aborts on failure
1118 * If errors are explicitly ignored, returns NULL on failure
1120 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1121 $info = $this->indexInfo( $table, $index, $fname );
1122 if ( is_null( $info ) ) {
1125 return $info !== false;
1131 * Get information about an index into an object
1132 * Returns false if the index does not exist
1134 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1135 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1136 # SHOW INDEX should work for 3.x and up:
1137 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1138 $table = $this->tableName( $table );
1139 $sql = 'SHOW INDEX FROM '.$table;
1140 $res = $this->query( $sql, $fname );
1146 while ( $row = $this->fetchObject( $res ) ) {
1147 if ( $row->Key_name
== $index ) {
1151 $this->freeResult($res);
1153 return empty($result) ?
false : $result;
1157 * Query whether a given table exists
1159 function tableExists( $table ) {
1160 $table = $this->tableName( $table );
1161 $old = $this->ignoreErrors( true );
1162 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1163 $this->ignoreErrors( $old );
1165 $this->freeResult( $res );
1173 * mysql_fetch_field() wrapper
1174 * Returns false if the field doesn't exist
1179 function fieldInfo( $table, $field ) {
1180 $table = $this->tableName( $table );
1181 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1182 $n = mysql_num_fields( $res->result
);
1183 for( $i = 0; $i < $n; $i++
) {
1184 $meta = mysql_fetch_field( $res->result
, $i );
1185 if( $field == $meta->name
) {
1186 return new MySQLField($meta);
1193 * mysql_field_type() wrapper
1195 function fieldType( $res, $index ) {
1196 if ( $res instanceof ResultWrapper
) {
1197 $res = $res->result
;
1199 return mysql_field_type( $res, $index );
1203 * Determines if a given index is unique
1205 function indexUnique( $table, $index ) {
1206 $indexInfo = $this->indexInfo( $table, $index );
1207 if ( !$indexInfo ) {
1210 return !$indexInfo[0]->Non_unique
;
1214 * INSERT wrapper, inserts an array into a table
1216 * $a may be a single associative array, or an array of these with numeric keys, for
1219 * Usually aborts on failure
1220 * If errors are explicitly ignored, returns success
1222 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1223 # No rows to insert, easy just return now
1224 if ( !count( $a ) ) {
1228 $table = $this->tableName( $table );
1229 if ( !is_array( $options ) ) {
1230 $options = array( $options );
1232 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1234 $keys = array_keys( $a[0] );
1237 $keys = array_keys( $a );
1240 $sql = 'INSERT ' . implode( ' ', $options ) .
1241 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1245 foreach ( $a as $row ) {
1251 $sql .= '(' . $this->makeList( $row ) . ')';
1254 $sql .= '(' . $this->makeList( $a ) . ')';
1256 return (bool)$this->query( $sql, $fname );
1260 * Make UPDATE options for the Database::update function
1263 * @param array $options The options passed to Database::update
1266 function makeUpdateOptions( $options ) {
1267 if( !is_array( $options ) ) {
1268 $options = array( $options );
1271 if ( in_array( 'LOW_PRIORITY', $options ) )
1272 $opts[] = $this->lowPriorityOption();
1273 if ( in_array( 'IGNORE', $options ) )
1275 return implode(' ', $opts);
1279 * UPDATE wrapper, takes a condition array and a SET array
1281 * @param string $table The table to UPDATE
1282 * @param array $values An array of values to SET
1283 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1284 * @param string $fname The Class::Function calling this function
1286 * @param array $options An array of UPDATE options, can be one or
1287 * more of IGNORE, LOW_PRIORITY
1290 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1291 $table = $this->tableName( $table );
1292 $opts = $this->makeUpdateOptions( $options );
1293 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1294 if ( $conds != '*' ) {
1295 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1297 return $this->query( $sql, $fname );
1301 * Makes an encoded list of strings from an array
1303 * LIST_COMMA - comma separated, no field names
1304 * LIST_AND - ANDed WHERE clause (without the WHERE)
1305 * LIST_OR - ORed WHERE clause (without the WHERE)
1306 * LIST_SET - comma separated with field names, like a SET clause
1307 * LIST_NAMES - comma separated field names
1309 function makeList( $a, $mode = LIST_COMMA
) {
1310 if ( !is_array( $a ) ) {
1311 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1316 foreach ( $a as $field => $value ) {
1318 if ( $mode == LIST_AND
) {
1320 } elseif($mode == LIST_OR
) {
1328 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1329 $list .= "($value)";
1330 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1332 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1333 if( count( $value ) == 0 ) {
1334 throw new MWException( __METHOD__
.': empty input' );
1335 } elseif( count( $value ) == 1 ) {
1336 // Special-case single values, as IN isn't terribly efficient
1337 // Don't necessarily assume the single key is 0; we don't
1338 // enforce linear numeric ordering on other arrays here.
1339 $value = array_values( $value );
1340 $list .= $field." = ".$this->addQuotes( $value[0] );
1342 $list .= $field." IN (".$this->makeList($value).") ";
1344 } elseif( is_null($value) ) {
1345 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1346 $list .= "$field IS ";
1347 } elseif ( $mode == LIST_SET
) {
1348 $list .= "$field = ";
1352 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1353 $list .= "$field = ";
1355 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1362 * Change the current database
1364 function selectDB( $db ) {
1365 $this->mDBname
= $db;
1366 return mysql_select_db( $db, $this->mConn
);
1370 * Get the current DB name
1372 function getDBname() {
1373 return $this->mDBname
;
1377 * Get the server hostname or IP address
1379 function getServer() {
1380 return $this->mServer
;
1384 * Format a table name ready for use in constructing an SQL query
1386 * This does two important things: it quotes the table names to clean them up,
1387 * and it adds a table prefix if only given a table name with no quotes.
1389 * All functions of this object which require a table name call this function
1390 * themselves. Pass the canonical name to such functions. This is only needed
1391 * when calling query() directly.
1393 * @param string $name database table name
1394 * @return string full database name
1396 function tableName( $name ) {
1397 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1398 # Skip the entire process when we have a string quoted on both ends.
1399 # Note that we check the end so that we will still quote any use of
1400 # use of `database`.table. But won't break things if someone wants
1401 # to query a database table with a dot in the name.
1402 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1404 # Lets test for any bits of text that should never show up in a table
1405 # name. Basically anything like JOIN or ON which are actually part of
1406 # SQL queries, but may end up inside of the table value to combine
1407 # sql. Such as how the API is doing.
1408 # Note that we use a whitespace test rather than a \b test to avoid
1409 # any remote case where a word like on may be inside of a table name
1410 # surrounded by symbols which may be considered word breaks.
1411 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1413 # Split database and table into proper variables.
1414 # We reverse the explode so that database.table and table both output
1415 # the correct table.
1416 @list
( $table, $database ) = array_reverse( explode( '.', $name, 2 ) );
1417 $prefix = $this->mTablePrefix
; # Default prefix
1419 # A database name has been specified in input. Quote the table name
1420 # because we don't want any prefixes added.
1421 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1423 # Note that we use the long format because php will complain in in_array if
1424 # the input is not an array, and will complain in is_array if it is not set.
1425 if( !isset( $database ) # Don't use shared database if pre selected.
1426 && isset( $wgSharedDB ) # We have a shared database
1427 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1428 && isset( $wgSharedTables )
1429 && is_array( $wgSharedTables )
1430 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1431 $database = $wgSharedDB;
1432 $prefix = isset( $wgSharedprefix ) ?
$wgSharedprefix : $prefix;
1435 # Quote the $database and $table and apply the prefix if not quoted.
1436 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1437 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1439 # Merge our database and table into our final table name.
1440 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1442 # We're finished, return.
1447 * Fetch a number of table names into an array
1448 * This is handy when you need to construct SQL for joins
1451 * extract($dbr->tableNames('user','watchlist'));
1452 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1453 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1455 public function tableNames() {
1456 $inArray = func_get_args();
1458 foreach ( $inArray as $name ) {
1459 $retVal[$name] = $this->tableName( $name );
1465 * Fetch a number of table names into an zero-indexed numerical array
1466 * This is handy when you need to construct SQL for joins
1469 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1470 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1471 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1473 public function tableNamesN() {
1474 $inArray = func_get_args();
1476 foreach ( $inArray as $name ) {
1477 $retVal[] = $this->tableName( $name );
1485 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1488 $use_index_safe = is_array($use_index) ?
$use_index : array();
1489 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1490 foreach ( $tables as $table ) {
1491 // Is there a JOIN and INDEX clause for this table?
1492 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1493 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1494 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1495 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1496 $retJOIN[] = $tableClause;
1497 // Is there an INDEX clause?
1498 } else if ( isset($use_index_safe[$table]) ) {
1499 $tableClause = $this->tableName( $table );
1500 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1501 $ret[] = $tableClause;
1502 // Is there a JOIN clause?
1503 } else if ( isset($join_conds_safe[$table]) ) {
1504 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1505 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1506 $retJOIN[] = $tableClause;
1508 $tableClause = $this->tableName( $table );
1509 $ret[] = $tableClause;
1512 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1513 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1514 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1515 // Compile our final table clause
1516 return implode(' ',array($straightJoins,$otherJoins) );
1520 * Wrapper for addslashes()
1521 * @param string $s String to be slashed.
1522 * @return string slashed string.
1524 function strencode( $s ) {
1525 return mysql_real_escape_string( $s, $this->mConn
);
1529 * If it's a string, adds quotes and backslashes
1530 * Otherwise returns as-is
1532 function addQuotes( $s ) {
1533 if ( is_null( $s ) ) {
1536 # This will also quote numeric values. This should be harmless,
1537 # and protects against weird problems that occur when they really
1538 # _are_ strings such as article titles and string->number->string
1539 # conversion is not 1:1.
1540 return "'" . $this->strencode( $s ) . "'";
1545 * Escape string for safe LIKE usage
1547 function escapeLike( $s ) {
1548 $s=$this->strencode( $s );
1549 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1554 * Returns an appropriately quoted sequence value for inserting a new row.
1555 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1556 * subclass will return an integer, and save the value for insertId()
1558 function nextSequenceValue( $seqName ) {
1564 * PostgreSQL doesn't have them and returns ""
1566 function useIndexClause( $index ) {
1567 return "FORCE INDEX ($index)";
1571 * REPLACE query wrapper
1572 * PostgreSQL simulates this with a DELETE followed by INSERT
1573 * $row is the row to insert, an associative array
1574 * $uniqueIndexes is an array of indexes. Each element may be either a
1575 * field name or an array of field names
1577 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1578 * However if you do this, you run the risk of encountering errors which wouldn't have
1581 * @todo migrate comment to phodocumentor format
1583 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1584 $table = $this->tableName( $table );
1587 if ( !is_array( reset( $rows ) ) ) {
1588 $rows = array( $rows );
1591 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1593 foreach ( $rows as $row ) {
1599 $sql .= '(' . $this->makeList( $row ) . ')';
1601 return $this->query( $sql, $fname );
1605 * DELETE where the condition is a join
1606 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1608 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1609 * join condition matches, set $conds='*'
1611 * DO NOT put the join condition in $conds
1613 * @param string $delTable The table to delete from.
1614 * @param string $joinTable The other table.
1615 * @param string $delVar The variable to join on, in the first table.
1616 * @param string $joinVar The variable to join on, in the second table.
1617 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1619 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1621 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1624 $delTable = $this->tableName( $delTable );
1625 $joinTable = $this->tableName( $joinTable );
1626 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1627 if ( $conds != '*' ) {
1628 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1631 return $this->query( $sql, $fname );
1635 * Returns the size of a text field, or -1 for "unlimited"
1637 function textFieldSize( $table, $field ) {
1638 $table = $this->tableName( $table );
1639 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1640 $res = $this->query( $sql, 'Database::textFieldSize' );
1641 $row = $this->fetchObject( $res );
1642 $this->freeResult( $res );
1645 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1654 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1656 function lowPriorityOption() {
1657 return 'LOW_PRIORITY';
1661 * DELETE query wrapper
1663 * Use $conds == "*" to delete all rows
1665 function delete( $table, $conds, $fname = 'Database::delete' ) {
1667 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1669 $table = $this->tableName( $table );
1670 $sql = "DELETE FROM $table";
1671 if ( $conds != '*' ) {
1672 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1674 return $this->query( $sql, $fname );
1678 * INSERT SELECT wrapper
1679 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1680 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1681 * $conds may be "*" to copy the whole table
1682 * srcTable may be an array of tables.
1684 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1685 $insertOptions = array(), $selectOptions = array() )
1687 $destTable = $this->tableName( $destTable );
1688 if ( is_array( $insertOptions ) ) {
1689 $insertOptions = implode( ' ', $insertOptions );
1691 if( !is_array( $selectOptions ) ) {
1692 $selectOptions = array( $selectOptions );
1694 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1695 if( is_array( $srcTable ) ) {
1696 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1698 $srcTable = $this->tableName( $srcTable );
1700 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1701 " SELECT $startOpts " . implode( ',', $varMap ) .
1702 " FROM $srcTable $useIndex ";
1703 if ( $conds != '*' ) {
1704 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1706 $sql .= " $tailOpts";
1707 return $this->query( $sql, $fname );
1711 * Construct a LIMIT query with optional offset
1712 * This is used for query pages
1713 * $sql string SQL query we will append the limit too
1714 * $limit integer the SQL limit
1715 * $offset integer the SQL offset (default false)
1717 function limitResult($sql, $limit, $offset=false) {
1718 if( !is_numeric($limit) ) {
1719 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1721 return "$sql LIMIT "
1722 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1725 function limitResultForUpdate($sql, $num) {
1726 return $this->limitResult($sql, $num, 0);
1730 * Returns an SQL expression for a simple conditional.
1733 * @param string $cond SQL expression which will result in a boolean value
1734 * @param string $trueVal SQL expression to return if true
1735 * @param string $falseVal SQL expression to return if false
1736 * @return string SQL fragment
1738 function conditional( $cond, $trueVal, $falseVal ) {
1739 return " IF($cond, $trueVal, $falseVal) ";
1743 * Returns a comand for str_replace function in SQL query.
1744 * Uses REPLACE() in MySQL
1746 * @param string $orig String or column to modify
1747 * @param string $old String or column to seek
1748 * @param string $new String or column to replace with
1750 function strreplace( $orig, $old, $new ) {
1751 return "REPLACE({$orig}, {$old}, {$new})";
1755 * Determines if the last failure was due to a deadlock
1757 function wasDeadlock() {
1758 return $this->lastErrno() == 1213;
1762 * Perform a deadlock-prone transaction.
1764 * This function invokes a callback function to perform a set of write
1765 * queries. If a deadlock occurs during the processing, the transaction
1766 * will be rolled back and the callback function will be called again.
1769 * $dbw->deadlockLoop( callback, ... );
1771 * Extra arguments are passed through to the specified callback function.
1773 * Returns whatever the callback function returned on its successful,
1774 * iteration, or false on error, for example if the retry limit was
1777 function deadlockLoop() {
1778 $myFname = 'Database::deadlockLoop';
1781 $args = func_get_args();
1782 $function = array_shift( $args );
1783 $oldIgnore = $this->ignoreErrors( true );
1784 $tries = DEADLOCK_TRIES
;
1785 if ( is_array( $function ) ) {
1786 $fname = $function[0];
1791 $retVal = call_user_func_array( $function, $args );
1792 $error = $this->lastError();
1793 $errno = $this->lastErrno();
1794 $sql = $this->lastQuery();
1797 if ( $this->wasDeadlock() ) {
1799 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1801 $this->reportQueryError( $error, $errno, $sql, $fname );
1804 } while( $this->wasDeadlock() && --$tries > 0 );
1805 $this->ignoreErrors( $oldIgnore );
1806 if ( $tries <= 0 ) {
1807 $this->query( 'ROLLBACK', $myFname );
1808 $this->reportQueryError( $error, $errno, $sql, $fname );
1811 $this->query( 'COMMIT', $myFname );
1817 * Do a SELECT MASTER_POS_WAIT()
1819 * @param string $file the binlog file
1820 * @param string $pos the binlog position
1821 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1823 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1824 $fname = 'Database::masterPosWait';
1825 wfProfileIn( $fname );
1827 # Commit any open transactions
1828 if ( $this->mTrxLevel
) {
1829 $this->immediateCommit();
1832 if ( !is_null( $this->mFakeSlaveLag
) ) {
1833 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1834 if ( $wait > $timeout * 1e6
) {
1835 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1836 wfProfileOut( $fname );
1838 } elseif ( $wait > 0 ) {
1839 wfDebug( "Fake slave waiting $wait us\n" );
1841 wfProfileOut( $fname );
1844 wfDebug( "Fake slave up to date ($wait us)\n" );
1845 wfProfileOut( $fname );
1850 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1851 $encFile = $this->addQuotes( $pos->file
);
1852 $encPos = intval( $pos->pos
);
1853 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1854 $res = $this->doQuery( $sql );
1855 if ( $res && $row = $this->fetchRow( $res ) ) {
1856 $this->freeResult( $res );
1857 wfProfileOut( $fname );
1860 wfProfileOut( $fname );
1866 * Get the position of the master from SHOW SLAVE STATUS
1868 function getSlavePos() {
1869 if ( !is_null( $this->mFakeSlaveLag
) ) {
1870 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1871 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1874 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1875 $row = $this->fetchObject( $res );
1877 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1884 * Get the position of the master from SHOW MASTER STATUS
1886 function getMasterPos() {
1887 if ( $this->mFakeMaster
) {
1888 return new MySQLMasterPos( 'fake', microtime( true ) );
1890 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1891 $row = $this->fetchObject( $res );
1893 return new MySQLMasterPos( $row->File
, $row->Position
);
1900 * Begin a transaction, committing any previously open transaction
1902 function begin( $fname = 'Database::begin' ) {
1903 $this->query( 'BEGIN', $fname );
1904 $this->mTrxLevel
= 1;
1910 function commit( $fname = 'Database::commit' ) {
1911 $this->query( 'COMMIT', $fname );
1912 $this->mTrxLevel
= 0;
1916 * Rollback a transaction.
1917 * No-op on non-transactional databases.
1919 function rollback( $fname = 'Database::rollback' ) {
1920 $this->query( 'ROLLBACK', $fname, true );
1921 $this->mTrxLevel
= 0;
1925 * Begin a transaction, committing any previously open transaction
1926 * @deprecated use begin()
1928 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1933 * Commit transaction, if one is open
1934 * @deprecated use commit()
1936 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1941 * Return MW-style timestamp used for MySQL schema
1943 function timestamp( $ts=0 ) {
1944 return wfTimestamp(TS_MW
,$ts);
1948 * Local database timestamp format or null
1950 function timestampOrNull( $ts = null ) {
1951 if( is_null( $ts ) ) {
1954 return $this->timestamp( $ts );
1961 function resultObject( $result ) {
1962 if( empty( $result ) ) {
1964 } elseif ( $result instanceof ResultWrapper
) {
1966 } elseif ( $result === true ) {
1967 // Successful write query
1970 return new ResultWrapper( $this, $result );
1975 * Return aggregated value alias
1977 function aggregateValue ($valuedata,$valuename='value') {
1982 * @return string wikitext of a link to the server software's web site
1984 function getSoftwareLink() {
1985 return "[http://www.mysql.com/ MySQL]";
1989 * @return string Version information from the database
1991 function getServerVersion() {
1992 return mysql_get_server_info( $this->mConn
);
1996 * Ping the server and try to reconnect if it there is no connection
1999 if( !function_exists( 'mysql_ping' ) ) {
2000 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2003 $ping = mysql_ping( $this->mConn
);
2008 // Need to reconnect manually in MySQL client 5.0.13+
2009 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2010 mysql_close( $this->mConn
);
2011 $this->mOpened
= false;
2012 $this->mConn
= false;
2013 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2021 * At the moment, this will only work if the DB user has the PROCESS privilege
2024 if ( !is_null( $this->mFakeSlaveLag
) ) {
2025 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2026 return $this->mFakeSlaveLag
;
2028 $res = $this->query( 'SHOW PROCESSLIST' );
2029 # Find slave SQL thread
2030 while ( $row = $this->fetchObject( $res ) ) {
2031 /* This should work for most situations - when default db
2032 * for thread is not specified, it had no events executed,
2033 * and therefore it doesn't know yet how lagged it is.
2035 * Relay log I/O thread does not select databases.
2037 if ( $row->User
== 'system user' &&
2038 $row->State
!= 'Waiting for master to send event' &&
2039 $row->State
!= 'Connecting to master' &&
2040 $row->State
!= 'Queueing master event to the relay log' &&
2041 $row->State
!= 'Waiting for master update' &&
2042 $row->State
!= 'Requesting binlog dump'
2044 # This is it, return the time (except -ve)
2045 if ( $row->Time
> 0x7fffffff ) {
2056 * Get status information from SHOW STATUS in an associative array
2058 function getStatus($which="%") {
2059 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2061 while ( $row = $this->fetchObject( $res ) ) {
2062 $status[$row->Variable_name
] = $row->Value
;
2068 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2070 function maxListLen() {
2074 function encodeBlob($b) {
2078 function decodeBlob($b) {
2083 * Override database's default connection timeout.
2084 * May be useful for very long batch queries such as
2085 * full-wiki dumps, where a single query reads out
2086 * over hours or days.
2087 * @param int $timeout in seconds
2089 public function setTimeout( $timeout ) {
2090 $this->query( "SET net_read_timeout=$timeout" );
2091 $this->query( "SET net_write_timeout=$timeout" );
2095 * Read and execute SQL commands from a file.
2096 * Returns true on success, error string on failure
2097 * @param string $filename File name to open
2098 * @param callback $lineCallback Optional function called before reading each line
2099 * @param callback $resultCallback Optional function called for each MySQL result
2101 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2102 $fp = fopen( $filename, 'r' );
2103 if ( false === $fp ) {
2104 return "Could not open \"{$filename}\".\n";
2106 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2112 * Read and execute commands from an open file handle
2113 * Returns true on success, error string on failure
2114 * @param string $fp File handle
2115 * @param callback $lineCallback Optional function called before reading each line
2116 * @param callback $resultCallback Optional function called for each MySQL result
2118 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2121 $dollarquote = false;
2123 while ( ! feof( $fp ) ) {
2124 if ( $lineCallback ) {
2125 call_user_func( $lineCallback );
2127 $line = trim( fgets( $fp, 1024 ) );
2128 $sl = strlen( $line ) - 1;
2130 if ( $sl < 0 ) { continue; }
2131 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2133 ## Allow dollar quoting for function declarations
2134 if (substr($line,0,4) == '$mw$') {
2136 $dollarquote = false;
2140 $dollarquote = true;
2143 else if (!$dollarquote) {
2144 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2146 $line = substr( $line, 0, $sl );
2150 if ( '' != $cmd ) { $cmd .= ' '; }
2154 $cmd = str_replace(';;', ";", $cmd);
2155 $cmd = $this->replaceVars( $cmd );
2156 $res = $this->query( $cmd, __METHOD__
, true );
2157 if ( $resultCallback ) {
2158 call_user_func( $resultCallback, $res );
2161 if ( false === $res ) {
2162 $err = $this->lastError();
2163 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2175 * Replace variables in sourced SQL
2177 protected function replaceVars( $ins ) {
2179 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2180 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2181 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2184 // Ordinary variables
2185 foreach ( $varnames as $var ) {
2186 if( isset( $GLOBALS[$var] ) ) {
2187 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2188 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2189 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2190 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2195 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2196 array( &$this, 'tableNameCallback' ), $ins );
2201 * Table name callback
2204 protected function tableNameCallback( $matches ) {
2205 return $this->tableName( $matches[1] );
2209 * Build a concatenation list to feed into a SQL query
2211 function buildConcat( $stringList ) {
2212 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2218 * Database abstraction object for mySQL
2219 * Inherit all methods and properties of Database::Database()
2221 * @addtogroup Database
2224 class DatabaseMysql
extends Database
{
2228 /******************************************************************************
2230 *****************************************************************************/
2234 * @addtogroup Database
2239 function DBObject($data) {
2240 $this->mData
= $data;
2248 return $this->mData
;
2254 * @addtogroup Database
2256 * This allows us to distinguish a blob from a normal string and an array of strings
2260 function __construct($data) {
2261 $this->mData
= $data;
2264 return $this->mData
;
2270 * @addtogroup Database
2273 private $name, $tablename, $default, $max_length, $nullable,
2274 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2275 function __construct ($info) {
2276 $this->name
= $info->name
;
2277 $this->tablename
= $info->table
;
2278 $this->default = $info->def
;
2279 $this->max_length
= $info->max_length
;
2280 $this->nullable
= !$info->not_null
;
2281 $this->is_pk
= $info->primary_key
;
2282 $this->is_unique
= $info->unique_key
;
2283 $this->is_multiple
= $info->multiple_key
;
2284 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2285 $this->type
= $info->type
;
2292 function tableName() {
2293 return $this->tableName
;
2296 function defaultValue() {
2297 return $this->default;
2300 function maxLength() {
2301 return $this->max_length
;
2304 function nullable() {
2305 return $this->nullable
;
2309 return $this->is_key
;
2312 function isMultipleKey() {
2313 return $this->is_multiple
;
2321 /******************************************************************************
2323 *****************************************************************************/
2326 * Database error base class
2327 * @addtogroup Database
2329 class DBError
extends MWException
{
2333 * Construct a database error
2334 * @param Database $db The database object which threw the error
2335 * @param string $error A simple error message to be used for debugging
2337 function __construct( Database
&$db, $error ) {
2339 parent
::__construct( $error );
2344 * @addtogroup Database
2346 class DBConnectionError
extends DBError
{
2349 function __construct( Database
&$db, $error = 'unknown error' ) {
2350 $msg = 'DB connection error';
2351 if ( trim( $error ) != '' ) {
2354 $this->error
= $error;
2355 parent
::__construct( $db, $msg );
2358 function useOutputPage() {
2359 // Not likely to work
2363 function useMessageCache() {
2364 // Not likely to work
2368 function getText() {
2369 return $this->getMessage() . "\n";
2372 function getLogMessage() {
2373 # Don't send to the exception log
2377 function getPageTitle() {
2379 return "$wgSitename has a problem";
2382 function getHTML() {
2383 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2384 global $wgSitename, $wgServer, $wgMessageCache;
2386 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2387 # Hard coding strings instead.
2389 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2390 $mainpage = 'Main Page';
2391 $searchdisabled = <<<EOT
2392 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2393 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2397 <!-- SiteSearch Google -->
2398 <FORM method=GET action=\"http://www.google.com/search\">
2399 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2400 <A HREF=\"http://www.google.com/\">
2401 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2402 border=\"0\" ALT=\"Google\"></A>
2405 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2406 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2408 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
2409 <input type='hidden' name='ie' value='$2'>
2410 <input type='hidden' name='oe' value='$2'>
2414 <!-- SiteSearch Google -->";
2415 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2417 # No database access
2418 if ( is_object( $wgMessageCache ) ) {
2419 $wgMessageCache->disable();
2422 if ( trim( $this->error
) == '' ) {
2423 $this->error
= $this->db
->getProperty('mServer');
2426 $text = str_replace( '$1', $this->error
, $noconnect );
2427 $text .= wfGetSiteNotice();
2429 if($wgUseFileCache) {
2434 $t = Title
::newFromURL( $title );
2435 } elseif (@/**/$_REQUEST['search']) {
2436 $search = $_REQUEST['search'];
2437 return $searchdisabled .
2438 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2439 $wgInputEncoding ), $googlesearch );
2441 $t = Title
::newFromText( $mainpage );
2445 $cache = new HTMLFileCache( $t );
2446 if( $cache->isFileCached() ) {
2447 // @todo, FIXME: $msg is not defined on the next line.
2448 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2449 $cachederror . "</b></p>\n";
2451 $tag = '<div id="article">';
2452 $text = str_replace(
2455 $cache->fetchPageText() );
2464 * @addtogroup Database
2466 class DBQueryError
extends DBError
{
2467 public $error, $errno, $sql, $fname;
2469 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2470 $message = "A database error has occurred\n" .
2472 "Function: $fname\n" .
2473 "Error: $errno $error\n";
2475 parent
::__construct( $db, $message );
2476 $this->error
= $error;
2477 $this->errno
= $errno;
2479 $this->fname
= $fname;
2482 function getText() {
2483 if ( $this->useMessageCache() ) {
2484 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2485 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2487 return $this->getMessage();
2492 global $wgShowSQLErrors;
2493 if( !$wgShowSQLErrors ) {
2494 return $this->msg( 'sqlhidden', 'SQL hidden' );
2500 function getLogMessage() {
2501 # Don't send to the exception log
2505 function getPageTitle() {
2506 return $this->msg( 'databaseerror', 'Database error' );
2509 function getHTML() {
2510 if ( $this->useMessageCache() ) {
2511 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2512 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2514 return nl2br( htmlspecialchars( $this->getMessage() ) );
2520 * @addtogroup Database
2522 class DBUnexpectedError
extends DBError
{}
2526 * Result wrapper for grabbing data queried by someone else
2527 * @addtogroup Database
2529 class ResultWrapper
implements Iterator
{
2530 var $db, $result, $pos = 0, $currentRow = null;
2533 * Create a new result object from a result resource and a Database object
2535 function ResultWrapper( $database, $result ) {
2536 $this->db
= $database;
2537 if ( $result instanceof ResultWrapper
) {
2538 $this->result
= $result->result
;
2540 $this->result
= $result;
2545 * Get the number of rows in a result object
2547 function numRows() {
2548 return $this->db
->numRows( $this->result
);
2552 * Fetch the next row from the given result object, in object form.
2553 * Fields can be retrieved with $row->fieldname, with fields acting like
2556 * @param $res SQL result object as returned from Database::query(), etc.
2557 * @return MySQL row object
2558 * @throws DBUnexpectedError Thrown if the database returns an error
2560 function fetchObject() {
2561 return $this->db
->fetchObject( $this->result
);
2565 * Fetch the next row from the given result object, in associative array
2566 * form. Fields are retrieved with $row['fieldname'].
2568 * @param $res SQL result object as returned from Database::query(), etc.
2569 * @return MySQL row object
2570 * @throws DBUnexpectedError Thrown if the database returns an error
2572 function fetchRow() {
2573 return $this->db
->fetchRow( $this->result
);
2577 * Free a result object
2580 $this->db
->freeResult( $this->result
);
2581 unset( $this->result
);
2586 * Change the position of the cursor in a result object
2587 * See mysql_data_seek()
2589 function seek( $row ) {
2590 $this->db
->dataSeek( $this->result
, $row );
2593 /*********************
2594 * Iterator functions
2595 * Note that using these in combination with the non-iterator functions
2596 * above may cause rows to be skipped or repeated.
2600 if ($this->numRows()) {
2601 $this->db
->dataSeek($this->result
, 0);
2604 $this->currentRow
= null;
2607 function current() {
2608 if ( is_null( $this->currentRow
) ) {
2611 return $this->currentRow
;
2620 $this->currentRow
= $this->fetchObject();
2621 return $this->currentRow
;
2625 return $this->current() !== false;
2629 class MySQLMasterPos
{
2632 function __construct( $file, $pos ) {
2633 $this->file
= $file;
2637 function __toString() {
2638 return "{$this->file}/{$this->pos}";