PageRenderTime 66ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/pear/MDB2/Driver/ibase.php

https://bitbucket.org/Yason/hg-armory
PHP | 1534 lines | 948 code | 122 blank | 464 comment | 185 complexity | 8af3c485261b50d7e54f86fd90df252f MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  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, Lorenzo Alberton |
  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: Lorenzo Alberton <l.alberton@quipo.it> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: ibase.php,v 1.224 2009/01/14 15:00:02 quipo Exp $
  47. /**
  48. * MDB2 FireBird/InterBase driver
  49. *
  50. * @package MDB2
  51. * @category Database
  52. * @author Lorenzo Alberton <l.alberton@quipo.it>
  53. */
  54. class MDB2_Driver_ibase extends MDB2_Driver_Common
  55. {
  56. // {{{ properties
  57. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
  58. var $identifier_quoting = array('start' => '', 'end' => '', 'escape' => false);
  59. var $transaction_id = 0;
  60. var $query_parameters = array();
  61. var $query_parameter_values = array();
  62. // }}}
  63. // {{{ constructor
  64. /**
  65. * Constructor
  66. */
  67. function __construct()
  68. {
  69. parent::__construct();
  70. $this->phptype = 'ibase';
  71. $this->dbsyntax = 'ibase';
  72. $this->supported['sequences'] = true;
  73. $this->supported['indexes'] = true;
  74. $this->supported['affected_rows'] = function_exists('ibase_affected_rows');
  75. $this->supported['summary_functions'] = true;
  76. $this->supported['order_by_text'] = true;
  77. $this->supported['transactions'] = true;
  78. $this->supported['savepoints'] = true;
  79. $this->supported['current_id'] = true;
  80. $this->supported['limit_queries'] = 'emulated';
  81. $this->supported['LOBs'] = true;
  82. $this->supported['replace'] = false;
  83. $this->supported['sub_selects'] = true;
  84. $this->supported['triggers'] = true;
  85. $this->supported['auto_increment'] = true;
  86. $this->supported['primary_key'] = true;
  87. $this->supported['result_introspection'] = true;
  88. $this->supported['prepared_statements'] = true;
  89. $this->supported['identifier_quoting'] = false;
  90. $this->supported['pattern_escaping'] = true;
  91. $this->supported['new_link'] = false;
  92. $this->options['DBA_username'] = false;
  93. $this->options['DBA_password'] = false;
  94. $this->options['database_path'] = '';
  95. $this->options['database_extension'] = '.gdb';
  96. $this->options['server_version'] = '';
  97. $this->options['max_identifiers_length'] = 31;
  98. }
  99. // }}}
  100. // {{{ errorInfo()
  101. /**
  102. * This method is used to collect information about an error
  103. *
  104. * @param integer $error
  105. * @return array
  106. * @access public
  107. */
  108. function errorInfo($error = null)
  109. {
  110. $native_msg = @ibase_errmsg();
  111. if (function_exists('ibase_errcode')) {
  112. $native_code = @ibase_errcode();
  113. } else {
  114. // memo for the interbase php module hackers: we need something similar
  115. // to mysql_errno() to retrieve error codes instead of this ugly hack
  116. if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/', $native_msg, $m)) {
  117. $native_code = (int)$m[2];
  118. } else {
  119. $native_code = null;
  120. }
  121. }
  122. if (is_null($error)) {
  123. $error = MDB2_ERROR;
  124. if ($native_code) {
  125. // try to interpret Interbase error code (that's why we need ibase_errno()
  126. // in the interbase module to return the real error code)
  127. switch ($native_code) {
  128. case -204:
  129. if (isset($m[3]) && is_int(strpos($m[3], 'Table unknown'))) {
  130. $errno = MDB2_ERROR_NOSUCHTABLE;
  131. }
  132. break;
  133. default:
  134. static $ecode_map;
  135. if (empty($ecode_map)) {
  136. $ecode_map = array(
  137. -104 => MDB2_ERROR_SYNTAX,
  138. -150 => MDB2_ERROR_ACCESS_VIOLATION,
  139. -151 => MDB2_ERROR_ACCESS_VIOLATION,
  140. -155 => MDB2_ERROR_NOSUCHTABLE,
  141. -157 => MDB2_ERROR_NOSUCHFIELD,
  142. -158 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  143. -170 => MDB2_ERROR_MISMATCH,
  144. -171 => MDB2_ERROR_MISMATCH,
  145. -172 => MDB2_ERROR_INVALID,
  146. // -204 => // Covers too many errors, need to use regex on msg
  147. -205 => MDB2_ERROR_NOSUCHFIELD,
  148. -206 => MDB2_ERROR_NOSUCHFIELD,
  149. -208 => MDB2_ERROR_INVALID,
  150. -219 => MDB2_ERROR_NOSUCHTABLE,
  151. -297 => MDB2_ERROR_CONSTRAINT,
  152. -303 => MDB2_ERROR_INVALID,
  153. -413 => MDB2_ERROR_INVALID_NUMBER,
  154. -530 => MDB2_ERROR_CONSTRAINT,
  155. -551 => MDB2_ERROR_ACCESS_VIOLATION,
  156. -552 => MDB2_ERROR_ACCESS_VIOLATION,
  157. // -607 => // Covers too many errors, need to use regex on msg
  158. -625 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  159. -803 => MDB2_ERROR_CONSTRAINT,
  160. -804 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  161. // -902 => // Covers too many errors, need to use regex on msg
  162. -904 => MDB2_ERROR_CONNECT_FAILED,
  163. -922 => MDB2_ERROR_NOSUCHDB,
  164. -923 => MDB2_ERROR_CONNECT_FAILED,
  165. -924 => MDB2_ERROR_CONNECT_FAILED
  166. );
  167. }
  168. if (isset($ecode_map[$native_code])) {
  169. $error = $ecode_map[$native_code];
  170. }
  171. break;
  172. }
  173. } else {
  174. static $error_regexps;
  175. if (!isset($error_regexps)) {
  176. $error_regexps = array(
  177. '/generator .* is not defined/'
  178. => MDB2_ERROR_SYNTAX, // for compat. w ibase_errcode()
  179. '/table.*(not exist|not found|unknown)/i'
  180. => MDB2_ERROR_NOSUCHTABLE,
  181. '/table .* already exists/i'
  182. => MDB2_ERROR_ALREADY_EXISTS,
  183. '/unsuccessful metadata update .* failed attempt to store duplicate value/i'
  184. => MDB2_ERROR_ALREADY_EXISTS,
  185. '/unsuccessful metadata update .* not found/i'
  186. => MDB2_ERROR_NOT_FOUND,
  187. '/validation error for column .* value "\*\*\* null/i'
  188. => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  189. '/violation of [\w ]+ constraint/i'
  190. => MDB2_ERROR_CONSTRAINT,
  191. '/conversion error from string/i'
  192. => MDB2_ERROR_INVALID_NUMBER,
  193. '/no permission for/i'
  194. => MDB2_ERROR_ACCESS_VIOLATION,
  195. '/arithmetic exception, numeric overflow, or string truncation/i'
  196. => MDB2_ERROR_INVALID,
  197. '/feature is not supported/i'
  198. => MDB2_ERROR_NOT_CAPABLE,
  199. );
  200. }
  201. foreach ($error_regexps as $regexp => $code) {
  202. if (preg_match($regexp, $native_msg, $m)) {
  203. $error = $code;
  204. break;
  205. }
  206. }
  207. }
  208. }
  209. return array($error, $native_code, $native_msg);
  210. }
  211. // }}}
  212. // {{{ quoteIdentifier()
  213. /**
  214. * Delimited identifiers are a nightmare with InterBase, so they're disabled
  215. *
  216. * @param string $str identifier name to be quoted
  217. * @param bool $check_option check the 'quote_identifier' option
  218. *
  219. * @return string quoted identifier string
  220. *
  221. * @access public
  222. */
  223. function quoteIdentifier($str, $check_option = false)
  224. {
  225. if ($check_option && !$this->options['quote_identifier']) {
  226. return $str;
  227. }
  228. return strtoupper($str);
  229. }
  230. // }}}
  231. // {{{ getConnection()
  232. /**
  233. * Returns a native connection
  234. *
  235. * @return mixed a valid MDB2 connection object,
  236. * or a MDB2 error object on error
  237. * @access public
  238. */
  239. function getConnection()
  240. {
  241. $result = $this->connect();
  242. if (PEAR::isError($result)) {
  243. return $result;
  244. }
  245. if ($this->in_transaction) {
  246. return $this->transaction_id;
  247. }
  248. return $this->connection;
  249. }
  250. // }}}
  251. // {{{ beginTransaction()
  252. /**
  253. * Start a transaction or set a savepoint.
  254. *
  255. * @param string name of a savepoint to set
  256. * @return mixed MDB2_OK on success, a MDB2 error on failure
  257. *
  258. * @access public
  259. */
  260. function beginTransaction($savepoint = null)
  261. {
  262. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  263. if (!is_null($savepoint)) {
  264. if (!$this->in_transaction) {
  265. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  266. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  267. }
  268. $query = 'SAVEPOINT '.$savepoint;
  269. return $this->_doQuery($query, true);
  270. } elseif ($this->in_transaction) {
  271. return MDB2_OK; //nothing to do
  272. }
  273. $connection = $this->getConnection();
  274. if (PEAR::isError($connection)) {
  275. return $connection;
  276. }
  277. $result = @ibase_trans(IBASE_DEFAULT, $connection);
  278. if (!$result) {
  279. return $this->raiseError(null, null, null,
  280. 'could not start a transaction', __FUNCTION__);
  281. }
  282. $this->transaction_id = $result;
  283. $this->in_transaction = true;
  284. return MDB2_OK;
  285. }
  286. // }}}
  287. // {{{ commit()
  288. /**
  289. * Commit the database changes done during a transaction that is in
  290. * progress or release a savepoint. This function may only be called when
  291. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  292. * transaction is implicitly started after committing the pending changes.
  293. *
  294. * @param string name of a savepoint to release
  295. * @return mixed MDB2_OK on success, a MDB2 error on failure
  296. *
  297. * @access public
  298. */
  299. function commit($savepoint = null)
  300. {
  301. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  302. if (!$this->in_transaction) {
  303. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  304. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  305. }
  306. if (!is_null($savepoint)) {
  307. $query = 'RELEASE SAVEPOINT '.$savepoint;
  308. return $this->_doQuery($query, true);
  309. }
  310. if (!@ibase_commit($this->transaction_id)) {
  311. return $this->raiseError(null, null, null,
  312. 'could not commit a transaction', __FUNCTION__);
  313. }
  314. $this->in_transaction = false;
  315. $this->transaction_id = 0;
  316. return MDB2_OK;
  317. }
  318. // }}}
  319. // {{{ rollback()
  320. /**
  321. * Cancel any database changes done during a transaction or since a specific
  322. * savepoint that is in progress. This function may only be called when
  323. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  324. * transaction is implicitly started after canceling the pending changes.
  325. *
  326. * @param string name of a savepoint to rollback to
  327. * @return mixed MDB2_OK on success, a MDB2 error on failure
  328. *
  329. * @access public
  330. */
  331. function rollback($savepoint = null)
  332. {
  333. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  334. if (!$this->in_transaction) {
  335. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  336. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  337. }
  338. if (!is_null($savepoint)) {
  339. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  340. return $this->_doQuery($query, true);
  341. }
  342. if ($this->transaction_id && !@ibase_rollback($this->transaction_id)) {
  343. return $this->raiseError(null, null, null,
  344. 'Could not rollback a pending transaction: '.@ibase_errmsg(), __FUNCTION__);
  345. }
  346. $this->in_transaction = false;
  347. $this->transaction_id = 0;
  348. return MDB2_OK;
  349. }
  350. // }}}
  351. // {{{ setTransactionIsolation()
  352. /**
  353. * Set the transacton isolation level.
  354. *
  355. * @param string standard isolation level (SQL-92)
  356. * READ UNCOMMITTED (allows dirty reads)
  357. * READ COMMITTED (prevents dirty reads)
  358. * REPEATABLE READ (prevents nonrepeatable reads)
  359. * SERIALIZABLE (prevents phantom reads)
  360. * @param array some transaction options:
  361. * 'wait' => 'WAIT' | 'NO WAIT'
  362. * 'rw' => 'READ WRITE' | 'READ ONLY'
  363. * @return mixed MDB2_OK on success, a MDB2 error on failure
  364. *
  365. * @access public
  366. * @since 2.1.1
  367. */
  368. function setTransactionIsolation($isolation, $options = array())
  369. {
  370. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  371. switch ($isolation) {
  372. case 'READ UNCOMMITTED':
  373. $ibase_isolation = 'READ COMMITTED RECORD_VERSION';
  374. break;
  375. case 'READ COMMITTED':
  376. $ibase_isolation = 'READ COMMITTED NO RECORD_VERSION';
  377. break;
  378. case 'REPEATABLE READ':
  379. $ibase_isolation = 'SNAPSHOT';
  380. break;
  381. case 'SERIALIZABLE':
  382. $ibase_isolation = 'SNAPSHOT TABLE STABILITY';
  383. break;
  384. default:
  385. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  386. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  387. }
  388. if (!empty($options['wait'])) {
  389. switch ($options['wait']) {
  390. case 'WAIT':
  391. case 'NO WAIT':
  392. $wait = $options['wait'];
  393. break;
  394. default:
  395. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  396. 'wait option is not supported: '.$options['wait'], __FUNCTION__);
  397. }
  398. }
  399. if (!empty($options['rw'])) {
  400. switch ($options['rw']) {
  401. case 'READ ONLY':
  402. case 'READ WRITE':
  403. $rw = $options['wait'];
  404. break;
  405. default:
  406. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  407. 'wait option is not supported: '.$options['rw'], __FUNCTION__);
  408. }
  409. }
  410. $query = "SET TRANSACTION $rw $wait ISOLATION LEVEL $ibase_isolation";
  411. return $this->_doQuery($query, true);
  412. }
  413. // }}}
  414. // {{{ getDatabaseFile($database_name)
  415. /**
  416. * Builds the string with path+dbname+extension
  417. *
  418. * @return string full database path+file
  419. * @access protected
  420. */
  421. function _getDatabaseFile($database_name)
  422. {
  423. if ($database_name == '') {
  424. return $database_name;
  425. }
  426. $ret = $this->options['database_path'] . $database_name;
  427. if (!preg_match('/\.[fg]db$/i', $database_name)) {
  428. $ret .= $this->options['database_extension'];
  429. }
  430. return $ret;
  431. }
  432. // }}}
  433. // {{{ _doConnect()
  434. /**
  435. * Does the grunt work of connecting to the database
  436. *
  437. * @return mixed connection resource on success, MDB2 Error Object on failure
  438. * @access protected
  439. */
  440. function _doConnect($username, $password, $database_name, $persistent = false)
  441. {
  442. if (!PEAR::loadExtension('interbase')) {
  443. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  444. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  445. }
  446. $database_file = $this->_getDatabaseFile($database_name);
  447. $dbhost = $this->dsn['hostspec'] ?
  448. ($this->dsn['hostspec'].':'.$database_file) : $database_file;
  449. $params = array();
  450. $params[] = $dbhost;
  451. $params[] = !empty($username) ? $username : null;
  452. $params[] = !empty($password) ? $password : null;
  453. $params[] = isset($this->dsn['charset']) ? $this->dsn['charset'] : null;
  454. $params[] = isset($this->dsn['buffers']) ? $this->dsn['buffers'] : null;
  455. $params[] = isset($this->dsn['dialect']) ? $this->dsn['dialect'] : null;
  456. $params[] = isset($this->dsn['role']) ? $this->dsn['role'] : null;
  457. $connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect';
  458. $connection = @call_user_func_array($connect_function, $params);
  459. if ($connection <= 0) {
  460. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  461. 'unable to establish a connection', __FUNCTION__);
  462. }
  463. if (empty($this->dsn['disable_iso_date'])) {
  464. if (function_exists('ibase_timefmt')) {
  465. @ibase_timefmt("%Y-%m-%d %H:%M:%S", IBASE_TIMESTAMP);
  466. @ibase_timefmt("%Y-%m-%d", IBASE_DATE);
  467. } else {
  468. @ini_set("ibase.timestampformat", "%Y-%m-%d %H:%M:%S");
  469. //@ini_set("ibase.timeformat", "%H:%M:%S");
  470. @ini_set("ibase.dateformat", "%Y-%m-%d");
  471. }
  472. }
  473. return $connection;
  474. }
  475. // }}}
  476. // {{{ connect()
  477. /**
  478. * Connect to the database
  479. *
  480. * @return true on success, MDB2 Error Object on failure
  481. * @access public
  482. */
  483. function connect()
  484. {
  485. $database_file = $this->_getDatabaseFile($this->database_name);
  486. if (is_resource($this->connection)) {
  487. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  488. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  489. && $this->connected_database_name == $database_file
  490. && $this->opened_persistent == $this->options['persistent']
  491. ) {
  492. return MDB2_OK;
  493. }
  494. $this->disconnect(false);
  495. }
  496. if (empty($this->database_name)) {
  497. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  498. 'unable to establish a connection', __FUNCTION__);
  499. }
  500. $connection = $this->_doConnect($this->dsn['username'],
  501. $this->dsn['password'],
  502. $this->database_name,
  503. $this->options['persistent']);
  504. if (PEAR::isError($connection)) {
  505. return $connection;
  506. }
  507. $this->connection =& $connection;
  508. $this->connected_dsn = $this->dsn;
  509. $this->connected_database_name = $database_file;
  510. $this->opened_persistent = $this->options['persistent'];
  511. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  512. $this->supported['limit_queries'] = ($this->dbsyntax == 'firebird') ? true : 'emulated';
  513. return MDB2_OK;
  514. }
  515. // }}}
  516. // {{{ databaseExists()
  517. /**
  518. * check if given database name is exists?
  519. *
  520. * @param string $name name of the database that should be checked
  521. *
  522. * @return mixed true/false on success, a MDB2 error on failure
  523. * @access public
  524. */
  525. function databaseExists($name)
  526. {
  527. $database_file = $this->_getDatabaseFile($name);
  528. $result = file_exists($database_file);
  529. return $result;
  530. }
  531. // }}}
  532. // {{{ disconnect()
  533. /**
  534. * Log out and disconnect from the database.
  535. *
  536. * @param boolean $force if the disconnect should be forced even if the
  537. * connection is opened persistently
  538. * @return mixed true on success, false if not connected and error
  539. * object on error
  540. * @access public
  541. */
  542. function disconnect($force = true)
  543. {
  544. if (is_resource($this->connection)) {
  545. if ($this->in_transaction) {
  546. $dsn = $this->dsn;
  547. $database_name = $this->database_name;
  548. $persistent = $this->options['persistent'];
  549. $this->dsn = $this->connected_dsn;
  550. $this->database_name = $this->connected_database_name;
  551. $this->options['persistent'] = $this->opened_persistent;
  552. $this->rollback();
  553. $this->dsn = $dsn;
  554. $this->database_name = $database_name;
  555. $this->options['persistent'] = $persistent;
  556. }
  557. if (!$this->opened_persistent || $force) {
  558. $ok = @ibase_close($this->connection);
  559. if (!$ok) {
  560. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  561. null, null, null, __FUNCTION__);
  562. }
  563. }
  564. } else {
  565. return false;
  566. }
  567. return parent::disconnect($force);
  568. }
  569. // }}}
  570. // {{{ standaloneQuery()
  571. /**
  572. * execute a query as DBA
  573. *
  574. * @param string $query the SQL query
  575. * @param mixed $types array that contains the types of the columns in
  576. * the result set
  577. * @param boolean $is_manip if the query is a manipulation query
  578. * @return mixed MDB2_OK on success, a MDB2 error on failure
  579. * @access public
  580. */
  581. function &standaloneQuery($query, $types = null, $is_manip = false)
  582. {
  583. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  584. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  585. $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
  586. if (PEAR::isError($connection)) {
  587. return $connection;
  588. }
  589. $offset = $this->offset;
  590. $limit = $this->limit;
  591. $this->offset = $this->limit = 0;
  592. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  593. $result =& $this->_doQuery($query, $is_manip, $connection);
  594. if (!PEAR::isError($result)) {
  595. $result = $this->_affectedRows($connection, $result);
  596. }
  597. @mysql_close($connection);
  598. return $result;
  599. }
  600. // }}}
  601. // {{{ _doQuery()
  602. /**
  603. * Execute a query
  604. * @param string $query query
  605. * @param boolean $is_manip if the query is a manipulation query
  606. * @param resource $connection
  607. * @param string $database_name
  608. * @return result or error object
  609. * @access protected
  610. */
  611. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  612. {
  613. $this->last_query = $query;
  614. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  615. if ($result) {
  616. if (PEAR::isError($result)) {
  617. return $result;
  618. }
  619. $query = $result;
  620. }
  621. if ($this->getOption('disable_query')) {
  622. if ($is_manip) {
  623. return 0;
  624. }
  625. return null;
  626. }
  627. if (is_null($connection)) {
  628. $connection = $this->getConnection();
  629. if (PEAR::isError($connection)) {
  630. return $connection;
  631. }
  632. }
  633. $result = @ibase_query($connection, $query);
  634. if ($result === false) {
  635. $err =& $this->raiseError(null, null, null,
  636. 'Could not execute statement', __FUNCTION__);
  637. return $err;
  638. }
  639. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  640. return $result;
  641. }
  642. // }}}
  643. // {{{ _affectedRows()
  644. /**
  645. * Returns the number of rows affected
  646. *
  647. * @param resource $result
  648. * @param resource $connection
  649. * @return mixed MDB2 Error Object or the number of rows affected
  650. * @access private
  651. */
  652. function _affectedRows($connection, $result = null)
  653. {
  654. if (is_null($connection)) {
  655. $connection = $this->getConnection();
  656. if (PEAR::isError($connection)) {
  657. return $connection;
  658. }
  659. }
  660. return (function_exists('ibase_affected_rows') ? @ibase_affected_rows($connection) : 0);
  661. }
  662. // }}}
  663. // {{{ _modifyQuery()
  664. /**
  665. * Changes a query string for various DBMS specific reasons
  666. *
  667. * @param string $query query to modify
  668. * @param boolean $is_manip if it is a DML query
  669. * @param integer $limit limit the number of rows
  670. * @param integer $offset start reading from given offset
  671. * @return string modified query
  672. * @access protected
  673. */
  674. function _modifyQuery($query, $is_manip, $limit, $offset)
  675. {
  676. if ($limit > 0 && $this->supports('limit_queries') === true) {
  677. $query = preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i',
  678. "SELECT FIRST $limit SKIP $offset", $query);
  679. }
  680. return $query;
  681. }
  682. // }}}
  683. // {{{ getServerVersion()
  684. /**
  685. * return version information about the server
  686. *
  687. * @param bool $native determines if the raw version string should be returned
  688. * @return mixed array/string with version information or MDB2 error object
  689. * @access public
  690. */
  691. function getServerVersion($native = false)
  692. {
  693. $server_info = false;
  694. if ($this->connected_server_info) {
  695. $server_info = $this->connected_server_info;
  696. } elseif ($this->options['server_version']) {
  697. $server_info = $this->options['server_version'];
  698. } else {
  699. $username = $this->options['DBA_username'] ? $this->options['DBA_username'] : $this->dsn['username'];
  700. $password = $this->options['DBA_password'] ? $this->options['DBA_password'] : $this->dsn['password'];
  701. $ibserv = @ibase_service_attach($this->dsn['hostspec'], $username, $password);
  702. $server_info = @ibase_server_info($ibserv, IBASE_SVC_SERVER_VERSION);
  703. @ibase_service_detach($ibserv);
  704. }
  705. if (!$server_info) {
  706. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  707. 'Requires either "server_version" or "DBA_username"/"DBA_password" option', __FUNCTION__);
  708. }
  709. // cache server_info
  710. $this->connected_server_info = $server_info;
  711. if (!$native) {
  712. //WI-V1.5.3.4854 Firebird 1.5
  713. //WI-T2.1.0.16780 Firebird 2.1 Beta 2
  714. if (!preg_match('/-[VT]([\d\.]*)/', $server_info, $matches)) {
  715. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  716. 'Could not parse version information:'.$server_info, __FUNCTION__);
  717. }
  718. $tmp = explode('.', $matches[1], 4);
  719. $server_info = array(
  720. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  721. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  722. 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  723. 'extra' => isset($tmp[3]) ? $tmp[3] : null,
  724. 'native' => $server_info,
  725. );
  726. }
  727. return $server_info;
  728. }
  729. // }}}
  730. // {{{ prepare()
  731. /**
  732. * Prepares a query for multiple execution with execute().
  733. * With some database backends, this is emulated.
  734. * prepare() requires a generic query as string like
  735. * 'INSERT INTO numbers VALUES(?,?)' or
  736. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  737. * The ? and :name and are placeholders which can be set using
  738. * bindParam() and the query can be sent off using the execute() method.
  739. * The allowed format for :name can be set with the 'bindname_format' option.
  740. *
  741. * @param string $query the query to prepare
  742. * @param mixed $types array that contains the types of the placeholders
  743. * @param mixed $result_types array that contains the types of the columns in
  744. * the result set or MDB2_PREPARE_RESULT, if set to
  745. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  746. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  747. * @return mixed resource handle for the prepared query on success, a MDB2
  748. * error on failure
  749. * @access public
  750. * @see bindParam, execute
  751. */
  752. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  753. {
  754. if ($this->options['emulate_prepared']) {
  755. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  756. return $obj;
  757. }
  758. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  759. $offset = $this->offset;
  760. $limit = $this->limit;
  761. $this->offset = $this->limit = 0;
  762. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  763. if ($result) {
  764. if (PEAR::isError($result)) {
  765. return $result;
  766. }
  767. $query = $result;
  768. }
  769. $placeholder_type_guess = $placeholder_type = null;
  770. $question = '?';
  771. $colon = ':';
  772. $positions = array();
  773. $position = 0;
  774. while ($position < strlen($query)) {
  775. $q_position = strpos($query, $question, $position);
  776. $c_position = strpos($query, $colon, $position);
  777. if ($q_position && $c_position) {
  778. $p_position = min($q_position, $c_position);
  779. } elseif ($q_position) {
  780. $p_position = $q_position;
  781. } elseif ($c_position) {
  782. $p_position = $c_position;
  783. } else {
  784. break;
  785. }
  786. if (is_null($placeholder_type)) {
  787. $placeholder_type_guess = $query[$p_position];
  788. }
  789. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  790. if (PEAR::isError($new_pos)) {
  791. return $new_pos;
  792. }
  793. if ($new_pos != $position) {
  794. $position = $new_pos;
  795. continue; //evaluate again starting from the new position
  796. }
  797. if ($query[$position] == $placeholder_type_guess) {
  798. if (is_null($placeholder_type)) {
  799. $placeholder_type = $query[$p_position];
  800. $question = $colon = $placeholder_type;
  801. }
  802. if ($placeholder_type == ':') {
  803. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  804. $parameter = preg_replace($regexp, '\\1', $query);
  805. if ($parameter === '') {
  806. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  807. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  808. return $err;
  809. }
  810. $positions[] = $parameter;
  811. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  812. } else {
  813. $positions[] = count($positions);
  814. }
  815. $position = $p_position + 1;
  816. } else {
  817. $position = $p_position;
  818. }
  819. }
  820. $connection = $this->getConnection();
  821. if (PEAR::isError($connection)) {
  822. return $connection;
  823. }
  824. $statement = @ibase_prepare($connection, $query);
  825. if (!$statement) {
  826. $err =& $this->raiseError(null, null, null,
  827. 'Could not create statement', __FUNCTION__);
  828. return $err;
  829. }
  830. $class_name = 'MDB2_Statement_'.$this->phptype;
  831. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  832. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  833. return $obj;
  834. }
  835. // }}}
  836. // {{{ getSequenceName()
  837. /**
  838. * adds sequence name formatting to a sequence name
  839. *
  840. * @param string $sqn name of the sequence
  841. * @return string formatted sequence name
  842. * @access public
  843. */
  844. function getSequenceName($sqn)
  845. {
  846. return strtoupper(parent::getSequenceName($sqn));
  847. }
  848. // }}}
  849. // {{{ nextID()
  850. /**
  851. * Returns the next free id of a sequence
  852. *
  853. * @param string $seq_name name of the sequence
  854. * @param boolean $ondemand when true the sequence is
  855. * automatic created, if it
  856. * not exists
  857. * @return mixed MDB2 Error Object or id
  858. * @access public
  859. */
  860. function nextID($seq_name, $ondemand = true)
  861. {
  862. $sequence_name = $this->getSequenceName($seq_name);
  863. $query = 'SELECT GEN_ID('.$sequence_name.', 1) as the_value FROM RDB$DATABASE';
  864. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  865. $this->expectError('*');
  866. $result = $this->queryOne($query, 'integer');
  867. $this->popExpect();
  868. $this->popErrorHandling();
  869. if (PEAR::isError($result)) {
  870. if ($ondemand) {
  871. $this->loadModule('Manager', null, true);
  872. $result = $this->manager->createSequence($seq_name);
  873. if (PEAR::isError($result)) {
  874. return $this->raiseError($result, null, null,
  875. 'on demand sequence could not be created', __FUNCTION__);
  876. } else {
  877. return $this->nextID($seq_name, false);
  878. }
  879. }
  880. }
  881. return $result;
  882. }
  883. // }}}
  884. // {{{ lastInsertID()
  885. /**
  886. * Returns the autoincrement ID if supported or $id or fetches the current
  887. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  888. *
  889. * @param string $table name of the table into which a new row was inserted
  890. * @param string $field name of the field into which a new row was inserted
  891. * @return mixed MDB2 Error Object or id
  892. * @access public
  893. */
  894. function lastInsertID($table = null, $field = null)
  895. {
  896. $seq = $table.(empty($field) ? '' : '_'.$field);
  897. return $this->currID($seq);
  898. }
  899. // }}}
  900. // {{{ currID()
  901. /**
  902. * Returns the current id of a sequence
  903. *
  904. * @param string $seq_name name of the sequence
  905. * @return mixed MDB2 Error Object or id
  906. * @access public
  907. */
  908. function currID($seq_name)
  909. {
  910. $sequence_name = $this->getSequenceName($seq_name);
  911. $query = 'SELECT GEN_ID('.$sequence_name.', 0) as the_value FROM RDB$DATABASE';
  912. $value = $this->queryOne($query);
  913. if (PEAR::isError($value)) {
  914. return $this->raiseError($value, null, null,
  915. 'Unable to select from ' . $seq_name, __FUNCTION__);
  916. }
  917. if (!is_numeric($value)) {
  918. return $this->raiseError(MDB2_ERROR, null, null,
  919. 'could not find value in sequence table', __FUNCTION__);
  920. }
  921. return $value;
  922. }
  923. // }}}
  924. }
  925. /**
  926. * MDB2 FireBird/InterBase result driver
  927. *
  928. * @package MDB2
  929. * @category Database
  930. * @author Lorenzo Alberton <l.alberton@quipo.it>
  931. */
  932. class MDB2_Result_ibase extends MDB2_Result_Common
  933. {
  934. // {{{ _skipLimitOffset()
  935. /**
  936. * Skip the first row of a result set.
  937. *
  938. * @param resource $result
  939. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  940. * @access protected
  941. */
  942. function _skipLimitOffset()
  943. {
  944. if ($this->db->supports('limit_queries') === true) {
  945. return true;
  946. }
  947. if ($this->limit) {
  948. if ($this->rownum > $this->limit) {
  949. return false;
  950. }
  951. }
  952. if ($this->offset) {
  953. while ($this->offset_count < $this->offset) {
  954. ++$this->offset_count;
  955. if (!is_array(@ibase_fetch_row($this->result))) {
  956. $this->offset_count = $this->offset;
  957. return false;
  958. }
  959. }
  960. }
  961. return true;
  962. }
  963. // }}}
  964. // {{{ fetchRow()
  965. /**
  966. * Fetch a row and insert the data into an existing array.
  967. *
  968. * @param int $fetchmode how the array data should be indexed
  969. * @param int $rownum number of the row where the data can be found
  970. * @return int data array on success, a MDB2 error on failure
  971. * @access public
  972. */
  973. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  974. {
  975. if ($this->result === true) {
  976. //query successfully executed, but without results...
  977. $null = null;
  978. return $null;
  979. }
  980. if (!$this->_skipLimitOffset()) {
  981. $null = null;
  982. return $null;
  983. }
  984. if (!is_null($rownum)) {
  985. $seek = $this->seek($rownum);
  986. if (PEAR::isError($seek)) {
  987. return $seek;
  988. }
  989. }
  990. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  991. $fetchmode = $this->db->fetchmode;
  992. }
  993. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  994. $row = @ibase_fetch_assoc($this->result);
  995. if (is_array($row)
  996. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  997. ) {
  998. $row = array_change_key_case($row, $this->db->options['field_case']);
  999. }
  1000. } else {
  1001. $row = @ibase_fetch_row($this->result);
  1002. }
  1003. if (!$row) {
  1004. if ($this->result === false) {
  1005. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1006. 'resultset has already been freed', __FUNCTION__);
  1007. return $err;
  1008. }
  1009. $null = null;
  1010. return $null;
  1011. }
  1012. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1013. $rtrim = false;
  1014. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1015. if (empty($this->types)) {
  1016. $mode += MDB2_PORTABILITY_RTRIM;
  1017. } else {
  1018. $rtrim = true;
  1019. }
  1020. }
  1021. if ($mode) {
  1022. $this->db->_fixResultArrayValues($row, $mode);
  1023. }
  1024. if (!empty($this->types)) {
  1025. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1026. }
  1027. if (!empty($this->values)) {
  1028. $this->_assignBindColumns($row);
  1029. }
  1030. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1031. $object_class = $this->db->options['fetch_class'];
  1032. if ($object_class == 'stdClass') {
  1033. $row = (object) $row;
  1034. } else {
  1035. $row = &new $object_class($row);
  1036. }
  1037. }
  1038. ++$this->rownum;
  1039. return $row;
  1040. }
  1041. // }}}
  1042. // {{{ _getColumnNames()
  1043. /**
  1044. * Retrieve the names of columns returned by the DBMS in a query result.
  1045. *
  1046. * @return mixed Array variable that holds the names of columns as keys
  1047. * or an MDB2 error on failure.
  1048. * Some DBMS may not return any columns when the result set
  1049. * does not contain any rows.
  1050. * @access private
  1051. */
  1052. function _getColumnNames()
  1053. {
  1054. $columns = array();
  1055. $numcols = $this->numCols();
  1056. if (PEAR::isError($numcols)) {
  1057. return $numcols;
  1058. }
  1059. for ($column = 0; $column < $numcols; $column++) {
  1060. $column_info = @ibase_field_info($this->result, $column);
  1061. $columns[$column_info['alias']] = $column;
  1062. }
  1063. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1064. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1065. }
  1066. return $columns;
  1067. }
  1068. // }}}
  1069. // {{{ numCols()
  1070. /**
  1071. * Count the number of columns returned by the DBMS in a query result.
  1072. *
  1073. * @return mixed integer value with the number of columns, a MDB2 error
  1074. * on failure
  1075. * @access public
  1076. */
  1077. function numCols()
  1078. {
  1079. if ($this->result === true) {
  1080. //query successfully executed, but without results...
  1081. return 0;
  1082. }
  1083. if (!is_resource($this->result)) {
  1084. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1085. 'numCols(): not a valid ibase resource', __FUNCTION__);
  1086. }
  1087. $cols = @ibase_num_fields($this->result);
  1088. if (is_null($cols)) {
  1089. if ($this->result === false) {
  1090. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1091. 'resultset has already been freed', __FUNCTION__);
  1092. } elseif (is_null($this->result)) {
  1093. return count($this->types);
  1094. }
  1095. return $this->db->raiseError(null, null, null,
  1096. 'Could not get column count', __FUNCTION__);
  1097. }
  1098. return $cols;
  1099. }
  1100. // }}}
  1101. // {{{ free()
  1102. /**
  1103. * Free the internal resources associated with $result.
  1104. *
  1105. * @return boolean true on success, false if $result is invalid
  1106. * @access public
  1107. */
  1108. function free()
  1109. {
  1110. if (is_resource($this->result) && $this->db->connection) {
  1111. $free = @ibase_free_result($this->result);
  1112. if ($free === false) {
  1113. return $this->db->raiseError(null, null, null,
  1114. 'Could not free result', __FUNCTION__);
  1115. }
  1116. }
  1117. $this->result = false;
  1118. return MDB2_OK;
  1119. }
  1120. // }}}
  1121. }
  1122. /**
  1123. * MDB2 FireBird/InterBase buffered result driver
  1124. *
  1125. * @package MDB2
  1126. * @category Database
  1127. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1128. */
  1129. class MDB2_BufferedResult_ibase extends MDB2_Result_ibase
  1130. {
  1131. // {{{ class vars
  1132. var $buffer;
  1133. var $buffer_rownum = - 1;
  1134. // }}}
  1135. // {{{ _fillBuffer()
  1136. /**
  1137. * Fill the row buffer
  1138. *
  1139. * @param int $rownum row number upto which the buffer should be filled
  1140. * if the row number is null all rows are ready into the buffer
  1141. * @return boolean true on success, false on failure
  1142. * @access protected
  1143. */
  1144. function _fillBuffer($rownum = null)
  1145. {
  1146. if (isset($this->buffer) && is_array($this->buffer)) {
  1147. if (is_null($rownum)) {
  1148. if (!end($this->buffer)) {
  1149. return false;
  1150. }
  1151. } elseif (isset($this->buffer[$rownum])) {
  1152. return (bool) $this->buffer[$rownum];
  1153. }
  1154. }
  1155. if (!$this->_skipLimitOffset()) {
  1156. return false;
  1157. }
  1158. $buffer = true;
  1159. while ((is_null($rownum) || $this->buffer_rownum < $rownum)
  1160. && (!$this->limit || $this->buffer_rownum < $this->limit)
  1161. && ($buffer = @ibase_fetch_row($this->result))
  1162. ) {
  1163. ++$this->buffer_rownum;
  1164. $this->buffer[$this->buffer_rownum] = $buffer;
  1165. }
  1166. if (!$buffer) {
  1167. ++$this->buffer_rownum;
  1168. $this->buffer[$this->buffer_rownum] = false;
  1169. return false;
  1170. } elseif ($this->limit && $this->buffer_rownum >= $this->limit) {
  1171. ++$this->buffer_rownum;
  1172. $this->buffer[$this->buffer_rownum] = false;
  1173. }
  1174. return true;
  1175. }
  1176. // }}}
  1177. // {{{ fetchRow()
  1178. /**
  1179. * Fetch a row and insert the data into an existing array.
  1180. *
  1181. * @param int $fetchmode how the array data should be indexed
  1182. * @param int $rownum number of the row where the data can be found
  1183. * @return int data array on success, a MDB2 error on failure
  1184. * @access public
  1185. */
  1186. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1187. {
  1188. if ($this->result === true || is_null($this->result)) {
  1189. //query successfully executed, but without results...
  1190. $null = null;
  1191. return $null;
  1192. }
  1193. if ($this->result === false) {
  1194. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1195. 'resultset has already been freed', __FUNCTION__);
  1196. return $err;
  1197. }
  1198. if (!is_null($rownum)) {
  1199. $seek = $this->seek($rownum);
  1200. if (PEAR::isError($seek)) {
  1201. return $seek;
  1202. }
  1203. }
  1204. $target_rownum = $this->rownum + 1;
  1205. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1206. $fetchmode = $this->db->fetchmode;
  1207. }
  1208. if (!$this->_fillBuffer($target_rownum)) {
  1209. $null = null;
  1210. return $null;
  1211. }
  1212. $row = $this->buffer[$target_rownum];
  1213. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1214. $column_names = $this->getColumnNames();
  1215. foreach ($column_names as $name => $i) {
  1216. $column_names[$name] = $row[$i];

Large files files are truncated, but you can click here to view the full file