mssql.php 29 KB

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