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