ibase.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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$
  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'] = true;
  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 (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. // {{{ escape()
  212. /**
  213. * Quotes a string so it can be safely used in a query. It will quote
  214. * the text so it can safely be used within a query.
  215. *
  216. * @param string the input string to quote
  217. * @param bool escape wildcards
  218. *
  219. * @return string quoted string
  220. *
  221. * @access public
  222. */
  223. function escape($text, $escape_wildcards = false)
  224. {
  225. //Remove a NULL-character (may break queries when inserted):
  226. $text = str_replace("\x00", '', $text);
  227. return parent::escape($text, $escape_wildcards);
  228. }
  229. // }}}
  230. // }}}
  231. // {{{ quoteIdentifier()
  232. /**
  233. * Delimited identifiers are a nightmare with InterBase, so they're disabled
  234. *
  235. * @param string $str identifier name to be quoted
  236. * @param bool $check_option check the 'quote_identifier' option
  237. *
  238. * @return string quoted identifier string
  239. *
  240. * @access public
  241. */
  242. function quoteIdentifier($str, $check_option = false)
  243. {
  244. if ($check_option && !$this->options['quote_identifier']) {
  245. return $str;
  246. }
  247. return parent::quoteIdentifier(strtoupper($str), $check_option);
  248. }
  249. // }}}
  250. // {{{ getConnection()
  251. /**
  252. * Returns a native connection
  253. *
  254. * @return mixed a valid MDB2 connection object,
  255. * or a MDB2 error object on error
  256. * @access public
  257. */
  258. function getConnection()
  259. {
  260. $result = $this->connect();
  261. if (MDB2::isError($result)) {
  262. return $result;
  263. }
  264. if ($this->in_transaction) {
  265. return $this->transaction_id;
  266. }
  267. return $this->connection;
  268. }
  269. // }}}
  270. // {{{ beginTransaction()
  271. /**
  272. * Start a transaction or set a savepoint.
  273. *
  274. * @param string name of a savepoint to set
  275. * @return mixed MDB2_OK on success, a MDB2 error on failure
  276. *
  277. * @access public
  278. */
  279. function beginTransaction($savepoint = null)
  280. {
  281. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  282. if (null !== $savepoint) {
  283. if (!$this->in_transaction) {
  284. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  285. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  286. }
  287. $query = 'SAVEPOINT '.$savepoint;
  288. return $this->_doQuery($query, true);
  289. }
  290. if ($this->in_transaction) {
  291. return MDB2_OK; //nothing to do
  292. }
  293. $connection = $this->getConnection();
  294. if (MDB2::isError($connection)) {
  295. return $connection;
  296. }
  297. $result = @ibase_trans(IBASE_DEFAULT, $connection);
  298. if (!$result) {
  299. return $this->raiseError(null, null, null,
  300. 'could not start a transaction', __FUNCTION__);
  301. }
  302. $this->transaction_id = $result;
  303. $this->in_transaction = true;
  304. return MDB2_OK;
  305. }
  306. // }}}
  307. // {{{ commit()
  308. /**
  309. * Commit the database changes done during a transaction that is in
  310. * progress or release a savepoint. This function may only be called when
  311. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  312. * transaction is implicitly started after committing the pending changes.
  313. *
  314. * @param string name of a savepoint to release
  315. * @return mixed MDB2_OK on success, a MDB2 error on failure
  316. *
  317. * @access public
  318. */
  319. function commit($savepoint = null)
  320. {
  321. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  322. if (!$this->in_transaction) {
  323. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  324. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  325. }
  326. if (null !== $savepoint) {
  327. $query = 'RELEASE SAVEPOINT '.$savepoint;
  328. return $this->_doQuery($query, true);
  329. }
  330. if (!@ibase_commit($this->transaction_id)) {
  331. return $this->raiseError(null, null, null,
  332. 'could not commit a transaction', __FUNCTION__);
  333. }
  334. $this->in_transaction = false;
  335. $this->transaction_id = 0;
  336. return MDB2_OK;
  337. }
  338. // }}}
  339. // {{{ rollback()
  340. /**
  341. * Cancel any database changes done during a transaction or since a specific
  342. * savepoint that is in progress. This function may only be called when
  343. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  344. * transaction is implicitly started after canceling the pending changes.
  345. *
  346. * @param string name of a savepoint to rollback to
  347. * @return mixed MDB2_OK on success, a MDB2 error on failure
  348. *
  349. * @access public
  350. */
  351. function rollback($savepoint = null)
  352. {
  353. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  354. if (!$this->in_transaction) {
  355. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  356. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  357. }
  358. if (null !== $savepoint) {
  359. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  360. return $this->_doQuery($query, true);
  361. }
  362. if ($this->transaction_id && !@ibase_rollback($this->transaction_id)) {
  363. return $this->raiseError(null, null, null,
  364. 'Could not rollback a pending transaction: '.@ibase_errmsg(), __FUNCTION__);
  365. }
  366. $this->in_transaction = false;
  367. $this->transaction_id = 0;
  368. return MDB2_OK;
  369. }
  370. // }}}
  371. // {{{ setTransactionIsolation()
  372. /**
  373. * Set the transacton isolation level.
  374. *
  375. * @param string standard isolation level (SQL-92)
  376. * READ UNCOMMITTED (allows dirty reads)
  377. * READ COMMITTED (prevents dirty reads)
  378. * REPEATABLE READ (prevents nonrepeatable reads)
  379. * SERIALIZABLE (prevents phantom reads)
  380. * @param array some transaction options:
  381. * 'wait' => 'WAIT' | 'NO WAIT'
  382. * 'rw' => 'READ WRITE' | 'READ ONLY'
  383. * @return mixed MDB2_OK on success, a MDB2 error on failure
  384. *
  385. * @access public
  386. * @since 2.1.1
  387. */
  388. function setTransactionIsolation($isolation, $options = array())
  389. {
  390. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  391. switch ($isolation) {
  392. case 'READ UNCOMMITTED':
  393. $ibase_isolation = 'READ COMMITTED RECORD_VERSION';
  394. break;
  395. case 'READ COMMITTED':
  396. $ibase_isolation = 'READ COMMITTED NO RECORD_VERSION';
  397. break;
  398. case 'REPEATABLE READ':
  399. $ibase_isolation = 'SNAPSHOT';
  400. break;
  401. case 'SERIALIZABLE':
  402. $ibase_isolation = 'SNAPSHOT TABLE STABILITY';
  403. break;
  404. default:
  405. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  406. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  407. }
  408. if (!empty($options['wait'])) {
  409. switch ($options['wait']) {
  410. case 'WAIT':
  411. case 'NO WAIT':
  412. $wait = $options['wait'];
  413. break;
  414. default:
  415. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  416. 'wait option is not supported: '.$options['wait'], __FUNCTION__);
  417. }
  418. }
  419. if (!empty($options['rw'])) {
  420. switch ($options['rw']) {
  421. case 'READ ONLY':
  422. case 'READ WRITE':
  423. $rw = $options['rw'];
  424. break;
  425. default:
  426. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  427. 'rw option is not supported: '.$options['rw'], __FUNCTION__);
  428. }
  429. }
  430. $query = "SET TRANSACTION $rw $wait ISOLATION LEVEL $ibase_isolation";
  431. return $this->_doQuery($query, true);
  432. }
  433. // }}}
  434. // {{{ getDatabaseFile($database_name)
  435. /**
  436. * Builds the string with path+dbname+extension
  437. *
  438. * @return string full database path+file
  439. * @access protected
  440. */
  441. function _getDatabaseFile($database_name)
  442. {
  443. if ($database_name == '') {
  444. return $database_name;
  445. }
  446. $ret = $this->options['database_path'] . $database_name;
  447. if (!preg_match('/\.[fg]db$/i', $database_name)) {
  448. $ret .= $this->options['database_extension'];
  449. }
  450. return $ret;
  451. }
  452. // }}}
  453. // {{{ _doConnect()
  454. /**
  455. * Does the grunt work of connecting to the database
  456. *
  457. * @return mixed connection resource on success, MDB2 Error Object on failure
  458. * @access protected
  459. */
  460. function _doConnect($username, $password, $database_name, $persistent = false)
  461. {
  462. if (!extension_loaded('interbase')) {
  463. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  464. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  465. }
  466. $database_file = $this->_getDatabaseFile($database_name);
  467. $dbhost = $this->dsn['hostspec'] ?
  468. ($this->dsn['hostspec'].':'.$database_file) : $database_file;
  469. $params = array();
  470. $params[] = $dbhost;
  471. $params[] = !empty($username) ? $username : null;
  472. $params[] = !empty($password) ? $password : null;
  473. $params[] = isset($this->dsn['charset']) ? $this->dsn['charset'] : null;
  474. $params[] = isset($this->dsn['buffers']) ? $this->dsn['buffers'] : null;
  475. $params[] = isset($this->dsn['dialect']) ? $this->dsn['dialect'] : null;
  476. $params[] = isset($this->dsn['role']) ? $this->dsn['role'] : null;
  477. $connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect';
  478. $connection = @call_user_func_array($connect_function, $params);
  479. if ($connection <= 0) {
  480. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  481. 'unable to establish a connection', __FUNCTION__);
  482. }
  483. if (empty($this->dsn['disable_iso_date'])) {
  484. if (function_exists('ibase_timefmt')) {
  485. @ibase_timefmt("%Y-%m-%d %H:%M:%S", IBASE_TIMESTAMP);
  486. @ibase_timefmt("%Y-%m-%d", IBASE_DATE);
  487. } else {
  488. @ini_set("ibase.timestampformat", "%Y-%m-%d %H:%M:%S");
  489. //@ini_set("ibase.timeformat", "%H:%M:%S");
  490. @ini_set("ibase.dateformat", "%Y-%m-%d");
  491. }
  492. }
  493. return $connection;
  494. }
  495. // }}}
  496. // {{{ connect()
  497. /**
  498. * Connect to the database
  499. *
  500. * @return true on success, MDB2 Error Object on failure
  501. * @access public
  502. */
  503. function connect()
  504. {
  505. $database_file = $this->_getDatabaseFile($this->database_name);
  506. if (is_resource($this->connection)) {
  507. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  508. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  509. && $this->connected_database_name == $database_file
  510. && $this->opened_persistent == $this->options['persistent']
  511. ) {
  512. return MDB2_OK;
  513. }
  514. $this->disconnect(false);
  515. }
  516. if (empty($this->database_name)) {
  517. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  518. 'unable to establish a connection', __FUNCTION__);
  519. }
  520. $connection = $this->_doConnect($this->dsn['username'],
  521. $this->dsn['password'],
  522. $this->database_name,
  523. $this->options['persistent']);
  524. if (MDB2::isError($connection)) {
  525. return $connection;
  526. }
  527. $this->connection =& $connection;
  528. $this->connected_dsn = $this->dsn;
  529. $this->connected_database_name = $database_file;
  530. $this->opened_persistent = $this->options['persistent'];
  531. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  532. $this->supported['limit_queries'] = ($this->dbsyntax == 'firebird') ? true : 'emulated';
  533. return MDB2_OK;
  534. }
  535. // }}}
  536. // {{{ databaseExists()
  537. /**
  538. * check if given database name is exists?
  539. *
  540. * @param string $name name of the database that should be checked
  541. *
  542. * @return mixed true/false on success, a MDB2 error on failure
  543. * @access public
  544. */
  545. function databaseExists($name)
  546. {
  547. $database_file = $this->_getDatabaseFile($name);
  548. $result = file_exists($database_file);
  549. return $result;
  550. }
  551. // }}}
  552. // {{{ disconnect()
  553. /**
  554. * Log out and disconnect from the database.
  555. *
  556. * @param boolean $force if the disconnect should be forced even if the
  557. * connection is opened persistently
  558. * @return mixed true on success, false if not connected and error
  559. * object on error
  560. * @access public
  561. */
  562. function disconnect($force = true)
  563. {
  564. if (is_resource($this->connection)) {
  565. if ($this->in_transaction) {
  566. $dsn = $this->dsn;
  567. $database_name = $this->database_name;
  568. $persistent = $this->options['persistent'];
  569. $this->dsn = $this->connected_dsn;
  570. $this->database_name = $this->connected_database_name;
  571. $this->options['persistent'] = $this->opened_persistent;
  572. $this->rollback();
  573. $this->dsn = $dsn;
  574. $this->database_name = $database_name;
  575. $this->options['persistent'] = $persistent;
  576. }
  577. if (!$this->opened_persistent || $force) {
  578. $ok = @ibase_close($this->connection);
  579. if (!$ok) {
  580. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  581. null, null, null, __FUNCTION__);
  582. }
  583. }
  584. } else {
  585. return false;
  586. }
  587. return parent::disconnect($force);
  588. }
  589. // }}}
  590. // {{{ standaloneQuery()
  591. /**
  592. * execute a query as DBA
  593. *
  594. * @param string $query the SQL query
  595. * @param mixed $types array that contains the types of the columns in
  596. * the result set
  597. * @param boolean $is_manip if the query is a manipulation query
  598. * @return mixed MDB2_OK on success, a MDB2 error on failure
  599. * @access public
  600. */
  601. function standaloneQuery($query, $types = null, $is_manip = false)
  602. {
  603. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  604. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  605. $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
  606. if (MDB2::isError($connection)) {
  607. return $connection;
  608. }
  609. $offset = $this->offset;
  610. $limit = $this->limit;
  611. $this->offset = $this->limit = 0;
  612. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  613. $result = $this->_doQuery($query, $is_manip, $connection);
  614. if (!MDB2::isError($result)) {
  615. $result = $this->_affectedRows($connection, $result);
  616. }
  617. @ibase_close($connection);
  618. return $result;
  619. }
  620. // }}}
  621. // {{{ _doQuery()
  622. /**
  623. * Execute a query
  624. * @param string $query query
  625. * @param boolean $is_manip if the query is a manipulation query
  626. * @param resource $connection
  627. * @param string $database_name
  628. * @return result or error object
  629. * @access protected
  630. */
  631. function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  632. {
  633. $this->last_query = $query;
  634. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  635. if ($result) {
  636. if (MDB2::isError($result)) {
  637. return $result;
  638. }
  639. $query = $result;
  640. }
  641. if ($this->getOption('disable_query')) {
  642. if ($is_manip) {
  643. return 0;
  644. }
  645. return null;
  646. }
  647. if (null === $connection) {
  648. $connection = $this->getConnection();
  649. if (MDB2::isError($connection)) {
  650. return $connection;
  651. }
  652. }
  653. $result = @ibase_query($connection, $query);
  654. if (false === $result) {
  655. $err = $this->raiseError(null, null, null,
  656. 'Could not execute statement', __FUNCTION__);
  657. return $err;
  658. }
  659. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  660. return $result;
  661. }
  662. // }}}
  663. // {{{ _affectedRows()
  664. /**
  665. * Returns the number of rows affected
  666. *
  667. * @param resource $result
  668. * @param resource $connection
  669. * @return mixed MDB2 Error Object or the number of rows affected
  670. * @access private
  671. */
  672. function _affectedRows($connection, $result = null)
  673. {
  674. if (null === $connection) {
  675. $connection = $this->getConnection();
  676. if (MDB2::isError($connection)) {
  677. return $connection;
  678. }
  679. }
  680. return (function_exists('ibase_affected_rows') ? @ibase_affected_rows($connection) : 0);
  681. }
  682. // }}}
  683. // {{{ _modifyQuery()
  684. /**
  685. * Changes a query string for various DBMS specific reasons
  686. *
  687. * @param string $query query to modify
  688. * @param boolean $is_manip if it is a DML query
  689. * @param integer $limit limit the number of rows
  690. * @param integer $offset start reading from given offset
  691. * @return string modified query
  692. * @access protected
  693. */
  694. function _modifyQuery($query, $is_manip, $limit, $offset)
  695. {
  696. if ($limit > 0 && $this->supports('limit_queries') === true) {
  697. $query = preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i',
  698. "SELECT FIRST $limit SKIP $offset", $query);
  699. }
  700. return $query;
  701. }
  702. // }}}
  703. // {{{ getServerVersion()
  704. /**
  705. * return version information about the server
  706. *
  707. * @param bool $native determines if the raw version string should be returned
  708. * @return mixed array/string with version information or MDB2 error object
  709. * @access public
  710. */
  711. function getServerVersion($native = false)
  712. {
  713. $server_info = false;
  714. if ($this->connected_server_info) {
  715. $server_info = $this->connected_server_info;
  716. } elseif ($this->options['server_version']) {
  717. $server_info = $this->options['server_version'];
  718. } else {
  719. $username = $this->options['DBA_username'] ? $this->options['DBA_username'] : $this->dsn['username'];
  720. $password = $this->options['DBA_password'] ? $this->options['DBA_password'] : $this->dsn['password'];
  721. $ibserv = @ibase_service_attach($this->dsn['hostspec'], $username, $password);
  722. $server_info = @ibase_server_info($ibserv, IBASE_SVC_SERVER_VERSION);
  723. @ibase_service_detach($ibserv);
  724. }
  725. if (!$server_info) {
  726. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  727. 'Requires either "server_version" or "DBA_username"/"DBA_password" option', __FUNCTION__);
  728. }
  729. // cache server_info
  730. $this->connected_server_info = $server_info;
  731. if (!$native) {
  732. //WI-V1.5.3.4854 Firebird 1.5
  733. //WI-T2.1.0.16780 Firebird 2.1 Beta 2
  734. if (!preg_match('/-[VT]([\d\.]*)/', $server_info, $matches)) {
  735. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  736. 'Could not parse version information:'.$server_info, __FUNCTION__);
  737. }
  738. $tmp = explode('.', $matches[1], 4);
  739. $server_info = array(
  740. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  741. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  742. 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  743. 'extra' => isset($tmp[3]) ? $tmp[3] : null,
  744. 'native' => $server_info,
  745. );
  746. }
  747. return $server_info;
  748. }
  749. // }}}
  750. // {{{ prepare()
  751. /**
  752. * Prepares a query for multiple execution with execute().
  753. * With some database backends, this is emulated.
  754. * prepare() requires a generic query as string like
  755. * 'INSERT INTO numbers VALUES(?,?)' or
  756. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  757. * The ? and :name and are placeholders which can be set using
  758. * bindParam() and the query can be sent off using the execute() method.
  759. * The allowed format for :name can be set with the 'bindname_format' option.
  760. *
  761. * @param string $query the query to prepare
  762. * @param mixed $types array that contains the types of the placeholders
  763. * @param mixed $result_types array that contains the types of the columns in
  764. * the result set or MDB2_PREPARE_RESULT, if set to
  765. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  766. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  767. * @return mixed resource handle for the prepared query on success, a MDB2
  768. * error on failure
  769. * @access public
  770. * @see bindParam, execute
  771. */
  772. function prepare($query, $types = null, $result_types = null, $lobs = array())
  773. {
  774. if ($this->options['emulate_prepared']) {
  775. return parent::prepare($query, $types, $result_types, $lobs);
  776. }
  777. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  778. $offset = $this->offset;
  779. $limit = $this->limit;
  780. $this->offset = $this->limit = 0;
  781. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  782. if ($result) {
  783. if (MDB2::isError($result)) {
  784. return $result;
  785. }
  786. $query = $result;
  787. }
  788. $placeholder_type_guess = $placeholder_type = null;
  789. $question = '?';
  790. $colon = ':';
  791. $positions = array();
  792. $position = 0;
  793. while ($position < strlen($query)) {
  794. $q_position = strpos($query, $question, $position);
  795. $c_position = strpos($query, $colon, $position);
  796. if ($q_position && $c_position) {
  797. $p_position = min($q_position, $c_position);
  798. } elseif ($q_position) {
  799. $p_position = $q_position;
  800. } elseif ($c_position) {
  801. $p_position = $c_position;
  802. } else {
  803. break;
  804. }
  805. if (null === $placeholder_type) {
  806. $placeholder_type_guess = $query[$p_position];
  807. }
  808. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  809. if (MDB2::isError($new_pos)) {
  810. return $new_pos;
  811. }
  812. if ($new_pos != $position) {
  813. $position = $new_pos;
  814. continue; //evaluate again starting from the new position
  815. }
  816. if ($query[$position] == $placeholder_type_guess) {
  817. if (null === $placeholder_type) {
  818. $placeholder_type = $query[$p_position];
  819. $question = $colon = $placeholder_type;
  820. }
  821. if ($placeholder_type == ':') {
  822. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  823. $parameter = preg_replace($regexp, '\\1', $query);
  824. if ($parameter === '') {
  825. $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  826. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  827. return $err;
  828. }
  829. $positions[] = $parameter;
  830. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  831. } else {
  832. $positions[] = count($positions);
  833. }
  834. $position = $p_position + 1;
  835. } else {
  836. $position = $p_position;
  837. }
  838. }
  839. $connection = $this->getConnection();
  840. if (MDB2::isError($connection)) {
  841. return $connection;
  842. }
  843. $statement = @ibase_prepare($connection, $query);
  844. if (!$statement) {
  845. $err = $this->raiseError(null, null, null,
  846. 'Could not create statement', __FUNCTION__);
  847. return $err;
  848. }
  849. $class_name = 'MDB2_Statement_'.$this->phptype;
  850. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  851. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  852. return $obj;
  853. }
  854. // }}}
  855. // {{{ getSequenceName()
  856. /**
  857. * adds sequence name formatting to a sequence name
  858. *
  859. * @param string $sqn name of the sequence
  860. * @return string formatted sequence name
  861. * @access public
  862. */
  863. function getSequenceName($sqn)
  864. {
  865. return strtoupper(parent::getSequenceName($sqn));
  866. }
  867. // }}}
  868. // {{{ nextID()
  869. /**
  870. * Returns the next free id of a sequence
  871. *
  872. * @param string $seq_name name of the sequence
  873. * @param boolean $ondemand when true the sequence is
  874. * automatic created, if it
  875. * not exists
  876. * @return mixed MDB2 Error Object or id
  877. * @access public
  878. */
  879. function nextID($seq_name, $ondemand = true)
  880. {
  881. $sequence_name = $this->getSequenceName($seq_name);
  882. $query = 'SELECT GEN_ID('.$sequence_name.', 1) as the_value FROM RDB$DATABASE';
  883. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  884. $this->expectError('*');
  885. $result = $this->queryOne($query, 'integer');
  886. $this->popExpect();
  887. $this->popErrorHandling();
  888. if (MDB2::isError($result)) {
  889. if ($ondemand) {
  890. $this->loadModule('Manager', null, true);
  891. $result = $this->manager->createSequence($seq_name);
  892. if (MDB2::isError($result)) {
  893. return $this->raiseError($result, null, null,
  894. 'on demand sequence could not be created', __FUNCTION__);
  895. } else {
  896. return $this->nextID($seq_name, false);
  897. }
  898. }
  899. }
  900. return $result;
  901. }
  902. // }}}
  903. // {{{ lastInsertID()
  904. /**
  905. * Returns the autoincrement ID if supported or $id or fetches the current
  906. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  907. *
  908. * @param string $table name of the table into which a new row was inserted
  909. * @param string $field name of the field into which a new row was inserted
  910. * @return mixed MDB2 Error Object or id
  911. * @access public
  912. */
  913. function lastInsertID($table = null, $field = null)
  914. {
  915. //$seq = $table.(empty($field) ? '' : '_'.$field);
  916. return $this->currID($table);
  917. }
  918. // }}}
  919. // {{{ currID()
  920. /**
  921. * Returns the current id of a sequence
  922. *
  923. * @param string $seq_name name of the sequence
  924. * @return mixed MDB2 Error Object or id
  925. * @access public
  926. */
  927. function currID($seq_name)
  928. {
  929. $sequence_name = $this->getSequenceName($seq_name);
  930. $query = 'SELECT GEN_ID('.$sequence_name.', 0) as the_value FROM RDB$DATABASE';
  931. $value = $this->queryOne($query);
  932. if (MDB2::isError($value)) {
  933. return $this->raiseError($value, null, null,
  934. 'Unable to select from ' . $seq_name, __FUNCTION__);
  935. }
  936. if (!is_numeric($value)) {
  937. return $this->raiseError(MDB2_ERROR, null, null,
  938. 'could not find value in sequence table', __FUNCTION__);
  939. }
  940. return $value;
  941. }
  942. // }}}
  943. }
  944. /**
  945. * MDB2 FireBird/InterBase result driver
  946. *
  947. * @package MDB2
  948. * @category Database
  949. * @author Lorenzo Alberton <l.alberton@quipo.it>
  950. */
  951. class MDB2_Result_ibase extends MDB2_Result_Common
  952. {
  953. // {{{ _skipLimitOffset()
  954. /**
  955. * Skip the first row of a result set.
  956. *
  957. * @param resource $result
  958. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  959. * @access protected
  960. */
  961. function _skipLimitOffset()
  962. {
  963. if ($this->db->supports('limit_queries') === true) {
  964. return true;
  965. }
  966. if ($this->limit) {
  967. if ($this->rownum > $this->limit) {
  968. return false;
  969. }
  970. }
  971. if ($this->offset) {
  972. while ($this->offset_count < $this->offset) {
  973. ++$this->offset_count;
  974. if (!is_array(@ibase_fetch_row($this->result))) {
  975. $this->offset_count = $this->offset;
  976. return false;
  977. }
  978. }
  979. }
  980. return true;
  981. }
  982. // }}}
  983. // {{{ fetchRow()
  984. /**
  985. * Fetch a row and insert the data into an existing array.
  986. *
  987. * @param int $fetchmode how the array data should be indexed
  988. * @param int $rownum number of the row where the data can be found
  989. * @return int data array on success, a MDB2 error on failure
  990. * @access public
  991. */
  992. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  993. {
  994. if (true === $this->result) {
  995. //query successfully executed, but without results...
  996. return null;
  997. }
  998. if (!$this->_skipLimitOffset()) {
  999. return null;
  1000. }
  1001. if (null !== $rownum) {
  1002. $seek = $this->seek($rownum);
  1003. if (MDB2::isError($seek)) {
  1004. return $seek;
  1005. }
  1006. }
  1007. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1008. $fetchmode = $this->db->fetchmode;
  1009. }
  1010. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  1011. || $fetchmode == MDB2_FETCHMODE_OBJECT
  1012. ) {
  1013. $row = @ibase_fetch_assoc($this->result);
  1014. if (is_array($row)
  1015. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1016. ) {
  1017. $row = array_change_key_case($row, $this->db->options['field_case']);
  1018. }
  1019. } else {
  1020. $row = @ibase_fetch_row($this->result);
  1021. }
  1022. if (!$row) {
  1023. if (false === $this->result) {
  1024. $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1025. 'resultset has already been freed', __FUNCTION__);
  1026. return $err;
  1027. }
  1028. return null;
  1029. }
  1030. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1031. $rtrim = false;
  1032. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1033. if (empty($this->types)) {
  1034. $mode += MDB2_PORTABILITY_RTRIM;
  1035. } else {
  1036. $rtrim = true;
  1037. }
  1038. }
  1039. if ($mode) {
  1040. $this->db->_fixResultArrayValues($row, $mode);
  1041. }
  1042. if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
  1043. && $fetchmode != MDB2_FETCHMODE_OBJECT)
  1044. && !empty($this->types)
  1045. ) {
  1046. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1047. } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
  1048. || $fetchmode == MDB2_FETCHMODE_OBJECT)
  1049. && !empty($this->types_assoc)
  1050. ) {
  1051. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1052. }
  1053. if (!empty($this->values)) {
  1054. $this->_assignBindColumns($row);
  1055. }
  1056. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1057. $object_class = $this->db->options['fetch_class'];
  1058. if ($object_class == 'stdClass') {
  1059. $row = (object) $row;
  1060. } else {
  1061. $rowObj = new $object_class($row);
  1062. $row = $rowObj;
  1063. }
  1064. }
  1065. ++$this->rownum;
  1066. return $row;
  1067. }
  1068. // }}}
  1069. // {{{ _getColumnNames()
  1070. /**
  1071. * Retrieve the names of columns returned by the DBMS in a query result.
  1072. *
  1073. * @return mixed Array variable that holds the names of columns as keys
  1074. * or an MDB2 error on failure.
  1075. * Some DBMS may not return any columns when the result set
  1076. * does not contain any rows.
  1077. * @access private
  1078. */
  1079. function _getColumnNames()
  1080. {
  1081. $columns = array();
  1082. $numcols = $this->numCols();
  1083. if (MDB2::isError($numcols)) {
  1084. return $numcols;
  1085. }
  1086. for ($column = 0; $column < $numcols; $column++) {
  1087. $column_info = @ibase_field_info($this->result, $column);
  1088. $columns[$column_info['alias']] = $column;
  1089. }
  1090. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1091. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1092. }
  1093. return $columns;
  1094. }
  1095. // }}}
  1096. // {{{ numCols()
  1097. /**
  1098. * Count the number of columns returned by the DBMS in a query result.
  1099. *
  1100. * @return mixed integer value with the number of columns, a MDB2 error
  1101. * on failure
  1102. * @access public
  1103. */
  1104. function numCols()
  1105. {
  1106. if (true === $this->result) {
  1107. //query successfully executed, but without results...
  1108. return 0;
  1109. }
  1110. if (!is_resource($this->result)) {
  1111. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1112. 'numCols(): not a valid ibase resource', __FUNCTION__);
  1113. }
  1114. $cols = @ibase_num_fields($this->result);
  1115. if (null === $cols) {
  1116. if (false === $this->result) {
  1117. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1118. 'resultset has already been freed', __FUNCTION__);
  1119. } elseif (null === $this->result) {
  1120. return count($this->types);
  1121. }
  1122. return $this->db->raiseError(null, null, null,
  1123. 'Could not get column count', __FUNCTION__);
  1124. }
  1125. return $cols;
  1126. }
  1127. // }}}
  1128. // {{{ free()
  1129. /**
  1130. * Free the internal resources associated with $result.
  1131. *
  1132. * @return boolean true on success, false if $result is invalid
  1133. * @access public
  1134. */
  1135. function free()
  1136. {
  1137. if (is_resource($this->result) && $this->db->connection) {
  1138. $free = @ibase_free_result($this->result);
  1139. if (false === $free) {
  1140. return $this->db->raiseError(null, null, null,
  1141. 'Could not free result', __FUNCTION__);
  1142. }
  1143. }
  1144. $this->result = false;
  1145. return MDB2_OK;
  1146. }
  1147. // }}}
  1148. }
  1149. /**
  1150. * MDB2 FireBird/InterBase buffered result driver
  1151. *
  1152. * @package MDB2
  1153. * @category Database
  1154. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1155. */
  1156. class MDB2_BufferedResult_ibase extends MDB2_Result_ibase
  1157. {
  1158. // {{{ class vars
  1159. var $buffer;
  1160. var $buffer_rownum = - 1;
  1161. // }}}
  1162. // {{{ _fillBuffer()
  1163. /**
  1164. * Fill the row buffer
  1165. *
  1166. * @param int $rownum row number upto which the buffer should be filled
  1167. * if the row number is null all rows are ready into the buffer
  1168. * @return boolean true on success, false on failure
  1169. * @access protected
  1170. */
  1171. function _fillBuffer($rownum = null)
  1172. {
  1173. if (isset($this->buffer) && is_array($this->buffer)) {
  1174. if (null === $rownum) {
  1175. if (!end($this->buffer)) {
  1176. return false;
  1177. }
  1178. } elseif (isset($this->buffer[$rownum])) {
  1179. return (bool) $this->buffer[$rownum];
  1180. }
  1181. }
  1182. if (!$this->_skipLimitOffset()) {
  1183. return false;
  1184. }
  1185. $buffer = true;
  1186. while (((null === $rownum) || $this->buffer_rownum < $rownum)
  1187. && (!$this->limit || $this->buffer_rownum < $this->limit)
  1188. && ($buffer = @ibase_fetch_row($this->result))
  1189. ) {
  1190. ++$this->buffer_rownum;
  1191. $this->buffer[$this->buffer_rownum] = $buffer;
  1192. }
  1193. if (!$buffer) {
  1194. ++$this->buffer_rownum;
  1195. $this->buffer[$this->buffer_rownum] = false;
  1196. return false;
  1197. } elseif ($this->limit && $this->buffer_rownum >= $this->limit) {
  1198. ++$this->buffer_rownum;
  1199. $this->buffer[$this->buffer_rownum] = false;
  1200. }
  1201. return true;
  1202. }
  1203. // }}}
  1204. // {{{ fetchRow()
  1205. /**
  1206. * Fetch a row and insert the data into an existing array.
  1207. *
  1208. * @param int $fetchmode how the array data should be indexed
  1209. * @param int $rownum number of the row where the data can be found
  1210. * @return int data array on success, a MDB2 error on failure
  1211. * @access public
  1212. */
  1213. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1214. {
  1215. if (true === $this->result || (null === $this->result)) {
  1216. //query successfully executed, but without results...
  1217. return null;
  1218. }
  1219. if (false === $this->result) {
  1220. $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1221. 'resultset has already been freed', __FUNCTION__);
  1222. return $err;
  1223. }
  1224. if (null !== $rownum) {
  1225. $seek = $this->seek($rownum);
  1226. if (MDB2::isError($seek)) {
  1227. return $seek;
  1228. }
  1229. }
  1230. $target_rownum = $this->rownum + 1;
  1231. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1232. $fetchmode = $this->db->fetchmode;
  1233. }
  1234. if (!$this->_fillBuffer($target_rownum)) {
  1235. return null;
  1236. }
  1237. $row = $this->buffer[$target_rownum];
  1238. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  1239. || $fetchmode == MDB2_FETCHMODE_OBJECT
  1240. ) {
  1241. $column_names = $this->getColumnNames();
  1242. foreach ($column_names as $name => $i) {
  1243. $column_names[$name] = $row[$i];
  1244. }
  1245. $row = $column_names;
  1246. }
  1247. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1248. $rtrim = false;
  1249. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1250. if (empty($this->types)) {
  1251. $mode += MDB2_PORTABILITY_RTRIM;
  1252. } else {
  1253. $rtrim = true;
  1254. }
  1255. }
  1256. if ($mode) {
  1257. $this->db->_fixResultArrayValues($row, $mode);
  1258. }
  1259. if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
  1260. && $fetchmode != MDB2_FETCHMODE_OBJECT)
  1261. && !empty($this->types)
  1262. ) {
  1263. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1264. } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
  1265. || $fetchmode == MDB2_FETCHMODE_OBJECT)
  1266. && !empty($this->types_assoc)
  1267. ) {
  1268. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1269. }
  1270. if (!empty($this->values)) {
  1271. $this->_assignBindColumns($row);
  1272. }
  1273. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1274. $object_class = $this->db->options['fetch_class'];
  1275. if ($object_class == 'stdClass') {
  1276. $row = (object) $row;
  1277. } else {
  1278. $rowObj = new $object_class($row);
  1279. $row = $rowObj;
  1280. }
  1281. }
  1282. ++$this->rownum;
  1283. return $row;
  1284. }
  1285. // }}}
  1286. // {{{ seek()
  1287. /**
  1288. * Seek to a specific row in a result set
  1289. *
  1290. * @param int $rownum number of the row where the data can be found
  1291. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1292. * @access public
  1293. */
  1294. function seek($rownum = 0)
  1295. {
  1296. if (false === $this->result) {
  1297. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1298. 'resultset has already been freed', __FUNCTION__);
  1299. }
  1300. $this->rownum = $rownum - 1;
  1301. return MDB2_OK;
  1302. }
  1303. // }}}
  1304. // {{{ valid()
  1305. /**
  1306. * Check if the end of the result set has been reached
  1307. *
  1308. * @return mixed true or false on sucess, a MDB2 error on failure
  1309. * @access public
  1310. */
  1311. function valid()
  1312. {
  1313. if (false === $this->result) {
  1314. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1315. 'resultset has already been freed', __FUNCTION__);
  1316. }
  1317. if (null === $this->result) {
  1318. return true;
  1319. }
  1320. if ($this->_fillBuffer($this->rownum + 1)) {
  1321. return true;
  1322. }
  1323. return false;
  1324. }
  1325. // }}}
  1326. // {{{ numRows()
  1327. /**
  1328. * Returns the number of rows in a result object
  1329. *
  1330. * @return mixed MDB2 Error Object or the number of rows
  1331. * @access public
  1332. */
  1333. function numRows()
  1334. {
  1335. if (false === $this->result) {
  1336. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1337. 'resultset has already been freed', __FUNCTION__);
  1338. }
  1339. if (null === $this->result) {
  1340. return 0;
  1341. }
  1342. $this->_fillBuffer();
  1343. return $this->buffer_rownum;
  1344. }
  1345. // }}}
  1346. // {{{ free()
  1347. /**
  1348. * Free the internal resources associated with $result.
  1349. *
  1350. * @return boolean true on success, false if $result is invalid
  1351. * @access public
  1352. */
  1353. function free()
  1354. {
  1355. $this->buffer = null;
  1356. $this->buffer_rownum = null;
  1357. return parent::free();
  1358. }
  1359. // }}}
  1360. }
  1361. /**
  1362. * MDB2 FireBird/InterBase statement driver
  1363. *
  1364. * @package MDB2
  1365. * @category Database
  1366. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1367. */
  1368. class MDB2_Statement_ibase extends MDB2_Statement_Common
  1369. {
  1370. // {{{ _execute()
  1371. /**
  1372. * Execute a prepared query statement helper method.
  1373. *
  1374. * @param mixed $result_class string which specifies which result class to use
  1375. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1376. *
  1377. * @return mixed MDB2_Result or integer (affected rows) on success,
  1378. * a MDB2 error on failure
  1379. * @access private
  1380. */
  1381. function _execute($result_class = true, $result_wrap_class = true)
  1382. {
  1383. if (null === $this->statement) {
  1384. $result = parent::_execute($result_class, $result_wrap_class);
  1385. return $result;
  1386. }
  1387. $this->db->last_query = $this->query;
  1388. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1389. if ($this->db->getOption('disable_query')) {
  1390. $result = $this->is_manip ? 0 : null;
  1391. return $result;
  1392. }
  1393. $connection = $this->db->getConnection();
  1394. if (MDB2::isError($connection)) {
  1395. return $connection;
  1396. }
  1397. $parameters = array(0 => $this->statement);
  1398. foreach ($this->positions as $parameter) {
  1399. if (!array_key_exists($parameter, $this->values)) {
  1400. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1401. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1402. }
  1403. $value = $this->values[$parameter];
  1404. $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
  1405. $quoted = $this->db->quote($value, $type, false);
  1406. if (MDB2::isError($quoted)) {
  1407. return $quoted;
  1408. }
  1409. $parameters[] = $quoted;
  1410. }
  1411. $result = @call_user_func_array('ibase_execute', $parameters);
  1412. if (false === $result) {
  1413. $err = $this->db->raiseError(null, null, null,
  1414. 'Could not execute statement', __FUNCTION__);
  1415. return $err;
  1416. }
  1417. if ($this->is_manip) {
  1418. $affected_rows = $this->db->_affectedRows($connection);
  1419. return $affected_rows;
  1420. }
  1421. $result = $this->db->_wrapResult($result, $this->result_types,
  1422. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1423. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1424. return $result;
  1425. }
  1426. // }}}
  1427. // }}}
  1428. // {{{ free()
  1429. /**
  1430. * Release resources allocated for the specified prepared query.
  1431. *
  1432. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1433. * @access public
  1434. */
  1435. function free()
  1436. {
  1437. if (null === $this->positions) {
  1438. return $this->db->raiseError(MDB2_ERROR, null, null,
  1439. 'Prepared statement has already been freed', __FUNCTION__);
  1440. }
  1441. $result = MDB2_OK;
  1442. if ((null !== $this->statement) && !@ibase_free_query($this->statement)) {
  1443. $result = $this->db->raiseError(null, null, null,
  1444. 'Could not free statement', __FUNCTION__);
  1445. }
  1446. parent::free();
  1447. return $result;
  1448. }
  1449. }
  1450. ?>