PageRenderTime 63ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/pear/MDB2/Driver/querysim.php

https://bitbucket.org/Yason/armory
PHP | 810 lines | 376 code | 47 blank | 387 comment | 64 complexity | b44679c57f33f7ac7f545b0a7691502f MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  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. // | Original QuerySim Concept & ColdFusion Author: Hal Helms |
  44. // | <hal.helms@teamallaire.com> |
  45. // | Bert Dawson <bdawson@redbanner.com> |
  46. // +----------------------------------------------------------------------+
  47. // | Original PHP Author: Alan Richmond <arichmond@bigfoot.com> |
  48. // | David Huyck <b@bombusbee.com> |
  49. // +----------------------------------------------------------------------+
  50. // | Special note concerning code documentation: |
  51. // | QuerySim was originally created for use during development of |
  52. // | applications built using the Fusebox framework. (www.fusebox.org) |
  53. // | Fusebox uses an XML style of documentation called Fusedoc. (Which |
  54. // | is admittedly not well suited to documenting classes and functions. |
  55. // | This short-coming is being addressed by the Fusebox community.) PEAR |
  56. // | uses a Javadoc style of documentation called PHPDoc. (www.phpdoc.de) |
  57. // | Since this class extension spans two groups of users, it is asked |
  58. // | that the members of each respect the documentation standard of the |
  59. // | other. So it is a further requirement that both documentation |
  60. // | standards be included and maintained. If assistance is required |
  61. // | please contact Alan Richmond. |
  62. // +----------------------------------------------------------------------+
  63. //
  64. // $Id: querysim.php,v 1.77 2006/10/20 20:14:28 lsmith Exp $
  65. //
  66. /*
  67. <fusedoc fuse="querysim.php" language="PHP">
  68. <responsibilities>
  69. I take information and turn it into a recordset that can be accessed
  70. through the PEAR MDB2 API. Based on Hal Helms' QuerySim.cfm ColdFusion
  71. custom tag available at halhelms.com.
  72. </responsibilities>
  73. <properties>
  74. <property name="API" value="PEAR MDB2" />
  75. <property name="version" value="0.2.1" />
  76. <property name="status" value="beta" />
  77. <history author="Hal Helms" email="hal.helms@teamallaire.com" type="Create" />
  78. <history author="Bert Dawson" email="bdawson@redbanner.com" type="Update">
  79. Extensive revision that is backwardly compatible but eliminates the
  80. need for a separate .sim file.
  81. </history>
  82. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Create" date="10-July-2002">
  83. Rewrote in PHP as an extention to the PEAR DB API.
  84. Functions supported:
  85. connect, disconnect, query, fetchRow, freeResult,
  86. numCols, numRows, getSpecialQuery
  87. David Huyck (bombusbee.com) added ability to escape special
  88. characters (i.e., delimiters) using a '\'.
  89. Extended PEAR DB options[] for adding incoming parameters. Added
  90. options: columnDelim, dataDelim, eolDelim
  91. </history>
  92. <history author="David Huyck" email="b@bombusbee.com" type="Update" date="19-July-2002">
  93. Added the ability to set the QuerySim options at runtime.
  94. Default options are:
  95. 'columnDelim' => ',', // Commas split the column names
  96. 'dataDelim' => '|', // Pipes split the data fields
  97. 'eolDelim' => chr(13).chr(10) // Carriage returns split the
  98. // lines of data
  99. Affected functions are:
  100. DB_querysim(): set the default options when the
  101. constructor method is called
  102. _parseQuerySim($query): altered the parsing of lines, column
  103. names, and data fields
  104. _empty2null: altered the way this function is called
  105. to simplify calling it
  106. </history>
  107. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Update" date="24-July-2002">
  108. Added error catching for malformed QuerySim text.
  109. Bug fix _empty2null(): altered version was returning unmodified
  110. lineData.
  111. Cleanup:
  112. PEAR compliant formatting, finished PHPDocs and added 'out' to
  113. Fusedoc 'io'.
  114. Broke up _parseQuerySim() into _buildResult() and _parseOnDelim()
  115. to containerize duplicate parse code.
  116. </history>
  117. <history author="David Huyck" email="b@bombusbee.com" type="Update" date="25-July-2002">
  118. Edited the _buildResult() and _parseOnDelim() functions to improve
  119. reliability of special character escaping.
  120. Re-introduced a custom setOption() method to throw an error when a
  121. person tries to set one of the delimiters to '\'.
  122. </history>
  123. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Update" date="27-July-2002">
  124. Added '/' delimiter param to preg_quote() in _empty2null() and
  125. _parseOnDelim() so '/' can be used as a delimiter.
  126. Added error check for columnDelim == eolDelim or dataDelim == eolDelim.
  127. Renamed some variables for consistancy.
  128. </history>
  129. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Update" date="30-July-2002">
  130. Removed protected function _empty2null(). Turns out preg_split()
  131. deals with empty elemants by making them zero length strings, just
  132. what they ended up being anyway. This should speed things up a little.
  133. Affected functions:
  134. _parseOnDelim() perform trim on line here, instead of in
  135. _empty2null().
  136. _buildResult() remove call to _empty2null().
  137. _empty2null() removed function.
  138. </history>
  139. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Update" date="1-Jan-2003">
  140. Ported to PEAR MDB2.
  141. Methods supported:
  142. connect, query, getColumnNames, numCols, valid, fetch,
  143. numRows, free, fetchRow, nextResult, setLimit
  144. (inherited).
  145. </history>
  146. <history
  147. Removed array_change_key_case() work around for <4.2.0 in
  148. getColumnNames(), found it already done in MDB2/Common.php.
  149. </history>
  150. <history author="Alan Richmond" email="arichmond@bigfoot.com" type="Update" date="3-Feb-2003">
  151. Changed default eolDelim to a *nix file eol, since we're trimming
  152. the result anyway, it makes no difference for Windows. Now only
  153. Mac file eols should need to be set (and other kinds of chars).
  154. </history>
  155. <note author="Alan Richmond">
  156. Got WAY too long. See querysim_readme.txt for instructions and some
  157. examples.
  158. io section only documents elements of DB_result that DB_querysim uses,
  159. adds or changes; see MDB2 and MDB2_Driver_Common for more info.
  160. io section uses some elements that are not Fusedoc 2.0 compliant:
  161. object and resource.
  162. </note>
  163. </properties>
  164. <io>
  165. <in>
  166. <file path="MDB2/Common.php" action="require_once" />
  167. </in>
  168. <out>
  169. <object name="MDB2_querysim" extends="MDB2_Driver_Common" instantiatedby="MDB2::connect()">
  170. <resource type="file" name="connection" oncondition="source is external file" scope="class" />
  171. <string name="phptype" default="querysim" />
  172. <string name="dbsyntax" default="querysim" />
  173. <array name="supported" comments="most of these don't actually do anything, they are enabled to simulate the option being available if checked">
  174. <boolean name="sequences" default="true" />
  175. <boolean name="indexes" default="true" />
  176. <boolean name="affected_rows" default="true" />
  177. <boolean name="summary_functions" default="true" />
  178. <boolean name="order_by_text" default="true" />
  179. <boolean name="current_id" default="true" />
  180. <boolean name="limit_querys" default="true" comments="this one is functional" />
  181. <boolean name="LOBs" default="true" />
  182. <boolean name="replace" default="true" />
  183. <boolean name="sub_selects" default="true" />
  184. <boolean name="transactions" default="true" />
  185. </array>
  186. <string name="last_query" comments="last value passed in with query()" />
  187. <array name="options" comments="these can be changed at run time">
  188. <string name="columnDelim" default="," />
  189. <string name="dataDelim" default="|" />
  190. <string name="eolDelim" default="chr(13).chr(10)" />
  191. </array>
  192. </object>
  193. <array name="result" comments="the simulated record set returned by ::query()">
  194. <array comments="columns">
  195. <string comments="column name" />
  196. </array>
  197. <array comments="data">
  198. <array comments="row">
  199. <string comments="data element" />
  200. </array>
  201. </array>
  202. </array>
  203. </out>
  204. </io>
  205. </fusedoc>
  206. */
  207. /**
  208. * MDB2 QuerySim driver
  209. *
  210. * @package MDB2
  211. * @category Database
  212. * @author Alan Richmond <arichmond@bigfoot.com>
  213. */
  214. class MDB2_Driver_querysim extends MDB2_Driver_Common
  215. {
  216. // }}}
  217. // {{{ constructor
  218. /**
  219. * Constructor
  220. */
  221. function __construct()
  222. {
  223. parent::__construct();
  224. $this->phptype = 'querysim';
  225. $this->dbsyntax = 'querysim';
  226. // Most of these are dummies to simulate availability if checked
  227. $this->supported['sequences'] = false;
  228. $this->supported['indexes'] = false;
  229. $this->supported['affected_rows'] = false;
  230. $this->supported['summary_functions'] = false;
  231. $this->supported['order_by_text'] = false;
  232. $this->supported['current_id'] = false;
  233. $this->supported['limit_queries'] = true;// this one is real
  234. $this->supported['LOBs'] = true;
  235. $this->supported['replace'] = false;
  236. $this->supported['sub_selects'] = false;
  237. $this->supported['transactions'] = false;
  238. $this->supported['savepoints'] = false;
  239. $this->supported['auto_increment'] = false;
  240. $this->supported['primary_key'] = false;
  241. $this->supported['result_introspection'] = false; // not implemented
  242. $this->supported['prepared_statements'] = false;
  243. $this->supported['identifier_quoting'] = false;
  244. $this->supported['pattern_escaping'] = false;
  245. $this->supported['new_link'] = false;
  246. $this->options['columnDelim'] = ',';
  247. $this->options['dataDelim'] = '|';
  248. $this->options['eolDelim'] = "\n";
  249. }
  250. // }}}
  251. // {{{ connect()
  252. /**
  253. * Open a file or simulate a successful database connect
  254. *
  255. * @access public
  256. *
  257. * @return mixed MDB2_OK string on success, a MDB2 error object on failure
  258. */
  259. function connect()
  260. {
  261. if (is_resource($this->connection)) {
  262. if ($this->connected_database_name == $this->database_name
  263. && ($this->opened_persistent == $this->options['persistent'])
  264. ) {
  265. return MDB2_OK;
  266. }
  267. if ($this->connected_database_name) {
  268. $this->_close($this->connection);
  269. }
  270. $this->disconnect();
  271. }
  272. $connection = 1;// sim connect
  273. // if external, check file...
  274. if ($this->database_name) {
  275. $file = $this->database_name;
  276. if (!file_exists($file)) {
  277. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  278. 'file not found', __FUNCTION__);
  279. }
  280. if (!is_file($file)) {
  281. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  282. 'not a file', __FUNCTION__);
  283. }
  284. if (!is_readable($file)) {
  285. return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
  286. 'could not open file - check permissions', __FUNCTION__);
  287. }
  288. // ...and open if persistent
  289. if ($this->options['persistent']) {
  290. $connection = @fopen($file, 'r');
  291. }
  292. }
  293. if (!empty($this->dsn['charset'])) {
  294. $result = $this->setCharset($this->dsn['charset'], $connection);
  295. if (PEAR::isError($result)) {
  296. return $result;
  297. }
  298. }
  299. $this->connection = $connection;
  300. $this->connected_database_name = $this->database_name;
  301. $this->opened_persistent = $this->options['persistent'];
  302. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  303. return MDB2_OK;
  304. }
  305. // }}}
  306. // {{{ disconnect()
  307. /**
  308. * Log out and disconnect from the database.
  309. *
  310. * @param boolean $force if the disconnect should be forced even if the
  311. * connection is opened persistently
  312. * @return mixed true on success, false if not connected and error
  313. * object on error
  314. * @access public
  315. */
  316. function disconnect($force = true)
  317. {
  318. if (is_resource($this->connection)) {
  319. if ($this->opened_persistent) {
  320. @fclose($this->connection);
  321. }
  322. }
  323. return parent::disconnect($force);
  324. }
  325. // }}}
  326. // {{{ _doQuery()
  327. /**
  328. * Execute a query
  329. * @param string $query query
  330. * @param boolean $is_manip if the query is a manipulation query
  331. * @param resource $connection
  332. * @param string $database_name
  333. * @return result or error object
  334. * @access protected
  335. */
  336. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  337. {
  338. if ($this->database_name) {
  339. $query = $this->_readFile();
  340. }
  341. $this->last_query = $query;
  342. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  343. if ($result) {
  344. if (PEAR::isError($result)) {
  345. return $result;
  346. }
  347. $query = $result;
  348. }
  349. if ($is_manip) {
  350. $err =& $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  351. 'Manipulation statements are not supported', __FUNCTION__);
  352. return $err;
  353. }
  354. if ($this->options['disable_query']) {
  355. $result = $is_manip ? 0 : null;
  356. return $result;
  357. }
  358. $result = $this->_buildResult($query);
  359. if (PEAR::isError($result)) {
  360. return $result;
  361. }
  362. if ($this->next_limit > 0) {
  363. $result[1] = array_slice($result[1], $this->next_offset, $this->next_limit);
  364. }
  365. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  366. return $result;
  367. }
  368. // }}}
  369. // {{{ _modifyQuery()
  370. /**
  371. * Changes a query string for various DBMS specific reasons
  372. *
  373. * @param string $query query to modify
  374. * @param boolean $is_manip if it is a DML query
  375. * @param integer $limit limit the number of rows
  376. * @param integer $offset start reading from given offset
  377. * @return string modified query
  378. * @access protected
  379. */
  380. function _modifyQuery($query, $is_manip, $limit, $offset)
  381. {
  382. $this->next_limit = $limit;
  383. $this->next_offset = $offset;
  384. return $query;
  385. }
  386. // }}}
  387. // {{{ _readFile()
  388. /**
  389. * Read an external file
  390. *
  391. * @param string filepath/filename
  392. *
  393. * @access protected
  394. *
  395. * @return string the contents of a file
  396. */
  397. function _readFile()
  398. {
  399. $buffer = '';
  400. if ($this->opened_persistent) {
  401. $connection = $this->getConnection();
  402. if (PEAR::isError($connection)) {
  403. return $connection;
  404. }
  405. while (!feof($connection)) {
  406. $buffer.= fgets($connection, 1024);
  407. }
  408. rewind($connection);
  409. } else {
  410. $connection = @fopen($this->connected_database_name, 'r');
  411. while (!feof($connection)) {
  412. $buffer.= fgets($connection, 1024);
  413. }
  414. @fclose($connection);
  415. }
  416. return $buffer;
  417. }
  418. // }}}
  419. // {{{ _buildResult()
  420. /**
  421. * Convert QuerySim text into an array
  422. *
  423. * @param string Text of simulated query
  424. *
  425. * @access protected
  426. *
  427. * @return multi-dimensional array containing the column names and data
  428. * from the QuerySim
  429. */
  430. function _buildResult($query)
  431. {
  432. $eolDelim = $this->options['eolDelim'];
  433. $columnDelim = $this->options['columnDelim'];
  434. $dataDelim = $this->options['dataDelim'];
  435. $columnNames = array();
  436. $data = array();
  437. if ($columnDelim == $eolDelim) {
  438. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  439. 'columnDelim and eolDelim must be different', __FUNCTION__);
  440. } elseif ($dataDelim == $eolDelim){
  441. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  442. 'dataDelim and eolDelim must be different', __FUNCTION__);
  443. }
  444. $query = trim($query);
  445. //tokenize escaped slashes
  446. $query = str_replace('\\\\', '[$double-slash$]', $query);
  447. if (!strlen($query)) {
  448. return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  449. 'empty querysim text', __FUNCTION__);
  450. }
  451. $lineData = $this->_parseOnDelim($query, $eolDelim);
  452. //kill the empty last row created by final eol char if it exists
  453. if (!strlen(trim($lineData[count($lineData) - 1]))) {
  454. unset($lineData[count($lineData) - 1]);
  455. }
  456. //populate columnNames array
  457. $thisLine = each($lineData);
  458. $columnNames = $this->_parseOnDelim($thisLine[1], $columnDelim);
  459. if ((in_array('', $columnNames)) || (in_array('NULL', $columnNames))) {
  460. return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  461. 'all column names must be defined', __FUNCTION__);
  462. }
  463. //replace double-slash tokens with single-slash
  464. $columnNames = str_replace('[$double-slash$]', '\\', $columnNames);
  465. $columnCount = count($columnNames);
  466. $rowNum = 0;
  467. //loop through data lines
  468. if (count($lineData) > 1) {
  469. while ($thisLine = each($lineData)) {
  470. $thisData = $this->_parseOnDelim($thisLine[1], $dataDelim);
  471. $thisDataCount = count($thisData);
  472. if ($thisDataCount != $columnCount) {
  473. $fileLineNo = $rowNum + 2;
  474. return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  475. "number of data elements ($thisDataCount) in line $fileLineNo not equal to number of defined columns ($columnCount)", __FUNCTION__);
  476. }
  477. //loop through data elements in data line
  478. foreach ($thisData as $thisElement) {
  479. if (strtoupper($thisElement) == 'NULL'){
  480. $thisElement = '';
  481. }
  482. //replace double-slash tokens with single-slash
  483. $data[$rowNum][] = str_replace('[$double-slash$]', '\\', $thisElement);
  484. }//end foreach
  485. ++$rowNum;
  486. }//end while
  487. }//end if
  488. return array($columnNames, $data);
  489. }
  490. // }}}
  491. // {{{ _parseOnDelim()
  492. /**
  493. * Split QuerySim string into an array on a delimiter
  494. *
  495. * @param string $thisLine Text of simulated query
  496. * @param string $delim The delimiter to split on
  497. *
  498. * @access protected
  499. *
  500. * @return array containing parsed string
  501. */
  502. function _parseOnDelim($thisLine, $delim)
  503. {
  504. $delimQuoted = preg_quote($delim, '/');
  505. $thisLine = trim($thisLine);
  506. $parsed = preg_split('/(?<!\\\\)' .$delimQuoted. '/', $thisLine);
  507. //replaces escaped delimiters
  508. $parsed = preg_replace('/\\\\' .$delimQuoted. '/', $delim, $parsed);
  509. if ($delim != $this->options['eolDelim']) {
  510. //replaces escape chars
  511. $parsed = preg_replace('/\\\\/', '', $parsed);
  512. }
  513. return $parsed;
  514. }
  515. // }}}
  516. // {{{ exec()
  517. /**
  518. * Execute a manipulation query to the database and return any the affected rows
  519. *
  520. * @param string $query the SQL query
  521. * @return mixed affected rows on success, a MDB2 error on failure
  522. * @access public
  523. */
  524. function exec($query)
  525. {
  526. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  527. 'Querysim only supports reading data', __FUNCTION__);
  528. }
  529. // }}}
  530. // {{{ getServerVersion()
  531. /**
  532. * return version information about the server
  533. *
  534. * @param string $native determines if the raw version string should be returned
  535. * @return mixed array/string with version information or MDB2 error object
  536. * @access public
  537. */
  538. function getServerVersion($native = false)
  539. {
  540. $server_info = '0.6.0';
  541. // cache server_info
  542. $this->connected_server_info = $server_info;
  543. if (!$native) {
  544. $tmp = explode('.', $server_info, 3);
  545. if (!isset($tmp[2]) || !preg_match('/(\d+)(.*)/', $tmp[2], $tmp2)) {
  546. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  547. $tmp2[1] = null;
  548. }
  549. $server_info = array(
  550. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  551. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  552. 'patch' => isset($tmp2[0]) ? $tmp2[0] : null,
  553. 'extra' => isset($tmp2[1]) ? $tmp2[1] : null,
  554. 'native' => $server_info,
  555. );
  556. }
  557. return $server_info;
  558. }
  559. }
  560. /**
  561. * MDB2 QuerySim result driver
  562. *
  563. * @package MDB2
  564. * @category Database
  565. * @author Alan Richmond <arichmond@bigfoot.com>
  566. */
  567. class MDB2_Result_querysim extends MDB2_Result_Common
  568. {
  569. // }}}
  570. // {{{ fetchRow()
  571. /**
  572. * Fetch a row and insert the data into an existing array.
  573. *
  574. * @param int $fetchmode how the array data should be indexed
  575. * @param int $rownum number of the row where the data can be found
  576. * @return int data array on success, a MDB2 error on failure
  577. * @access public
  578. */
  579. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  580. {
  581. if ($this->result === false) {
  582. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  583. 'resultset has already been freed', __FUNCTION__);
  584. return $err;
  585. } elseif (is_null($this->result)) {
  586. return null;
  587. }
  588. if (!is_null($rownum)) {
  589. $seek = $this->seek($rownum);
  590. if (PEAR::isError($seek)) {
  591. return $seek;
  592. }
  593. }
  594. $target_rownum = $this->rownum + 1;
  595. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  596. $fetchmode = $this->db->fetchmode;
  597. }
  598. if (!isset($this->result[1][$target_rownum])) {
  599. $null = null;
  600. return $null;
  601. }
  602. $row = $this->result[1][$target_rownum];
  603. // make row associative
  604. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  605. $column_names = $this->getColumnNames();
  606. foreach ($column_names as $name => $i) {
  607. $column_names[$name] = $row[$i];
  608. }
  609. $row = $column_names;
  610. }
  611. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  612. $rtrim = false;
  613. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  614. if (empty($this->types)) {
  615. $mode += MDB2_PORTABILITY_RTRIM;
  616. } else {
  617. $rtrim = true;
  618. }
  619. }
  620. if ($mode) {
  621. $this->db->_fixResultArrayValues($row, $mode);
  622. }
  623. if (!empty($this->types)) {
  624. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  625. }
  626. if (!empty($this->values)) {
  627. $this->_assignBindColumns($row);
  628. }
  629. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  630. $object_class = $this->db->options['fetch_class'];
  631. if ($object_class == 'stdClass') {
  632. $row = (object) $row;
  633. } else {
  634. $row = &new $object_class($row);
  635. }
  636. }
  637. ++$this->rownum;
  638. return $row;
  639. }
  640. // }}}
  641. // {{{ _getColumnNames()
  642. /**
  643. * Retrieve the names of columns returned by the DBMS in a query result.
  644. *
  645. * @return mixed Array variable that holds the names of columns as keys
  646. * or an MDB2 error on failure.
  647. * Some DBMS may not return any columns when the result set
  648. * does not contain any rows.
  649. * @access private
  650. */
  651. function _getColumnNames()
  652. {
  653. if ($this->result === false) {
  654. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  655. 'resultset has already been freed', __FUNCTION__);
  656. } elseif (is_null($this->result)) {
  657. return array();
  658. }
  659. $columns = array_flip($this->result[0]);
  660. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  661. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  662. }
  663. return $columns;
  664. }
  665. // }}}
  666. // {{{ numCols()
  667. /**
  668. * Count the number of columns returned by the DBMS in a query result.
  669. *
  670. * @access public
  671. * @return mixed integer value with the number of columns, a MDB2 error
  672. * on failure
  673. */
  674. function numCols()
  675. {
  676. if ($this->result === false) {
  677. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  678. 'resultset has already been freed', __FUNCTION__);
  679. } elseif (is_null($this->result)) {
  680. return count($this->types);
  681. }
  682. $cols = count($this->result[0]);
  683. return $cols;
  684. }
  685. }
  686. /**
  687. * MDB2 QuerySim buffered result driver
  688. *
  689. * @package MDB2
  690. * @category Database
  691. * @author Alan Richmond <arichmond@bigfoot.com>
  692. */
  693. class MDB2_BufferedResult_querysim extends MDB2_Result_querysim
  694. {
  695. // }}}
  696. // {{{ seek()
  697. /**
  698. * Seek to a specific row in a result set
  699. *
  700. * @param int $rownum number of the row where the data can be found
  701. * @return mixed MDB2_OK on success, a MDB2 error on failure
  702. * @access public
  703. */
  704. function seek($rownum = 0)
  705. {
  706. if ($this->result === false) {
  707. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  708. 'resultset has already been freed', __FUNCTION__);
  709. }
  710. $this->rownum = $rownum - 1;
  711. return MDB2_OK;
  712. }
  713. // }}}
  714. // {{{ valid()
  715. /**
  716. * Check if the end of the result set has been reached
  717. *
  718. * @return mixed true or false on sucess, a MDB2 error on failure
  719. * @access public
  720. */
  721. function valid()
  722. {
  723. $numrows = $this->numRows();
  724. if (PEAR::isError($numrows)) {
  725. return $numrows;
  726. }
  727. return $this->rownum < ($numrows - 1);
  728. }
  729. // }}}
  730. // {{{ numRows()
  731. /**
  732. * Returns the number of rows in a result object
  733. *
  734. * @return mixed MDB2 Error Object or the number of rows
  735. * @access public
  736. */
  737. function numRows()
  738. {
  739. if ($this->result === false) {
  740. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  741. 'resultset has already been freed', __FUNCTION__);
  742. } elseif (is_null($this->result)) {
  743. return 0;
  744. }
  745. $rows = count($this->result[1]);
  746. return $rows;
  747. }
  748. }
  749. /**
  750. * MDB2 QuerySim statement driver
  751. *
  752. * @package MDB2
  753. * @category Database
  754. * @author Alan Richmond <arichmond@bigfoot.com>
  755. */
  756. class MDB2_Statement_querysim extends MDB2_Statement_Common
  757. {
  758. }
  759. ?>