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

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