4165df1c3e6e60e888200fbc5de72b0480be1baa
3 * This script is the MSSQL Server database abstraction layer
5 * See maintenance/mssql/README for development notes and other specific information
11 class DatabaseMssql
extends Database
{
22 function __construct($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0, $tablePrefix = 'get from global') {
25 global $wgOut, $wgDBprefix, $wgCommandLineMode;
26 if (!isset($wgOut)) $wgOut = NULL; # Can't get a reference if it hasn't been set yet
27 $this->mOut
=& $wgOut;
28 $this->mFailFunction
= $failFunction;
29 $this->mFlags
= $flags;
31 if ( $this->mFlags
& DBO_DEFAULT
) {
32 if ( $wgCommandLineMode ) {
33 $this->mFlags
&= ~DBO_TRX
;
35 $this->mFlags |
= DBO_TRX
;
39 /** Get the default table prefix*/
40 $this->mTablePrefix
= $tablePrefix == 'get from global' ?
$wgDBprefix : $tablePrefix;
42 if ($server) $this->open($server, $user, $password, $dbName);
47 * todo: check if these should be true like parent class
49 function implicitGroupby() { return false; }
50 function implicitOrderby() { return false; }
52 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
53 return new DatabaseMssql($server, $user, $password, $dbName, $failFunction, $flags);
56 /** Open an MSSQL database and return a resource handle to it
57 * NOTE: only $dbName is used, the other parameters are irrelevant for MSSQL databases
59 function open($server,$user,$password,$dbName) {
60 wfProfileIn(__METHOD__
);
62 # Test for missing mysql.so
63 # First try to load it
64 if (!@extension_loaded
('mssql')) {
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if (!function_exists( 'mssql_connect')) {
71 throw new DBConnectionError( $this, "MSSQL functions missing, have you compiled PHP with the --with-mssql option?\n" );
75 $this->mServer
= $server;
77 $this->mPassword
= $password;
78 $this->mDBname
= $dbName;
80 wfProfileIn("dbconnect-$server");
82 # Try to connect up to three times
83 # The kernel's default SYN retransmission period is far too slow for us,
84 # so we use a short timeout plus a manual retry.
87 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
91 if ($this->mFlags
& DBO_PERSISTENT
) {
92 @/**/$this->mConn
= mssql_pconnect($server, $user, $password);
94 # Create a new connection...
95 @/**/$this->mConn
= mssql_connect($server, $user, $password, true);
99 wfProfileOut("dbconnect-$server");
102 if ($this->mConn
!== false) {
103 $success = @/**/mssql_select_db($dbName, $this->mConn
);
105 $error = "Error selecting database $dbName on server {$this->mServer} " .
106 "from client host {$wguname['nodename']}\n";
107 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
111 wfDebug("DB connection error\n");
112 wfDebug("Server: $server, User: $user, Password: ".substr($password, 0, 3)."...\n");
117 $success = (bool)$this->mConn
;
120 if (!$success) $this->reportConnectionError();
121 $this->mOpened
= $success;
122 wfProfileOut(__METHOD__
);
127 * Close an MSSQL database
130 $this->mOpened
= false;
132 if ($this->trxLevel()) $this->immediateCommit();
133 return mssql_close($this->mConn
);
138 * - MSSQL doesn't seem to do buffered results
139 * - the trasnaction syntax is modified here to avoid having to replicate
140 * Database::query which uses BEGIN, COMMIT, ROLLBACK
142 function doQuery($sql) {
143 if ($sql == 'BEGIN' ||
$sql == 'COMMIT' ||
$sql == 'ROLLBACK') return true; # $sql .= ' TRANSACTION';
144 $sql = preg_replace('|[^\x07-\x7e]|','?',$sql); # TODO: need to fix unicode - just removing it here while testing
145 $ret = mssql_query($sql, $this->mConn
);
146 if ($ret === false) {
147 $err = mssql_get_last_message();
148 if ($err) $this->mlastError
= $err;
149 $row = mssql_fetch_row(mssql_query('select @@ERROR'));
150 if ($row[0]) $this->mlastErrorNo
= $row[0];
151 } else $this->mlastErrorNo
= false;
156 * @param mixed $res A SQL result
159 * Free a result object
161 function freeResult( $res ) {
162 if ( $res instanceof ResultWrapper
) {
165 if ( !@/**/mssql_free_result( $res ) ) {
166 throw new DBUnexpectedError( $this, "Unable to free MSSQL result" );
171 * Fetch the next row from the given result object, in object form.
172 * Fields can be retrieved with $row->fieldname, with fields acting like
175 * @param $res SQL result object as returned from Database::query(), etc.
176 * @return MySQL row object
177 * @throws DBUnexpectedError Thrown if the database returns an error
179 function fetchObject( $res ) {
180 if ( $res instanceof ResultWrapper
) {
183 @/**/$row = mssql_fetch_object( $res );
184 if ( $this->lastErrno() ) {
185 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
191 * Fetch the next row from the given result object, in associative array
192 * form. Fields are retrieved with $row['fieldname'].
194 * @param $res SQL result object as returned from Database::query(), etc.
195 * @return MySQL row object
196 * @throws DBUnexpectedError Thrown if the database returns an error
198 function fetchRow( $res ) {
199 if ( $res instanceof ResultWrapper
) {
202 @/**/$row = mssql_fetch_array( $res );
203 if ( $this->lastErrno() ) {
204 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
210 * Get the number of rows in a result object
212 function numRows( $res ) {
213 if ( $res instanceof ResultWrapper
) {
216 @/**/$n = mssql_num_rows( $res );
217 if ( $this->lastErrno() ) {
218 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
224 * Get the number of fields in a result object
225 * See documentation for mysql_num_fields()
227 function numFields( $res ) {
228 if ( $res instanceof ResultWrapper
) {
231 return mssql_num_fields( $res );
235 * Get a field name in a result object
236 * See documentation for mysql_field_name():
237 * http://www.php.net/mysql_field_name
239 function fieldName( $res, $n ) {
240 if ( $res instanceof ResultWrapper
) {
243 return mssql_field_name( $res, $n );
247 * Get the inserted value of an auto-increment row
249 * The value inserted should be fetched from nextSequenceValue()
252 * $id = $dbw->nextSequenceValue('page_page_id_seq');
253 * $dbw->insert('page',array('page_id' => $id));
254 * $id = $dbw->insertId();
256 function insertId() {
257 $row = mssql_fetch_row(mssql_query('select @@IDENTITY'));
262 * Change the position of the cursor in a result object
263 * See mysql_data_seek()
265 function dataSeek( $res, $row ) {
266 if ( $res instanceof ResultWrapper
) {
269 return mssql_data_seek( $res, $row );
273 * Get the last error number
275 function lastErrno() {
276 return $this->mlastErrorNo
;
280 * Get a description of the last error
282 function lastError() {
283 return $this->mlastError
;
287 * Get the number of rows affected by the last write query
289 function affectedRows() {
290 return mssql_rows_affected( $this->mConn
);
294 * Simple UPDATE wrapper
295 * Usually aborts on failure
296 * If errors are explicitly ignored, returns success
298 * This function exists for historical reasons, Database::update() has a more standard
299 * calling convention and feature set
301 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
303 if ($value == "NULL") $value = "''"; # see comments in makeListWithoutNulls()
304 $table = $this->tableName( $table );
305 $sql = "UPDATE $table SET $var = '" .
306 $this->strencode( $value ) . "' WHERE ($cond)";
307 return (bool)$this->query( $sql, $fname );
311 * Simple SELECT wrapper, returns a single field, input must be encoded
312 * Usually aborts on failure
313 * If errors are explicitly ignored, returns FALSE on failure
315 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
316 if ( !is_array( $options ) ) {
317 $options = array( $options );
319 $options['LIMIT'] = 1;
321 $res = $this->select( $table, $var, $cond, $fname, $options );
322 if ( $res === false ||
!$this->numRows( $res ) ) {
325 $row = $this->fetchRow( $res );
326 if ( $row !== false ) {
327 $this->freeResult( $res );
335 * Returns an optional USE INDEX clause to go after the table, and a
336 * string to go at the end of the query
340 * @param array $options an associative array of options to be turned into
341 * an SQL query, valid keys are listed in the function.
344 function makeSelectOptions( $options ) {
345 $preLimitTail = $postLimitTail = '';
348 $noKeyOptions = array();
349 foreach ( $options as $key => $option ) {
350 if ( is_numeric( $key ) ) {
351 $noKeyOptions[$option] = true;
355 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
356 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
357 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
359 //if (isset($options['LIMIT'])) {
360 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
361 // isset($options['OFFSET']) ? $options['OFFSET']
365 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
366 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
367 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
369 # Various MySQL extensions
370 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
371 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
372 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
373 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
374 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
375 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
376 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
377 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
379 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
380 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
385 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
391 * @param mixed $table Array or string, table name(s) (prefix auto-added)
392 * @param mixed $vars Array or string, field name(s) to be retrieved
393 * @param mixed $conds Array or string, condition(s) for WHERE
394 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
395 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
396 * see Database::makeSelectOptions code for list of supported stuff
397 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
399 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
401 if( is_array( $vars ) ) {
402 $vars = implode( ',', $vars );
404 if( !is_array( $options ) ) {
405 $options = array( $options );
407 if( is_array( $table ) ) {
408 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
409 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
411 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
412 } elseif ($table!='') {
413 if ($table{0}==' ') {
414 $from = ' FROM ' . $table;
416 $from = ' FROM ' . $this->tableName( $table );
422 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
424 if( !empty( $conds ) ) {
425 if ( is_array( $conds ) ) {
426 $conds = $this->makeList( $conds, LIST_AND
);
428 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
430 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
433 if (isset($options['LIMIT']))
434 $sql = $this->limitResult($sql, $options['LIMIT'],
435 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
436 $sql = "$sql $postLimitTail";
438 if (isset($options['EXPLAIN'])) {
439 $sql = 'EXPLAIN ' . $sql;
441 return $this->query( $sql, $fname );
445 * Estimate rows in dataset
446 * Returns estimated count, based on EXPLAIN output
447 * Takes same arguments as Database::select()
449 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
451 $res = $this->select ($table, 'COUNT(*)', $conds, $fname, $options );
453 $row = $this->fetchObject($res);
456 $this->freeResult($res);
461 * Determines whether a field exists in a table
462 * Usually aborts on failure
463 * If errors are explicitly ignored, returns NULL on failure
465 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
466 $table = $this->tableName( $table );
467 $sql = "SELECT TOP 1 * FROM $table";
468 $res = $this->query( $sql, 'Database::fieldExists' );
471 while ( $row = $this->fetchArray( $res ) ) {
472 if ( isset($row[$field]) ) {
478 $this->freeResult( $res );
483 * Get information about an index into an object
484 * Returns false if the index does not exist
486 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
488 throw new DBUnexpectedError( $this, 'Database::indexInfo called which is not supported yet' );
491 $table = $this->tableName( $table );
492 $sql = 'SHOW INDEX FROM '.$table;
493 $res = $this->query( $sql, $fname );
499 while ( $row = $this->fetchObject( $res ) ) {
500 if ( $row->Key_name
== $index ) {
504 $this->freeResult($res);
506 return empty($result) ?
false : $result;
510 * Query whether a given table exists
512 function tableExists( $table ) {
513 $table = $this->tableName( $table );
514 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'" );
515 $exist = ($res->numRows() > 0);
516 $this->freeResult($res);
521 * mysql_fetch_field() wrapper
522 * Returns false if the field doesn't exist
527 function fieldInfo( $table, $field ) {
528 $table = $this->tableName( $table );
529 $res = $this->query( "SELECT TOP 1 * FROM $table" );
530 $n = mssql_num_fields( $res->result
);
531 for( $i = 0; $i < $n; $i++
) {
532 $meta = mssql_fetch_field( $res->result
, $i );
533 if( $field == $meta->name
) {
534 return new MSSQLField($meta);
541 * mysql_field_type() wrapper
543 function fieldType( $res, $index ) {
544 if ( $res instanceof ResultWrapper
) {
547 return mssql_field_type( $res, $index );
551 * INSERT wrapper, inserts an array into a table
553 * $a may be a single associative array, or an array of these with numeric keys, for
556 * Usually aborts on failure
557 * If errors are explicitly ignored, returns success
559 * Same as parent class implementation except that it removes primary key from column lists
560 * because MSSQL doesn't support writing nulls to IDENTITY (AUTO_INCREMENT) columns
562 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
563 # No rows to insert, easy just return now
564 if ( !count( $a ) ) {
567 $table = $this->tableName( $table );
568 if ( !is_array( $options ) ) {
569 $options = array( $options );
572 # todo: need to record primary keys at table create time, and remove NULL assignments to them
573 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
575 $keys = array_keys( $a[0] );
576 # if (ereg('_id$',$keys[0])) {
578 if (is_null($i[$keys[0]])) unset($i[$keys[0]]); # remove primary-key column from multiple insert lists if empty value
581 $keys = array_keys( $a[0] );
584 $keys = array_keys( $a );
585 # if (ereg('_id$',$keys[0]) && empty($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
586 if (is_null($a[$keys[0]])) unset($a[$keys[0]]); # remove primary-key column from insert list if empty value
587 $keys = array_keys( $a );
590 # handle IGNORE option
592 # MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
593 # MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
594 $ignore = in_array('IGNORE',$options);
596 # remove IGNORE from options list
598 $oldoptions = $options;
600 foreach ($oldoptions as $o) if ($o != 'IGNORE') $options[] = $o;
603 $keylist = implode(',', $keys);
604 $sql = 'INSERT '.implode(' ', $options)." INTO $table (".implode(',', $keys).') VALUES ';
607 # If multiple and ignore, then do each row as a separate conditional insert
608 foreach ($a as $row) {
609 $prival = $row[$keys[0]];
610 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
611 if (!$this->query("$sql (".$this->makeListWithoutNulls($row).')', $fname)) return false;
616 foreach ($a as $row) {
617 if ($first) $first = false; else $sql .= ',';
618 $sql .= '('.$this->makeListWithoutNulls($row).')';
623 $prival = $a[$keys[0]];
624 $sql = "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival') $sql";
626 $sql .= '('.$this->makeListWithoutNulls($a).')';
628 return (bool)$this->query( $sql, $fname );
632 * MSSQL doesn't allow implicit casting of NULL's into non-null values for NOT NULL columns
633 * for now I've just converted the NULL's in the lists for updates and inserts into empty strings
634 * which get implicitly casted to 0 for numeric columns
635 * NOTE: the set() method above converts NULL to empty string as well but not via this method
637 function makeListWithoutNulls($a, $mode = LIST_COMMA
) {
638 return str_replace("NULL","''",$this->makeList($a,$mode));
642 * UPDATE wrapper, takes a condition array and a SET array
644 * @param string $table The table to UPDATE
645 * @param array $values An array of values to SET
646 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
647 * @param string $fname The Class::Function calling this function
649 * @param array $options An array of UPDATE options, can be one or
650 * more of IGNORE, LOW_PRIORITY
653 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
654 $table = $this->tableName( $table );
655 $opts = $this->makeUpdateOptions( $options );
656 $sql = "UPDATE $opts $table SET " . $this->makeListWithoutNulls( $values, LIST_SET
);
657 if ( $conds != '*' ) {
658 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
660 return $this->query( $sql, $fname );
664 * Make UPDATE options for the Database::update function
667 * @param array $options The options passed to Database::update
670 function makeUpdateOptions( $options ) {
671 if( !is_array( $options ) ) {
672 $options = array( $options );
675 if ( in_array( 'LOW_PRIORITY', $options ) )
676 $opts[] = $this->lowPriorityOption();
677 if ( in_array( 'IGNORE', $options ) )
679 return implode(' ', $opts);
683 * Change the current database
685 function selectDB( $db ) {
686 $this->mDBname
= $db;
687 return mssql_select_db( $db, $this->mConn
);
691 * MSSQL has a problem with the backtick quoting, so all this does is ensure the prefix is added exactly once
693 function tableName($name) {
694 return strpos($name, $this->mTablePrefix
) === 0 ?
$name : "{$this->mTablePrefix}$name";
698 * MSSQL doubles quotes instead of escaping them
699 * @param string $s String to be slashed.
700 * @return string slashed string.
702 function strencode($s) {
703 return str_replace("'","''",$s);
709 function useIndexClause( $index ) {
714 * REPLACE query wrapper
715 * PostgreSQL simulates this with a DELETE followed by INSERT
716 * $row is the row to insert, an associative array
717 * $uniqueIndexes is an array of indexes. Each element may be either a
718 * field name or an array of field names
720 * It may be more efficient to leave off unique indexes which are unlikely to collide.
721 * However if you do this, you run the risk of encountering errors which wouldn't have
724 * @todo migrate comment to phodocumentor format
726 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
727 $table = $this->tableName( $table );
730 if ( !is_array( reset( $rows ) ) ) {
731 $rows = array( $rows );
734 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
736 foreach ( $rows as $row ) {
742 $sql .= '(' . $this->makeList( $row ) . ')';
744 return $this->query( $sql, $fname );
748 * DELETE where the condition is a join
749 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
751 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
752 * join condition matches, set $conds='*'
754 * DO NOT put the join condition in $conds
756 * @param string $delTable The table to delete from.
757 * @param string $joinTable The other table.
758 * @param string $delVar The variable to join on, in the first table.
759 * @param string $joinVar The variable to join on, in the second table.
760 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
762 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
764 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
767 $delTable = $this->tableName( $delTable );
768 $joinTable = $this->tableName( $joinTable );
769 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
770 if ( $conds != '*' ) {
771 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
774 return $this->query( $sql, $fname );
778 * Returns the size of a text field, or -1 for "unlimited"
780 function textFieldSize( $table, $field ) {
781 $table = $this->tableName( $table );
782 $sql = "SELECT TOP 1 * FROM $table;";
783 $res = $this->query( $sql, 'Database::textFieldSize' );
784 $row = $this->fetchObject( $res );
785 $this->freeResult( $res );
788 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
797 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
799 function lowPriorityOption() {
800 return 'LOW_PRIORITY';
804 * INSERT SELECT wrapper
805 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
806 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
807 * $conds may be "*" to copy the whole table
808 * srcTable may be an array of tables.
810 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
811 $insertOptions = array(), $selectOptions = array() )
813 $destTable = $this->tableName( $destTable );
814 if ( is_array( $insertOptions ) ) {
815 $insertOptions = implode( ' ', $insertOptions );
817 if( !is_array( $selectOptions ) ) {
818 $selectOptions = array( $selectOptions );
820 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
821 if( is_array( $srcTable ) ) {
822 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
824 $srcTable = $this->tableName( $srcTable );
826 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
827 " SELECT $startOpts " . implode( ',', $varMap ) .
828 " FROM $srcTable $useIndex ";
829 if ( $conds != '*' ) {
830 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
832 $sql .= " $tailOpts";
833 return $this->query( $sql, $fname );
837 * Construct a LIMIT query with optional offset
838 * This is used for query pages
839 * $sql string SQL query we will append the limit to
840 * $limit integer the SQL limit
841 * $offset integer the SQL offset (default false)
843 function limitResult($sql, $limit, $offset=false) {
844 if( !is_numeric($limit) ) {
845 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
848 throw new DBUnexpectedError( $this, 'Database::limitResult called with non-zero offset which is not supported yet' );
850 $sql = ereg_replace("^SELECT", "SELECT TOP $limit", $sql);
856 * Returns an SQL expression for a simple conditional.
858 * @param string $cond SQL expression which will result in a boolean value
859 * @param string $trueVal SQL expression to return if true
860 * @param string $falseVal SQL expression to return if false
861 * @return string SQL fragment
863 function conditional( $cond, $trueVal, $falseVal ) {
864 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
868 * Should determine if the last failure was due to a deadlock
869 * - don't know how to do this in MSSQL
871 function wasDeadlock() {
876 * Begin a transaction, committing any previously open transaction
877 * @deprecated use begin()
879 function immediateBegin( $fname = 'Database::immediateBegin' ) {
884 * Commit transaction, if one is open
885 * @deprecated use commit()
887 function immediateCommit( $fname = 'Database::immediateCommit' ) {
892 * Return MW-style timestamp used for MySQL schema
894 function timestamp( $ts=0 ) {
895 return wfTimestamp(TS_MW
,$ts);
899 * Local database timestamp format or null
901 function timestampOrNull( $ts = null ) {
902 if( is_null( $ts ) ) {
905 return $this->timestamp( $ts );
910 * @return string wikitext of a link to the server software's web site
912 function getSoftwareLink() {
913 return "[http://www.microsoft.com/sql/default.mspx Microsoft SQL Server 2005 Home]";
917 * @return string Version information from the database
919 function getServerVersion() {
920 $row = mssql_fetch_row(mssql_query('select @@VERSION'));
921 return ereg("^(.+[0-9]+\\.[0-9]+\\.[0-9]+) ",$row[0],$m) ?
$m[1] : $row[0];
924 function limitResultForUpdate($sql, $num) {
931 public function setTimeout($timeout) { return; }
934 wfDebug("Function ping() not written for MSSQL yet");
939 * How lagged is this slave?
941 public function getLag() {
946 * Called by the installer script
947 * - this is the same way as DatabasePostgresql.php, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
949 public function setup_database() {
950 global $IP,$wgDBTableOptions;
951 $wgDBTableOptions = '';
952 $mysql_tmpl = "$IP/maintenance/tables.sql";
953 $mysql_iw = "$IP/maintenance/interwiki.sql";
954 $mssql_tmpl = "$IP/maintenance/mssql/tables.sql";
956 # Make an MSSQL template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
957 if (!file_exists($mssql_tmpl)) { # todo: make this conditional again
958 $sql = file_get_contents($mysql_tmpl);
959 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
960 $sql = preg_replace('/^\s*(UNIQUE )?(INDEX|KEY|FULLTEXT).+?$/m', '', $sql); # These indexes should be created with a CREATE INDEX query
961 $sql = preg_replace('/(\sKEY) [^\(]+\(/is', '$1 (', $sql); # "KEY foo (foo)" should just be "KEY (foo)"
962 $sql = preg_replace('/(varchar\([0-9]+\))\s+binary/i', '$1', $sql); # "varchar(n) binary" cannot be followed by "binary"
963 $sql = preg_replace('/(var)?binary\(([0-9]+)\)/ie', '"varchar(".strlen(pow(2,$2)).")"', $sql); # use varchar(chars) not binary(bits)
964 $sql = preg_replace('/ (var)?binary/i', ' varchar', $sql); # use varchar not binary
965 $sql = preg_replace('/(varchar\([0-9]+\)(?! N))/', '$1 NULL', $sql); # MSSQL complains if NULL is put into a varchar
966 #$sql = preg_replace('/ binary/i',' varchar',$sql); # MSSQL binary's can't be assigned with strings, so use varchar's instead
967 #$sql = preg_replace('/(binary\([0-9]+\) (NOT NULL )?default) [\'"].*?[\'"]/i','$1 0',$sql); # binary default cannot be string
968 $sql = preg_replace('/[a-z]*(blob|text)([ ,])/i', 'text$2', $sql); # no BLOB types in MSSQL
969 $sql = preg_replace('/\).+?;/',');', $sql); # remove all table options
970 $sql = preg_replace('/ (un)?signed/i', '', $sql);
971 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
972 $sql = str_replace(' bool ', ' bit ', $sql);
973 $sql = str_replace('auto_increment', 'IDENTITY(1,1)', $sql);
974 #$sql = preg_replace('/NOT NULL(?! IDENTITY)/', 'NULL', $sql); # Allow NULL's for non IDENTITY columns
976 # Tidy up and write file
977 $sql = preg_replace('/,\s*\)/s', "\n)", $sql); # Remove spurious commas left after INDEX removals
978 $sql = preg_replace('/^\s*^/m', '', $sql); # Remove empty lines
979 $sql = preg_replace('/;$/m', ";\n", $sql); # Separate each statement with an empty line
980 file_put_contents($mssql_tmpl, $sql);
983 # Parse the MSSQL template replacing inline variables such as /*$wgDBprefix*/
984 $err = $this->sourceFile($mssql_tmpl);
985 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
987 # Use DatabasePostgres's code to populate interwiki from MySQL template
988 $f = fopen($mysql_iw,'r');
989 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
990 $sql = "INSERT INTO {$this->mTablePrefix}interwiki(iw_prefix,iw_url,iw_local) VALUES ";
992 $line = fgets($f,1024);
994 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
995 $this->query("$sql $matches[1],$matches[2])");
1002 * @addtogroup Database
1004 class MSSQLField
extends MySQLField
{
1006 function __construct() {
1009 static function fromText($db, $table, $field) {
1010 $n = new MSSQLField
;
1012 $n->tablename
= $table;
1016 } // end DatabaseMssql class