MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file pgsql.php

Documentation is available at pgsql.php

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

Documentation generated on Mon, 11 Mar 2019 15:10:56 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.