mssql.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's mssql extension
  5. * for interacting with Microsoft SQL Server databases
  6. *
  7. * PHP version 5
  8. *
  9. * LICENSE: This source file is subject to version 3.0 of the PHP license
  10. * that is available through the world-wide-web at the following URI:
  11. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  12. * the PHP License and are unable to obtain it through the web, please
  13. * send a note to license@php.net so we can mail you a copy immediately.
  14. *
  15. * @category Database
  16. * @package DB
  17. * @author Sterling Hughes <sterling@php.net>
  18. * @author Daniel Convissor <danielc@php.net>
  19. * @copyright 1997-2007 The PHP Group
  20. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  21. * @version CVS: $Id$
  22. * @link http://pear.php.net/package/DB
  23. */
  24. /**
  25. * Obtain the DB_common class so it can be extended from
  26. */
  27. require_once 'DB/common.php';
  28. /**
  29. * The methods PEAR DB uses to interact with PHP's mssql extension
  30. * for interacting with Microsoft SQL Server databases
  31. *
  32. * These methods overload the ones declared in DB_common.
  33. *
  34. * DB's mssql driver is only for Microsfoft SQL Server databases.
  35. *
  36. * If you're connecting to a Sybase database, you MUST specify "sybase"
  37. * as the "phptype" in the DSN.
  38. *
  39. * This class only works correctly if you have compiled PHP using
  40. * --with-mssql=[dir_to_FreeTDS].
  41. *
  42. * @category Database
  43. * @package DB
  44. * @author Sterling Hughes <sterling@php.net>
  45. * @author Daniel Convissor <danielc@php.net>
  46. * @copyright 1997-2007 The PHP Group
  47. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  48. * @version Release: 1.8.2
  49. * @link http://pear.php.net/package/DB
  50. */
  51. class DB_mssql extends DB_common
  52. {
  53. // {{{ properties
  54. /**
  55. * The DB driver type (mysql, oci8, odbc, etc.)
  56. * @var string
  57. */
  58. var $phptype = 'mssql';
  59. /**
  60. * The database syntax variant to be used (db2, access, etc.), if any
  61. * @var string
  62. */
  63. var $dbsyntax = 'mssql';
  64. /**
  65. * The capabilities of this DB implementation
  66. *
  67. * The 'new_link' element contains the PHP version that first provided
  68. * new_link support for this DBMS. Contains false if it's unsupported.
  69. *
  70. * Meaning of the 'limit' element:
  71. * + 'emulate' = emulate with fetch row by number
  72. * + 'alter' = alter the query
  73. * + false = skip rows
  74. *
  75. * @var array
  76. */
  77. var $features = array(
  78. 'limit' => 'emulate',
  79. 'new_link' => false,
  80. 'numrows' => true,
  81. 'pconnect' => true,
  82. 'prepare' => false,
  83. 'ssl' => false,
  84. 'transactions' => true,
  85. );
  86. /**
  87. * A mapping of native error codes to DB error codes
  88. * @var array
  89. */
  90. // XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX
  91. var $errorcode_map = array(
  92. 102 => DB_ERROR_SYNTAX,
  93. 110 => DB_ERROR_VALUE_COUNT_ON_ROW,
  94. 155 => DB_ERROR_NOSUCHFIELD,
  95. 156 => DB_ERROR_SYNTAX,
  96. 170 => DB_ERROR_SYNTAX,
  97. 207 => DB_ERROR_NOSUCHFIELD,
  98. 208 => DB_ERROR_NOSUCHTABLE,
  99. 245 => DB_ERROR_INVALID_NUMBER,
  100. 319 => DB_ERROR_SYNTAX,
  101. 321 => DB_ERROR_NOSUCHFIELD,
  102. 325 => DB_ERROR_SYNTAX,
  103. 336 => DB_ERROR_SYNTAX,
  104. 515 => DB_ERROR_CONSTRAINT_NOT_NULL,
  105. 547 => DB_ERROR_CONSTRAINT,
  106. 1018 => DB_ERROR_SYNTAX,
  107. 1035 => DB_ERROR_SYNTAX,
  108. 1913 => DB_ERROR_ALREADY_EXISTS,
  109. 2209 => DB_ERROR_SYNTAX,
  110. 2223 => DB_ERROR_SYNTAX,
  111. 2248 => DB_ERROR_SYNTAX,
  112. 2256 => DB_ERROR_SYNTAX,
  113. 2257 => DB_ERROR_SYNTAX,
  114. 2627 => DB_ERROR_CONSTRAINT,
  115. 2714 => DB_ERROR_ALREADY_EXISTS,
  116. 3607 => DB_ERROR_DIVZERO,
  117. 3701 => DB_ERROR_NOSUCHTABLE,
  118. 7630 => DB_ERROR_SYNTAX,
  119. 8134 => DB_ERROR_DIVZERO,
  120. 9303 => DB_ERROR_SYNTAX,
  121. 9317 => DB_ERROR_SYNTAX,
  122. 9318 => DB_ERROR_SYNTAX,
  123. 9331 => DB_ERROR_SYNTAX,
  124. 9332 => DB_ERROR_SYNTAX,
  125. 15253 => DB_ERROR_SYNTAX,
  126. );
  127. /**
  128. * The raw database connection created by PHP
  129. * @var resource
  130. */
  131. var $connection;
  132. /**
  133. * The DSN information for connecting to a database
  134. * @var array
  135. */
  136. var $dsn = array();
  137. /**
  138. * Should data manipulation queries be committed automatically?
  139. * @var bool
  140. * @access private
  141. */
  142. var $autocommit = true;
  143. /**
  144. * The quantity of transactions begun
  145. *
  146. * {@internal While this is private, it can't actually be designated
  147. * private in PHP 5 because it is directly accessed in the test suite.}}
  148. *
  149. * @var integer
  150. * @access private
  151. */
  152. var $transaction_opcount = 0;
  153. /**
  154. * The database specified in the DSN
  155. *
  156. * It's a fix to allow calls to different databases in the same script.
  157. *
  158. * @var string
  159. * @access private
  160. */
  161. var $_db = null;
  162. // }}}
  163. // {{{ constructor
  164. /**
  165. * This constructor calls <kbd>$this->DB_common()</kbd>
  166. *
  167. * @return void
  168. */
  169. function DB_mssql()
  170. {
  171. $this->DB_common();
  172. }
  173. // }}}
  174. // {{{ connect()
  175. /**
  176. * Connect to the database server, log in and open the database
  177. *
  178. * Don't call this method directly. Use DB::connect() instead.
  179. *
  180. * @param array $dsn the data source name
  181. * @param bool $persistent should the connection be persistent?
  182. *
  183. * @return int DB_OK on success. A DB_Error object on failure.
  184. */
  185. function connect($dsn, $persistent = false)
  186. {
  187. if (!PEAR::loadExtension('mssql') && !PEAR::loadExtension('sybase')
  188. && !PEAR::loadExtension('sybase_ct'))
  189. {
  190. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  191. }
  192. $this->dsn = $dsn;
  193. if ($dsn['dbsyntax']) {
  194. $this->dbsyntax = $dsn['dbsyntax'];
  195. }
  196. $params = array(
  197. $dsn['hostspec'] ? $dsn['hostspec'] : 'localhost',
  198. $dsn['username'] ? $dsn['username'] : null,
  199. $dsn['password'] ? $dsn['password'] : null,
  200. );
  201. if ($dsn['port']) {
  202. $params[0] .= ((substr(PHP_OS, 0, 3) == 'WIN') ? ',' : ':')
  203. . $dsn['port'];
  204. }
  205. $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect';
  206. $this->connection = @call_user_func_array($connect_function, $params);
  207. if (!$this->connection) {
  208. return $this->raiseError(DB_ERROR_CONNECT_FAILED,
  209. null, null, null,
  210. @mssql_get_last_message());
  211. }
  212. if ($dsn['database']) {
  213. if (!@mssql_select_db($dsn['database'], $this->connection)) {
  214. return $this->raiseError(DB_ERROR_NODBSELECTED,
  215. null, null, null,
  216. @mssql_get_last_message());
  217. }
  218. $this->_db = $dsn['database'];
  219. }
  220. return DB_OK;
  221. }
  222. // }}}
  223. // {{{ disconnect()
  224. /**
  225. * Disconnects from the database server
  226. *
  227. * @return bool TRUE on success, FALSE on failure
  228. */
  229. function disconnect()
  230. {
  231. $ret = @mssql_close($this->connection);
  232. $this->connection = null;
  233. return $ret;
  234. }
  235. // }}}
  236. // {{{ simpleQuery()
  237. /**
  238. * Sends a query to the database server
  239. *
  240. * @param string the SQL query string
  241. *
  242. * @return mixed + a PHP result resrouce for successful SELECT queries
  243. * + the DB_OK constant for other successful queries
  244. * + a DB_Error object on failure
  245. */
  246. function simpleQuery($query)
  247. {
  248. $ismanip = $this->_checkManip($query);
  249. $this->last_query = $query;
  250. if (!@mssql_select_db($this->_db, $this->connection)) {
  251. return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
  252. }
  253. $query = $this->modifyQuery($query);
  254. if (!$this->autocommit && $ismanip) {
  255. if ($this->transaction_opcount == 0) {
  256. $result = @mssql_query('BEGIN TRAN', $this->connection);
  257. if (!$result) {
  258. return $this->mssqlRaiseError();
  259. }
  260. }
  261. $this->transaction_opcount++;
  262. }
  263. $result = @mssql_query($query, $this->connection);
  264. if (!$result) {
  265. return $this->mssqlRaiseError();
  266. }
  267. // Determine which queries that should return data, and which
  268. // should return an error code only.
  269. return $ismanip ? DB_OK : $result;
  270. }
  271. // }}}
  272. // {{{ nextResult()
  273. /**
  274. * Move the internal mssql result pointer to the next available result
  275. *
  276. * @param a valid fbsql result resource
  277. *
  278. * @access public
  279. *
  280. * @return true if a result is available otherwise return false
  281. */
  282. function nextResult($result)
  283. {
  284. return @mssql_next_result($result);
  285. }
  286. // }}}
  287. // {{{ fetchInto()
  288. /**
  289. * Places a row from the result set into the given array
  290. *
  291. * Formating of the array and the data therein are configurable.
  292. * See DB_result::fetchInto() for more information.
  293. *
  294. * This method is not meant to be called directly. Use
  295. * DB_result::fetchInto() instead. It can't be declared "protected"
  296. * because DB_result is a separate object.
  297. *
  298. * @param resource $result the query result resource
  299. * @param array $arr the referenced array to put the data in
  300. * @param int $fetchmode how the resulting array should be indexed
  301. * @param int $rownum the row number to fetch (0 = first row)
  302. *
  303. * @return mixed DB_OK on success, NULL when the end of a result set is
  304. * reached or on failure
  305. *
  306. * @see DB_result::fetchInto()
  307. */
  308. function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  309. {
  310. if ($rownum !== null) {
  311. if (!@mssql_data_seek($result, $rownum)) {
  312. return null;
  313. }
  314. }
  315. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  316. $arr = @mssql_fetch_assoc($result);
  317. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  318. $arr = array_change_key_case($arr, CASE_LOWER);
  319. }
  320. } else {
  321. $arr = @mssql_fetch_row($result);
  322. }
  323. if (!$arr) {
  324. return null;
  325. }
  326. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  327. $this->_rtrimArrayValues($arr);
  328. }
  329. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  330. $this->_convertNullArrayValuesToEmpty($arr);
  331. }
  332. return DB_OK;
  333. }
  334. // }}}
  335. // {{{ freeResult()
  336. /**
  337. * Deletes the result set and frees the memory occupied by the result set
  338. *
  339. * This method is not meant to be called directly. Use
  340. * DB_result::free() instead. It can't be declared "protected"
  341. * because DB_result is a separate object.
  342. *
  343. * @param resource $result PHP's query result resource
  344. *
  345. * @return bool TRUE on success, FALSE if $result is invalid
  346. *
  347. * @see DB_result::free()
  348. */
  349. function freeResult($result)
  350. {
  351. return is_resource($result) ? mssql_free_result($result) : false;
  352. }
  353. // }}}
  354. // {{{ numCols()
  355. /**
  356. * Gets the number of columns in a result set
  357. *
  358. * This method is not meant to be called directly. Use
  359. * DB_result::numCols() instead. It can't be declared "protected"
  360. * because DB_result is a separate object.
  361. *
  362. * @param resource $result PHP's query result resource
  363. *
  364. * @return int the number of columns. A DB_Error object on failure.
  365. *
  366. * @see DB_result::numCols()
  367. */
  368. function numCols($result)
  369. {
  370. $cols = @mssql_num_fields($result);
  371. if (!$cols) {
  372. return $this->mssqlRaiseError();
  373. }
  374. return $cols;
  375. }
  376. // }}}
  377. // {{{ numRows()
  378. /**
  379. * Gets the number of rows in a result set
  380. *
  381. * This method is not meant to be called directly. Use
  382. * DB_result::numRows() instead. It can't be declared "protected"
  383. * because DB_result is a separate object.
  384. *
  385. * @param resource $result PHP's query result resource
  386. *
  387. * @return int the number of rows. A DB_Error object on failure.
  388. *
  389. * @see DB_result::numRows()
  390. */
  391. function numRows($result)
  392. {
  393. $rows = @mssql_num_rows($result);
  394. if ($rows === false) {
  395. return $this->mssqlRaiseError();
  396. }
  397. return $rows;
  398. }
  399. // }}}
  400. // {{{ autoCommit()
  401. /**
  402. * Enables or disables automatic commits
  403. *
  404. * @param bool $onoff true turns it on, false turns it off
  405. *
  406. * @return int DB_OK on success. A DB_Error object if the driver
  407. * doesn't support auto-committing transactions.
  408. */
  409. function autoCommit($onoff = false)
  410. {
  411. // XXX if $this->transaction_opcount > 0, we should probably
  412. // issue a warning here.
  413. $this->autocommit = $onoff ? true : false;
  414. return DB_OK;
  415. }
  416. // }}}
  417. // {{{ commit()
  418. /**
  419. * Commits the current transaction
  420. *
  421. * @return int DB_OK on success. A DB_Error object on failure.
  422. */
  423. function commit()
  424. {
  425. if ($this->transaction_opcount > 0) {
  426. if (!@mssql_select_db($this->_db, $this->connection)) {
  427. return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
  428. }
  429. $result = @mssql_query('COMMIT TRAN', $this->connection);
  430. $this->transaction_opcount = 0;
  431. if (!$result) {
  432. return $this->mssqlRaiseError();
  433. }
  434. }
  435. return DB_OK;
  436. }
  437. // }}}
  438. // {{{ rollback()
  439. /**
  440. * Reverts the current transaction
  441. *
  442. * @return int DB_OK on success. A DB_Error object on failure.
  443. */
  444. function rollback()
  445. {
  446. if ($this->transaction_opcount > 0) {
  447. if (!@mssql_select_db($this->_db, $this->connection)) {
  448. return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
  449. }
  450. $result = @mssql_query('ROLLBACK TRAN', $this->connection);
  451. $this->transaction_opcount = 0;
  452. if (!$result) {
  453. return $this->mssqlRaiseError();
  454. }
  455. }
  456. return DB_OK;
  457. }
  458. // }}}
  459. // {{{ affectedRows()
  460. /**
  461. * Determines the number of rows affected by a data maniuplation query
  462. *
  463. * 0 is returned for queries that don't manipulate data.
  464. *
  465. * @return int the number of rows. A DB_Error object on failure.
  466. */
  467. function affectedRows()
  468. {
  469. if ($this->_last_query_manip) {
  470. $res = @mssql_query('select @@rowcount', $this->connection);
  471. if (!$res) {
  472. return $this->mssqlRaiseError();
  473. }
  474. $ar = @mssql_fetch_row($res);
  475. if (!$ar) {
  476. $result = 0;
  477. } else {
  478. @mssql_free_result($res);
  479. $result = $ar[0];
  480. }
  481. } else {
  482. $result = 0;
  483. }
  484. return $result;
  485. }
  486. // }}}
  487. // {{{ nextId()
  488. /**
  489. * Returns the next free id in a sequence
  490. *
  491. * @param string $seq_name name of the sequence
  492. * @param boolean $ondemand when true, the seqence is automatically
  493. * created if it does not exist
  494. *
  495. * @return int the next id number in the sequence.
  496. * A DB_Error object on failure.
  497. *
  498. * @see DB_common::nextID(), DB_common::getSequenceName(),
  499. * DB_mssql::createSequence(), DB_mssql::dropSequence()
  500. */
  501. function nextId($seq_name, $ondemand = true)
  502. {
  503. $seqname = $this->getSequenceName($seq_name);
  504. if (!@mssql_select_db($this->_db, $this->connection)) {
  505. return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
  506. }
  507. $repeat = 0;
  508. do {
  509. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  510. $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
  511. $this->popErrorHandling();
  512. if ($ondemand && DB::isError($result) &&
  513. ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
  514. {
  515. $repeat = 1;
  516. $result = $this->createSequence($seq_name);
  517. if (DB::isError($result)) {
  518. return $this->raiseError($result);
  519. }
  520. } elseif (!DB::isError($result)) {
  521. $result = $this->query("SELECT IDENT_CURRENT('$seqname')");
  522. if (DB::isError($result)) {
  523. /* Fallback code for MS SQL Server 7.0, which doesn't have
  524. * IDENT_CURRENT. This is *not* safe for concurrent
  525. * requests, and really, if you're using it, you're in a
  526. * world of hurt. Nevertheless, it's here to ensure BC. See
  527. * bug #181 for the gory details.*/
  528. $result = $this->query("SELECT @@IDENTITY FROM $seqname");
  529. }
  530. $repeat = 0;
  531. } else {
  532. $repeat = false;
  533. }
  534. } while ($repeat);
  535. if (DB::isError($result)) {
  536. return $this->raiseError($result);
  537. }
  538. $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
  539. return $result[0];
  540. }
  541. /**
  542. * Creates a new sequence
  543. *
  544. * @param string $seq_name name of the new sequence
  545. *
  546. * @return int DB_OK on success. A DB_Error object on failure.
  547. *
  548. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  549. * DB_mssql::nextID(), DB_mssql::dropSequence()
  550. */
  551. function createSequence($seq_name)
  552. {
  553. return $this->query('CREATE TABLE '
  554. . $this->getSequenceName($seq_name)
  555. . ' ([id] [int] IDENTITY (1, 1) NOT NULL,'
  556. . ' [vapor] [int] NULL)');
  557. }
  558. // }}}
  559. // {{{ dropSequence()
  560. /**
  561. * Deletes a sequence
  562. *
  563. * @param string $seq_name name of the sequence to be deleted
  564. *
  565. * @return int DB_OK on success. A DB_Error object on failure.
  566. *
  567. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  568. * DB_mssql::nextID(), DB_mssql::createSequence()
  569. */
  570. function dropSequence($seq_name)
  571. {
  572. return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
  573. }
  574. // }}}
  575. // {{{ escapeSimple()
  576. /**
  577. * Escapes a string in a manner suitable for SQL Server.
  578. *
  579. * @param string $str the string to be escaped
  580. * @return string the escaped string
  581. *
  582. * @see DB_common::quoteSmart()
  583. * @since Method available since Release 1.6.0
  584. */
  585. function escapeSimple($str)
  586. {
  587. return str_replace(
  588. array("'", "\\\r\n", "\\\n"),
  589. array("''", "\\\\\r\n\r\n", "\\\\\n\n"),
  590. $str
  591. );
  592. }
  593. // }}}
  594. // {{{ quoteIdentifier()
  595. /**
  596. * Quotes a string so it can be safely used as a table or column name
  597. *
  598. * @param string $str identifier name to be quoted
  599. *
  600. * @return string quoted identifier string
  601. *
  602. * @see DB_common::quoteIdentifier()
  603. * @since Method available since Release 1.6.0
  604. */
  605. function quoteIdentifier($str)
  606. {
  607. return '[' . str_replace(']', ']]', $str) . ']';
  608. }
  609. // }}}
  610. // {{{ mssqlRaiseError()
  611. /**
  612. * Produces a DB_Error object regarding the current problem
  613. *
  614. * @param int $errno if the error is being manually raised pass a
  615. * DB_ERROR* constant here. If this isn't passed
  616. * the error information gathered from the DBMS.
  617. *
  618. * @return object the DB_Error object
  619. *
  620. * @see DB_common::raiseError(),
  621. * DB_mssql::errorNative(), DB_mssql::errorCode()
  622. */
  623. function mssqlRaiseError($code = null)
  624. {
  625. $message = @mssql_get_last_message();
  626. if (!$code) {
  627. $code = $this->errorNative();
  628. }
  629. return $this->raiseError($this->errorCode($code, $message),
  630. null, null, null, "$code - $message");
  631. }
  632. // }}}
  633. // {{{ errorNative()
  634. /**
  635. * Gets the DBMS' native error code produced by the last query
  636. *
  637. * @return int the DBMS' error code
  638. */
  639. function errorNative()
  640. {
  641. $res = @mssql_query('select @@ERROR as ErrorCode', $this->connection);
  642. if (!$res) {
  643. return DB_ERROR;
  644. }
  645. $row = @mssql_fetch_row($res);
  646. return $row[0];
  647. }
  648. // }}}
  649. // {{{ errorCode()
  650. /**
  651. * Determines PEAR::DB error code from mssql's native codes.
  652. *
  653. * If <var>$nativecode</var> isn't known yet, it will be looked up.
  654. *
  655. * @param mixed $nativecode mssql error code, if known
  656. * @return integer an error number from a DB error constant
  657. * @see errorNative()
  658. */
  659. function errorCode($nativecode = null, $msg = '')
  660. {
  661. if (!$nativecode) {
  662. $nativecode = $this->errorNative();
  663. }
  664. if (isset($this->errorcode_map[$nativecode])) {
  665. if ($nativecode == 3701
  666. && preg_match('/Cannot drop the index/i', $msg))
  667. {
  668. return DB_ERROR_NOT_FOUND;
  669. }
  670. return $this->errorcode_map[$nativecode];
  671. } else {
  672. return DB_ERROR;
  673. }
  674. }
  675. // }}}
  676. // {{{ tableInfo()
  677. /**
  678. * Returns information about a table or a result set
  679. *
  680. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  681. * is a table name.
  682. *
  683. * @param object|string $result DB_result object from a query or a
  684. * string containing the name of a table.
  685. * While this also accepts a query result
  686. * resource identifier, this behavior is
  687. * deprecated.
  688. * @param int $mode a valid tableInfo mode
  689. *
  690. * @return array an associative array with the information requested.
  691. * A DB_Error object on failure.
  692. *
  693. * @see DB_common::tableInfo()
  694. */
  695. function tableInfo($result, $mode = null)
  696. {
  697. if (is_string($result)) {
  698. /*
  699. * Probably received a table name.
  700. * Create a result resource identifier.
  701. */
  702. if (!@mssql_select_db($this->_db, $this->connection)) {
  703. return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
  704. }
  705. $id = @mssql_query("SELECT * FROM $result WHERE 1=0",
  706. $this->connection);
  707. $got_string = true;
  708. } elseif (isset($result->result)) {
  709. /*
  710. * Probably received a result object.
  711. * Extract the result resource identifier.
  712. */
  713. $id = $result->result;
  714. $got_string = false;
  715. } else {
  716. /*
  717. * Probably received a result resource identifier.
  718. * Copy it.
  719. * Deprecated. Here for compatibility only.
  720. */
  721. $id = $result;
  722. $got_string = false;
  723. }
  724. if (!is_resource($id)) {
  725. return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA);
  726. }
  727. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  728. $case_func = 'strtolower';
  729. } else {
  730. $case_func = 'strval';
  731. }
  732. $count = @mssql_num_fields($id);
  733. $res = array();
  734. if ($mode) {
  735. $res['num_fields'] = $count;
  736. }
  737. for ($i = 0; $i < $count; $i++) {
  738. if ($got_string) {
  739. $flags = $this->_mssql_field_flags($result,
  740. @mssql_field_name($id, $i));
  741. if (DB::isError($flags)) {
  742. return $flags;
  743. }
  744. } else {
  745. $flags = '';
  746. }
  747. $res[$i] = array(
  748. 'table' => $got_string ? $case_func($result) : '',
  749. 'name' => $case_func(@mssql_field_name($id, $i)),
  750. 'type' => @mssql_field_type($id, $i),
  751. 'len' => @mssql_field_length($id, $i),
  752. 'flags' => $flags,
  753. );
  754. if ($mode & DB_TABLEINFO_ORDER) {
  755. $res['order'][$res[$i]['name']] = $i;
  756. }
  757. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  758. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  759. }
  760. }
  761. // free the result only if we were called on a table
  762. if ($got_string) {
  763. @mssql_free_result($id);
  764. }
  765. return $res;
  766. }
  767. // }}}
  768. // {{{ _mssql_field_flags()
  769. /**
  770. * Get a column's flags
  771. *
  772. * Supports "not_null", "primary_key",
  773. * "auto_increment" (mssql identity), "timestamp" (mssql timestamp),
  774. * "unique_key" (mssql unique index, unique check or primary_key) and
  775. * "multiple_key" (multikey index)
  776. *
  777. * mssql timestamp is NOT similar to the mysql timestamp so this is maybe
  778. * not useful at all - is the behaviour of mysql_field_flags that primary
  779. * keys are alway unique? is the interpretation of multiple_key correct?
  780. *
  781. * @param string $table the table name
  782. * @param string $column the field name
  783. *
  784. * @return string the flags
  785. *
  786. * @access private
  787. * @author Joern Barthel <j_barthel@web.de>
  788. */
  789. function _mssql_field_flags($table, $column)
  790. {
  791. static $tableName = null;
  792. static $flags = array();
  793. if ($table != $tableName) {
  794. $flags = array();
  795. $tableName = $table;
  796. // get unique and primary keys
  797. $res = $this->getAll("EXEC SP_HELPINDEX $table", DB_FETCHMODE_ASSOC);
  798. if (DB::isError($res)) {
  799. return $res;
  800. }
  801. foreach ($res as $val) {
  802. $keys = explode(', ', $val['index_keys']);
  803. if (sizeof($keys) > 1) {
  804. foreach ($keys as $key) {
  805. $this->_add_flag($flags[$key], 'multiple_key');
  806. }
  807. }
  808. if (strpos($val['index_description'], 'primary key')) {
  809. foreach ($keys as $key) {
  810. $this->_add_flag($flags[$key], 'primary_key');
  811. }
  812. } elseif (strpos($val['index_description'], 'unique')) {
  813. foreach ($keys as $key) {
  814. $this->_add_flag($flags[$key], 'unique_key');
  815. }
  816. }
  817. }
  818. // get auto_increment, not_null and timestamp
  819. $res = $this->getAll("EXEC SP_COLUMNS $table", DB_FETCHMODE_ASSOC);
  820. if (DB::isError($res)) {
  821. return $res;
  822. }
  823. foreach ($res as $val) {
  824. $val = array_change_key_case($val, CASE_LOWER);
  825. if ($val['nullable'] == '0') {
  826. $this->_add_flag($flags[$val['column_name']], 'not_null');
  827. }
  828. if (strpos($val['type_name'], 'identity')) {
  829. $this->_add_flag($flags[$val['column_name']], 'auto_increment');
  830. }
  831. if (strpos($val['type_name'], 'timestamp')) {
  832. $this->_add_flag($flags[$val['column_name']], 'timestamp');
  833. }
  834. }
  835. }
  836. if (array_key_exists($column, $flags)) {
  837. return(implode(' ', $flags[$column]));
  838. }
  839. return '';
  840. }
  841. // }}}
  842. // {{{ _add_flag()
  843. /**
  844. * Adds a string to the flags array if the flag is not yet in there
  845. * - if there is no flag present the array is created
  846. *
  847. * @param array &$array the reference to the flag-array
  848. * @param string $value the flag value
  849. *
  850. * @return void
  851. *
  852. * @access private
  853. * @author Joern Barthel <j_barthel@web.de>
  854. */
  855. function _add_flag(&$array, $value)
  856. {
  857. if (!is_array($array)) {
  858. $array = array($value);
  859. } elseif (!in_array($value, $array)) {
  860. array_push($array, $value);
  861. }
  862. }
  863. // }}}
  864. // {{{ getSpecialQuery()
  865. /**
  866. * Obtains the query string needed for listing a given type of objects
  867. *
  868. * @param string $type the kind of objects you want to retrieve
  869. *
  870. * @return string the SQL query string or null if the driver doesn't
  871. * support the object type requested
  872. *
  873. * @access protected
  874. * @see DB_common::getListOf()
  875. */
  876. function getSpecialQuery($type)
  877. {
  878. switch ($type) {
  879. case 'tables':
  880. return "SELECT name FROM sysobjects WHERE type = 'U'"
  881. . ' ORDER BY name';
  882. case 'views':
  883. return "SELECT name FROM sysobjects WHERE type = 'V'";
  884. default:
  885. return null;
  886. }
  887. }
  888. // }}}
  889. }
  890. /*
  891. * Local variables:
  892. * tab-width: 4
  893. * c-basic-offset: 4
  894. * End:
  895. */
  896. ?>