3 * This script is the MSSQL Server database abstraction layer
5 * See maintenance/mssql/README for development notes and other specific information
13 class DatabaseMssql
extends DatabaseBase
{
24 function __construct($server = false, $user = false, $password = false, $dbName = false,
25 $failFunction = false, $flags = 0, $tablePrefix = 'get from global') {
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;
33 if ( $this->mFlags
& DBO_DEFAULT
) {
34 if ( $wgCommandLineMode ) {
35 $this->mFlags
&= ~DBO_TRX
;
37 $this->mFlags |
= DBO_TRX
;
41 /** Get the default table prefix*/
42 $this->mTablePrefix
= $tablePrefix == 'get from global' ?
$wgDBprefix : $tablePrefix;
44 if ($server) $this->open($server, $user, $password, $dbName);
53 * todo: check if these should be true like parent class
55 function implicitGroupby() { return false; }
56 function implicitOrderby() { return false; }
58 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
59 return new DatabaseMssql($server, $user, $password, $dbName, $failFunction, $flags);
62 /** Open an MSSQL database and return a resource handle to it
63 * NOTE: only $dbName is used, the other parameters are irrelevant for MSSQL databases
65 function open($server,$user,$password,$dbName) {
66 wfProfileIn(__METHOD__
);
68 # Test for missing mysql.so
69 # First try to load it
70 if (!@extension_loaded
('mssql')) {
75 # Otherwise we get a suppressed fatal error, which is very hard to track down
76 if (!function_exists( 'mssql_connect')) {
77 throw new DBConnectionError( $this, "MSSQL functions missing, have you compiled PHP with the --with-mssql option?\n" );
81 $this->mServer
= $server;
83 $this->mPassword
= $password;
84 $this->mDBname
= $dbName;
86 wfProfileIn("dbconnect-$server");
88 # Try to connect up to three times
89 # The kernel's default SYN retransmission period is far too slow for us,
90 # so we use a short timeout plus a manual retry.
93 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
97 if ($this->mFlags
& DBO_PERSISTENT
) {
98 @/**/$this->mConn
= mssql_pconnect($server, $user, $password);
100 # Create a new connection...
101 @/**/$this->mConn
= mssql_connect($server, $user, $password, true);
105 wfProfileOut("dbconnect-$server");
108 if ($this->mConn
!== false) {
109 $success = @/**/mssql_select_db($dbName, $this->mConn
);
111 $error = "Error selecting database $dbName on server {$this->mServer} " .
112 "from client host " . wfHostname() . "\n";
113 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
117 wfDebug("DB connection error\n");
118 wfDebug("Server: $server, User: $user, Password: ".substr($password, 0, 3)."...\n");
123 $success = (bool)$this->mConn
;
126 if (!$success) $this->reportConnectionError();
127 $this->mOpened
= $success;
128 wfProfileOut(__METHOD__
);
133 * Close an MSSQL database
136 $this->mOpened
= false;
138 if ($this->trxLevel()) $this->commit();
139 return mssql_close($this->mConn
);
144 * - MSSQL doesn't seem to do buffered results
145 * - the trasnaction syntax is modified here to avoid having to replicate
146 * Database::query which uses BEGIN, COMMIT, ROLLBACK
148 function doQuery($sql) {
149 if ($sql == 'BEGIN' ||
$sql == 'COMMIT' ||
$sql == 'ROLLBACK') return true; # $sql .= ' TRANSACTION';
150 $sql = preg_replace('|[^\x07-\x7e]|','?',$sql); # TODO: need to fix unicode - just removing it here while testing
151 $ret = mssql_query($sql, $this->mConn
);
152 if ($ret === false) {
153 $err = mssql_get_last_message();
154 if ($err) $this->mlastError
= $err;
155 $row = mssql_fetch_row(mssql_query('select @@ERROR'));
156 if ($row[0]) $this->mlastErrorNo
= $row[0];
157 } else $this->mlastErrorNo
= false;
162 * Free a result object
164 function freeResult( $res ) {
165 if ( $res instanceof ResultWrapper
) {
168 if ( !@/**/mssql_free_result( $res ) ) {
169 throw new DBUnexpectedError( $this, "Unable to free MSSQL result" );
174 * Fetch the next row from the given result object, in object form.
175 * Fields can be retrieved with $row->fieldname, with fields acting like
178 * @param $res SQL result object as returned from Database::query(), etc.
179 * @return MySQL row object
180 * @throws DBUnexpectedError Thrown if the database returns an error
182 function fetchObject( $res ) {
183 if ( $res instanceof ResultWrapper
) {
186 @/**/$row = mssql_fetch_object( $res );
187 if ( $this->lastErrno() ) {
188 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
194 * Fetch the next row from the given result object, in associative array
195 * form. Fields are retrieved with $row['fieldname'].
197 * @param $res SQL result object as returned from Database::query(), etc.
198 * @return MySQL row object
199 * @throws DBUnexpectedError Thrown if the database returns an error
201 function fetchRow( $res ) {
202 if ( $res instanceof ResultWrapper
) {
205 @/**/$row = mssql_fetch_array( $res );
206 if ( $this->lastErrno() ) {
207 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
213 * Get the number of rows in a result object
215 function numRows( $res ) {
216 if ( $res instanceof ResultWrapper
) {
219 @/**/$n = mssql_num_rows( $res );
220 if ( $this->lastErrno() ) {
221 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
227 * Get the number of fields in a result object
228 * See documentation for mysql_num_fields()
229 * @param $res SQL result object as returned from Database::query(), etc.
231 function numFields( $res ) {
232 if ( $res instanceof ResultWrapper
) {
235 return mssql_num_fields( $res );
239 * Get a field name in a result object
240 * See documentation for mysql_field_name():
241 * http://www.php.net/mysql_field_name
242 * @param $res SQL result object as returned from Database::query(), etc.
245 function fieldName( $res, $n ) {
246 if ( $res instanceof ResultWrapper
) {
249 return mssql_field_name( $res, $n );
253 * Get the inserted value of an auto-increment row
255 * The value inserted should be fetched from nextSequenceValue()
258 * $id = $dbw->nextSequenceValue('page_page_id_seq');
259 * $dbw->insert('page',array('page_id' => $id));
260 * $id = $dbw->insertId();
262 function insertId() {
263 $row = mssql_fetch_row(mssql_query('select @@IDENTITY'));
268 * Change the position of the cursor in a result object
269 * See mysql_data_seek()
270 * @param $res SQL result object as returned from Database::query(), etc.
271 * @param $row Database row
273 function dataSeek( $res, $row ) {
274 if ( $res instanceof ResultWrapper
) {
277 return mssql_data_seek( $res, $row );
281 * Get the last error number
283 function lastErrno() {
284 return $this->mlastErrorNo
;
288 * Get a description of the last error
290 function lastError() {
291 return $this->mlastError
;
295 * Get the number of rows affected by the last write query
297 function affectedRows() {
298 return mssql_rows_affected( $this->mConn
);
302 * Simple UPDATE wrapper
303 * Usually aborts on failure
304 * If errors are explicitly ignored, returns success
306 * This function exists for historical reasons, Database::update() has a more standard
307 * calling convention and feature set
309 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
311 if ($value == "NULL") $value = "''"; # see comments in makeListWithoutNulls()
312 $table = $this->tableName( $table );
313 $sql = "UPDATE $table SET $var = '" .
314 $this->strencode( $value ) . "' WHERE ($cond)";
315 return (bool)$this->query( $sql, $fname );
319 * Simple SELECT wrapper, returns a single field, input must be encoded
320 * Usually aborts on failure
321 * If errors are explicitly ignored, returns FALSE on failure
323 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
324 if ( !is_array( $options ) ) {
325 $options = array( $options );
327 $options['LIMIT'] = 1;
329 $res = $this->select( $table, $var, $cond, $fname, $options );
330 if ( $res === false ||
!$this->numRows( $res ) ) {
333 $row = $this->fetchRow( $res );
334 if ( $row !== false ) {
335 $this->freeResult( $res );
343 * Returns an optional USE INDEX clause to go after the table, and a
344 * string to go at the end of the query
348 * @param $options Array: an associative array of options to be turned into
349 * an SQL query, valid keys are listed in the function.
352 function makeSelectOptions( $options ) {
353 $preLimitTail = $postLimitTail = '';
356 $noKeyOptions = array();
357 foreach ( $options as $key => $option ) {
358 if ( is_numeric( $key ) ) {
359 $noKeyOptions[$option] = true;
363 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
364 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
365 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
367 //if (isset($options['LIMIT'])) {
368 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
369 // isset($options['OFFSET']) ? $options['OFFSET']
373 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
374 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
375 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
377 # Various MySQL extensions
378 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
379 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
380 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
381 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
382 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
383 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
384 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
385 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
387 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
388 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
393 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
399 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
400 * @param $vars Mixed: Array or string, field name(s) to be retrieved
401 * @param $conds Mixed: Array or string, condition(s) for WHERE
402 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
403 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
404 * see Database::makeSelectOptions code for list of supported stuff
405 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
407 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
409 if( is_array( $vars ) ) {
410 $vars = implode( ',', $vars );
412 if( !is_array( $options ) ) {
413 $options = array( $options );
415 if( is_array( $table ) ) {
416 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
417 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
419 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
420 } elseif ($table!='') {
421 if ($table{0}==' ') {
422 $from = ' FROM ' . $table;
424 $from = ' FROM ' . $this->tableName( $table );
430 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
432 if( !empty( $conds ) ) {
433 if ( is_array( $conds ) ) {
434 $conds = $this->makeList( $conds, LIST_AND
);
436 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
438 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
441 if (isset($options['LIMIT']))
442 $sql = $this->limitResult($sql, $options['LIMIT'],
443 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
444 $sql = "$sql $postLimitTail";
446 if (isset($options['EXPLAIN'])) {
447 $sql = 'EXPLAIN ' . $sql;
449 return $this->query( $sql, $fname );
453 * Determines whether a field exists in a table
454 * Usually aborts on failure
455 * If errors are explicitly ignored, returns NULL on failure
457 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
458 $table = $this->tableName( $table );
459 $sql = "SELECT TOP 1 * FROM $table";
460 $res = $this->query( $sql, 'Database::fieldExists' );
463 while ( $row = $this->fetchArray( $res ) ) {
464 if ( isset($row[$field]) ) {
470 $this->freeResult( $res );
475 * Get information about an index into an object
476 * Returns false if the index does not exist
478 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
480 throw new DBUnexpectedError( $this, 'Database::indexInfo called which is not supported yet' );
483 $table = $this->tableName( $table );
484 $sql = 'SHOW INDEX FROM '.$table;
485 $res = $this->query( $sql, $fname );
491 while ( $row = $this->fetchObject( $res ) ) {
492 if ( $row->Key_name
== $index ) {
496 $this->freeResult($res);
498 return empty($result) ?
false : $result;
502 * Query whether a given table exists
504 function tableExists( $table ) {
505 $table = $this->tableName( $table );
506 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'" );
507 $exist = ($res->numRows() > 0);
508 $this->freeResult($res);
513 * mysql_fetch_field() wrapper
514 * Returns false if the field doesn't exist
519 function fieldInfo( $table, $field ) {
520 $table = $this->tableName( $table );
521 $res = $this->query( "SELECT TOP 1 * FROM $table" );
522 $n = mssql_num_fields( $res->result
);
523 for( $i = 0; $i < $n; $i++
) {
524 $meta = mssql_fetch_field( $res->result
, $i );
525 if( $field == $meta->name
) {
526 return new MSSQLField($meta);
533 * mysql_field_type() wrapper
535 function fieldType( $res, $index ) {
536 if ( $res instanceof ResultWrapper
) {
539 return mssql_field_type( $res, $index );
543 * INSERT wrapper, inserts an array into a table
545 * $a may be a single associative array, or an array of these with numeric keys, for
548 * Usually aborts on failure
549 * If errors are explicitly ignored, returns success
551 * Same as parent class implementation except that it removes primary key from column lists
552 * because MSSQL doesn't support writing nulls to IDENTITY (AUTO_INCREMENT) columns
554 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
555 # No rows to insert, easy just return now
556 if ( !count( $a ) ) {
559 $table = $this->tableName( $table );
560 if ( !is_array( $options ) ) {
561 $options = array( $options );
564 # todo: need to record primary keys at table create time, and remove NULL assignments to them
565 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
567 $keys = array_keys( $a[0] );
568 # if (ereg('_id$',$keys[0])) {
570 if (is_null($i[$keys[0]])) unset($i[$keys[0]]); # remove primary-key column from multiple insert lists if empty value
573 $keys = array_keys( $a[0] );
576 $keys = array_keys( $a );
577 # if (ereg('_id$',$keys[0]) && empty($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
578 if (is_null($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
579 $keys = array_keys( $a );
582 # handle IGNORE option
584 # MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
585 # MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
586 $ignore = in_array('IGNORE',$options);
588 # remove IGNORE from options list
590 $oldoptions = $options;
592 foreach ($oldoptions as $o) if ($o != 'IGNORE') $options[] = $o;
595 $keylist = implode(',', $keys);
596 $sql = 'INSERT '.implode(' ', $options)." INTO $table (".implode(',', $keys).') VALUES ';
599 # If multiple and ignore, then do each row as a separate conditional insert
600 foreach ($a as $row) {
601 $prival = $row[$keys[0]];
602 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
603 if (!$this->query("$sql (".$this->makeListWithoutNulls($row).')', $fname)) return false;
608 foreach ($a as $row) {
609 if ($first) $first = false; else $sql .= ',';
610 $sql .= '('.$this->makeListWithoutNulls($row).')';
615 $prival = $a[$keys[0]];
616 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
618 $sql .= '('.$this->makeListWithoutNulls($a).')';
620 return (bool)$this->query( $sql, $fname );
624 * MSSQL doesn't allow implicit casting of NULL's into non-null values for NOT NULL columns
625 * for now I've just converted the NULL's in the lists for updates and inserts into empty strings
626 * which get implicitly casted to 0 for numeric columns
627 * NOTE: the set() method above converts NULL to empty string as well but not via this method
629 function makeListWithoutNulls($a, $mode = LIST_COMMA
) {
630 return str_replace("NULL","''",$this->makeList($a,$mode));
634 * UPDATE wrapper, takes a condition array and a SET array
636 * @param $table String: The table to UPDATE
637 * @param $values Array: An array of values to SET
638 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
639 * @param $fname String: The Class::Function calling this function
641 * @param $options Array: An array of UPDATE options, can be one or
642 * more of IGNORE, LOW_PRIORITY
645 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
646 $table = $this->tableName( $table );
647 $opts = $this->makeUpdateOptions( $options );
648 $sql = "UPDATE $opts $table SET " . $this->makeListWithoutNulls( $values, LIST_SET
);
649 if ( $conds != '*' ) {
650 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
652 return $this->query( $sql, $fname );
656 * Make UPDATE options for the Database::update function
659 * @param $options Array: The options passed to Database::update
662 function makeUpdateOptions( $options ) {
663 if( !is_array( $options ) ) {
664 $options = array( $options );
667 if ( in_array( 'LOW_PRIORITY', $options ) )
668 $opts[] = $this->lowPriorityOption();
669 if ( in_array( 'IGNORE', $options ) )
671 return implode(' ', $opts);
675 * Change the current database
677 function selectDB( $db ) {
678 $this->mDBname
= $db;
679 return mssql_select_db( $db, $this->mConn
);
683 * MSSQL has a problem with the backtick quoting, so all this does is ensure the prefix is added exactly once
685 function tableName($name) {
686 return strpos($name, $this->mTablePrefix
) === 0 ?
$name : "{$this->mTablePrefix}$name";
690 * MSSQL doubles quotes instead of escaping them
691 * @param $s String to be slashed.
692 * @return string slashed string.
694 function strencode($s) {
695 return str_replace("'","''",$s);
699 * REPLACE query wrapper
700 * PostgreSQL simulates this with a DELETE followed by INSERT
701 * $row is the row to insert, an associative array
702 * $uniqueIndexes is an array of indexes. Each element may be either a
703 * field name or an array of field names
705 * It may be more efficient to leave off unique indexes which are unlikely to collide.
706 * However if you do this, you run the risk of encountering errors which wouldn't have
709 * @todo migrate comment to phodocumentor format
711 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
712 $table = $this->tableName( $table );
715 if ( !is_array( reset( $rows ) ) ) {
716 $rows = array( $rows );
719 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
721 foreach ( $rows as $row ) {
727 $sql .= '(' . $this->makeList( $row ) . ')';
729 return $this->query( $sql, $fname );
733 * DELETE where the condition is a join
734 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
736 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
737 * join condition matches, set $conds='*'
739 * DO NOT put the join condition in $conds
741 * @param $delTable String: The table to delete from.
742 * @param $joinTable String: The other table.
743 * @param $delVar String: The variable to join on, in the first table.
744 * @param $joinVar String: The variable to join on, in the second table.
745 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
746 * @param $fname String: Calling function name
748 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
750 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
753 $delTable = $this->tableName( $delTable );
754 $joinTable = $this->tableName( $joinTable );
755 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
756 if ( $conds != '*' ) {
757 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
760 return $this->query( $sql, $fname );
764 * Returns the size of a text field, or -1 for "unlimited"
766 function textFieldSize( $table, $field ) {
767 $table = $this->tableName( $table );
768 $sql = "SELECT TOP 1 * FROM $table;";
769 $res = $this->query( $sql, 'Database::textFieldSize' );
770 $row = $this->fetchObject( $res );
771 $this->freeResult( $res );
774 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
783 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
785 function lowPriorityOption() {
786 return 'LOW_PRIORITY';
790 * INSERT SELECT wrapper
791 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
792 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
793 * $conds may be "*" to copy the whole table
794 * srcTable may be an array of tables.
796 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
797 $insertOptions = array(), $selectOptions = array() )
799 $destTable = $this->tableName( $destTable );
800 if ( is_array( $insertOptions ) ) {
801 $insertOptions = implode( ' ', $insertOptions );
803 if( !is_array( $selectOptions ) ) {
804 $selectOptions = array( $selectOptions );
806 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
807 if( is_array( $srcTable ) ) {
808 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
810 $srcTable = $this->tableName( $srcTable );
812 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
813 " SELECT $startOpts " . implode( ',', $varMap ) .
814 " FROM $srcTable $useIndex ";
815 if ( $conds != '*' ) {
816 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
818 $sql .= " $tailOpts";
819 return $this->query( $sql, $fname );
823 * Construct a LIMIT query with optional offset
824 * This is used for query pages
825 * $sql string SQL query we will append the limit to
826 * $limit integer the SQL limit
827 * $offset integer the SQL offset (default false)
829 function limitResult($sql, $limit, $offset=false) {
830 if( !is_numeric($limit) ) {
831 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
834 throw new DBUnexpectedError( $this, 'Database::limitResult called with non-zero offset which is not supported yet' );
836 $sql = preg_replace("^SELECT", "SELECT TOP $limit", $sql);
842 * Should determine if the last failure was due to a deadlock
845 function wasDeadlock() {
846 return $this->lastErrno() == 1205;
850 * Return MW-style timestamp used for MySQL schema
852 function timestamp( $ts=0 ) {
853 return wfTimestamp(TS_MW
,$ts);
857 * Local database timestamp format or null
859 function timestampOrNull( $ts = null ) {
860 if( is_null( $ts ) ) {
863 return $this->timestamp( $ts );
868 * @return string wikitext of a link to the server software's web site
870 function getSoftwareLink() {
871 return "[http://www.microsoft.com/sql/default.mspx Microsoft SQL Server 2005 Home]";
875 * @return string Version information from the database
877 function getServerVersion() {
878 $row = mssql_fetch_row(mssql_query('select @@VERSION'));
879 return preg_match("^(.+[0-9]+\\.[0-9]+\\.[0-9]+) ",$row[0],$m) ?
$m[1] : $row[0];
882 function limitResultForUpdate($sql, $num) {
887 * How lagged is this slave?
889 public function getLag() {
894 * Called by the installer script
895 * - this is the same way as DatabasePostgresql.php, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
897 public function setup_database() {
898 global $IP,$wgDBTableOptions;
899 $wgDBTableOptions = '';
900 $mysql_tmpl = "$IP/maintenance/tables.sql";
901 $mysql_iw = "$IP/maintenance/interwiki.sql";
902 $mssql_tmpl = "$IP/maintenance/mssql/tables.sql";
904 # Make an MSSQL template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
905 if (!file_exists($mssql_tmpl)) { # todo: make this conditional again
906 $sql = file_get_contents($mysql_tmpl);
907 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
908 $sql = preg_replace('/^\s*(UNIQUE )?(INDEX|KEY|FULLTEXT).+?$/m', '', $sql); # These indexes should be created with a CREATE INDEX query
909 $sql = preg_replace('/(\sKEY) [^\(]+\(/is', '$1 (', $sql); # "KEY foo (foo)" should just be "KEY (foo)"
910 $sql = preg_replace('/(varchar\([0-9]+\))\s+binary/i', '$1', $sql); # "varchar(n) binary" cannot be followed by "binary"
911 $sql = preg_replace('/(var)?binary\(([0-9]+)\)/ie', '"varchar(".strlen(pow(2,$2)).")"', $sql); # use varchar(chars) not binary(bits)
912 $sql = preg_replace('/ (var)?binary/i', ' varchar', $sql); # use varchar not binary
913 $sql = preg_replace('/(varchar\([0-9]+\)(?! N))/', '$1 NULL', $sql); # MSSQL complains if NULL is put into a varchar
914 #$sql = preg_replace('/ binary/i',' varchar',$sql); # MSSQL binary's can't be assigned with strings, so use varchar's instead
915 #$sql = preg_replace('/(binary\([0-9]+\) (NOT NULL )?default) [\'"].*?[\'"]/i','$1 0',$sql); # binary default cannot be string
916 $sql = preg_replace('/[a-z]*(blob|text)([ ,])/i', 'text$2', $sql); # no BLOB types in MSSQL
917 $sql = preg_replace('/\).+?;/',');', $sql); # remove all table options
918 $sql = preg_replace('/ (un)?signed/i', '', $sql);
919 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
920 $sql = str_replace(' bool ', ' bit ', $sql);
921 $sql = str_replace('auto_increment', 'IDENTITY(1,1)', $sql);
922 #$sql = preg_replace('/NOT NULL(?! IDENTITY)/', 'NULL', $sql); # Allow NULL's for non IDENTITY columns
924 # Tidy up and write file
925 $sql = preg_replace('/,\s*\)/s', "\n)", $sql); # Remove spurious commas left after INDEX removals
926 $sql = preg_replace('/^\s*^/m', '', $sql); # Remove empty lines
927 $sql = preg_replace('/;$/m', ";\n", $sql); # Separate each statement with an empty line
928 file_put_contents($mssql_tmpl, $sql);
931 # Parse the MSSQL template replacing inline variables such as /*$wgDBprefix*/
932 $err = $this->sourceFile($mssql_tmpl);
933 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
935 # Use DatabasePostgres's code to populate interwiki from MySQL template
936 $f = fopen($mysql_iw,'r');
937 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
938 $sql = "INSERT INTO {$this->mTablePrefix}interwiki(iw_prefix,iw_url,iw_local) VALUES ";
940 $line = fgets($f,1024);
942 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
943 $this->query("$sql $matches[1],$matches[2])");
947 public function getSearchEngine() {
948 return "SearchEngineDummy";
955 class MSSQLField
extends MySQLField
{
957 function __construct() {
960 static function fromText($db, $table, $field) {
963 $n->tablename
= $table;
967 } // end DatabaseMssql class