Followup r60051, with the rest of the callers and removing a useless subclassing...
[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->commit();
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 * Determines whether a field exists in a table
450 * Usually aborts on failure
451 * If errors are explicitly ignored, returns NULL on failure
452 */
453 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
454 $table = $this->tableName( $table );
455 $sql = "SELECT TOP 1 * FROM $table";
456 $res = $this->query( $sql, 'Database::fieldExists' );
457
458 $found = false;
459 while ( $row = $this->fetchArray( $res ) ) {
460 if ( isset($row[$field]) ) {
461 $found = true;
462 break;
463 }
464 }
465
466 $this->freeResult( $res );
467 return $found;
468 }
469
470 /**
471 * Get information about an index into an object
472 * Returns false if the index does not exist
473 */
474 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
475
476 throw new DBUnexpectedError( $this, 'Database::indexInfo called which is not supported yet' );
477 return null;
478
479 $table = $this->tableName( $table );
480 $sql = 'SHOW INDEX FROM '.$table;
481 $res = $this->query( $sql, $fname );
482 if ( !$res ) {
483 return null;
484 }
485
486 $result = array();
487 while ( $row = $this->fetchObject( $res ) ) {
488 if ( $row->Key_name == $index ) {
489 $result[] = $row;
490 }
491 }
492 $this->freeResult($res);
493
494 return empty($result) ? false : $result;
495 }
496
497 /**
498 * Query whether a given table exists
499 */
500 function tableExists( $table ) {
501 $table = $this->tableName( $table );
502 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'" );
503 $exist = ($res->numRows() > 0);
504 $this->freeResult($res);
505 return $exist;
506 }
507
508 /**
509 * mysql_fetch_field() wrapper
510 * Returns false if the field doesn't exist
511 *
512 * @param $table
513 * @param $field
514 */
515 function fieldInfo( $table, $field ) {
516 $table = $this->tableName( $table );
517 $res = $this->query( "SELECT TOP 1 * FROM $table" );
518 $n = mssql_num_fields( $res->result );
519 for( $i = 0; $i < $n; $i++ ) {
520 $meta = mssql_fetch_field( $res->result, $i );
521 if( $field == $meta->name ) {
522 return new MSSQLField($meta);
523 }
524 }
525 return false;
526 }
527
528 /**
529 * mysql_field_type() wrapper
530 */
531 function fieldType( $res, $index ) {
532 if ( $res instanceof ResultWrapper ) {
533 $res = $res->result;
534 }
535 return mssql_field_type( $res, $index );
536 }
537
538 /**
539 * INSERT wrapper, inserts an array into a table
540 *
541 * $a may be a single associative array, or an array of these with numeric keys, for
542 * multi-row insert.
543 *
544 * Usually aborts on failure
545 * If errors are explicitly ignored, returns success
546 *
547 * Same as parent class implementation except that it removes primary key from column lists
548 * because MSSQL doesn't support writing nulls to IDENTITY (AUTO_INCREMENT) columns
549 */
550 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
551 # No rows to insert, easy just return now
552 if ( !count( $a ) ) {
553 return true;
554 }
555 $table = $this->tableName( $table );
556 if ( !is_array( $options ) ) {
557 $options = array( $options );
558 }
559
560 # todo: need to record primary keys at table create time, and remove NULL assignments to them
561 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
562 $multi = true;
563 $keys = array_keys( $a[0] );
564 # if (ereg('_id$',$keys[0])) {
565 foreach ($a as $i) {
566 if (is_null($i[$keys[0]])) unset($i[$keys[0]]); # remove primary-key column from multiple insert lists if empty value
567 }
568 # }
569 $keys = array_keys( $a[0] );
570 } else {
571 $multi = false;
572 $keys = array_keys( $a );
573 # if (ereg('_id$',$keys[0]) && empty($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
574 if (is_null($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
575 $keys = array_keys( $a );
576 }
577
578 # handle IGNORE option
579 # example:
580 # MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
581 # MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
582 $ignore = in_array('IGNORE',$options);
583
584 # remove IGNORE from options list
585 if ($ignore) {
586 $oldoptions = $options;
587 $options = array();
588 foreach ($oldoptions as $o) if ($o != 'IGNORE') $options[] = $o;
589 }
590
591 $keylist = implode(',', $keys);
592 $sql = 'INSERT '.implode(' ', $options)." INTO $table (".implode(',', $keys).') VALUES ';
593 if ($multi) {
594 if ($ignore) {
595 # If multiple and ignore, then do each row as a separate conditional insert
596 foreach ($a as $row) {
597 $prival = $row[$keys[0]];
598 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
599 if (!$this->query("$sql (".$this->makeListWithoutNulls($row).')', $fname)) return false;
600 }
601 return true;
602 } else {
603 $first = true;
604 foreach ($a as $row) {
605 if ($first) $first = false; else $sql .= ',';
606 $sql .= '('.$this->makeListWithoutNulls($row).')';
607 }
608 }
609 } else {
610 if ($ignore) {
611 $prival = $a[$keys[0]];
612 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
613 }
614 $sql .= '('.$this->makeListWithoutNulls($a).')';
615 }
616 return (bool)$this->query( $sql, $fname );
617 }
618
619 /**
620 * MSSQL doesn't allow implicit casting of NULL's into non-null values for NOT NULL columns
621 * for now I've just converted the NULL's in the lists for updates and inserts into empty strings
622 * which get implicitly casted to 0 for numeric columns
623 * NOTE: the set() method above converts NULL to empty string as well but not via this method
624 */
625 function makeListWithoutNulls($a, $mode = LIST_COMMA) {
626 return str_replace("NULL","''",$this->makeList($a,$mode));
627 }
628
629 /**
630 * UPDATE wrapper, takes a condition array and a SET array
631 *
632 * @param $table String: The table to UPDATE
633 * @param $values Array: An array of values to SET
634 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
635 * @param $fname String: The Class::Function calling this function
636 * (for the log)
637 * @param $options Array: An array of UPDATE options, can be one or
638 * more of IGNORE, LOW_PRIORITY
639 * @return bool
640 */
641 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
642 $table = $this->tableName( $table );
643 $opts = $this->makeUpdateOptions( $options );
644 $sql = "UPDATE $opts $table SET " . $this->makeListWithoutNulls( $values, LIST_SET );
645 if ( $conds != '*' ) {
646 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
647 }
648 return $this->query( $sql, $fname );
649 }
650
651 /**
652 * Make UPDATE options for the Database::update function
653 *
654 * @private
655 * @param $options Array: The options passed to Database::update
656 * @return string
657 */
658 function makeUpdateOptions( $options ) {
659 if( !is_array( $options ) ) {
660 $options = array( $options );
661 }
662 $opts = array();
663 if ( in_array( 'LOW_PRIORITY', $options ) )
664 $opts[] = $this->lowPriorityOption();
665 if ( in_array( 'IGNORE', $options ) )
666 $opts[] = 'IGNORE';
667 return implode(' ', $opts);
668 }
669
670 /**
671 * Change the current database
672 */
673 function selectDB( $db ) {
674 $this->mDBname = $db;
675 return mssql_select_db( $db, $this->mConn );
676 }
677
678 /**
679 * MSSQL has a problem with the backtick quoting, so all this does is ensure the prefix is added exactly once
680 */
681 function tableName($name) {
682 return strpos($name, $this->mTablePrefix) === 0 ? $name : "{$this->mTablePrefix}$name";
683 }
684
685 /**
686 * MSSQL doubles quotes instead of escaping them
687 * @param $s String to be slashed.
688 * @return string slashed string.
689 */
690 function strencode($s) {
691 return str_replace("'","''",$s);
692 }
693
694 /**
695 * REPLACE query wrapper
696 * PostgreSQL simulates this with a DELETE followed by INSERT
697 * $row is the row to insert, an associative array
698 * $uniqueIndexes is an array of indexes. Each element may be either a
699 * field name or an array of field names
700 *
701 * It may be more efficient to leave off unique indexes which are unlikely to collide.
702 * However if you do this, you run the risk of encountering errors which wouldn't have
703 * occurred in MySQL
704 *
705 * @todo migrate comment to phodocumentor format
706 */
707 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
708 $table = $this->tableName( $table );
709
710 # Single row case
711 if ( !is_array( reset( $rows ) ) ) {
712 $rows = array( $rows );
713 }
714
715 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
716 $first = true;
717 foreach ( $rows as $row ) {
718 if ( $first ) {
719 $first = false;
720 } else {
721 $sql .= ',';
722 }
723 $sql .= '(' . $this->makeList( $row ) . ')';
724 }
725 return $this->query( $sql, $fname );
726 }
727
728 /**
729 * DELETE where the condition is a join
730 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
731 *
732 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
733 * join condition matches, set $conds='*'
734 *
735 * DO NOT put the join condition in $conds
736 *
737 * @param $delTable String: The table to delete from.
738 * @param $joinTable String: The other table.
739 * @param $delVar String: The variable to join on, in the first table.
740 * @param $joinVar String: The variable to join on, in the second table.
741 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
742 * @param $fname String: Calling function name
743 */
744 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
745 if ( !$conds ) {
746 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
747 }
748
749 $delTable = $this->tableName( $delTable );
750 $joinTable = $this->tableName( $joinTable );
751 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
752 if ( $conds != '*' ) {
753 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
754 }
755
756 return $this->query( $sql, $fname );
757 }
758
759 /**
760 * Returns the size of a text field, or -1 for "unlimited"
761 */
762 function textFieldSize( $table, $field ) {
763 $table = $this->tableName( $table );
764 $sql = "SELECT TOP 1 * FROM $table;";
765 $res = $this->query( $sql, 'Database::textFieldSize' );
766 $row = $this->fetchObject( $res );
767 $this->freeResult( $res );
768
769 $m = array();
770 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
771 $size = $m[1];
772 } else {
773 $size = -1;
774 }
775 return $size;
776 }
777
778 /**
779 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
780 */
781 function lowPriorityOption() {
782 return 'LOW_PRIORITY';
783 }
784
785 /**
786 * INSERT SELECT wrapper
787 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
788 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
789 * $conds may be "*" to copy the whole table
790 * srcTable may be an array of tables.
791 */
792 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
793 $insertOptions = array(), $selectOptions = array() )
794 {
795 $destTable = $this->tableName( $destTable );
796 if ( is_array( $insertOptions ) ) {
797 $insertOptions = implode( ' ', $insertOptions );
798 }
799 if( !is_array( $selectOptions ) ) {
800 $selectOptions = array( $selectOptions );
801 }
802 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
803 if( is_array( $srcTable ) ) {
804 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
805 } else {
806 $srcTable = $this->tableName( $srcTable );
807 }
808 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
809 " SELECT $startOpts " . implode( ',', $varMap ) .
810 " FROM $srcTable $useIndex ";
811 if ( $conds != '*' ) {
812 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
813 }
814 $sql .= " $tailOpts";
815 return $this->query( $sql, $fname );
816 }
817
818 /**
819 * Construct a LIMIT query with optional offset
820 * This is used for query pages
821 * $sql string SQL query we will append the limit to
822 * $limit integer the SQL limit
823 * $offset integer the SQL offset (default false)
824 */
825 function limitResult($sql, $limit, $offset=false) {
826 if( !is_numeric($limit) ) {
827 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
828 }
829 if ($offset) {
830 throw new DBUnexpectedError( $this, 'Database::limitResult called with non-zero offset which is not supported yet' );
831 } else {
832 $sql = ereg_replace("^SELECT", "SELECT TOP $limit", $sql);
833 }
834 return $sql;
835 }
836
837 /**
838 * Should determine if the last failure was due to a deadlock
839 * @return bool
840 */
841 function wasDeadlock() {
842 return $this->lastErrno() == 1205;
843 }
844
845 /**
846 * Return MW-style timestamp used for MySQL schema
847 */
848 function timestamp( $ts=0 ) {
849 return wfTimestamp(TS_MW,$ts);
850 }
851
852 /**
853 * Local database timestamp format or null
854 */
855 function timestampOrNull( $ts = null ) {
856 if( is_null( $ts ) ) {
857 return null;
858 } else {
859 return $this->timestamp( $ts );
860 }
861 }
862
863 /**
864 * @return string wikitext of a link to the server software's web site
865 */
866 function getSoftwareLink() {
867 return "[http://www.microsoft.com/sql/default.mspx Microsoft SQL Server 2005 Home]";
868 }
869
870 /**
871 * @return string Version information from the database
872 */
873 function getServerVersion() {
874 $row = mssql_fetch_row(mssql_query('select @@VERSION'));
875 return ereg("^(.+[0-9]+\\.[0-9]+\\.[0-9]+) ",$row[0],$m) ? $m[1] : $row[0];
876 }
877
878 function limitResultForUpdate($sql, $num) {
879 return $sql;
880 }
881
882 /**
883 * How lagged is this slave?
884 */
885 public function getLag() {
886 return 0;
887 }
888
889 /**
890 * Called by the installer script
891 * - this is the same way as DatabasePostgresql.php, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
892 */
893 public function setup_database() {
894 global $IP,$wgDBTableOptions;
895 $wgDBTableOptions = '';
896 $mysql_tmpl = "$IP/maintenance/tables.sql";
897 $mysql_iw = "$IP/maintenance/interwiki.sql";
898 $mssql_tmpl = "$IP/maintenance/mssql/tables.sql";
899
900 # Make an MSSQL template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
901 if (!file_exists($mssql_tmpl)) { # todo: make this conditional again
902 $sql = file_get_contents($mysql_tmpl);
903 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
904 $sql = preg_replace('/^\s*(UNIQUE )?(INDEX|KEY|FULLTEXT).+?$/m', '', $sql); # These indexes should be created with a CREATE INDEX query
905 $sql = preg_replace('/(\sKEY) [^\(]+\(/is', '$1 (', $sql); # "KEY foo (foo)" should just be "KEY (foo)"
906 $sql = preg_replace('/(varchar\([0-9]+\))\s+binary/i', '$1', $sql); # "varchar(n) binary" cannot be followed by "binary"
907 $sql = preg_replace('/(var)?binary\(([0-9]+)\)/ie', '"varchar(".strlen(pow(2,$2)).")"', $sql); # use varchar(chars) not binary(bits)
908 $sql = preg_replace('/ (var)?binary/i', ' varchar', $sql); # use varchar not binary
909 $sql = preg_replace('/(varchar\([0-9]+\)(?! N))/', '$1 NULL', $sql); # MSSQL complains if NULL is put into a varchar
910 #$sql = preg_replace('/ binary/i',' varchar',$sql); # MSSQL binary's can't be assigned with strings, so use varchar's instead
911 #$sql = preg_replace('/(binary\([0-9]+\) (NOT NULL )?default) [\'"].*?[\'"]/i','$1 0',$sql); # binary default cannot be string
912 $sql = preg_replace('/[a-z]*(blob|text)([ ,])/i', 'text$2', $sql); # no BLOB types in MSSQL
913 $sql = preg_replace('/\).+?;/',');', $sql); # remove all table options
914 $sql = preg_replace('/ (un)?signed/i', '', $sql);
915 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
916 $sql = str_replace(' bool ', ' bit ', $sql);
917 $sql = str_replace('auto_increment', 'IDENTITY(1,1)', $sql);
918 #$sql = preg_replace('/NOT NULL(?! IDENTITY)/', 'NULL', $sql); # Allow NULL's for non IDENTITY columns
919
920 # Tidy up and write file
921 $sql = preg_replace('/,\s*\)/s', "\n)", $sql); # Remove spurious commas left after INDEX removals
922 $sql = preg_replace('/^\s*^/m', '', $sql); # Remove empty lines
923 $sql = preg_replace('/;$/m', ";\n", $sql); # Separate each statement with an empty line
924 file_put_contents($mssql_tmpl, $sql);
925 }
926
927 # Parse the MSSQL template replacing inline variables such as /*$wgDBprefix*/
928 $err = $this->sourceFile($mssql_tmpl);
929 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__);
930
931 # Use DatabasePostgres's code to populate interwiki from MySQL template
932 $f = fopen($mysql_iw,'r');
933 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
934 $sql = "INSERT INTO {$this->mTablePrefix}interwiki(iw_prefix,iw_url,iw_local) VALUES ";
935 while (!feof($f)) {
936 $line = fgets($f,1024);
937 $matches = array();
938 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
939 $this->query("$sql $matches[1],$matches[2])");
940 }
941 }
942
943 public function getSearchEngine() {
944 return "SearchEngineDummy";
945 }
946 }
947
948 /**
949 * @ingroup Database
950 */
951 class MSSQLField extends MySQLField {
952
953 function __construct() {
954 }
955
956 static function fromText($db, $table, $field) {
957 $n = new MSSQLField;
958 $n->name = $field;
959 $n->tablename = $table;
960 return $n;
961 }
962
963 } // end DatabaseMssql class
964