PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/common/libraries/plugin/pear/MDB2/Driver/mssql.php

https://bitbucket.org/chamilo/chamilo/
PHP | 1133 lines | 898 code | 35 blank | 200 comment | 66 complexity | 8277e94eb986fc424a6d540d1d2ba966 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-3.0, MIT
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Frank M. Kromann <frank@kromann.info> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mssql.php 137 2009-11-09 13:24:37Z vanpouckesven $
  47. //
  48. // {{{ Class MDB2_Driver_mssql
  49. /**
  50. * MDB2 MSSQL Server driver
  51. *
  52. * @package MDB2
  53. * @category Database
  54. * @author Frank M. Kromann <frank@kromann.info>
  55. */
  56. class MDB2_Driver_mssql extends MDB2_Driver_Common
  57. {
  58. // {{{ properties
  59. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
  60. var $identifier_quoting = array('start' => '[', 'end' => ']', 'escape' => ']');
  61. // }}}
  62. // {{{ constructor
  63. /**
  64. * Constructor
  65. */
  66. function __construct()
  67. {
  68. parent :: __construct();
  69. $this->phptype = 'mssql';
  70. $this->dbsyntax = 'mssql';
  71. $this->supported['sequences'] = 'emulated';
  72. $this->supported['indexes'] = true;
  73. $this->supported['affected_rows'] = true;
  74. $this->supported['transactions'] = true;
  75. $this->supported['savepoints'] = false;
  76. $this->supported['summary_functions'] = true;
  77. $this->supported['order_by_text'] = true;
  78. $this->supported['current_id'] = 'emulated';
  79. $this->supported['limit_queries'] = 'emulated';
  80. $this->supported['LOBs'] = true;
  81. $this->supported['replace'] = 'emulated';
  82. $this->supported['sub_selects'] = true;
  83. $this->supported['triggers'] = true;
  84. $this->supported['auto_increment'] = true;
  85. $this->supported['primary_key'] = true;
  86. $this->supported['result_introspection'] = true;
  87. $this->supported['prepared_statements'] = 'emulated';
  88. $this->supported['pattern_escaping'] = true;
  89. $this->supported['new_link'] = true;
  90. $this->options['DBA_username'] = false;
  91. $this->options['DBA_password'] = false;
  92. $this->options['database_device'] = false;
  93. $this->options['database_size'] = false;
  94. $this->options['max_identifiers_length'] = 128; // MS Access: 64
  95. }
  96. // }}}
  97. // {{{ errorInfo()
  98. /**
  99. * This method is used to collect information about an error
  100. *
  101. * @param integer $error
  102. * @return array
  103. * @access public
  104. */
  105. function errorInfo($error = null, $connection = null)
  106. {
  107. if (is_null($connection)) {
  108. $connection = $this->connection;
  109. }
  110. $native_code = null;
  111. if ($connection) {
  112. $result = @mssql_query('select @@ERROR as ErrorCode', $connection);
  113. if ($result) {
  114. $native_code = @mssql_result($result, 0, 0);
  115. @mssql_free_result($result);
  116. }
  117. }
  118. $native_msg = @mssql_get_last_message();
  119. if (is_null($error)) {
  120. static $ecode_map;
  121. if (empty($ecode_map)) {
  122. $ecode_map = array(
  123. 102 => MDB2_ERROR_SYNTAX,
  124. 110 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  125. 155 => MDB2_ERROR_NOSUCHFIELD,
  126. 156 => MDB2_ERROR_SYNTAX,
  127. 170 => MDB2_ERROR_SYNTAX,
  128. 207 => MDB2_ERROR_NOSUCHFIELD,
  129. 208 => MDB2_ERROR_NOSUCHTABLE,
  130. 245 => MDB2_ERROR_INVALID_NUMBER,
  131. 319 => MDB2_ERROR_SYNTAX,
  132. 321 => MDB2_ERROR_NOSUCHFIELD,
  133. 325 => MDB2_ERROR_SYNTAX,
  134. 336 => MDB2_ERROR_SYNTAX,
  135. 515 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  136. 547 => MDB2_ERROR_CONSTRAINT,
  137. 911 => MDB2_ERROR_NOT_FOUND,
  138. 1018 => MDB2_ERROR_SYNTAX,
  139. 1035 => MDB2_ERROR_SYNTAX,
  140. 1801 => MDB2_ERROR_ALREADY_EXISTS,
  141. 1913 => MDB2_ERROR_ALREADY_EXISTS,
  142. 2209 => MDB2_ERROR_SYNTAX,
  143. 2223 => MDB2_ERROR_SYNTAX,
  144. 2248 => MDB2_ERROR_SYNTAX,
  145. 2256 => MDB2_ERROR_SYNTAX,
  146. 2257 => MDB2_ERROR_SYNTAX,
  147. 2627 => MDB2_ERROR_CONSTRAINT,
  148. 2714 => MDB2_ERROR_ALREADY_EXISTS,
  149. 3607 => MDB2_ERROR_DIVZERO,
  150. 3701 => MDB2_ERROR_NOSUCHTABLE,
  151. 7630 => MDB2_ERROR_SYNTAX,
  152. 8134 => MDB2_ERROR_DIVZERO,
  153. 9303 => MDB2_ERROR_SYNTAX,
  154. 9317 => MDB2_ERROR_SYNTAX,
  155. 9318 => MDB2_ERROR_SYNTAX,
  156. 9331 => MDB2_ERROR_SYNTAX,
  157. 9332 => MDB2_ERROR_SYNTAX,
  158. 15253 => MDB2_ERROR_SYNTAX,
  159. );
  160. }
  161. if (isset($ecode_map[$native_code])) {
  162. if ($native_code == 3701
  163. && preg_match('/Cannot drop the index/i', $native_msg)
  164. ) {
  165. $error = MDB2_ERROR_NOT_FOUND;
  166. } else {
  167. $error = $ecode_map[$native_code];
  168. }
  169. }
  170. }
  171. return array($error, $native_code, $native_msg);
  172. }
  173. // }}}
  174. // {{{ function escapePattern($text)
  175. /**
  176. * Quotes pattern (% and _) characters in a string)
  177. *
  178. * @param string the input string to quote
  179. *
  180. * @return string quoted string
  181. *
  182. * @access public
  183. */
  184. function escapePattern($text)
  185. {
  186. $text = str_replace("[", "[ [ ]", $text);
  187. foreach ($this->wildcards as $wildcard) {
  188. $text = str_replace($wildcard, '[' . $wildcard . ']', $text);
  189. }
  190. return $text;
  191. }
  192. // }}}
  193. // {{{ beginTransaction()
  194. /**
  195. * Start a transaction or set a savepoint.
  196. *
  197. * @param string name of a savepoint to set
  198. * @return mixed MDB2_OK on success, a MDB2 error on failure
  199. *
  200. * @access public
  201. */
  202. function beginTransaction($savepoint = null)
  203. {
  204. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  205. if (!is_null($savepoint)) {
  206. if (!$this->in_transaction) {
  207. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  208. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  209. }
  210. $query = 'SAVE TRANSACTION '.$savepoint;
  211. return $this->_doQuery($query, true);
  212. } elseif ($this->in_transaction) {
  213. return MDB2_OK; //nothing to do
  214. }
  215. if (!$this->destructor_registered && $this->opened_persistent) {
  216. $this->destructor_registered = true;
  217. register_shutdown_function('MDB2_closeOpenTransactions');
  218. }
  219. $result =& $this->_doQuery('BEGIN TRANSACTION', true);
  220. if (PEAR::isError($result)) {
  221. return $result;
  222. }
  223. $this->in_transaction = true;
  224. return MDB2_OK;
  225. }
  226. // }}}
  227. // {{{ commit()
  228. /**
  229. * Commit the database changes done during a transaction that is in
  230. * progress or release a savepoint. This function may only be called when
  231. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  232. * transaction is implicitly started after committing the pending changes.
  233. *
  234. * @param string name of a savepoint to release
  235. * @return mixed MDB2_OK on success, a MDB2 error on failure
  236. *
  237. * @access public
  238. */
  239. function commit($savepoint = null)
  240. {
  241. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  242. if (!$this->in_transaction) {
  243. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  244. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  245. }
  246. if (!is_null($savepoint)) {
  247. return MDB2_OK;
  248. }
  249. $result =& $this->_doQuery('COMMIT TRANSACTION', true);
  250. if (PEAR::isError($result)) {
  251. return $result;
  252. }
  253. $this->in_transaction = false;
  254. return MDB2_OK;
  255. }
  256. // }}}
  257. // {{{ rollback()
  258. /**
  259. * Cancel any database changes done during a transaction or since a specific
  260. * savepoint that is in progress. This function may only be called when
  261. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  262. * transaction is implicitly started after canceling the pending changes.
  263. *
  264. * @param string name of a savepoint to rollback to
  265. * @return mixed MDB2_OK on success, a MDB2 error on failure
  266. *
  267. * @access public
  268. */
  269. function rollback($savepoint = null)
  270. {
  271. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  272. if (!$this->in_transaction) {
  273. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  274. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  275. }
  276. if (!is_null($savepoint)) {
  277. $query = 'ROLLBACK TRANSACTION '.$savepoint;
  278. return $this->_doQuery($query, true);
  279. }
  280. $result =& $this->_doQuery('ROLLBACK TRANSACTION', true);
  281. if (PEAR::isError($result)) {
  282. return $result;
  283. }
  284. $this->in_transaction = false;
  285. return MDB2_OK;
  286. }
  287. // }}}
  288. // {{{ _doConnect()
  289. /**
  290. * do the grunt work of the connect
  291. *
  292. * @return connection on success or MDB2 Error Object on failure
  293. * @access protected
  294. */
  295. function _doConnect($username, $password, $persistent = false)
  296. {
  297. if (!PEAR::loadExtension($this->phptype) && !PEAR::loadExtension('sybase_ct')) {
  298. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  299. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  300. }
  301. $params = array(
  302. $this->dsn['hostspec'] ? $this->dsn['hostspec'] : 'localhost',
  303. $username ? $username : null,
  304. $password ? $password : null,
  305. );
  306. if ($this->dsn['port']) {
  307. $params[0].= ((substr(PHP_OS, 0, 3) == 'WIN') ? ',' : ':').$this->dsn['port'];
  308. }
  309. if (!$persistent) {
  310. if ($this->_isNewLinkSet()) {
  311. $params[] = true;
  312. } else {
  313. $params[] = false;
  314. }
  315. }
  316. $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect';
  317. $connection = @call_user_func_array($connect_function, $params);
  318. if ($connection <= 0) {
  319. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  320. 'unable to establish a connection', __FUNCTION__, __FUNCTION__);
  321. }
  322. @mssql_query('SET ANSI_NULL_DFLT_ON ON', $connection);
  323. /*
  324. if (!empty($this->dsn['charset'])) {
  325. $result = $this->setCharset($this->dsn['charset'], $connection);
  326. if (PEAR::isError($result)) {
  327. return $result;
  328. }
  329. }
  330. */
  331. if ((bool)ini_get('mssql.datetimeconvert')) {
  332. @ini_set('mssql.datetimeconvert', '0');
  333. }
  334. if (empty($this->dsn['disable_iso_date'])) {
  335. @mssql_query('SET DATEFORMAT ymd', $connection);
  336. }
  337. return $connection;
  338. }
  339. // }}}
  340. // {{{ connect()
  341. /**
  342. * Connect to the database
  343. *
  344. * @return true on success, MDB2 Error Object on failure
  345. */
  346. function connect()
  347. {
  348. if (is_resource($this->connection)) {
  349. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  350. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  351. && $this->opened_persistent == $this->options['persistent']
  352. ) {
  353. return MDB2_OK;
  354. }
  355. $this->disconnect(false);
  356. }
  357. $connection = $this->_doConnect(
  358. $this->dsn['username'],
  359. $this->dsn['password'],
  360. $this->options['persistent']
  361. );
  362. if (PEAR::isError($connection)) {
  363. return $connection;
  364. }
  365. $this->connection = $connection;
  366. $this->connected_dsn = $this->dsn;
  367. $this->connected_database_name = '';
  368. $this->opened_persistent = $this->options['persistent'];
  369. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  370. if ($this->database_name) {
  371. if ($this->database_name != $this->connected_database_name) {
  372. if (!@mssql_select_db($this->database_name, $connection)) {
  373. $err = $this->raiseError(null, null, null,
  374. 'Could not select the database: '.$this->database_name, __FUNCTION__);
  375. return $err;
  376. }
  377. $this->connected_database_name = $this->database_name;
  378. }
  379. }
  380. return MDB2_OK;
  381. }
  382. // }}}
  383. // {{{ databaseExists()
  384. /**
  385. * check if given database name is exists?
  386. *
  387. * @param string $name name of the database that should be checked
  388. *
  389. * @return mixed true/false on success, a MDB2 error on failure
  390. * @access public
  391. */
  392. function databaseExists($name)
  393. {
  394. $connection = $this->_doConnect($this->dsn['username'],
  395. $this->dsn['password'],
  396. $this->options['persistent']);
  397. if (PEAR::isError($connection)) {
  398. return $connection;
  399. }
  400. $result = @mssql_select_db($name, $connection);
  401. $errorInfo = $this->errorInfo(null, $connection);
  402. @mssql_close($connection);
  403. if (!$result) {
  404. if ($errorInfo[0] != MDB2_ERROR_NOT_FOUND) {
  405. exit;
  406. $result = $this->raiseError($errorInfo[0], null, null, $errorInfo[2], __FUNCTION__);
  407. return $result;
  408. }
  409. $result = false;
  410. }
  411. return $result;
  412. }
  413. // }}}
  414. // {{{ disconnect()
  415. /**
  416. * Log out and disconnect from the database.
  417. *
  418. * @param boolean $force if the disconnect should be forced even if the
  419. * connection is opened persistently
  420. * @return mixed true on success, false if not connected and error
  421. * object on error
  422. * @access public
  423. */
  424. function disconnect($force = true)
  425. {
  426. if (is_resource($this->connection)) {
  427. if ($this->in_transaction) {
  428. $dsn = $this->dsn;
  429. $database_name = $this->database_name;
  430. $persistent = $this->options['persistent'];
  431. $this->dsn = $this->connected_dsn;
  432. $this->database_name = $this->connected_database_name;
  433. $this->options['persistent'] = $this->opened_persistent;
  434. $this->rollback();
  435. $this->dsn = $dsn;
  436. $this->database_name = $database_name;
  437. $this->options['persistent'] = $persistent;
  438. }
  439. if (!$this->opened_persistent || $force) {
  440. $ok = @mssql_close($this->connection);
  441. if (!$ok) {
  442. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  443. null, null, null, __FUNCTION__);
  444. }
  445. }
  446. } else {
  447. return false;
  448. }
  449. return parent::disconnect($force);
  450. }
  451. // }}}
  452. // {{{ standaloneQuery()
  453. /**
  454. * execute a query as DBA
  455. *
  456. * @param string $query the SQL query
  457. * @param mixed $types array that contains the types of the columns in
  458. * the result set
  459. * @param boolean $is_manip if the query is a manipulation query
  460. * @return mixed MDB2_OK on success, a MDB2 error on failure
  461. * @access public
  462. */
  463. function &standaloneQuery($query, $types = null, $is_manip = false)
  464. {
  465. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  466. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  467. $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
  468. if (PEAR::isError($connection)) {
  469. return $connection;
  470. }
  471. $offset = $this->offset;
  472. $limit = $this->limit;
  473. $this->offset = $this->limit = 0;
  474. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  475. $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  476. if (!PEAR::isError($result)) {
  477. $result = $this->_affectedRows($connection, $result);
  478. }
  479. @mssql_close($connection);
  480. return $result;
  481. }
  482. // }}}
  483. // {{{ _doQuery()
  484. /**
  485. * Execute a query
  486. * @param string $query query
  487. * @param boolean $is_manip if the query is a manipulation query
  488. * @param resource $connection
  489. * @param string $database_name
  490. * @return result or error object
  491. * @access protected
  492. */
  493. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  494. {
  495. $this->last_query = $query;
  496. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  497. if ($result) {
  498. if (PEAR::isError($result)) {
  499. return $result;
  500. }
  501. $query = $result;
  502. }
  503. if ($this->options['disable_query']) {
  504. $result = $is_manip ? 0 : null;
  505. return $result;
  506. }
  507. if (is_null($connection)) {
  508. $connection = $this->getConnection();
  509. if (PEAR::isError($connection)) {
  510. return $connection;
  511. }
  512. }
  513. if (is_null($database_name)) {
  514. $database_name = $this->database_name;
  515. }
  516. if ($database_name) {
  517. if ($database_name != $this->connected_database_name) {
  518. if (!@mssql_select_db($database_name, $connection)) {
  519. $err = $this->raiseError(null, null, null,
  520. 'Could not select the database: '.$database_name, __FUNCTION__);
  521. return $err;
  522. }
  523. $this->connected_database_name = $database_name;
  524. }
  525. }
  526. $result = @mssql_query($query, $connection);
  527. if (!$result) {
  528. $err =& $this->raiseError(null, null, null,
  529. 'Could not execute statement', __FUNCTION__);
  530. return $err;
  531. }
  532. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  533. return $result;
  534. }
  535. // }}}
  536. // {{{ _affectedRows()
  537. /**
  538. * Returns the number of rows affected
  539. *
  540. * @param resource $result
  541. * @param resource $connection
  542. * @return mixed MDB2 Error Object or the number of rows affected
  543. * @access private
  544. */
  545. function _affectedRows($connection, $result = null)
  546. {
  547. if (is_null($connection)) {
  548. $connection = $this->getConnection();
  549. if (PEAR::isError($connection)) {
  550. return $connection;
  551. }
  552. }
  553. return @mssql_rows_affected($connection);
  554. }
  555. // }}}
  556. // {{{ _modifyQuery()
  557. /**
  558. * Changes a query string for various DBMS specific reasons
  559. *
  560. * @param string $query query to modify
  561. * @param boolean $is_manip if it is a DML query
  562. * @param integer $limit limit the number of rows
  563. * @param integer $offset start reading from given offset
  564. * @return string modified query
  565. * @access protected
  566. */
  567. function _modifyQuery($query, $is_manip, $limit, $offset)
  568. {
  569. if ($limit > 0) {
  570. $fetch = $offset + $limit;
  571. if (!$is_manip) {
  572. return preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',
  573. "\\1SELECT\\2 TOP $fetch", $query);
  574. }
  575. }
  576. return $query;
  577. }
  578. // }}}
  579. // {{{ getServerVersion()
  580. /**
  581. * return version information about the server
  582. *
  583. * @param bool $native determines if the raw version string should be returned
  584. * @return mixed array/string with version information or MDB2 error object
  585. * @access public
  586. */
  587. function getServerVersion($native = false)
  588. {
  589. if ($this->connected_server_info) {
  590. $server_info = $this->connected_server_info;
  591. } else {
  592. $query = 'SELECT @@VERSION';
  593. $server_info = $this->queryOne($query, 'text');
  594. if (PEAR::isError($server_info)) {
  595. return $server_info;
  596. }
  597. }
  598. // cache server_info
  599. $this->connected_server_info = $server_info;
  600. if (!$native && !PEAR::isError($server_info)) {
  601. if (preg_match('/(\d+)\.(\d+)\.(\d+)/', $server_info, $tmp)) {
  602. $server_info = array(
  603. 'major' => $tmp[1],
  604. 'minor' => $tmp[2],
  605. 'patch' => $tmp[3],
  606. 'extra' => null,
  607. 'native' => $server_info,
  608. );
  609. } else {
  610. $server_info = array(
  611. 'major' => null,
  612. 'minor' => null,
  613. 'patch' => null,
  614. 'extra' => null,
  615. 'native' => $server_info,
  616. );
  617. }
  618. }
  619. return $server_info;
  620. }
  621. // }}}
  622. // {{{ _checkSequence
  623. /**
  624. * Checks if there's a sequence that exists.
  625. *
  626. * @param string $seq_name The sequence name to verify.
  627. * @return bool $tableExists The value if the table exists or not
  628. * @access private
  629. */
  630. function _checkSequence($seq_name)
  631. {
  632. $query = "SELECT * FROM $seq_name";
  633. $tableExists =& $this->_doQuery($query, true);
  634. if (PEAR::isError($tableExists)) {
  635. if ($tableExists->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  636. return false;
  637. }
  638. //return $tableExists;
  639. return false;
  640. }
  641. return mssql_result($tableExists, 0, 0);
  642. }
  643. // }}}
  644. // {{{ nextID()
  645. /**
  646. * Returns the next free id of a sequence
  647. *
  648. * @param string $seq_name name of the sequence
  649. * @param boolean $ondemand when true the sequence is
  650. * automatic created, if it
  651. * not exists
  652. *
  653. * @return mixed MDB2 Error Object or id
  654. * @access public
  655. */
  656. function nextID($seq_name, $ondemand = true)
  657. {
  658. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  659. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  660. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  661. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  662. $seq_val = $this->_checkSequence($sequence_name);
  663. if ($seq_val) {
  664. $query = "SET IDENTITY_INSERT $sequence_name OFF ".
  665. "INSERT INTO $sequence_name DEFAULT VALUES";
  666. } else {
  667. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (0)";
  668. }
  669. $result =& $this->_doQuery($query, true);
  670. $this->popExpect();
  671. $this->popErrorHandling();
  672. if (PEAR::isError($result)) {
  673. if ($ondemand && !$this->_checkSequence($sequence_name)) {
  674. $this->loadModule('Manager', null, true);
  675. $result = $this->manager->createSequence($seq_name);
  676. if (PEAR::isError($result)) {
  677. return $this->raiseError($result, null, null,
  678. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  679. } else {
  680. /**
  681. * Little off-by-one problem with the sequence emulation
  682. * here being fixed, that instead of re-calling nextID
  683. * and forcing an increment by one, we simply check if it
  684. * exists, then we get the last inserted id if it does.
  685. *
  686. * In theory, $seq_name should be created otherwise there would
  687. * have been an error thrown somewhere up there..
  688. *
  689. * @todo confirm
  690. */
  691. if ($this->_checkSequence($seq_name)) {
  692. return $this->lastInsertID($seq_name);
  693. }
  694. return $this->nextID($seq_name, false);
  695. }
  696. }
  697. return $result;
  698. }
  699. $value = $this->lastInsertID($sequence_name);
  700. if (is_numeric($value)) {
  701. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  702. $result =& $this->_doQuery($query, true);
  703. if (PEAR::isError($result)) {
  704. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  705. }
  706. }
  707. return $value;
  708. }
  709. // }}}
  710. // {{{ lastInsertID()
  711. /**
  712. * Returns the autoincrement ID if supported or $id or fetches the current
  713. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  714. *
  715. * @param string $table name of the table into which a new row was inserted
  716. * @param string $field name of the field into which a new row was inserted
  717. *
  718. * @return mixed MDB2 Error Object or id
  719. * @access public
  720. */
  721. function lastInsertID($table = null, $field = null)
  722. {
  723. $server_info = $this->getServerVersion();
  724. if (is_array($server_info) && !is_null($server_info['major'])
  725. && $server_info['major'] >= 8
  726. ) {
  727. $query = "SELECT IDENT_CURRENT('$table')";
  728. } else {
  729. $query = "SELECT @@IDENTITY";
  730. if (!is_null($table)) {
  731. $query .= ' FROM '.$this->quoteIdentifier($table, true);
  732. }
  733. }
  734. return $this->queryOne($query, 'integer');
  735. }
  736. // }}}
  737. }
  738. // }}}
  739. // {{{ Class MDB2_Result_mssql
  740. /**
  741. * MDB2 MSSQL Server result driver
  742. *
  743. * @package MDB2
  744. * @category Database
  745. * @author Frank M. Kromann <frank@kromann.info>
  746. */
  747. class MDB2_Result_mssql extends MDB2_Result_Common
  748. {
  749. // {{{ _skipLimitOffset()
  750. /**
  751. * Skip the first row of a result set.
  752. *
  753. * @param resource $result
  754. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  755. * @access protected
  756. */
  757. function _skipLimitOffset()
  758. {
  759. if ($this->limit) {
  760. if ($this->rownum >= $this->limit) {
  761. return false;
  762. }
  763. }
  764. if ($this->offset) {
  765. while ($this->offset_count < $this->offset) {
  766. ++$this->offset_count;
  767. if (!is_array(@mssql_fetch_row($this->result))) {
  768. $this->offset_count = $this->limit;
  769. return false;
  770. }
  771. }
  772. }
  773. return MDB2_OK;
  774. }
  775. // }}}
  776. // {{{ fetchRow()
  777. /**
  778. * Fetch a row and insert the data into an existing array.
  779. *
  780. * @param int $fetchmode how the array data should be indexed
  781. * @param int $rownum number of the row where the data can be found
  782. * @return int data array on success, a MDB2 error on failure
  783. * @access public
  784. */
  785. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  786. {
  787. if (!$this->_skipLimitOffset()) {
  788. $null = null;
  789. return $null;
  790. }
  791. if (!is_null($rownum)) {
  792. $seek = $this->seek($rownum);
  793. if (PEAR::isError($seek)) {
  794. return $seek;
  795. }
  796. }
  797. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  798. $fetchmode = $this->db->fetchmode;
  799. }
  800. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  801. $row = @mssql_fetch_assoc($this->result);
  802. if (is_array($row)
  803. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  804. ) {
  805. $row = array_change_key_case($row, $this->db->options['field_case']);
  806. }
  807. } else {
  808. $row = @mssql_fetch_row($this->result);
  809. }
  810. if (!$row) {
  811. if ($this->result === false) {
  812. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  813. 'resultset has already been freed', __FUNCTION__);
  814. return $err;
  815. }
  816. $null = null;
  817. return $null;
  818. }
  819. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  820. $rtrim = false;
  821. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  822. if (empty($this->types)) {
  823. $mode += MDB2_PORTABILITY_RTRIM;
  824. } else {
  825. $rtrim = true;
  826. }
  827. }
  828. if ($mode) {
  829. $this->db->_fixResultArrayValues($row, $mode);
  830. }
  831. if (!($fetchmode & MDB2_FETCHMODE_ASSOC) && !empty($this->types)) {
  832. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  833. } elseif (($fetchmode & MDB2_FETCHMODE_ASSOC) && !empty($this->types_assoc)) {
  834. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  835. }
  836. if (!empty($this->values)) {
  837. $this->_assignBindColumns($row);
  838. }
  839. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  840. $object_class = $this->db->options['fetch_class'];
  841. if ($object_class == 'stdClass') {
  842. $row = (object) $row;
  843. } else {
  844. $row = &new $object_class($row);
  845. }
  846. }
  847. ++$this->rownum;
  848. return $row;
  849. }
  850. // }}}
  851. // {{{ _getColumnNames()
  852. /**
  853. * Retrieve the names of columns returned by the DBMS in a query result.
  854. *
  855. * @return mixed Array variable that holds the names of columns as keys
  856. * or an MDB2 error on failure.
  857. * Some DBMS may not return any columns when the result set
  858. * does not contain any rows.
  859. * @access private
  860. */
  861. function _getColumnNames()
  862. {
  863. $columns = array();
  864. $numcols = $this->numCols();
  865. if (PEAR::isError($numcols)) {
  866. return $numcols;
  867. }
  868. for ($column = 0; $column < $numcols; $column++) {
  869. $column_name = @mssql_field_name($this->result, $column);
  870. $columns[$column_name] = $column;
  871. }
  872. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  873. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  874. }
  875. return $columns;
  876. }
  877. // }}}
  878. // {{{ numCols()
  879. /**
  880. * Count the number of columns returned by the DBMS in a query result.
  881. *
  882. * @return mixed integer value with the number of columns, a MDB2 error
  883. * on failure
  884. * @access public
  885. */
  886. function numCols()
  887. {
  888. $cols = @mssql_num_fields($this->result);
  889. if (is_null($cols)) {
  890. if ($this->result === false) {
  891. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  892. 'resultset has already been freed', __FUNCTION__);
  893. } elseif (is_null($this->result)) {
  894. return count($this->types);
  895. }
  896. return $this->db->raiseError(null, null, null,
  897. 'Could not get column count', __FUNCTION__);
  898. }
  899. return $cols;
  900. }
  901. // }}}
  902. // {{{ nextResult()
  903. /**
  904. * Move the internal result pointer to the next available result
  905. *
  906. * @return true on success, false if there is no more result set or an error object on failure
  907. * @access public
  908. */
  909. function nextResult()
  910. {
  911. if ($this->result === false) {
  912. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  913. 'resultset has already been freed', __FUNCTION__);
  914. } elseif (is_null($this->result)) {
  915. return false;
  916. }
  917. return @mssql_next_result($this->result);
  918. }
  919. // }}}
  920. // {{{ free()
  921. /**
  922. * Free the internal resources associated with $result.
  923. *
  924. * @return boolean true on success, false if $result is invalid
  925. * @access public
  926. */
  927. function free()
  928. {
  929. if (is_resource($this->result) && $this->db->connection) {
  930. $free = @mssql_free_result($this->result);
  931. if ($free === false) {
  932. return $this->db->raiseError(null, null, null,
  933. 'Could not free result', __FUNCTION__);
  934. }
  935. }
  936. $this->result = false;
  937. return MDB2_OK;
  938. }
  939. // }}}
  940. }
  941. // }}}
  942. // {{{ class MDB2_BufferedResult_mssql
  943. /**
  944. * MDB2 MSSQL Server buffered result driver
  945. *
  946. * @package MDB2
  947. * @category Database
  948. * @author Frank M. Kromann <frank@kromann.info>
  949. */
  950. class MDB2_BufferedResult_mssql extends MDB2_Result_mssql
  951. {
  952. // {{{ seek()
  953. /**
  954. * Seek to a specific row in a result set
  955. *
  956. * @param int $rownum number of the row where the data can be found
  957. * @return mixed MDB2_OK on success, a MDB2 error on failure
  958. * @access public
  959. */
  960. function seek($rownum = 0)
  961. {
  962. if ($this->rownum != ($rownum - 1) && !@mssql_data_seek($this->result, $rownum)) {
  963. if ($this->result === false) {
  964. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  965. 'resultset has already been freed', __FUNCTION__);
  966. } elseif (is_null($this->result)) {
  967. return MDB2_OK;
  968. }
  969. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  970. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  971. }
  972. $this->rownum = $rownum - 1;
  973. return MDB2_OK;
  974. }
  975. // }}}
  976. // {{{ valid()
  977. /**
  978. * Check if the end of the result set has been reached
  979. *
  980. * @return mixed true or false on sucess, a MDB2 error on failure
  981. * @access public
  982. */
  983. function valid()
  984. {
  985. $numrows = $this->numRows();
  986. if (PEAR::isError($numrows)) {
  987. return $numrows;
  988. }
  989. return $this->rownum < ($numrows - 1);
  990. }
  991. // }}}
  992. // {{{ numRows()
  993. /**
  994. * Returns the number of rows in a result object
  995. *
  996. * @return mixed MDB2 Error Object or the number of rows
  997. * @access public
  998. */
  999. function numRows()
  1000. {
  1001. $rows = @mssql_num_rows($this->result);
  1002. if (is_null($rows)) {
  1003. if ($this->result === false) {
  1004. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1005. 'resultset has already been freed', __FUNCTION__);
  1006. } elseif (is_null($this->result)) {
  1007. return 0;
  1008. }
  1009. return $this->db->raiseError(null, null, null,
  1010. 'Could not get row count', __FUNCTION__);
  1011. }
  1012. if ($this->limit) {
  1013. $rows -= $this->offset;
  1014. if ($rows > $this->limit) {
  1015. $rows = $this->limit;
  1016. }
  1017. if ($rows < 0) {
  1018. $rows = 0;
  1019. }
  1020. }
  1021. return $rows;
  1022. }
  1023. }
  1024. // }}}
  1025. // {{{ MDB2_Statement_mssql
  1026. /**
  1027. * MDB2 MSSQL Server statement driver
  1028. *
  1029. * @package MDB2
  1030. * @category Database
  1031. * @author Frank M. Kromann <frank@kromann.info>
  1032. */
  1033. class MDB2_Statement_mssql extends MDB2_Statement_Common
  1034. {
  1035. }
  1036. // }}}
  1037. ?>