PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

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