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