DatabaseMssql.php 32 KB

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