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