]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/db/DatabaseMssql.php
MediaWiki 1.16.0
[autoinstallsdev/mediawiki.git] / includes / db / DatabaseMssql.php
1 <?php
2 /**
3  * This script is the MSSQL Server database abstraction layer
4  *
5  * See maintenance/mssql/README for development notes and other specific information
6  * @ingroup Database
7  * @file
8  */
9
10 /**
11  * @ingroup Database
12  */
13 class DatabaseMssql extends DatabaseBase {
14
15         var $mAffectedRows;
16         var $mLastResult;
17         var $mLastError;
18         var $mLastErrorNo;
19         var $mDatabaseFile;
20
21         /**
22          * Constructor
23          */
24         function __construct($server = false, $user = false, $password = false, $dbName = false,
25                         $failFunction = false, $flags = 0, $tablePrefix = 'get from global') {
26
27                 global $wgOut, $wgDBprefix, $wgCommandLineMode;
28                 if (!isset($wgOut)) $wgOut = null; # Can't get a reference if it hasn't been set yet
29                 $this->mOut =& $wgOut;
30                 $this->mFailFunction = $failFunction;
31                 $this->mFlags = $flags;
32
33                 if ( $this->mFlags & DBO_DEFAULT ) {
34                         if ( $wgCommandLineMode ) {
35                                 $this->mFlags &= ~DBO_TRX;
36                         } else {
37                                 $this->mFlags |= DBO_TRX;
38                         }
39                 }
40
41                 /** Get the default table prefix*/
42                 $this->mTablePrefix = $tablePrefix == 'get from global' ? $wgDBprefix : $tablePrefix;
43
44                 if ($server) $this->open($server, $user, $password, $dbName);
45
46         }
47
48         function getType() {
49                 return 'mssql';
50         }
51
52         /**
53          * todo: check if these should be true like parent class
54          */
55         function implicitGroupby()   { return false; }
56         function implicitOrderby()   { return false; }
57
58         static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
59                 return new DatabaseMssql($server, $user, $password, $dbName, $failFunction, $flags);
60         }
61
62         /** Open an MSSQL database and return a resource handle to it
63          *  NOTE: only $dbName is used, the other parameters are irrelevant for MSSQL databases
64          */
65         function open($server,$user,$password,$dbName) {
66                 wfProfileIn(__METHOD__);
67
68                 # Test for missing mysql.so
69                 # First try to load it
70                 if (!@extension_loaded('mssql')) {
71                         @dl('mssql.so');
72                 }
73
74                 # Fail now
75                 # Otherwise we get a suppressed fatal error, which is very hard to track down
76                 if (!function_exists( 'mssql_connect')) {
77                         throw new DBConnectionError( $this, "MSSQL functions missing, have you compiled PHP with the --with-mssql option?\n" );
78                 }
79
80                 $this->close();
81                 $this->mServer   = $server;
82                 $this->mUser     = $user;
83                 $this->mPassword = $password;
84                 $this->mDBname   = $dbName;
85
86                 wfProfileIn("dbconnect-$server");
87
88                 # Try to connect up to three times
89                 # The kernel's default SYN retransmission period is far too slow for us,
90                 # so we use a short timeout plus a manual retry.
91                 $this->mConn = false;
92                 $max = 3;
93                 for ( $i = 0; $i < $max && !$this->mConn; $i++ ) {
94                         if ( $i > 1 ) {
95                                 usleep( 1000 );
96                         }
97                         if ($this->mFlags & DBO_PERSISTENT) {
98                                 @/**/$this->mConn = mssql_pconnect($server, $user, $password);
99                         } else {
100                                 # Create a new connection...
101                                 @/**/$this->mConn = mssql_connect($server, $user, $password, true);
102                         }
103                 }
104                 
105                 wfProfileOut("dbconnect-$server");
106
107                 if ($dbName != '') {
108                         if ($this->mConn !== false) {
109                                 $success = @/**/mssql_select_db($dbName, $this->mConn);
110                                 if (!$success) {
111                                         $error = "Error selecting database $dbName on server {$this->mServer} " .
112                                                 "from client host " . wfHostname() . "\n";
113                                         wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
114                                         wfDebug( $error );
115                                 }
116                         } else {
117                                 wfDebug("DB connection error\n");
118                                 wfDebug("Server: $server, User: $user, Password: ".substr($password, 0, 3)."...\n");
119                                 $success = false;
120                         }
121                 } else {
122                         # Delay USE query
123                         $success = (bool)$this->mConn;
124                 }
125
126                 if (!$success) $this->reportConnectionError();
127                 $this->mOpened = $success;
128                 wfProfileOut(__METHOD__);
129                 return $success;
130         }
131
132         /**
133          * Close an MSSQL database
134          */
135         function close() {
136                 $this->mOpened = false;
137                 if ($this->mConn) {
138                         if ($this->trxLevel()) $this->commit();
139                         return mssql_close($this->mConn);
140                 } else return true;
141         }
142
143         /**
144          * - MSSQL doesn't seem to do buffered results
145          * - the trasnaction syntax is modified here to avoid having to replicate
146          *   Database::query which uses BEGIN, COMMIT, ROLLBACK
147          */
148         function doQuery($sql) {
149                 if ($sql == 'BEGIN' || $sql == 'COMMIT' || $sql == 'ROLLBACK') return true; # $sql .= ' TRANSACTION';
150                 $sql = preg_replace('|[^\x07-\x7e]|','?',$sql); # TODO: need to fix unicode - just removing it here while testing
151                 $ret = mssql_query($sql, $this->mConn);
152                 if ($ret === false) {
153                         $err = mssql_get_last_message();
154                         if ($err) $this->mlastError = $err;
155                         $row = mssql_fetch_row(mssql_query('select @@ERROR'));
156                         if ($row[0]) $this->mlastErrorNo = $row[0];
157                 } else $this->mlastErrorNo = false;
158                 return $ret;
159         }
160
161         /**
162          * Free a result object
163          */
164         function freeResult( $res ) {
165                 if ( $res instanceof ResultWrapper ) {
166                         $res = $res->result;
167                 }
168                 if ( !@/**/mssql_free_result( $res ) ) {
169                         throw new DBUnexpectedError( $this, "Unable to free MSSQL result" );
170                 }
171         }
172
173         /**
174          * Fetch the next row from the given result object, in object form.
175          * Fields can be retrieved with $row->fieldname, with fields acting like
176          * member variables.
177          *
178          * @param $res SQL result object as returned from Database::query(), etc.
179          * @return MySQL row object
180          * @throws DBUnexpectedError Thrown if the database returns an error
181          */
182         function fetchObject( $res ) {
183                 if ( $res instanceof ResultWrapper ) {
184                         $res = $res->result;
185                 }
186                 @/**/$row = mssql_fetch_object( $res );
187                 if ( $this->lastErrno() ) {
188                         throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
189                 }
190                 return $row;
191         }
192
193         /**
194          * Fetch the next row from the given result object, in associative array
195          * form.  Fields are retrieved with $row['fieldname'].
196          *
197          * @param $res SQL result object as returned from Database::query(), etc.
198          * @return MySQL row object
199          * @throws DBUnexpectedError Thrown if the database returns an error
200          */
201         function fetchRow( $res ) {
202                 if ( $res instanceof ResultWrapper ) {
203                         $res = $res->result;
204                 }
205                 @/**/$row = mssql_fetch_array( $res );
206                 if ( $this->lastErrno() ) {
207                         throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
208                 }
209                 return $row;
210         }
211
212         /**
213          * Get the number of rows in a result object
214          */
215         function numRows( $res ) {
216                 if ( $res instanceof ResultWrapper ) {
217                         $res = $res->result;
218                 }
219                 @/**/$n = mssql_num_rows( $res );
220                 if ( $this->lastErrno() ) {
221                         throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
222                 }
223                 return $n;
224         }
225
226         /**
227          * Get the number of fields in a result object
228          * See documentation for mysql_num_fields()
229          * @param $res SQL result object as returned from Database::query(), etc.
230          */
231         function numFields( $res ) {
232                 if ( $res instanceof ResultWrapper ) {
233                         $res = $res->result;
234                 }
235                 return mssql_num_fields( $res );
236         }
237
238         /**
239          * Get a field name in a result object
240          * See documentation for mysql_field_name():
241          * http://www.php.net/mysql_field_name
242          * @param $res SQL result object as returned from Database::query(), etc.
243          * @param $n Int
244          */
245         function fieldName( $res, $n ) {
246                 if ( $res instanceof ResultWrapper ) {
247                         $res = $res->result;
248                 }
249                 return mssql_field_name( $res, $n );
250         }
251
252         /**
253          * Get the inserted value of an auto-increment row
254          *
255          * The value inserted should be fetched from nextSequenceValue()
256          *
257          * Example:
258          * $id = $dbw->nextSequenceValue('page_page_id_seq');
259          * $dbw->insert('page',array('page_id' => $id));
260          * $id = $dbw->insertId();
261          */
262         function insertId() {
263                 $row = mssql_fetch_row(mssql_query('select @@IDENTITY'));
264                 return $row[0];
265         }
266
267         /**
268          * Change the position of the cursor in a result object
269          * See mysql_data_seek()
270          * @param $res SQL result object as returned from Database::query(), etc.
271          * @param $row Database row
272          */
273         function dataSeek( $res, $row ) {
274                 if ( $res instanceof ResultWrapper ) {
275                         $res = $res->result;
276                 }
277                 return mssql_data_seek( $res, $row );
278         }
279
280         /**
281          * Get the last error number
282          */
283         function lastErrno() {
284                 return $this->mlastErrorNo;
285         }
286
287         /**
288          * Get a description of the last error
289          */
290         function lastError() {
291                 return $this->mlastError;
292         }
293
294         /**
295          * Get the number of rows affected by the last write query
296          */
297         function affectedRows() {
298                 return mssql_rows_affected( $this->mConn );
299         }
300
301         /**
302          * Simple UPDATE wrapper
303          * Usually aborts on failure
304          * If errors are explicitly ignored, returns success
305          *
306          * This function exists for historical reasons, Database::update() has a more standard
307          * calling convention and feature set
308          */
309         function set( $table, $var, $value, $cond, $fname = 'Database::set' )
310         {
311                 if ($value == "NULL") $value = "''"; # see comments in makeListWithoutNulls()
312                 $table = $this->tableName( $table );
313                 $sql = "UPDATE $table SET $var = '" .
314                   $this->strencode( $value ) . "' WHERE ($cond)";
315                 return (bool)$this->query( $sql, $fname );
316         }
317
318         /**
319          * Simple SELECT wrapper, returns a single field, input must be encoded
320          * Usually aborts on failure
321          * If errors are explicitly ignored, returns FALSE on failure
322          */
323         function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
324                 if ( !is_array( $options ) ) {
325                         $options = array( $options );
326                 }
327                 $options['LIMIT'] = 1;
328
329                 $res = $this->select( $table, $var, $cond, $fname, $options );
330                 if ( $res === false || !$this->numRows( $res ) ) {
331                         return false;
332                 }
333                 $row = $this->fetchRow( $res );
334                 if ( $row !== false ) {
335                         $this->freeResult( $res );
336                         return $row[0];
337                 } else {
338                         return false;
339                 }
340         }
341
342         /**
343          * Returns an optional USE INDEX clause to go after the table, and a
344          * string to go at the end of the query
345          *
346          * @private
347          *
348          * @param $options Array: an associative array of options to be turned into
349          *              an SQL query, valid keys are listed in the function.
350          * @return array
351          */
352         function makeSelectOptions( $options ) {
353                 $preLimitTail = $postLimitTail = '';
354                 $startOpts = '';
355
356                 $noKeyOptions = array();
357                 foreach ( $options as $key => $option ) {
358                         if ( is_numeric( $key ) ) {
359                                 $noKeyOptions[$option] = true;
360                         }
361                 }
362
363                 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
364                 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
365                 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
366                 
367                 //if (isset($options['LIMIT'])) {
368                 //      $tailOpts .= $this->limitResult('', $options['LIMIT'],
369                 //              isset($options['OFFSET']) ? $options['OFFSET'] 
370                 //              : false);
371                 //}
372
373                 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
374                 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
375                 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
376
377                 # Various MySQL extensions
378                 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
379                 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
380                 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
381                 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
382                 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
383                 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
384                 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
385                 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
386
387                 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
388                         $useIndex = $this->useIndexClause( $options['USE INDEX'] );
389                 } else {
390                         $useIndex = '';
391                 }
392                 
393                 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
394         }
395
396         /**
397          * SELECT wrapper
398          *
399          * @param $table   Mixed: Array or string, table name(s) (prefix auto-added)
400          * @param $vars    Mixed: Array or string, field name(s) to be retrieved
401          * @param $conds   Mixed: Array or string, condition(s) for WHERE
402          * @param $fname   String: Calling function name (use __METHOD__) for logs/profiling
403          * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
404          *                        see Database::makeSelectOptions code for list of supported stuff
405          * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
406          */
407         function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
408         {
409                 if( is_array( $vars ) ) {
410                         $vars = implode( ',', $vars );
411                 }
412                 if( !is_array( $options ) ) {
413                         $options = array( $options );
414                 }
415                 if( is_array( $table ) ) {
416                         if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
417                                 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
418                         else
419                                 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
420                 } elseif ($table!='') {
421                         if ($table{0}==' ') {
422                                 $from = ' FROM ' . $table;
423                         } else {
424                                 $from = ' FROM ' . $this->tableName( $table );
425                         }
426                 } else {
427                         $from = '';
428                 }
429
430                 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
431
432                 if( !empty( $conds ) ) {
433                         if ( is_array( $conds ) ) {
434                                 $conds = $this->makeList( $conds, LIST_AND );
435                         }
436                         $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
437                 } else {
438                         $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
439                 }
440
441                 if (isset($options['LIMIT']))
442                         $sql = $this->limitResult($sql, $options['LIMIT'],
443                                 isset($options['OFFSET']) ? $options['OFFSET'] : false);
444                 $sql = "$sql $postLimitTail";
445                 
446                 if (isset($options['EXPLAIN'])) {
447                         $sql = 'EXPLAIN ' . $sql;
448                 }
449                 return $this->query( $sql, $fname );
450         }
451
452         /**
453          * Determines whether a field exists in a table
454          * Usually aborts on failure
455          * If errors are explicitly ignored, returns NULL on failure
456          */
457         function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
458                 $table = $this->tableName( $table );
459                 $sql = "SELECT TOP 1 * FROM $table";
460                 $res = $this->query( $sql, 'Database::fieldExists' );
461
462                 $found = false;
463                 while ( $row = $this->fetchArray( $res ) ) {
464                         if ( isset($row[$field]) ) {
465                                 $found = true;
466                                 break;
467                         }
468                 }
469
470                 $this->freeResult( $res );
471                 return $found;
472         }
473
474         /**
475          * Get information about an index into an object
476          * Returns false if the index does not exist
477          */
478         function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
479
480                 throw new DBUnexpectedError( $this, 'Database::indexInfo called which is not supported yet' );
481                 return null;
482
483                 $table = $this->tableName( $table );
484                 $sql = 'SHOW INDEX FROM '.$table;
485                 $res = $this->query( $sql, $fname );
486                 if ( !$res ) {
487                         return null;
488                 }
489
490                 $result = array();
491                 while ( $row = $this->fetchObject( $res ) ) {
492                         if ( $row->Key_name == $index ) {
493                                 $result[] = $row;
494                         }
495                 }
496                 $this->freeResult($res);
497                 
498                 return empty($result) ? false : $result;
499         }
500
501         /**
502          * Query whether a given table exists
503          */
504         function tableExists( $table ) {
505                 $table = $this->tableName( $table );
506                 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'" );
507                 $exist = ($res->numRows() > 0);
508                 $this->freeResult($res);
509                 return $exist;
510         }
511
512         /**
513          * mysql_fetch_field() wrapper
514          * Returns false if the field doesn't exist
515          *
516          * @param $table
517          * @param $field
518          */
519         function fieldInfo( $table, $field ) {
520                 $table = $this->tableName( $table );
521                 $res = $this->query( "SELECT TOP 1 * FROM $table" );
522                 $n = mssql_num_fields( $res->result );
523                 for( $i = 0; $i < $n; $i++ ) {
524                         $meta = mssql_fetch_field( $res->result, $i );
525                         if( $field == $meta->name ) {
526                                 return new MSSQLField($meta);
527                         }
528                 }
529                 return false;
530         }
531
532         /**
533          * mysql_field_type() wrapper
534          */
535         function fieldType( $res, $index ) {
536                 if ( $res instanceof ResultWrapper ) {
537                         $res = $res->result;
538                 }
539                 return mssql_field_type( $res, $index );
540         }
541
542         /**
543          * INSERT wrapper, inserts an array into a table
544          *
545          * $a may be a single associative array, or an array of these with numeric keys, for
546          * multi-row insert.
547          *
548          * Usually aborts on failure
549          * If errors are explicitly ignored, returns success
550          * 
551          * Same as parent class implementation except that it removes primary key from column lists
552          * because MSSQL doesn't support writing nulls to IDENTITY (AUTO_INCREMENT) columns
553          */
554         function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
555                 # No rows to insert, easy just return now
556                 if ( !count( $a ) ) {
557                         return true;
558                 }
559                 $table = $this->tableName( $table );
560                 if ( !is_array( $options ) ) {
561                         $options = array( $options );
562                 }
563                 
564                 # todo: need to record primary keys at table create time, and remove NULL assignments to them
565                 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
566                         $multi = true;
567                         $keys = array_keys( $a[0] );
568 #                       if (ereg('_id$',$keys[0])) {
569                                 foreach ($a as $i) {
570                                         if (is_null($i[$keys[0]])) unset($i[$keys[0]]); # remove primary-key column from multiple insert lists if empty value
571                                 }
572 #                       }
573                         $keys = array_keys( $a[0] );
574                 } else {
575                         $multi = false;
576                         $keys = array_keys( $a );
577 #                       if (ereg('_id$',$keys[0]) && empty($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
578                         if (is_null($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
579                         $keys = array_keys( $a );
580                 }
581
582                 # handle IGNORE option
583                 # example:
584                 #   MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
585                 #   MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
586                 $ignore = in_array('IGNORE',$options);
587
588                 # remove IGNORE from options list
589                 if ($ignore) {
590                         $oldoptions = $options;
591                         $options = array();
592                         foreach ($oldoptions as $o) if ($o != 'IGNORE') $options[] = $o;
593                 }
594
595                 $keylist = implode(',', $keys);
596                 $sql = 'INSERT '.implode(' ', $options)." INTO $table (".implode(',', $keys).') VALUES ';
597                 if ($multi) {
598                         if ($ignore) {
599                                 # If multiple and ignore, then do each row as a separate conditional insert
600                                 foreach ($a as $row) {
601                                         $prival = $row[$keys[0]];
602                                         $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
603                                         if (!$this->query("$sql (".$this->makeListWithoutNulls($row).')', $fname)) return false;
604                                 }
605                                 return true;
606                         } else {
607                                 $first = true;
608                                 foreach ($a as $row) {
609                                         if ($first) $first = false; else $sql .= ',';
610                                         $sql .= '('.$this->makeListWithoutNulls($row).')';
611                                 }
612                         }
613                 } else {
614                         if ($ignore) {
615                                 $prival = $a[$keys[0]];
616                                 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
617                         }
618                         $sql .= '('.$this->makeListWithoutNulls($a).')';
619                 }
620                 return (bool)$this->query( $sql, $fname );
621         }
622
623         /**
624          * MSSQL doesn't allow implicit casting of NULL's into non-null values for NOT NULL columns
625          *   for now I've just converted the NULL's in the lists for updates and inserts into empty strings
626          *   which get implicitly casted to 0 for numeric columns
627          * NOTE: the set() method above converts NULL to empty string as well but not via this method
628          */
629         function makeListWithoutNulls($a, $mode = LIST_COMMA) {
630                 return str_replace("NULL","''",$this->makeList($a,$mode));
631         }
632
633         /**
634          * UPDATE wrapper, takes a condition array and a SET array
635          *
636          * @param $table   String: The table to UPDATE
637          * @param $values  Array: An array of values to SET
638          * @param $conds   Array: An array of conditions (WHERE). Use '*' to update all rows.
639          * @param $fname   String: The Class::Function calling this function
640          *                        (for the log)
641          * @param $options Array: An array of UPDATE options, can be one or
642          *                        more of IGNORE, LOW_PRIORITY
643          * @return bool
644          */
645         function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
646                 $table = $this->tableName( $table );
647                 $opts = $this->makeUpdateOptions( $options );
648                 $sql = "UPDATE $opts $table SET " . $this->makeListWithoutNulls( $values, LIST_SET );
649                 if ( $conds != '*' ) {
650                         $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
651                 }
652                 return $this->query( $sql, $fname );
653         }
654
655         /**
656          * Make UPDATE options for the Database::update function
657          *
658          * @private
659          * @param $options Array: The options passed to Database::update
660          * @return string
661          */
662         function makeUpdateOptions( $options ) {
663                 if( !is_array( $options ) ) {
664                         $options = array( $options );
665                 }
666                 $opts = array();
667                 if ( in_array( 'LOW_PRIORITY', $options ) )
668                         $opts[] = $this->lowPriorityOption();
669                 if ( in_array( 'IGNORE', $options ) )
670                         $opts[] = 'IGNORE';
671                 return implode(' ', $opts);
672         }
673
674         /**
675          * Change the current database
676          */
677         function selectDB( $db ) {
678                 $this->mDBname = $db;
679                 return mssql_select_db( $db, $this->mConn );
680         }
681
682         /**
683          * MSSQL has a problem with the backtick quoting, so all this does is ensure the prefix is added exactly once
684          */
685         function tableName($name) {
686                 return strpos($name, $this->mTablePrefix) === 0 ? $name : "{$this->mTablePrefix}$name";
687         }
688
689         /**
690          * MSSQL doubles quotes instead of escaping them
691          * @param $s String to be slashed.
692          * @return string slashed string.
693          */
694         function strencode($s) {
695                 return str_replace("'","''",$s);
696         }
697
698         /**
699          * REPLACE query wrapper
700          * PostgreSQL simulates this with a DELETE followed by INSERT
701          * $row is the row to insert, an associative array
702          * $uniqueIndexes is an array of indexes. Each element may be either a
703          * field name or an array of field names
704          *
705          * It may be more efficient to leave off unique indexes which are unlikely to collide.
706          * However if you do this, you run the risk of encountering errors which wouldn't have
707          * occurred in MySQL
708          *
709          * @todo migrate comment to phodocumentor format
710          */
711         function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
712                 $table = $this->tableName( $table );
713
714                 # Single row case
715                 if ( !is_array( reset( $rows ) ) ) {
716                         $rows = array( $rows );
717                 }
718
719                 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
720                 $first = true;
721                 foreach ( $rows as $row ) {
722                         if ( $first ) {
723                                 $first = false;
724                         } else {
725                                 $sql .= ',';
726                         }
727                         $sql .= '(' . $this->makeList( $row ) . ')';
728                 }
729                 return $this->query( $sql, $fname );
730         }
731
732         /**
733          * DELETE where the condition is a join
734          * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
735          *
736          * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
737          * join condition matches, set $conds='*'
738          *
739          * DO NOT put the join condition in $conds
740          *
741          * @param $delTable String: The table to delete from.
742          * @param $joinTable String: The other table.
743          * @param $delVar String: The variable to join on, in the first table.
744          * @param $joinVar String: The variable to join on, in the second table.
745          * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
746          * @param $fname String: Calling function name
747          */
748         function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
749                 if ( !$conds ) {
750                         throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
751                 }
752
753                 $delTable = $this->tableName( $delTable );
754                 $joinTable = $this->tableName( $joinTable );
755                 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
756                 if ( $conds != '*' ) {
757                         $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
758                 }
759
760                 return $this->query( $sql, $fname );
761         }
762
763         /**
764          * Returns the size of a text field, or -1 for "unlimited"
765          */
766         function textFieldSize( $table, $field ) {
767                 $table = $this->tableName( $table );
768                 $sql = "SELECT TOP 1 * FROM $table;";
769                 $res = $this->query( $sql, 'Database::textFieldSize' );
770                 $row = $this->fetchObject( $res );
771                 $this->freeResult( $res );
772
773                 $m = array();
774                 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
775                         $size = $m[1];
776                 } else {
777                         $size = -1;
778                 }
779                 return $size;
780         }
781
782         /**
783          * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
784          */
785         function lowPriorityOption() {
786                 return 'LOW_PRIORITY';
787         }
788
789         /**
790          * INSERT SELECT wrapper
791          * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
792          * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
793          * $conds may be "*" to copy the whole table
794          * srcTable may be an array of tables.
795          */
796         function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
797                 $insertOptions = array(), $selectOptions = array() )
798         {
799                 $destTable = $this->tableName( $destTable );
800                 if ( is_array( $insertOptions ) ) {
801                         $insertOptions = implode( ' ', $insertOptions );
802                 }
803                 if( !is_array( $selectOptions ) ) {
804                         $selectOptions = array( $selectOptions );
805                 }
806                 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
807                 if( is_array( $srcTable ) ) {
808                         $srcTable =  implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
809                 } else {
810                         $srcTable = $this->tableName( $srcTable );
811                 }
812                 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
813                         " SELECT $startOpts " . implode( ',', $varMap ) .
814                         " FROM $srcTable $useIndex ";
815                 if ( $conds != '*' ) {
816                         $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
817                 }
818                 $sql .= " $tailOpts";
819                 return $this->query( $sql, $fname );
820         }
821
822         /**
823          * Construct a LIMIT query with optional offset
824          * This is used for query pages
825          * $sql string SQL query we will append the limit to
826          * $limit integer the SQL limit
827          * $offset integer the SQL offset (default false)
828          */
829         function limitResult($sql, $limit, $offset=false) {
830                 if( !is_numeric($limit) ) {
831                         throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
832                 }
833                 if ($offset) {
834                         throw new DBUnexpectedError( $this, 'Database::limitResult called with non-zero offset which is not supported yet' );
835                 } else {
836                         $sql = ereg_replace("^SELECT", "SELECT TOP $limit", $sql);
837                 }
838                 return $sql;
839         }
840
841         /**
842          * Should determine if the last failure was due to a deadlock
843          * @return bool
844          */
845         function wasDeadlock() {
846                 return $this->lastErrno() == 1205;
847         }
848
849         /**
850          * Return MW-style timestamp used for MySQL schema
851          */
852         function timestamp( $ts=0 ) {
853                 return wfTimestamp(TS_MW,$ts);
854         }
855
856         /**
857          * Local database timestamp format or null
858          */
859         function timestampOrNull( $ts = null ) {
860                 if( is_null( $ts ) ) {
861                         return null;
862                 } else {
863                         return $this->timestamp( $ts );
864                 }
865         }
866
867         /**
868          * @return string wikitext of a link to the server software's web site
869          */
870         function getSoftwareLink() {
871                 return "[http://www.microsoft.com/sql/default.mspx Microsoft SQL Server 2005 Home]";
872         }
873
874         /**
875          * @return string Version information from the database
876          */
877         function getServerVersion() {
878                 $row = mssql_fetch_row(mssql_query('select @@VERSION'));
879                 return ereg("^(.+[0-9]+\\.[0-9]+\\.[0-9]+) ",$row[0],$m) ? $m[1] : $row[0];
880         }
881
882         function limitResultForUpdate($sql, $num) {
883                 return $sql;
884         }
885
886         /**
887          * How lagged is this slave?
888          */
889         public function getLag() {
890                 return 0;
891         }
892
893         /**
894          * Called by the installer script
895          * - this is the same way as DatabasePostgresql.php, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
896          */
897         public function setup_database() {
898                 global $IP,$wgDBTableOptions;
899                 $wgDBTableOptions = '';
900                 $mysql_tmpl = "$IP/maintenance/tables.sql";
901                 $mysql_iw   = "$IP/maintenance/interwiki.sql";
902                 $mssql_tmpl = "$IP/maintenance/mssql/tables.sql";
903
904                 # Make an MSSQL template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
905                 if (!file_exists($mssql_tmpl)) { # todo: make this conditional again
906                         $sql = file_get_contents($mysql_tmpl);
907                         $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
908                         $sql = preg_replace('/^\s*(UNIQUE )?(INDEX|KEY|FULLTEXT).+?$/m', '', $sql); # These indexes should be created with a CREATE INDEX query
909                         $sql = preg_replace('/(\sKEY) [^\(]+\(/is', '$1 (', $sql); # "KEY foo (foo)" should just be "KEY (foo)"
910                         $sql = preg_replace('/(varchar\([0-9]+\))\s+binary/i', '$1', $sql); # "varchar(n) binary" cannot be followed by "binary"
911                         $sql = preg_replace('/(var)?binary\(([0-9]+)\)/ie', '"varchar(".strlen(pow(2,$2)).")"', $sql); # use varchar(chars) not binary(bits)
912                         $sql = preg_replace('/ (var)?binary/i', ' varchar', $sql); # use varchar not binary
913                         $sql = preg_replace('/(varchar\([0-9]+\)(?! N))/', '$1 NULL', $sql); # MSSQL complains if NULL is put into a varchar
914                         #$sql = preg_replace('/ binary/i',' varchar',$sql); # MSSQL binary's can't be assigned with strings, so use varchar's instead
915                         #$sql = preg_replace('/(binary\([0-9]+\) (NOT NULL )?default) [\'"].*?[\'"]/i','$1 0',$sql); # binary default cannot be string
916                         $sql = preg_replace('/[a-z]*(blob|text)([ ,])/i', 'text$2', $sql); # no BLOB types in MSSQL
917                         $sql = preg_replace('/\).+?;/',');', $sql); # remove all table options
918                         $sql = preg_replace('/ (un)?signed/i', '', $sql);
919                         $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
920                         $sql = str_replace(' bool ', ' bit ', $sql);
921                         $sql = str_replace('auto_increment', 'IDENTITY(1,1)', $sql);
922                         #$sql = preg_replace('/NOT NULL(?! IDENTITY)/', 'NULL', $sql); # Allow NULL's for non IDENTITY columns
923
924                         # Tidy up and write file
925                         $sql = preg_replace('/,\s*\)/s', "\n)", $sql); # Remove spurious commas left after INDEX removals
926                         $sql = preg_replace('/^\s*^/m', '', $sql); # Remove empty lines
927                         $sql = preg_replace('/;$/m', ";\n", $sql); # Separate each statement with an empty line
928                         file_put_contents($mssql_tmpl, $sql);
929                 }
930
931                 # Parse the MSSQL template replacing inline variables such as /*$wgDBprefix*/
932                 $err = $this->sourceFile($mssql_tmpl);
933                 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__);
934
935                 # Use DatabasePostgres's code to populate interwiki from MySQL template
936                 $f = fopen($mysql_iw,'r');
937                 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
938                 $sql = "INSERT INTO {$this->mTablePrefix}interwiki(iw_prefix,iw_url,iw_local) VALUES ";
939                 while (!feof($f)) {
940                         $line = fgets($f,1024);
941                         $matches = array();
942                         if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
943                         $this->query("$sql $matches[1],$matches[2])");
944                 }
945         }
946         
947         public function getSearchEngine() {
948                 return "SearchEngineDummy";
949         }
950 }
951
952 /**
953  * @ingroup Database
954  */
955 class MSSQLField extends MySQLField {
956
957         function __construct() {
958         }
959
960         static function fromText($db, $table, $field) {
961                 $n = new MSSQLField;
962                 $n->name = $field;
963                 $n->tablename = $table;
964                 return $n;
965         }
966
967 } // end DatabaseMssql class
968