PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/pear/MDB2/Driver/pgsql.php

https://bitbucket.org/Yason/armory
PHP | 1519 lines | 986 code | 108 blank | 425 comment | 230 complexity | b989a41625d1d8b0a8a3c60f3064185f 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 |
  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: Paul Cooper <pgc@ucecom.com> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: pgsql.php,v 1.203 2008/11/29 14:04:46 afz Exp $
  47. /**
  48. * MDB2 PostGreSQL driver
  49. *
  50. * @package MDB2
  51. * @category Database
  52. * @author Paul Cooper <pgc@ucecom.com>
  53. */
  54. class MDB2_Driver_pgsql 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' => '"');
  59. // }}}
  60. // {{{ constructor
  61. /**
  62. * Constructor
  63. */
  64. function __construct()
  65. {
  66. parent::__construct();
  67. $this->phptype = 'pgsql';
  68. $this->dbsyntax = 'pgsql';
  69. $this->supported['sequences'] = true;
  70. $this->supported['indexes'] = true;
  71. $this->supported['affected_rows'] = true;
  72. $this->supported['summary_functions'] = true;
  73. $this->supported['order_by_text'] = true;
  74. $this->supported['transactions'] = true;
  75. $this->supported['savepoints'] = true;
  76. $this->supported['current_id'] = true;
  77. $this->supported['limit_queries'] = true;
  78. $this->supported['LOBs'] = true;
  79. $this->supported['replace'] = 'emulated';
  80. $this->supported['sub_selects'] = true;
  81. $this->supported['triggers'] = true;
  82. $this->supported['auto_increment'] = 'emulated';
  83. $this->supported['primary_key'] = true;
  84. $this->supported['result_introspection'] = true;
  85. $this->supported['prepared_statements'] = true;
  86. $this->supported['identifier_quoting'] = true;
  87. $this->supported['pattern_escaping'] = true;
  88. $this->supported['new_link'] = true;
  89. $this->options['DBA_username'] = false;
  90. $this->options['DBA_password'] = false;
  91. $this->options['multi_query'] = false;
  92. $this->options['disable_smart_seqname'] = true;
  93. $this->options['max_identifiers_length'] = 63;
  94. }
  95. // }}}
  96. // {{{ errorInfo()
  97. /**
  98. * This method is used to collect information about an error
  99. *
  100. * @param integer $error
  101. * @return array
  102. * @access public
  103. */
  104. function errorInfo($error = null)
  105. {
  106. // Fall back to MDB2_ERROR if there was no mapping.
  107. $error_code = MDB2_ERROR;
  108. $native_msg = '';
  109. if (is_resource($error)) {
  110. $native_msg = @pg_result_error($error);
  111. } elseif ($this->connection) {
  112. $native_msg = @pg_last_error($this->connection);
  113. if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
  114. $native_msg = 'Database connection has been lost.';
  115. $error_code = MDB2_ERROR_CONNECT_FAILED;
  116. }
  117. } else {
  118. $native_msg = @pg_last_error();
  119. }
  120. static $error_regexps;
  121. if (empty($error_regexps)) {
  122. $error_regexps = array(
  123. '/column .* (of relation .*)?does not exist/i'
  124. => MDB2_ERROR_NOSUCHFIELD,
  125. '/(relation|sequence|table).*does not exist|class .* not found/i'
  126. => MDB2_ERROR_NOSUCHTABLE,
  127. '/database .* does not exist/'
  128. => MDB2_ERROR_NOT_FOUND,
  129. '/constraint .* does not exist/'
  130. => MDB2_ERROR_NOT_FOUND,
  131. '/index .* does not exist/'
  132. => MDB2_ERROR_NOT_FOUND,
  133. '/database .* already exists/i'
  134. => MDB2_ERROR_ALREADY_EXISTS,
  135. '/relation .* already exists/i'
  136. => MDB2_ERROR_ALREADY_EXISTS,
  137. '/(divide|division) by zero$/i'
  138. => MDB2_ERROR_DIVZERO,
  139. '/pg_atoi: error in .*: can\'t parse /i'
  140. => MDB2_ERROR_INVALID_NUMBER,
  141. '/invalid input syntax for( type)? (integer|numeric)/i'
  142. => MDB2_ERROR_INVALID_NUMBER,
  143. '/value .* is out of range for type \w*int/i'
  144. => MDB2_ERROR_INVALID_NUMBER,
  145. '/integer out of range/i'
  146. => MDB2_ERROR_INVALID_NUMBER,
  147. '/value too long for type character/i'
  148. => MDB2_ERROR_INVALID,
  149. '/attribute .* not found|relation .* does not have attribute/i'
  150. => MDB2_ERROR_NOSUCHFIELD,
  151. '/column .* specified in USING clause does not exist in (left|right) table/i'
  152. => MDB2_ERROR_NOSUCHFIELD,
  153. '/parser: parse error at or near/i'
  154. => MDB2_ERROR_SYNTAX,
  155. '/syntax error at/'
  156. => MDB2_ERROR_SYNTAX,
  157. '/column reference .* is ambiguous/i'
  158. => MDB2_ERROR_SYNTAX,
  159. '/permission denied/'
  160. => MDB2_ERROR_ACCESS_VIOLATION,
  161. '/violates not-null constraint/'
  162. => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  163. '/violates [\w ]+ constraint/'
  164. => MDB2_ERROR_CONSTRAINT,
  165. '/referential integrity violation/'
  166. => MDB2_ERROR_CONSTRAINT,
  167. '/more expressions than target columns/i'
  168. => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  169. );
  170. }
  171. if (is_numeric($error) && $error < 0) {
  172. $error_code = $error;
  173. } else {
  174. foreach ($error_regexps as $regexp => $code) {
  175. if (preg_match($regexp, $native_msg)) {
  176. $error_code = $code;
  177. break;
  178. }
  179. }
  180. }
  181. return array($error_code, null, $native_msg);
  182. }
  183. // }}}
  184. // {{{ escape()
  185. /**
  186. * Quotes a string so it can be safely used in a query. It will quote
  187. * the text so it can safely be used within a query.
  188. *
  189. * @param string the input string to quote
  190. * @param bool escape wildcards
  191. *
  192. * @return string quoted string
  193. *
  194. * @access public
  195. */
  196. function escape($text, $escape_wildcards = false)
  197. {
  198. if ($escape_wildcards) {
  199. $text = $this->escapePattern($text);
  200. }
  201. $connection = $this->getConnection();
  202. if (PEAR::isError($connection)) {
  203. return $connection;
  204. }
  205. if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
  206. $text = @pg_escape_string($connection, $text);
  207. } else {
  208. $text = @pg_escape_string($text);
  209. }
  210. return $text;
  211. }
  212. // }}}
  213. // {{{ beginTransaction()
  214. /**
  215. * Start a transaction or set a savepoint.
  216. *
  217. * @param string name of a savepoint to set
  218. * @return mixed MDB2_OK on success, a MDB2 error on failure
  219. *
  220. * @access public
  221. */
  222. function beginTransaction($savepoint = null)
  223. {
  224. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  225. if (!is_null($savepoint)) {
  226. if (!$this->in_transaction) {
  227. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  228. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  229. }
  230. $query = 'SAVEPOINT '.$savepoint;
  231. return $this->_doQuery($query, true);
  232. } elseif ($this->in_transaction) {
  233. return MDB2_OK; //nothing to do
  234. }
  235. if (!$this->destructor_registered && $this->opened_persistent) {
  236. $this->destructor_registered = true;
  237. register_shutdown_function('MDB2_closeOpenTransactions');
  238. }
  239. $result =& $this->_doQuery('BEGIN', true);
  240. if (PEAR::isError($result)) {
  241. return $result;
  242. }
  243. $this->in_transaction = true;
  244. return MDB2_OK;
  245. }
  246. // }}}
  247. // {{{ commit()
  248. /**
  249. * Commit the database changes done during a transaction that is in
  250. * progress or release a savepoint. This function may only be called when
  251. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  252. * transaction is implicitly started after committing the pending changes.
  253. *
  254. * @param string name of a savepoint to release
  255. * @return mixed MDB2_OK on success, a MDB2 error on failure
  256. *
  257. * @access public
  258. */
  259. function commit($savepoint = null)
  260. {
  261. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  262. if (!$this->in_transaction) {
  263. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  264. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  265. }
  266. if (!is_null($savepoint)) {
  267. $query = 'RELEASE SAVEPOINT '.$savepoint;
  268. return $this->_doQuery($query, true);
  269. }
  270. $result =& $this->_doQuery('COMMIT', true);
  271. if (PEAR::isError($result)) {
  272. return $result;
  273. }
  274. $this->in_transaction = false;
  275. return MDB2_OK;
  276. }
  277. // }}}
  278. // {{{ rollback()
  279. /**
  280. * Cancel any database changes done during a transaction or since a specific
  281. * savepoint that is in progress. This function may only be called when
  282. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  283. * transaction is implicitly started after canceling the pending changes.
  284. *
  285. * @param string name of a savepoint to rollback to
  286. * @return mixed MDB2_OK on success, a MDB2 error on failure
  287. *
  288. * @access public
  289. */
  290. function rollback($savepoint = null)
  291. {
  292. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  293. if (!$this->in_transaction) {
  294. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  295. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  296. }
  297. if (!is_null($savepoint)) {
  298. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  299. return $this->_doQuery($query, true);
  300. }
  301. $query = 'ROLLBACK';
  302. $result =& $this->_doQuery($query, true);
  303. if (PEAR::isError($result)) {
  304. return $result;
  305. }
  306. $this->in_transaction = false;
  307. return MDB2_OK;
  308. }
  309. // }}}
  310. // {{{ function setTransactionIsolation()
  311. /**
  312. * Set the transacton isolation level.
  313. *
  314. * @param string standard isolation level
  315. * READ UNCOMMITTED (allows dirty reads)
  316. * READ COMMITTED (prevents dirty reads)
  317. * REPEATABLE READ (prevents nonrepeatable reads)
  318. * SERIALIZABLE (prevents phantom reads)
  319. * @return mixed MDB2_OK on success, a MDB2 error on failure
  320. *
  321. * @access public
  322. * @since 2.1.1
  323. */
  324. function setTransactionIsolation($isolation)
  325. {
  326. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  327. switch ($isolation) {
  328. case 'READ UNCOMMITTED':
  329. case 'READ COMMITTED':
  330. case 'REPEATABLE READ':
  331. case 'SERIALIZABLE':
  332. break;
  333. default:
  334. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  335. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  336. }
  337. $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
  338. return $this->_doQuery($query, true);
  339. }
  340. // }}}
  341. // {{{ _doConnect()
  342. /**
  343. * Do the grunt work of connecting to the database
  344. *
  345. * @return mixed connection resource on success, MDB2 Error Object on failure
  346. * @access protected
  347. */
  348. function _doConnect($username, $password, $database_name, $persistent = false)
  349. {
  350. if (!PEAR::loadExtension($this->phptype)) {
  351. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  352. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  353. }
  354. if ($database_name == '') {
  355. $database_name = 'template1';
  356. }
  357. $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
  358. $params = array('');
  359. if ($protocol == 'tcp') {
  360. if ($this->dsn['hostspec']) {
  361. $params[0].= 'host=' . $this->dsn['hostspec'];
  362. }
  363. if ($this->dsn['port']) {
  364. $params[0].= ' port=' . $this->dsn['port'];
  365. }
  366. } elseif ($protocol == 'unix') {
  367. // Allow for pg socket in non-standard locations.
  368. if ($this->dsn['socket']) {
  369. $params[0].= 'host=' . $this->dsn['socket'];
  370. }
  371. if ($this->dsn['port']) {
  372. $params[0].= ' port=' . $this->dsn['port'];
  373. }
  374. }
  375. if ($database_name) {
  376. $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
  377. }
  378. if ($username) {
  379. $params[0].= ' user=\'' . addslashes($username) . '\'';
  380. }
  381. if ($password) {
  382. $params[0].= ' password=\'' . addslashes($password) . '\'';
  383. }
  384. if (!empty($this->dsn['options'])) {
  385. $params[0].= ' options=' . $this->dsn['options'];
  386. }
  387. if (!empty($this->dsn['tty'])) {
  388. $params[0].= ' tty=' . $this->dsn['tty'];
  389. }
  390. if (!empty($this->dsn['connect_timeout'])) {
  391. $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
  392. }
  393. if (!empty($this->dsn['sslmode'])) {
  394. $params[0].= ' sslmode=' . $this->dsn['sslmode'];
  395. }
  396. if (!empty($this->dsn['service'])) {
  397. $params[0].= ' service=' . $this->dsn['service'];
  398. }
  399. if ($this->_isNewLinkSet()) {
  400. if (version_compare(phpversion(), '4.3.0', '>=')) {
  401. $params[] = PGSQL_CONNECT_FORCE_NEW;
  402. }
  403. }
  404. $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
  405. $connection = @call_user_func_array($connect_function, $params);
  406. if (!$connection) {
  407. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  408. 'unable to establish a connection', __FUNCTION__);
  409. }
  410. if (empty($this->dsn['disable_iso_date'])) {
  411. if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
  412. return $this->raiseError(null, null, null,
  413. 'Unable to set date style to iso', __FUNCTION__);
  414. }
  415. }
  416. if (!empty($this->dsn['charset'])) {
  417. $result = $this->setCharset($this->dsn['charset'], $connection);
  418. if (PEAR::isError($result)) {
  419. return $result;
  420. }
  421. }
  422. return $connection;
  423. }
  424. // }}}
  425. // {{{ connect()
  426. /**
  427. * Connect to the database
  428. *
  429. * @return true on success, MDB2 Error Object on failure
  430. * @access public
  431. */
  432. function connect()
  433. {
  434. if (is_resource($this->connection)) {
  435. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  436. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  437. && $this->connected_database_name == $this->database_name
  438. && ($this->opened_persistent == $this->options['persistent'])
  439. ) {
  440. return MDB2_OK;
  441. }
  442. $this->disconnect(false);
  443. }
  444. if ($this->database_name) {
  445. $connection = $this->_doConnect($this->dsn['username'],
  446. $this->dsn['password'],
  447. $this->database_name,
  448. $this->options['persistent']);
  449. if (PEAR::isError($connection)) {
  450. return $connection;
  451. }
  452. $this->connection = $connection;
  453. $this->connected_dsn = $this->dsn;
  454. $this->connected_database_name = $this->database_name;
  455. $this->opened_persistent = $this->options['persistent'];
  456. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  457. }
  458. return MDB2_OK;
  459. }
  460. // }}}
  461. // {{{ setCharset()
  462. /**
  463. * Set the charset on the current connection
  464. *
  465. * @param string charset
  466. * @param resource connection handle
  467. *
  468. * @return true on success, MDB2 Error Object on failure
  469. */
  470. function setCharset($charset, $connection = null)
  471. {
  472. if (is_null($connection)) {
  473. $connection = $this->getConnection();
  474. if (PEAR::isError($connection)) {
  475. return $connection;
  476. }
  477. }
  478. if (is_array($charset)) {
  479. $charset = array_shift($charset);
  480. $this->warnings[] = 'postgresql does not support setting client collation';
  481. }
  482. $result = @pg_set_client_encoding($connection, $charset);
  483. if ($result == -1) {
  484. return $this->raiseError(null, null, null,
  485. 'Unable to set client charset: '.$charset, __FUNCTION__);
  486. }
  487. return MDB2_OK;
  488. }
  489. // }}}
  490. // {{{ databaseExists()
  491. /**
  492. * check if given database name is exists?
  493. *
  494. * @param string $name name of the database that should be checked
  495. *
  496. * @return mixed true/false on success, a MDB2 error on failure
  497. * @access public
  498. */
  499. function databaseExists($name)
  500. {
  501. $res = $this->_doConnect($this->dsn['username'],
  502. $this->dsn['password'],
  503. $this->escape($name),
  504. $this->options['persistent']);
  505. if (!PEAR::isError($res)) {
  506. return true;
  507. }
  508. return false;
  509. }
  510. // }}}
  511. // {{{ disconnect()
  512. /**
  513. * Log out and disconnect from the database.
  514. *
  515. * @param boolean $force if the disconnect should be forced even if the
  516. * connection is opened persistently
  517. * @return mixed true on success, false if not connected and error
  518. * object on error
  519. * @access public
  520. */
  521. function disconnect($force = true)
  522. {
  523. if (is_resource($this->connection)) {
  524. if ($this->in_transaction) {
  525. $dsn = $this->dsn;
  526. $database_name = $this->database_name;
  527. $persistent = $this->options['persistent'];
  528. $this->dsn = $this->connected_dsn;
  529. $this->database_name = $this->connected_database_name;
  530. $this->options['persistent'] = $this->opened_persistent;
  531. $this->rollback();
  532. $this->dsn = $dsn;
  533. $this->database_name = $database_name;
  534. $this->options['persistent'] = $persistent;
  535. }
  536. if (!$this->opened_persistent || $force) {
  537. $ok = @pg_close($this->connection);
  538. if (!$ok) {
  539. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  540. null, null, null, __FUNCTION__);
  541. }
  542. }
  543. } else {
  544. return false;
  545. }
  546. return parent::disconnect($force);
  547. }
  548. // }}}
  549. // {{{ standaloneQuery()
  550. /**
  551. * execute a query as DBA
  552. *
  553. * @param string $query the SQL query
  554. * @param mixed $types array that contains the types of the columns in
  555. * the result set
  556. * @param boolean $is_manip if the query is a manipulation query
  557. * @return mixed MDB2_OK on success, a MDB2 error on failure
  558. * @access public
  559. */
  560. function &standaloneQuery($query, $types = null, $is_manip = false)
  561. {
  562. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  563. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  564. $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
  565. if (PEAR::isError($connection)) {
  566. return $connection;
  567. }
  568. $offset = $this->offset;
  569. $limit = $this->limit;
  570. $this->offset = $this->limit = 0;
  571. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  572. $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  573. if (!PEAR::isError($result)) {
  574. if ($is_manip) {
  575. $result = $this->_affectedRows($connection, $result);
  576. } else {
  577. $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
  578. }
  579. }
  580. @pg_close($connection);
  581. return $result;
  582. }
  583. // }}}
  584. // {{{ _doQuery()
  585. /**
  586. * Execute a query
  587. * @param string $query query
  588. * @param boolean $is_manip if the query is a manipulation query
  589. * @param resource $connection
  590. * @param string $database_name
  591. * @return result or error object
  592. * @access protected
  593. */
  594. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  595. {
  596. $this->last_query = $query;
  597. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  598. if ($result) {
  599. if (PEAR::isError($result)) {
  600. return $result;
  601. }
  602. $query = $result;
  603. }
  604. if ($this->options['disable_query']) {
  605. $result = $is_manip ? 0 : null;
  606. return $result;
  607. }
  608. if (is_null($connection)) {
  609. $connection = $this->getConnection();
  610. if (PEAR::isError($connection)) {
  611. return $connection;
  612. }
  613. }
  614. $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
  615. $result = @$function($connection, $query);
  616. if (!$result) {
  617. $err =& $this->raiseError(null, null, null,
  618. 'Could not execute statement', __FUNCTION__);
  619. return $err;
  620. } elseif ($this->options['multi_query']) {
  621. if (!($result = @pg_get_result($connection))) {
  622. $err =& $this->raiseError(null, null, null,
  623. 'Could not get the first result from a multi query', __FUNCTION__);
  624. return $err;
  625. }
  626. }
  627. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  628. return $result;
  629. }
  630. // }}}
  631. // {{{ _affectedRows()
  632. /**
  633. * Returns the number of rows affected
  634. *
  635. * @param resource $result
  636. * @param resource $connection
  637. * @return mixed MDB2 Error Object or the number of rows affected
  638. * @access private
  639. */
  640. function _affectedRows($connection, $result = null)
  641. {
  642. if (is_null($connection)) {
  643. $connection = $this->getConnection();
  644. if (PEAR::isError($connection)) {
  645. return $connection;
  646. }
  647. }
  648. return @pg_affected_rows($result);
  649. }
  650. // }}}
  651. // {{{ _modifyQuery()
  652. /**
  653. * Changes a query string for various DBMS specific reasons
  654. *
  655. * @param string $query query to modify
  656. * @param boolean $is_manip if it is a DML query
  657. * @param integer $limit limit the number of rows
  658. * @param integer $offset start reading from given offset
  659. * @return string modified query
  660. * @access protected
  661. */
  662. function _modifyQuery($query, $is_manip, $limit, $offset)
  663. {
  664. if ($limit > 0
  665. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  666. ) {
  667. $query = rtrim($query);
  668. if (substr($query, -1) == ';') {
  669. $query = substr($query, 0, -1);
  670. }
  671. if ($is_manip) {
  672. $query = $this->_modifyManipQuery($query, $limit);
  673. } else {
  674. $query.= " LIMIT $limit OFFSET $offset";
  675. }
  676. }
  677. return $query;
  678. }
  679. // }}}
  680. // {{{ _modifyManipQuery()
  681. /**
  682. * Changes a manip query string for various DBMS specific reasons
  683. *
  684. * @param string $query query to modify
  685. * @param integer $limit limit the number of rows
  686. * @return string modified query
  687. * @access protected
  688. */
  689. function _modifyManipQuery($query, $limit)
  690. {
  691. $pos = strpos(strtolower($query), 'where');
  692. $where = $pos ? substr($query, $pos) : '';
  693. $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
  694. $from_clause = '([\w\.]+)';
  695. $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
  696. $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
  697. $matches = preg_match($pattern, $query, $match);
  698. if ($matches) {
  699. $manip = $match[1];
  700. $from = $match[2];
  701. $what = (count($matches) == 6) ? $match[5] : $match[3];
  702. return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
  703. }
  704. //return error?
  705. return $query;
  706. }
  707. // }}}
  708. // {{{ getServerVersion()
  709. /**
  710. * return version information about the server
  711. *
  712. * @param bool $native determines if the raw version string should be returned
  713. * @return mixed array/string with version information or MDB2 error object
  714. * @access public
  715. */
  716. function getServerVersion($native = false)
  717. {
  718. $query = 'SHOW SERVER_VERSION';
  719. if ($this->connected_server_info) {
  720. $server_info = $this->connected_server_info;
  721. } else {
  722. $server_info = $this->queryOne($query, 'text');
  723. if (PEAR::isError($server_info)) {
  724. return $server_info;
  725. }
  726. }
  727. // cache server_info
  728. $this->connected_server_info = $server_info;
  729. if (!$native && !PEAR::isError($server_info)) {
  730. $tmp = explode('.', $server_info, 3);
  731. if (empty($tmp[2])
  732. && isset($tmp[1])
  733. && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
  734. ) {
  735. $server_info = array(
  736. 'major' => $tmp[0],
  737. 'minor' => $tmp2[1],
  738. 'patch' => null,
  739. 'extra' => $tmp2[2],
  740. 'native' => $server_info,
  741. );
  742. } else {
  743. $server_info = array(
  744. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  745. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  746. 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  747. 'extra' => null,
  748. 'native' => $server_info,
  749. );
  750. }
  751. }
  752. return $server_info;
  753. }
  754. // }}}
  755. // {{{ prepare()
  756. /**
  757. * Prepares a query for multiple execution with execute().
  758. * With some database backends, this is emulated.
  759. * prepare() requires a generic query as string like
  760. * 'INSERT INTO numbers VALUES(?,?)' or
  761. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  762. * The ? and :name and are placeholders which can be set using
  763. * bindParam() and the query can be sent off using the execute() method.
  764. * The allowed format for :name can be set with the 'bindname_format' option.
  765. *
  766. * @param string $query the query to prepare
  767. * @param mixed $types array that contains the types of the placeholders
  768. * @param mixed $result_types array that contains the types of the columns in
  769. * the result set or MDB2_PREPARE_RESULT, if set to
  770. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  771. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  772. * @return mixed resource handle for the prepared query on success, a MDB2
  773. * error on failure
  774. * @access public
  775. * @see bindParam, execute
  776. */
  777. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  778. {
  779. if ($this->options['emulate_prepared']) {
  780. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  781. return $obj;
  782. }
  783. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  784. $offset = $this->offset;
  785. $limit = $this->limit;
  786. $this->offset = $this->limit = 0;
  787. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  788. if ($result) {
  789. if (PEAR::isError($result)) {
  790. return $result;
  791. }
  792. $query = $result;
  793. }
  794. $pgtypes = function_exists('pg_prepare') ? false : array();
  795. if ($pgtypes !== false && !empty($types)) {
  796. $this->loadModule('Datatype', null, true);
  797. }
  798. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  799. $placeholder_type_guess = $placeholder_type = null;
  800. $question = '?';
  801. $colon = ':';
  802. $positions = array();
  803. $position = $parameter = 0;
  804. while ($position < strlen($query)) {
  805. $q_position = strpos($query, $question, $position);
  806. $c_position = strpos($query, $colon, $position);
  807. //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
  808. $doublecolon_position = strpos($query, '::', $position);
  809. if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
  810. $c_position = strpos($query, $colon, $position+2);
  811. }
  812. if ($q_position && $c_position) {
  813. $p_position = min($q_position, $c_position);
  814. } elseif ($q_position) {
  815. $p_position = $q_position;
  816. } elseif ($c_position) {
  817. $p_position = $c_position;
  818. } else {
  819. break;
  820. }
  821. if (is_null($placeholder_type)) {
  822. $placeholder_type_guess = $query[$p_position];
  823. }
  824. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  825. if (PEAR::isError($new_pos)) {
  826. return $new_pos;
  827. }
  828. if ($new_pos != $position) {
  829. $position = $new_pos;
  830. continue; //evaluate again starting from the new position
  831. }
  832. if ($query[$position] == $placeholder_type_guess) {
  833. if (is_null($placeholder_type)) {
  834. $placeholder_type = $query[$p_position];
  835. $question = $colon = $placeholder_type;
  836. if (!empty($types) && is_array($types)) {
  837. if ($placeholder_type == ':') {
  838. } else {
  839. $types = array_values($types);
  840. }
  841. }
  842. }
  843. if ($placeholder_type_guess == '?') {
  844. $length = 1;
  845. $name = $parameter;
  846. } else {
  847. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  848. $param = preg_replace($regexp, '\\1', $query);
  849. if ($param === '') {
  850. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  851. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  852. return $err;
  853. }
  854. $length = strlen($param) + 1;
  855. $name = $param;
  856. }
  857. if ($pgtypes !== false) {
  858. if (is_array($types) && array_key_exists($name, $types)) {
  859. $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
  860. } elseif (is_array($types) && array_key_exists($parameter, $types)) {
  861. $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
  862. } else {
  863. $pgtypes[] = 'text';
  864. }
  865. }
  866. if (($key_parameter = array_search($name, $positions))) {
  867. $next_parameter = 1;
  868. foreach ($positions as $key => $value) {
  869. if ($key_parameter == $key) {
  870. break;
  871. }
  872. ++$next_parameter;
  873. }
  874. } else {
  875. ++$parameter;
  876. $next_parameter = $parameter;
  877. $positions[] = $name;
  878. }
  879. $query = substr_replace($query, '$'.$parameter, $position, $length);
  880. $position = $p_position + strlen($parameter);
  881. } else {
  882. $position = $p_position;
  883. }
  884. }
  885. $connection = $this->getConnection();
  886. if (PEAR::isError($connection)) {
  887. return $connection;
  888. }
  889. static $prep_statement_counter = 1;
  890. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
  891. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  892. if ($pgtypes === false) {
  893. $result = @pg_prepare($connection, $statement_name, $query);
  894. if (!$result) {
  895. $err =& $this->raiseError(null, null, null,
  896. 'Unable to create prepared statement handle', __FUNCTION__);
  897. return $err;
  898. }
  899. } else {
  900. $types_string = '';
  901. if ($pgtypes) {
  902. $types_string = ' ('.implode(', ', $pgtypes).') ';
  903. }
  904. $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  905. $statement =& $this->_doQuery($query, true, $connection);
  906. if (PEAR::isError($statement)) {
  907. return $statement;
  908. }
  909. }
  910. $class_name = 'MDB2_Statement_'.$this->phptype;
  911. $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  912. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  913. return $obj;
  914. }
  915. // }}}
  916. // {{{ function getSequenceName($sqn)
  917. /**
  918. * adds sequence name formatting to a sequence name
  919. *
  920. * @param string name of the sequence
  921. *
  922. * @return string formatted sequence name
  923. *
  924. * @access public
  925. */
  926. function getSequenceName($sqn)
  927. {
  928. if (false === $this->options['disable_smart_seqname']) {
  929. if (strpos($sqn, '_') !== false) {
  930. list($table, $field) = explode('_', $sqn, 2);
  931. }
  932. $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
  933. if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
  934. $order_by = ' a.attnum';
  935. $schema_clause = ' AND n.nspname=current_schema()';
  936. } else {
  937. $schemas = explode(',', $schema_list);
  938. $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
  939. $counter = 1;
  940. $order_by = ' CASE ';
  941. foreach ($schemas as $schema) {
  942. $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
  943. }
  944. $order_by .= ' ELSE '.$counter.' END, a.attnum';
  945. }
  946. $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
  947. FROM pg_attrdef d
  948. WHERE d.adrelid = a.attrelid
  949. AND d.adnum = a.attnum
  950. AND a.atthasdef
  951. ) FROM 'nextval[^'']*''([^'']*)')
  952. FROM pg_attribute a
  953. LEFT JOIN pg_class c ON c.oid = a.attrelid
  954. LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
  955. LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
  956. WHERE (c.relname = ".$this->quote($sqn, 'text');
  957. if (!empty($field)) {
  958. $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
  959. }
  960. $query .= " )"
  961. .$schema_clause."
  962. AND NOT a.attisdropped
  963. AND a.attnum > 0
  964. AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
  965. ORDER BY ".$order_by;
  966. $seqname = $this->queryOne($query);
  967. if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
  968. return $seqname;
  969. }
  970. }
  971. return parent::getSequenceName($sqn);
  972. }
  973. // }}}
  974. // {{{ nextID()
  975. /**
  976. * Returns the next free id of a sequence
  977. *
  978. * @param string $seq_name name of the sequence
  979. * @param boolean $ondemand when true the sequence is
  980. * automatic created, if it
  981. * not exists
  982. * @return mixed MDB2 Error Object or id
  983. * @access public
  984. */
  985. function nextID($seq_name, $ondemand = true)
  986. {
  987. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  988. $query = "SELECT NEXTVAL('$sequence_name')";
  989. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  990. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  991. $result = $this->queryOne($query, 'integer');
  992. $this->popExpect();
  993. $this->popErrorHandling();
  994. if (PEAR::isError($result)) {
  995. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  996. $this->loadModule('Manager', null, true);
  997. $result = $this->manager->createSequence($seq_name);
  998. if (PEAR::isError($result)) {
  999. return $this->raiseError($result, null, null,
  1000. 'on demand sequence could not be created', __FUNCTION__);
  1001. }
  1002. return $this->nextId($seq_name, false);
  1003. }
  1004. }
  1005. return $result;
  1006. }
  1007. // }}}
  1008. // {{{ lastInsertID()
  1009. /**
  1010. * Returns the autoincrement ID if supported or $id or fetches the current
  1011. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1012. *
  1013. * @param string $table name of the table into which a new row was inserted
  1014. * @param string $field name of the field into which a new row was inserted
  1015. * @return mixed MDB2 Error Object or id
  1016. * @access public
  1017. */
  1018. function lastInsertID($table = null, $field = null)
  1019. {
  1020. if (empty($table) && empty($field)) {
  1021. return $this->queryOne('SELECT lastval()', 'integer');
  1022. }
  1023. $seq = $table.(empty($field) ? '' : '_'.$field);
  1024. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
  1025. return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
  1026. }
  1027. // }}}
  1028. // {{{ currID()
  1029. /**
  1030. * Returns the current id of a sequence
  1031. *
  1032. * @param string $seq_name name of the sequence
  1033. * @return mixed MDB2 Error Object or id
  1034. * @access public
  1035. */
  1036. function currID($seq_name)
  1037. {
  1038. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1039. return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
  1040. }
  1041. }
  1042. /**
  1043. * MDB2 PostGreSQL result driver
  1044. *
  1045. * @package MDB2
  1046. * @category Database
  1047. * @author Paul Cooper <pgc@ucecom.com>
  1048. */
  1049. class MDB2_Result_pgsql extends MDB2_Result_Common
  1050. {
  1051. // }}}
  1052. // {{{ fetchRow()
  1053. /**
  1054. * Fetch a row and insert the data into an existing array.
  1055. *
  1056. * @param int $fetchmode how the array data should be indexed
  1057. * @param int $rownum number of the row where the data can be found
  1058. * @return int data array on success, a MDB2 error on failure
  1059. * @access public
  1060. */
  1061. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1062. {
  1063. if (!is_null($rownum)) {
  1064. $seek = $this->seek($rownum);
  1065. if (PEAR::isError($seek)) {
  1066. return $seek;
  1067. }
  1068. }
  1069. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1070. $fetchmode = $this->db->fetchmode;
  1071. }
  1072. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1073. $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
  1074. if (is_array($row)
  1075. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1076. ) {
  1077. $row = array_change_key_case($row, $this->db->options['field_case']);
  1078. }
  1079. } else {
  1080. $row = @pg_fetch_row($this->result);
  1081. }
  1082. if (!$row) {
  1083. if ($this->result === false) {
  1084. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1085. 'resultset has already been freed', __FUNCTION__);
  1086. return $err;
  1087. }
  1088. $null = null;
  1089. return $null;
  1090. }
  1091. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1092. $rtrim = false;
  1093. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1094. if (empty($this->types)) {
  1095. $mode += MDB2_PORTABILITY_RTRIM;
  1096. } else {
  1097. $rtrim = true;
  1098. }
  1099. }
  1100. if ($mode) {
  1101. $this->db->_fixResultArrayValues($row, $mode);
  1102. }
  1103. if (!empty($this->types)) {
  1104. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1105. }
  1106. if (!empty($this->values)) {
  1107. $this->_assignBindColumns($row);
  1108. }
  1109. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1110. $object_class = $this->db->options['fetch_class'];
  1111. if ($object_class == 'stdClass') {
  1112. $row = (object) $row;
  1113. } else {
  1114. $row = &new $object_class($row);
  1115. }
  1116. }
  1117. ++$this->rownum;
  1118. return $row;
  1119. }
  1120. // }}}
  1121. // {{{ _getColumnNames()
  1122. /**
  1123. * Retrieve the names of columns returned by the DBMS in a query result.
  1124. *
  1125. * @return mixed Array variable that holds the names of columns as keys
  1126. * or an MDB2 error on failure.
  1127. * Some DBMS may not return any columns when the result set
  1128. * does not contain any rows.
  1129. * @access private
  1130. */
  1131. function _getColumnNames()
  1132. {
  1133. $columns = array();
  1134. $numcols = $this->numCols();
  1135. if (PEAR::isError($numcols)) {
  1136. return $numcols;
  1137. }
  1138. for ($column = 0; $column < $numcols; $column++) {
  1139. $column_name = @pg_field_name($this->result, $column);
  1140. $columns[$column_name] = $column;
  1141. }
  1142. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1143. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1144. }
  1145. return $columns;
  1146. }
  1147. // }}}
  1148. // {{{ numCols()
  1149. /**
  1150. * Count the number of columns returned by the DBMS in a query result.
  1151. *
  1152. * @access public
  1153. * @return mixed integer value with the number of columns, a MDB2 error
  1154. * on failure
  1155. */
  1156. function numCols()
  1157. {
  1158. $cols = @pg_num_fields($this->result);
  1159. if (is_null($cols)) {
  1160. if ($this->result === false) {
  1161. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1162. 'resultset has already been freed', __FUNCTION__);
  1163. } elseif (is_null($this->result)) {
  1164. return count($this->types);
  1165. }
  1166. return $this->db->raiseError(null, null, null,
  1167. 'Could not get column count', __FUNCTION__);
  1168. }
  1169. return $cols;
  1170. }
  1171. // }}}
  1172. // {{{ nextResult()
  1173. /**
  1174. * Move the internal result pointer to the next available result
  1175. *
  1176. * @return true on success, false if there is no more result set or an error object on failure
  1177. * @access public
  1178. */
  1179. function nextResult()
  1180. {
  1181. $connection = $this->db->getConnection();
  1182. if (PEAR::isError($connection)) {
  1183. return $connection;
  1184. }
  1185. if (!($this->result = @pg_get_result($connection))) {
  1186. return false;
  1187. }
  1188. return MDB2_OK;
  1189. }
  1190. // }}}
  1191. // {{{ free()
  1192. /**
  1193. * Free the internal resources associated with result.
  1194. *
  1195. * @return boolean true on success, false if result is invalid
  1196. * @access public
  1197. */
  1198. function free()
  1199. {
  1200. if (is_resource($this->result) && $this->db->connection) {
  1201. $free = @pg_free_result($this->result);
  1202. if ($free === false) {
  1203. return $this->db->raiseError(null, null, null,
  1204. 'Could not free result', __FUNCTION__);
  1205. }
  1206. }
  1207. $this->result = false;
  1208. return MDB2_OK;
  1209. }
  1210. }
  1211. /**
  1212. * MDB2 PostGreSQL buffered result driver
  1213. *
  1214. * @package MDB2
  1215. * @category Database
  1216. * @author Paul Cooper <pgc@ucecom.com>
  1217. */
  1218. class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
  1219. {
  1220. // {{{ seek()
  1221. /**
  1222. * Seek to a specific row in a result set
  1223. *
  1224. * @param int $rownum number of the row where the data can be found
  1225. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1226. * @access public
  1227. */
  1228. function seek($rownum = 0)
  1229. {
  1230. if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
  1231. if ($this->result === false) {
  1232. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1233. 'resultset has already been freed', __FUNCTION__);
  1234. } elseif (is_null($this->result)) {
  1235. return MDB2_OK;
  1236. }
  1237. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1238. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1239. }
  1240. $this->rownum = $rownum - 1;
  1241. return MDB2_OK;
  1242. }
  1243. // }}}
  1244. // {{{ valid()
  1245. /**
  1246. * Check if the end of the result set has been reached
  1247. *
  1248. * @return mixed true or false on sucess, a MDB2 error on failure
  1249. * @ac…

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