PageRenderTime 60ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

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

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