7a6cd9b5a2b5c5b741d216bcaf6dd8c948974cb0
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
9 * Depends on the CacheManager
11 require_once( 'CacheManager.php' );
14 define( 'LIST_COMMA', 0 );
16 define( 'LIST_AND', 1 );
18 define( 'LIST_SET', 2 );
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
28 * Database abstraction object
34 #------------------------------------------------------------------------------
36 #------------------------------------------------------------------------------
42 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
43 var $mOut, $mOpened = false;
51 #------------------------------------------------------------------------------
53 #------------------------------------------------------------------------------
54 # These optionally set a variable and return the previous state
57 * Fail function, takes a Database as a parameter
58 * Set to false for default, 1 for ignore errors
60 function failFunction( $function = NULL ) {
61 return wfSetVar( $this->mFailFunction
, $function );
65 * Output page, used for reporting errors
66 * FALSE means discard output
68 function &setOutputPage( &$out ) {
73 * Boolean, controls output of large amounts of debug information
75 function debug( $debug = NULL ) {
76 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
80 * Turns buffering of SQL result sets on (true) or off (false).
81 * Default is "on" and it should not be changed without good reasons.
83 function bufferResults( $buffer = NULL ) {
84 if ( is_null( $buffer ) ) {
85 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
87 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
92 * Turns on (false) or off (true) the automatic generation and sending
93 * of a "we're sorry, but there has been a database error" page on
94 * database errors. Default is on (false). When turned off, the
95 * code should use wfLastErrno() and wfLastError() to handle the
96 * situation as appropriate.
98 function ignoreErrors( $ignoreErrors = NULL ) {
99 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
103 * The current depth of nested transactions
104 * @param integer $level
106 function trxLevel( $level = NULL ) {
107 return wfSetVar( $this->mTrxLevel
, $level );
113 function lastQuery() { return $this->mLastQuery
; }
114 function isOpen() { return $this->mOpened
; }
117 #------------------------------------------------------------------------------
119 #------------------------------------------------------------------------------
122 * @param string $server database server host
123 * @param string $user database user name
124 * @param string $password database user password
125 * @param string $dbname database name
129 * @param failFunction
131 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
133 function Database( $server = false, $user = false, $password = false, $dbName = false,
134 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
136 global $wgOut, $wgDBprefix, $wgCommandLineMode;
137 # Can't get a reference if it hasn't been set yet
138 if ( !isset( $wgOut ) ) {
141 $this->mOut
=& $wgOut;
143 $this->mFailFunction
= $failFunction;
144 $this->mFlags
= $flags;
146 if ( $this->mFlags
& DBO_DEFAULT
) {
147 if ( $wgCommandLineMode ) {
148 $this->mFlags
&= ~DBO_TRX
;
150 $this->mFlags |
= DBO_TRX
;
154 /** Get the default table prefix*/
155 if ( $tablePrefix == 'get from global' ) {
156 $this->mTablePrefix
= $wgDBprefix;
158 $this->mTablePrefix
= $tablePrefix;
162 $this->open( $server, $user, $password, $dbName );
168 * @param failFunction
171 function newFromParams( $server, $user, $password, $dbName,
172 $failFunction = false, $flags = 0 )
174 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
178 * Usually aborts on failure
179 * If the failFunction is set to a non-zero integer, returns success
181 function open( $server, $user, $password, $dbName ) {
182 # Test for missing mysql.so
183 # Otherwise we get a suppressed fatal error, which is very hard to track down
184 if ( !function_exists( 'mysql_connect' ) ) {
185 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
189 $this->mServer
= $server;
190 $this->mUser
= $user;
191 $this->mPassword
= $password;
192 $this->mDBname
= $dbName;
196 @/**/$this->mConn
= mysql_connect( $server, $user, $password );
197 if ( $dbName != '' ) {
198 if ( $this->mConn
!== false ) {
199 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
201 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
204 wfDebug( "DB connection error\n" );
205 wfDebug( "Server: $server, User: $user, Password: " .
206 substr( $password, 0, 3 ) . "...\n" );
211 $success = !!$this->mConn
;
215 $this->reportConnectionError();
218 $this->mOpened
= $success;
224 * Closes a database connection.
225 * if it is open : commits any open transactions
227 * @return bool operation success. true if already closed.
231 $this->mOpened
= false;
232 if ( $this->mConn
) {
233 if ( $this->trxLevel() ) {
234 $this->immediateCommit();
236 return mysql_close( $this->mConn
);
244 * @param string $msg error message ?
245 * @todo parameter $msg is not used
247 function reportConnectionError( $msg = '') {
248 if ( $this->mFailFunction
) {
249 if ( !is_int( $this->mFailFunction
) ) {
250 $ff = $this->mFailFunction
;
251 $ff( $this, mysql_error() );
254 wfEmergencyAbort( $this, mysql_error() );
259 * Usually aborts on failure
260 * If errors are explicitly ignored, returns success
262 function query( $sql, $fname = '', $tempIgnore = false ) {
263 global $wgProfiling, $wgCommandLineMode;
265 if ( $wgProfiling ) {
266 # generalizeSQL will probably cut down the query to reasonable
267 # logging size most of the time. The substr is really just a sanity check.
268 $profName = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
269 wfProfileIn( $profName );
272 $this->mLastQuery
= $sql;
274 if ( $this->debug() ) {
275 $sqlx = substr( $sql, 0, 500 );
276 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
277 wfDebug( "SQL: $sqlx\n" );
279 # Add a comment for easy SHOW PROCESSLIST interpretation
281 $commentedSql = "/* $fname */ $sql";
283 $commentedSql = $sql;
286 # If DBO_TRX is set, start a transaction
287 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() && $sql != 'BEGIN' ) {
291 # Do the query and handle errors
292 $ret = $this->doQuery( $commentedSql );
293 if ( false === $ret ) {
294 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
297 if ( $wgProfiling ) {
298 wfProfileOut( $profName );
304 * The DBMS-dependent part of query()
305 * @param string $sql SQL query.
307 function doQuery( $sql ) {
308 if( $this->bufferResults() ) {
309 $ret = mysql_query( $sql, $this->mConn
);
311 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
320 * @param string $fname
321 * @param bool $tempIgnore
323 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
324 global $wgCommandLineMode, $wgFullyInitialised;
325 # Ignore errors during error handling to avoid infinite recursion
326 $ignore = $this->ignoreErrors( true );
328 if( $ignore ||
$tempIgnore ) {
329 wfDebug("SQL ERROR (ignored): " . $error . "\n");
331 $sql1line = str_replace( "\n", "\\n", $sql );
332 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
333 wfDebug("SQL ERROR: " . $error . "\n");
334 if ( $wgCommandLineMode ||
!$this->mOut ||
empty( $wgFullyInitialised ) ) {
335 $message = "A database error has occurred\n" .
337 "Function: $fname\n" .
338 "Error: $errno $error\n";
339 if ( !$wgCommandLineMode ) {
340 $message = nl2br( $message );
342 wfDebugDieBacktrace( $message );
344 // this calls wfAbruptExit()
345 $this->mOut
->databaseError( $fname, $sql, $error, $errno );
348 $this->ignoreErrors( $ignore );
353 * @param mixed $res A SQL result
358 function freeResult( $res ) {
359 if ( !@/**/mysql_free_result( $res ) ) {
360 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
365 * @todo FIXME: HACK HACK HACK HACK debug
367 function fetchObject( $res ) {
368 @/**/$row = mysql_fetch_object( $res );
369 # FIXME: HACK HACK HACK HACK debug
370 if( mysql_errno() ) {
371 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
379 function fetchRow( $res ) {
380 @/**/$row = mysql_fetch_array( $res );
381 if (mysql_errno() ) {
382 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
390 function numRows( $res ) {
391 @/**/$n = mysql_num_rows( $res );
392 if( mysql_errno() ) {
393 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
401 function numFields( $res ) { return mysql_num_fields( $res ); }
406 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
410 function insertId() { return mysql_insert_id( $this->mConn
); }
414 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
418 function lastErrno() { return mysql_errno(); }
422 function lastError() { return mysql_error(); }
426 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
427 /**#@-*/ // end of template : @param $result
431 * Simple UPDATE wrapper
432 * Usually aborts on failure
433 * If errors are explicitly ignored, returns success
435 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
437 $table = $this->tableName( $table );
438 $sql = "UPDATE $table SET $var = '" .
439 $this->strencode( $value ) . "' WHERE ($cond)";
440 return !!$this->query( $sql, DB_MASTER
, $fname );
446 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
447 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
451 * Simple SELECT wrapper, returns a single field, input must be encoded
452 * Usually aborts on failure
453 * If errors are explicitly ignored, returns FALSE on failure
455 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
456 if ( !is_array( $options ) ) {
457 $options = array( $options );
459 $options['LIMIT'] = 1;
461 $res = $this->select( $table, $var, $cond, $fname, $options );
462 if ( $res === false ||
!$this->numRows( $res ) ) {
465 $row = $this->fetchRow( $res );
466 if ( $row !== false ) {
467 $this->freeResult( $res );
475 * Returns an optional USE INDEX clause to go after the table, and a
476 * string to go at the end of the query
478 function makeSelectOptions( $options ) {
479 if ( !is_array( $options ) ) {
480 $options = array( $options );
485 if ( isset( $options['ORDER BY'] ) ) {
486 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
488 if ( isset( $options['LIMIT'] ) ) {
489 $tailOpts .= " LIMIT {$options['LIMIT']}";
492 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
493 $tailOpts .= ' FOR UPDATE';
496 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
497 $tailOpts .= ' LOCK IN SHARE MODE';
500 if ( isset( $options['USE INDEX'] ) ) {
501 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
505 return array( $useIndex, $tailOpts );
511 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
513 if ( is_array( $vars ) ) {
514 $vars = implode( ',', $vars );
517 $from = ' FROM ' .$this->tableName( $table );
521 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
523 if ( $conds !== false && $conds != '' ) {
524 if ( is_array( $conds ) ) {
525 $conds = $this->makeList( $conds, LIST_AND
);
527 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
529 $sql = "SELECT $vars $from $useIndex $tailOpts";
531 return $this->query( $sql, $fname );
537 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
538 return $this->selectRow( $table, $vars, $conds, $fname, $options );
543 * Single row SELECT wrapper
544 * Aborts or returns FALSE on error
546 * $vars: the selected variables
547 * $conds: a condition map, terms are ANDed together.
548 * Items with numeric keys are taken to be literal conditions
549 * Takes an array of selected variables, and a condition map, which is ANDed
550 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
551 * would return an object where $obj->cur_id is the ID of the Astronomy article
553 * @todo migrate documentation to phpdocumentor format
555 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
556 $options['LIMIT'] = 1;
557 $res = $this->select( $table, $vars, $conds, $fname, $options );
558 if ( $res === false ||
!$this->numRows( $res ) ) {
561 $obj = $this->fetchObject( $res );
562 $this->freeResult( $res );
568 * Removes most variables from an SQL query and replaces them with X or N for numbers.
569 * It's only slightly flawed. Don't use for anything important.
571 * @param string $sql A SQL Query
574 function generalizeSQL( $sql ) {
575 # This does the same as the regexp below would do, but in such a way
576 # as to avoid crashing php on some large strings.
577 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
579 $sql = str_replace ( "\\\\", '', $sql);
580 $sql = str_replace ( "\\'", '', $sql);
581 $sql = str_replace ( "\\\"", '', $sql);
582 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
583 $sql = preg_replace ('/".*"/s', "'X'", $sql);
585 # All newlines, tabs, etc replaced by single space
586 $sql = preg_replace ( "/\s+/", ' ', $sql);
589 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
595 * Determines whether a field exists in a table
596 * Usually aborts on failure
597 * If errors are explicitly ignored, returns NULL on failure
599 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
600 $table = $this->tableName( $table );
601 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE
, $fname );
608 while ( $row = $this->fetchObject( $res ) ) {
609 if ( $row->Field
== $field ) {
618 * Determines whether an index exists
619 * Usually aborts on failure
620 * If errors are explicitly ignored, returns NULL on failure
622 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
623 $info = $this->indexInfo( $table, $index, $fname );
624 if ( is_null( $info ) ) {
627 return $info !== false;
635 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
636 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
637 # SHOW INDEX should work for 3.x and up:
638 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
639 $table = $this->tableName( $table );
640 $sql = 'SHOW INDEX FROM '.$table;
641 $res = $this->query( $sql, $fname );
646 while ( $row = $this->fetchObject( $res ) ) {
647 if ( $row->Key_name
== $index ) {
658 function tableExists( $table ) {
659 $table = $this->tableName( $table );
660 $old = $this->ignoreErrors( true );
661 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
662 $this->ignoreErrors( $old );
664 $this->freeResult( $res );
676 function fieldInfo( $table, $field ) {
677 $table = $this->tableName( $table );
678 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
679 $n = mysql_num_fields( $res );
680 for( $i = 0; $i < $n; $i++
) {
681 $meta = mysql_fetch_field( $res, $i );
682 if( $field == $meta->name
) {
692 function fieldType( $res, $index ) {
693 return mysql_field_type( $res, $index );
699 function indexUnique( $table, $index ) {
700 $indexInfo = $this->indexInfo( $table, $index );
704 return !$indexInfo->Non_unique
;
710 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
711 return $this->insert( $table, $a, $fname = 'Database::insertArray', $options = array() );
715 * INSERT wrapper, inserts an array into a table
717 * $a may be a single associative array, or an array of these with numeric keys, for
720 * Usually aborts on failure
721 * If errors are explicitly ignored, returns success
723 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
724 # No rows to insert, easy just return now
725 if ( !count( $a ) ) {
729 $table = $this->tableName( $table );
730 if ( !is_array( $options ) ) {
731 $options = array( $options );
733 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
735 $keys = array_keys( $a[0] );
738 $keys = array_keys( $a );
741 $sql = 'INSERT ' . implode( ' ', $options ) .
742 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
746 foreach ( $a as $row ) {
752 $sql .= '(' . $this->makeList( $row ) . ')';
755 $sql .= '(' . $this->makeList( $a ) . ')';
757 return !!$this->query( $sql, $fname );
763 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
764 return $this->update( $table, $values, $conds, $fname );
768 * UPDATE wrapper, takes a condition array and a SET array
770 function update( $table, $values, $conds, $fname = 'Database::update' ) {
771 $table = $this->tableName( $table );
772 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET
);
773 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
774 $this->query( $sql, $fname );
778 * Makes a wfStrencoded list from an array
779 * $mode: LIST_COMMA - comma separated, no field names
780 * LIST_AND - ANDed WHERE clause (without the WHERE)
781 * LIST_SET - comma separated with field names, like a SET clause
783 function makeList( $a, $mode = LIST_COMMA
) {
784 if ( !is_array( $a ) ) {
785 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
790 foreach ( $a as $field => $value ) {
792 if ( $mode == LIST_AND
) {
800 if ( $mode == LIST_AND
&& is_numeric( $field ) ) {
803 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
806 $list .= $this->addQuotes( $value );
815 function selectDB( $db ) {
816 $this->mDBname
= $db;
817 mysql_select_db( $db, $this->mConn
);
823 function startTimer( $timeout ) {
825 if( function_exists( 'mysql_thread_id' ) ) {
826 # This will kill the query if it's still running after $timeout seconds.
827 $tid = mysql_thread_id( $this->mConn
);
828 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
833 * Does nothing at all
836 function stopTimer() { }
839 * @param string $name database table name
842 function tableName( $name ) {
844 if ( $this->mTablePrefix
!== '' ) {
845 if ( strpos( '.', $name ) === false ) {
846 $name = $this->mTablePrefix
. $name;
849 if ( isset( $wgSharedDB ) && 'user' == $name ) {
850 $name = $wgSharedDB . '.' . $name;
858 function tableNames() {
859 $inArray = func_get_args();
861 foreach ( $inArray as $name ) {
862 $retVal[$name] = $this->tableName( $name );
868 * Wrapper for addslashes()
869 * @param string $s String to be slashed.
870 * @return string slashed string.
872 function strencode( $s ) {
873 return addslashes( $s );
877 * If it's a string, adds quotes and backslashes
878 * Otherwise returns as-is
880 function addQuotes( $s ) {
881 if ( is_null( $s ) ) {
884 # This will also quote numeric values. This should be harmless,
885 # and protects against weird problems that occur when they really
886 # _are_ strings such as article titles and string->number->string
887 # conversion is not 1:1.
888 $s = "'" . $this->strencode( $s ) . "'";
894 * Returns an appropriately quoted sequence value for inserting a new row.
895 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
896 * subclass will return an integer, and save the value for insertId()
898 function nextSequenceValue( $seqName ) {
904 * PostgreSQL doesn't have them and returns ""
906 function useIndexClause( $index ) {
907 return 'USE INDEX ('.$index.')';
911 * REPLACE query wrapper
912 * PostgreSQL simulates this with a DELETE followed by INSERT
913 * $row is the row to insert, an associative array
914 * $uniqueIndexes is an array of indexes. Each element may be either a
915 * field name or an array of field names
917 * It may be more efficient to leave off unique indexes which are unlikely to collide.
918 * However if you do this, you run the risk of encountering errors which wouldn't have
921 * @todo migrate comment to phodocumentor format
923 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
924 $table = $this->tableName( $table );
927 if ( !is_array( reset( $rows ) ) ) {
928 $rows = array( $rows );
931 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .') VALUES ';
933 foreach ( $rows as $row ) {
939 $sql .= '(' . $this->makeList( $row ) . ')';
941 return $this->query( $sql, $fname );
945 * DELETE where the condition is a join
946 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
948 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
949 * join condition matches, set $conds='*'
951 * DO NOT put the join condition in $conds
953 * @param string $delTable The table to delete from.
954 * @param string $joinTable The other table.
955 * @param string $delVar The variable to join on, in the first table.
956 * @param string $joinVar The variable to join on, in the second table.
957 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
959 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
961 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
964 $delTable = $this->tableName( $delTable );
965 $joinTable = $this->tableName( $joinTable );
966 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
967 if ( $conds != '*' ) {
968 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
971 return $this->query( $sql, $fname );
975 * Returns the size of a text field, or -1 for "unlimited"
977 function textFieldSize( $table, $field ) {
978 $table = $this->tableName( $table );
979 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
980 $res = $this->query( $sql, 'Database::textFieldSize' );
981 $row = $this->fetchObject( $res );
982 $this->freeResult( $res );
984 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
993 * @return string Always return 'LOW_PRIORITY'
995 function lowPriorityOption() {
996 return 'LOW_PRIORITY';
1000 * Use $conds == "*" to delete all rows
1003 function delete( $table, $conds, $fname = 'Database::delete' ) {
1005 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1007 $table = $this->tableName( $table );
1008 $sql = "DELETE FROM $table ";
1009 if ( $conds != '*' ) {
1010 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1012 return $this->query( $sql, $fname );
1016 * INSERT SELECT wrapper
1017 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1018 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1019 * $conds may be "*" to copy the whole table
1021 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1022 $destTable = $this->tableName( $destTable );
1023 $srcTable = $this->tableName( $srcTable );
1024 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1025 ' SELECT ' . implode( ',', $varMap ) .
1027 if ( $conds != '*' ) {
1028 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1030 return $this->query( $sql, $fname );
1036 function limitResult($limit,$offset) {
1037 return ' LIMIT '.(is_numeric($offset)?
"{$offset},":"")."{$limit} ";
1043 function wasDeadlock() {
1044 return $this->lastErrno() == 1213;
1050 function deadlockLoop() {
1051 $myFname = 'Database::deadlockLoop';
1053 $this->query( 'BEGIN', $myFname );
1054 $args = func_get_args();
1055 $function = array_shift( $args );
1056 $oldIgnore = $dbw->ignoreErrors( true );
1057 $tries = DEADLOCK_TRIES
;
1058 if ( is_array( $function ) ) {
1059 $fname = $function[0];
1064 $retVal = call_user_func_array( $function, $args );
1065 $error = $this->lastError();
1066 $errno = $this->lastErrno();
1067 $sql = $this->lastQuery();
1070 if ( $dbw->wasDeadlock() ) {
1072 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1074 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1077 } while( $dbw->wasDeadlock
&& --$tries > 0 );
1078 $this->ignoreErrors( $oldIgnore );
1079 if ( $tries <= 0 ) {
1080 $this->query( 'ROLLBACK', $myFname );
1081 $this->reportQueryError( $error, $errno, $sql, $fname );
1084 $this->query( 'COMMIT', $myFname );
1090 * Do a SELECT MASTER_POS_WAIT()
1093 function masterPosWait( $file, $pos, $timeout ) {
1094 $encFile = $this->strencode( $file );
1095 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1096 $res = $this->query( $sql, 'Database::masterPosWait' );
1097 if ( $res && $row = $this->fetchRow( $res ) ) {
1098 $this->freeResult( $res );
1106 * Get the position of the master from SHOW SLAVE STATUS
1108 function getSlavePos() {
1109 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1110 $row = $this->fetchObject( $res );
1112 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1114 return array( false, false );
1119 * Get the position of the master from SHOW MASTER STATUS
1121 function getMasterPos() {
1122 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1123 $row = $this->fetchObject( $res );
1125 return array( $row->File
, $row->Position
);
1127 return array( false, false );
1132 * Begin a transaction, or if a transaction has already started, continue it
1134 function begin( $fname = 'Database::begin' ) {
1135 if ( !$this->mTrxLevel
) {
1136 $this->immediateBegin( $fname );
1143 * End a transaction, or decrement the nest level if transactions are nested
1145 function commit( $fname = 'Database::commit' ) {
1146 if ( $this->mTrxLevel
) {
1149 if ( !$this->mTrxLevel
) {
1150 $this->immediateCommit( $fname );
1155 * Rollback a transaction
1157 function rollback( $fname = 'Database::rollback' ) {
1158 $this->query( 'ROLLBACK', $fname );
1159 $this->mTrxLevel
= 0;
1163 * Begin a transaction, committing any previously open transaction
1165 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1166 $this->query( 'BEGIN', $fname );
1167 $this->mTrxLevel
= 1;
1171 * Commit transaction, if one is open
1173 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1174 $this->query( 'COMMIT', $fname );
1175 $this->mTrxLevel
= 0;
1179 * Return MW-style timestamp used for MySQL schema
1181 function timestamp( $ts=0 ) {
1182 return wfTimestamp(TS_MW
,$ts);
1188 function &resultObject( &$result ) {
1189 if( empty( $result ) ) {
1192 return new ResultWrapper( $this, $result );
1198 * Database abstraction object for mySQL
1199 * Inherit all methods and properties of Database::Database()
1200 * @category database
1204 class DatabaseMysql
extends Database
{
1210 * Result wrapper for grabbing data queried by someone else
1211 * @category database
1214 class ResultWrapper
{
1220 function ResultWrapper( $database, $result ) {
1221 $this->db
=& $database;
1222 $this->result
=& $result;
1228 function numRows() {
1229 return $this->db
->numRows( $this->result
);
1235 function &fetchObject() {
1236 return $this->db
->fetchObject( $this->result
);
1242 function &fetchRow() {
1243 return $this->db
->fetchRow( $this->result
);
1250 $this->db
->freeResult( $this->result
);
1251 unset( $this->result
);
1256 #------------------------------------------------------------------------------
1258 #------------------------------------------------------------------------------
1261 * Standard fail function, called by default when a connection cannot be
1263 * Displays the file cache if possible
1265 function wfEmergencyAbort( &$conn, $error ) {
1266 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1268 if( !headers_sent() ) {
1269 header( 'HTTP/1.0 500 Internal Server Error' );
1270 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1271 /* Don't cache error pages! They cause no end of trouble... */
1272 header( 'Cache-control: none' );
1273 header( 'Pragma: nocache' );
1275 $msg = $wgSiteNotice;
1276 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1279 if($wgUseFileCache) {
1284 $t = Title
::newFromURL( $title );
1285 } elseif (@/**/$_REQUEST['search']) {
1286 $search = $_REQUEST['search'];
1287 echo wfMsgNoDB( 'searchdisabled' );
1288 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1291 $t = Title
::newFromText( wfMsgNoDB( 'mainpage' ) );
1295 $cache = new CacheManager( $t );
1296 if( $cache->isFileCached() ) {
1297 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1298 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1300 $tag = '<div id="article">';
1301 $text = str_replace(
1304 $cache->fetchPageText() );