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-2004 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.88 2005/12/29 18:25:07 lsmith 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 $escape_quotes = "\\";
  59.  
  60.     // }}}
  61.     // {{{ constructor
  62.  
  63.     /**
  64.      * Constructor
  65.      */
  66.     function __construct()
  67.     {
  68.         parent::__construct();
  69.  
  70.         $this->phptype 'pgsql';
  71.         $this->dbsyntax 'pgsql';
  72.  
  73.         $this->supported['sequences'= true;
  74.         $this->supported['indexes'= true;
  75.         $this->supported['affected_rows'= true;
  76.         $this->supported['summary_functions'= true;
  77.         $this->supported['order_by_text'= true;
  78.         $this->supported['transactions'= true;
  79.         $this->supported['current_id'= true;
  80.         $this->supported['limit_queries'= true;
  81.         $this->supported['LOBs'= true;
  82.         $this->supported['replace''emulated';
  83.         $this->supported['sub_selects'= true;
  84.         $this->supported['auto_increment''emulated';
  85.         $this->supported['primary_key'= true;
  86.     }
  87.  
  88.     // }}}
  89.     // {{{ errorInfo()
  90.  
  91.     /**
  92.      * This method is used to collect information about an error
  93.      *
  94.      * @param integer $error 
  95.      * @return array 
  96.      * @access public
  97.      */
  98.     function errorInfo($error = null)
  99.     {
  100.         // Fall back to MDB2_ERROR if there was no mapping.
  101.         $error_code = MDB2_ERROR;
  102.  
  103.         $native_msg '';
  104.         if (is_resource($error)) {
  105.             $native_msg @pg_result_error($error);
  106.         elseif ($this->connection{
  107.             $native_msg @pg_last_error($this->connection);
  108.             if (!$native_msg && @pg_connection_status($this->connection=== PGSQL_CONNECTION_BAD{
  109.                 $native_msg 'Database connection has been lost.';
  110.                 $error_code = MDB2_ERROR_CONNECT_FAILED;
  111.             }
  112.         }
  113.  
  114.         static $error_regexps;
  115.         if (empty($error_regexps)) {
  116.             $error_regexps = array(
  117.                 '/column .* (of relation .*)?does not exist/i'
  118.                     => MDB2_ERROR_NOSUCHFIELD,
  119.                 '/(relation|sequence|table).*does not exist|class .* not found/i'
  120.                     => MDB2_ERROR_NOSUCHTABLE,
  121.                 '/index .* does not exist/'
  122.                     => MDB2_ERROR_NOT_FOUND,
  123.                 '/relation .* already exists/i'
  124.                     => MDB2_ERROR_ALREADY_EXISTS,
  125.                 '/(divide|division) by zero$/i'
  126.                     => MDB2_ERROR_DIVZERO,
  127.                 '/pg_atoi: error in .*: can\'t parse /i'
  128.                     => MDB2_ERROR_INVALID_NUMBER,
  129.                 '/invalid input syntax for( type)? (integer|numeric)/i'
  130.                     => MDB2_ERROR_INVALID_NUMBER,
  131.                 '/value .* is out of range for type \w*int/i'
  132.                     => MDB2_ERROR_INVALID_NUMBER,
  133.                 '/integer out of range/i'
  134.                     => MDB2_ERROR_INVALID_NUMBER,
  135.                 '/value too long for type character/i'
  136.                     => MDB2_ERROR_INVALID,
  137.                 '/attribute .* not found|relation .* does not have attribute/i'
  138.                     => MDB2_ERROR_NOSUCHFIELD,
  139.                 '/column .* specified in USING clause does not exist in (left|right) table/i'
  140.                     => MDB2_ERROR_NOSUCHFIELD,
  141.                 '/parser: parse error at or near/i'
  142.                     => MDB2_ERROR_SYNTAX,
  143.                 '/syntax error at/'
  144.                     => MDB2_ERROR_SYNTAX,
  145.                 '/column reference .* is ambiguous/i'
  146.                     => MDB2_ERROR_SYNTAX,
  147.                 '/permission denied/'
  148.                     => MDB2_ERROR_ACCESS_VIOLATION,
  149.                 '/violates not-null constraint/'
  150.                     => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  151.                 '/violates [\w ]+ constraint/'
  152.                     => MDB2_ERROR_CONSTRAINT,
  153.                 '/referential integrity violation/'
  154.                     => MDB2_ERROR_CONSTRAINT,
  155.                 '/more expressions than target columns/i'
  156.                     => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  157.             );
  158.         }
  159.         foreach ($error_regexps as $regexp => $code{
  160.             if (preg_match($regexp$native_msg)) {
  161.                 $error_code $code;
  162.                 break;
  163.             }
  164.         }
  165.  
  166.         return array($error_codenull$native_msg);
  167.     }
  168.  
  169.     // }}}
  170.     // {{{ beginTransaction()
  171.  
  172.     /**
  173.      * Start a transaction.
  174.      *
  175.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  176.      * @access public
  177.      */
  178.     function beginTransaction()
  179.     {
  180.         $this->debug('starting transaction''beginTransaction');
  181.         if ($this->in_transaction{
  182.             return MDB2_OK;  //nothing to do
  183.         }
  184.         if (!$this->destructor_registered && $this->opened_persistent{
  185.             $this->destructor_registered = true;
  186.             register_shutdown_function('MDB2_closeOpenTransactions');
  187.         }
  188.         $result $this->_doQuery('BEGIN'true);
  189.         if (PEAR::isError($result)) {
  190.             return $result;
  191.         }
  192.         $this->in_transaction = true;
  193.         return MDB2_OK;
  194.     }
  195.  
  196.     // }}}
  197.     // {{{ commit()
  198.  
  199.     /**
  200.      * Commit the database changes done during a transaction that is in
  201.      * progress.
  202.      *
  203.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  204.      * @access public
  205.      */
  206.     function commit()
  207.     {
  208.         $this->debug('commit transaction''commit');
  209.         if (!$this->in_transaction{
  210.             return $this->raiseError(MDB2_ERRORnullnull,
  211.                 'commit: transaction changes are being auto committed');
  212.         }
  213.         $result $this->_doQuery('COMMIT'true);
  214.         if (PEAR::isError($result)) {
  215.             return $result;
  216.         }
  217.         $this->in_transaction = false;
  218.         return MDB2_OK;
  219.     }
  220.  
  221.     // }}}
  222.     // {{{ rollback()
  223.  
  224.     /**
  225.      * Cancel any database changes done during a transaction that is in
  226.      * progress.
  227.      *
  228.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  229.      * @access public
  230.      */
  231.     function rollback()
  232.     {
  233.         $this->debug('rolling back transaction''rollback');
  234.         if (!$this->in_transaction{
  235.             return $this->raiseError(MDB2_ERRORnullnull,
  236.                 'rollback: transactions can not be rolled back when changes are auto committed');
  237.         }
  238.         $result $this->_doQuery('ROLLBACK'true);
  239.         if (PEAR::isError($result)) {
  240.             return $result;
  241.         }
  242.         $this->in_transaction = false;
  243.         return MDB2_OK;
  244.     }
  245.  
  246.     // }}}
  247.     // {{{ _doConnect()
  248.  
  249.     /**
  250.      * Does the grunt work of connecting to the database
  251.      *
  252.      * @return mixed connection resource on success, MDB2 Error Object on failure
  253.      * @access protected
  254.      ***/
  255.     function _doConnect($database_name$persistent = false)
  256.     {
  257.         if ($database_name == ''{
  258.             $database_name 'template1';
  259.         }
  260.  
  261.         $protocol $this->dsn['protocol'$this->dsn['protocol''tcp';
  262.  
  263.         $params = array('');
  264.         if ($protocol == 'tcp'{
  265.             if ($this->dsn['hostspec']{
  266.                 $params[0].= 'host=' $this->dsn['hostspec'];
  267.             }
  268.             if ($this->dsn['port']{
  269.                 $params[0].= ' port=' $this->dsn['port'];
  270.             }
  271.         elseif ($protocol == 'unix'{
  272.             // Allow for pg socket in non-standard locations.
  273.             if ($this->dsn['socket']{
  274.                 $params[0].= 'host=' $this->dsn['socket'];
  275.             }
  276.             if ($this->dsn['port']{
  277.                 $params[0].= ' port=' $this->dsn['port'];
  278.             }
  279.         }
  280.         if ($database_name{
  281.             $params[0].= ' dbname=\'' addslashes($database_name'\'';
  282.         }
  283.         if ($this->dsn['username']{
  284.             $params[0].= ' user=\'' addslashes($this->dsn['username']'\'';
  285.         }
  286.         if ($this->dsn['password']{
  287.             $params[0].= ' password=\'' addslashes($this->dsn['password']'\'';
  288.         }
  289.         if (!empty($this->dsn['options'])) {
  290.             $params[0].= ' options=' $this->dsn['options'];
  291.         }
  292.         if (!empty($this->dsn['tty'])) {
  293.             $params[0].= ' tty=' $this->dsn['tty'];
  294.         }
  295.         if (!empty($this->dsn['connect_timeout'])) {
  296.             $params[0].= ' connect_timeout=' $this->dsn['connect_timeout'];
  297.         }
  298.         if (!empty($this->dsn['sslmode'])) {
  299.             $params[0].= ' sslmode=' $this->dsn['sslmode'];
  300.         }
  301.         if (!empty($this->dsn['service'])) {
  302.             $params[0].= ' service=' $this->dsn['service'];
  303.         }
  304.  
  305.         if (isset($this->dsn['new_link'])
  306.             && ($this->dsn['new_link'== 'true' || $this->dsn['new_link'=== true))
  307.         {
  308.             if (version_compare(phpversion()'4.3.0''>=')) {
  309.                 $params[= PGSQL_CONNECT_FORCE_NEW;
  310.             }
  311.         }
  312.  
  313.         $connect_function $persistent 'pg_pconnect' 'pg_connect';
  314.  
  315.         putenv('PGDATESTYLE=ISO');
  316.  
  317.         @ini_set('track_errors'true);
  318.         $php_errormsg '';
  319.         $connection @call_user_func_array($connect_function$params);
  320.         @ini_restore('track_errors');
  321.         if (!$connection{
  322.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED,
  323.                 nullnullstrip_tags($php_errormsg));
  324.         }
  325.         return $connection;
  326.     }
  327.  
  328.     // }}}
  329.     // {{{ connect()
  330.  
  331.     /**
  332.      * Connect to the database
  333.      *
  334.      * @return true on success, MDB2 Error Object on failure
  335.      * @access public
  336.      ***/
  337.     function connect()
  338.     {
  339.         if (is_resource($this->connection)) {
  340.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0
  341.                 && $this->connected_database_name == $this->database_name
  342.                 && ($this->opened_persistent == $this->options['persistent'])
  343.             {
  344.                 return MDB2_OK;
  345.             }
  346.             $this->disconnect(false);
  347.         }
  348.  
  349.         if (!PEAR::loadExtension($this->phptype)) {
  350.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  351.                 'connect: extension '.$this->phptype.' is not compiled into PHP');
  352.         }
  353.  
  354.         if ($this->database_name{
  355.             $connection $this->_doConnect($this->database_name$this->options['persistent']);
  356.             if (PEAR::isError($connection)) {
  357.                 return $connection;
  358.             }
  359.             $this->connection $connection;
  360.             $this->connected_dsn $this->dsn;
  361.             $this->connected_database_name $this->database_name;
  362.             $this->opened_persistent $this->options['persistent'];
  363.             $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  364.         }
  365.         return MDB2_OK;
  366.     }
  367.  
  368.     // }}}
  369.     // {{{ disconnect()
  370.  
  371.     /**
  372.      * Log out and disconnect from the database.
  373.      *
  374.      * @return mixed true on success, false if not connected and error
  375.      *                 object on error
  376.      * @access public
  377.      */
  378.     function disconnect($force = true)
  379.     {
  380.         if (is_resource($this->connection)) {
  381.             if ($this->in_transaction{
  382.                 $this->rollback();
  383.             }
  384.             if (!$this->opened_persistent || $force{
  385.                 @pg_close($this->connection);
  386.             }
  387.             $this->connection = 0;
  388.             $this->in_transaction = false;
  389.         }
  390.         return MDB2_OK;
  391.     }
  392.  
  393.     // }}}
  394.     // {{{ standaloneQuery()
  395.  
  396.    /**
  397.      * execute a query as DBA
  398.      *
  399.      * @param string $query the SQL query
  400.      * @param mixed   $types  array that contains the types of the columns in
  401.      *                         the result set
  402.      * @param boolean $is_manip  if the query is a manipulation query
  403.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  404.      * @access public
  405.      */
  406.     function &standaloneQuery($query$types = null$is_manip = false)
  407.     {
  408.         $connection $this->_doConnect('template1'false);
  409.         if (PEAR::isError($connection)) {
  410.             $err =$this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  411.                 'Cannot connect to template1');
  412.             return $err;
  413.         }
  414.  
  415.         $offset $this->row_offset;
  416.         $limit $this->row_limit;
  417.         $this->row_offset $this->row_limit = 0;
  418.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  419.  
  420.         $result $this->_doQuery($query$is_manip$connectionfalse);
  421.         @pg_close($connection);
  422.         if (PEAR::isError($result)) {
  423.             return $result;
  424.         }
  425.  
  426.         if ($is_manip{
  427.             $affected_rows =  $this->_affectedRows($connection$result);
  428.             return $affected_rows;
  429.         }
  430.         $result =$this->_wrapResult($result$typestruefalse$limit$offset);
  431.         return $result;
  432.     }
  433.  
  434.     // }}}
  435.     // {{{ _doQuery()
  436.  
  437.     /**
  438.      * Execute a query
  439.      * @param string $query  query
  440.      * @param boolean $is_manip  if the query is a manipulation query
  441.      * @param resource $connection 
  442.      * @param string $database_name 
  443.      * @return result or error object
  444.      * @access protected
  445.      */
  446.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  447.     {
  448.         $this->last_query $query;
  449.         $this->debug($query'query');
  450.         if ($this->options['disable_query']{
  451.             if ($is_manip{
  452.                 return 0;
  453.             }
  454.             return null;
  455.         }
  456.  
  457.         if (is_null($connection)) {
  458.             $connection $this->getConnection();
  459.             if (PEAR::isError($connection)) {
  460.                 return $connection;
  461.             }
  462.         }
  463.  
  464.         $result @pg_query($connection$query);
  465.         if (!$result{
  466.             return $this->raiseError();
  467.         }
  468.  
  469.         return $result;
  470.     }
  471.  
  472.     // }}}
  473.     // {{{ _affectedRows()
  474.  
  475.     /**
  476.      * returns the number of rows affected
  477.      *
  478.      * @param resource $result 
  479.      * @param resource $connection 
  480.      * @return mixed MDB2 Error Object or the number of rows affected
  481.      * @access private
  482.      */
  483.     function _affectedRows($connection$result = null)
  484.     {
  485.         if (is_null($connection)) {
  486.             $connection $this->getConnection();
  487.             if (PEAR::isError($connection)) {
  488.                 return $connection;
  489.             }
  490.         }
  491.         return @pg_affected_rows($result);
  492.     }
  493.  
  494.     // }}}
  495.     // {{{ _modifyQuery()
  496.  
  497.     /**
  498.      * Changes a query string for various DBMS specific reasons
  499.      *
  500.      * @param string $query  query to modify
  501.      * @return the new (modified) query
  502.      * @access protected
  503.      */
  504.     function _modifyQuery($query$is_manip$limit$offset)
  505.     {
  506.         if ($limit > 0
  507.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  508.         {
  509.             $query rtrim($query);
  510.             if (substr($query-1== ';'{
  511.                 $query substr($query0-1);
  512.             }
  513.             if ($is_manip{
  514.                 $manip preg_replace('/^(DELETE FROM|UPDATE).*$/''\\1'$query);
  515.                 $from $match[2];
  516.                 $where $match[3];
  517.                 $query $manip.' '.$from.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
  518.             else {
  519.                 $query.= " LIMIT $limit OFFSET $offset";
  520.             }
  521.         }
  522.         return $query;
  523.     }
  524.  
  525.     // }}}
  526.     // {{{ getServerVersion()
  527.  
  528.     /**
  529.      * return version information about the server
  530.      *
  531.      * @param string     $native  determines if the raw version string should be returned
  532.      * @return mixed array with versoin information or row string
  533.      * @access public
  534.      */
  535.     function getServerVersion($native = false)
  536.     {
  537.         $query 'SHOW SERVER_VERSION';
  538.         $server_info $this->queryOne($query'text');
  539.         if (!$native && !PEAR::isError($server_info)) {
  540.             $tmp explode('.'$server_info);
  541.             if (!array_key_exists(2$tmp)) {
  542.                 preg_match('/(\d+)(.*)/'@$tmp[1]$tmp2);
  543.                 $server_info = array(
  544.                     'major' => @$tmp[0],
  545.                     'minor' => @$tmp2[1],
  546.                     'patch' => null,
  547.                     'extra' => @$tmp2[2],
  548.                     'native' => $server_info,
  549.                 );
  550.             else {
  551.                 $server_info = array(
  552.                     'major' => @$tmp[0],
  553.                     'minor' => @$tmp[1],
  554.                     'patch' => @$tmp[2],
  555.                     'extra' => null,
  556.                     'native' => $server_info,
  557.                 );
  558.             }
  559.         }
  560.         return $server_info;
  561.     }
  562.  
  563.     // }}}
  564.     // {{{ prepare()
  565.  
  566.     /**
  567.      * Prepares a query for multiple execution with execute().
  568.      * With some database backends, this is emulated.
  569.      * prepare() requires a generic query as string like
  570.      * 'INSERT INTO numbers VALUES(?,?)' or
  571.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  572.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  573.      * bindParam() and the query can be send off using the execute() method.
  574.      *
  575.      * @param string $query the query to prepare
  576.      * @param mixed   $types  array that contains the types of the placeholders
  577.      * @param mixed   $result_types  array that contains the types of the columns in
  578.      *                         the result set, if set to MDB2_PREPARE_MANIP the
  579.                               query is handled as a manipulation query
  580.      * @return mixed resource handle for the prepared query on success, a MDB2
  581.      *         error on failure
  582.      * @access public
  583.      * @see bindParam, execute
  584.      */
  585.     function &prepare($query$types = null$result_types = null)
  586.     {
  587.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  588.         $this->debug($query'prepare');
  589.         if (!empty($types)) {
  590.             $this->loadModule('Datatype');
  591.         }
  592.         $query $this->_modifyQuery($query$is_manip$this->row_limit$this->row_offset);
  593.         $placeholder_type_guess $placeholder_type = null;
  594.         $question '?';
  595.         $colon ':';
  596.         $position $parameter = 0;
  597.         while ($position strlen($query)) {
  598.             $q_position strpos($query$question$position);
  599.             $c_position strpos($query$colon$position);
  600.             if ($q_position && $c_position{
  601.                 $p_position min($q_position$c_position);
  602.             elseif ($q_position{
  603.                 $p_position $q_position;
  604.             elseif ($c_position{
  605.                 $p_position $c_position;
  606.             else {
  607.                 break;
  608.             }
  609.             if (is_null($placeholder_type)) {
  610.                 $placeholder_type_guess $query[$p_position];
  611.             }
  612.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  613.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  614.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  615.                         'prepare: query with an unterminated text string specified');
  616.                     return $err;
  617.                 }
  618.                 switch ($this->escape_quotes{
  619.                 case '':
  620.                 case "'":
  621.                     $position $end_quote + 1;
  622.                     break;
  623.                 default:
  624.                     if ($end_quote == $quote + 1{
  625.                         $position $end_quote + 1;
  626.                     else {
  627.                         if ($query[$end_quote-1== $this->escape_quotes{
  628.                             $position $end_quote;
  629.                         else {
  630.                             $position $end_quote + 1;
  631.                         }
  632.                     }
  633.                     break;
  634.                 }
  635.             elseif ($query[$position== $placeholder_type_guess{
  636.                 if (is_null($placeholder_type)) {
  637.                     $placeholder_type $query[$p_position];
  638.                     $question $colon $placeholder_type;
  639.                     if (is_array($types&& !empty($types)) {
  640.                         if ($placeholder_type == ':'{
  641.                         else {
  642.                             $types array_values($types);
  643.                         }
  644.                     }
  645.                 }
  646.                 if ($placeholder_type_guess == '?'{
  647.                     $length = 1;
  648.                     $name $parameter;
  649.                 else {
  650.                     $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  651.                     if ($name === ''{
  652.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  653.                             'prepare: named parameter with an empty name');
  654.                         return $err;
  655.                     }
  656.                     $length strlen($name+ 1;
  657.                 }
  658.                 if (array_key_exists($name$types)) {
  659.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$name]);
  660.                 elseif (array_key_exists($parameter$types)) {
  661.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$parameter]);
  662.                 else {
  663.                     $pgtypes['text';
  664.                 }
  665.                 $query substr_replace($query'$'.++$parameter$position$length);
  666.                 $position $p_position strlen($parameter);
  667.             else {
  668.                 $position $p_position;
  669.             }
  670.         }
  671.         $connection $this->getConnection();
  672.         if (PEAR::isError($connection)) {
  673.             return $connection;
  674.         }
  675.  
  676.         $types_string '';
  677.         if ($pgtypes{
  678.             $types_string ' ('.implode(', '$pgtypes).') ';
  679.         }
  680.         $statement_name 'MDB2_Statement_'.$this->phptype.md5(time());
  681.         $query 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  682.         $statement $this->_doQuery($query$is_manip$connection);
  683.         if (PEAR::isError($statement)) {
  684.             return $statement;
  685.         }
  686.  
  687.         $class_name 'MDB2_Statement_'.$this->phptype;
  688.         $obj =new $class_name($this$statement_name$query$types$result_types$is_manip$this->row_limit$this->row_offset);
  689.         return $obj;
  690.     }
  691.  
  692.     // }}}
  693.     // {{{ nextID()
  694.  
  695.     /**
  696.      * returns the next free id of a sequence
  697.      *
  698.      * @param string $seq_name name of the sequence
  699.      * @param boolean $ondemand when true the seqence is
  700.      *                           automatic created, if it
  701.      *                           not exists
  702.      * @return mixed MDB2 Error Object or id
  703.      * @access public
  704.      */
  705.     function nextID($seq_name$ondemand = true)
  706.     {
  707.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  708.         $query = "SELECT NEXTVAL('$sequence_name')";
  709.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  710.         $result $this->queryOne($query'integer');
  711.         $this->popExpect();
  712.         if (PEAR::isError($result)) {
  713.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  714.                 $this->loadModule('Manager');
  715.                 $result $this->manager->createSequence($seq_name1);
  716.                 if (PEAR::isError($result)) {
  717.                     return $this->raiseError(MDB2_ERRORnullnull,
  718.                         'nextID: on demand sequence could not be created');
  719.                 }
  720.                 return $this->nextId($seq_namefalse);
  721.             }
  722.         }
  723.         return $result;
  724.     }
  725.  
  726.     // }}}
  727.     // {{{ currID()
  728.  
  729.     /**
  730.      * returns the current id of a sequence
  731.      *
  732.      * @param string $seq_name name of the sequence
  733.      * @return mixed MDB2 Error Object or id
  734.      * @access public
  735.      */
  736.     function currID($seq_name)
  737.     {
  738.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  739.         return $this->queryOne("SELECT last_value FROM $sequence_name"'integer');
  740.     }
  741. }
  742.  
  743. class MDB2_Result_pgsql extends MDB2_Result_Common
  744. {
  745.     // }}}
  746.     // {{{ fetchRow()
  747.  
  748.     /**
  749.      * Fetch a row and insert the data into an existing array.
  750.      *
  751.      * @param int       $fetchmode  how the array data should be indexed
  752.      * @param int    $rownum    number of the row where the data can be found
  753.      * @return int data array on success, a MDB2 error on failure
  754.      * @access public
  755.      */
  756.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  757.     {
  758.         if (!is_null($rownum)) {
  759.             $seek $this->seek($rownum);
  760.             if (PEAR::isError($seek)) {
  761.                 return $seek;
  762.             }
  763.         }
  764.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  765.             $fetchmode $this->db->fetchmode;
  766.         }
  767.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  768.             $row @pg_fetch_array($this->resultnullPGSQL_ASSOC);
  769.             if (is_array($row)
  770.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  771.             {
  772.                 $row array_change_key_case($row$this->db->options['field_case']);
  773.             }
  774.         else {
  775.             $row @pg_fetch_row($this->result);
  776.         }
  777.         if (!$row{
  778.             if (is_null($this->result)) {
  779.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  780.                     'fetchRow: resultset has already been freed');
  781.                 return $err;
  782.             }
  783.             $null = null;
  784.             return $null;
  785.         }
  786.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  787.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  788.         }
  789.         if (!empty($this->values)) {
  790.             $this->_assignBindColumns($row);
  791.         }
  792.         if (!empty($this->types)) {
  793.             $row $this->db->datatype->convertResultRow($this->types$row);
  794.         }
  795.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  796.             $object_class $this->db->options['fetch_class'];
  797.             if ($object_class == 'stdClass'{
  798.                 $row = (object) $row;
  799.             else {
  800.                 $row &new $object_class($row);
  801.             }
  802.         }
  803.         ++$this->rownum;
  804.         return $row;
  805.     }
  806.  
  807.     // }}}
  808.     // {{{ _getColumnNames()
  809.  
  810.     /**
  811.      * Retrieve the names of columns returned by the DBMS in a query result.
  812.      *
  813.      * @return mixed                an associative array variable
  814.      *                               that will hold the names of columns. The
  815.      *                               indexes of the array are the column names
  816.      *                               mapped to lower case and the values are the
  817.      *                               respective numbers of the columns starting
  818.      *                               from 0. Some DBMS may not return any
  819.      *                               columns when the result set does not
  820.      *                               contain any rows.
  821.      *
  822.      *                               a MDB2 error on failure
  823.      * @access private
  824.      */
  825.     function _getColumnNames()
  826.     {
  827.         $columns = array();
  828.         $numcols $this->numCols();
  829.         if (PEAR::isError($numcols)) {
  830.             return $numcols;
  831.         }
  832.         for ($column = 0; $column $numcols$column++{
  833.             $column_name @pg_field_name($this->result$column);
  834.             $columns[$column_name$column;
  835.         }
  836.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  837.             $columns array_change_key_case($columns$this->db->options['field_case']);
  838.         }
  839.         return $columns;
  840.     }
  841.  
  842.     // }}}
  843.     // {{{ numCols()
  844.  
  845.     /**
  846.      * Count the number of columns returned by the DBMS in a query result.
  847.      *
  848.      * @access public
  849.      * @return mixed integer value with the number of columns, a MDB2 error
  850.      *                        on failure
  851.      */
  852.     function numCols()
  853.     {
  854.         $cols @pg_num_fields($this->result);
  855.         if (is_null($cols)) {
  856.             if (is_null($this->result)) {
  857.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  858.                     'numCols: resultset has already been freed');
  859.             }
  860.             return $this->db->raiseError();
  861.         }
  862.         return $cols;
  863.     }
  864.  
  865.     // }}}
  866.     // {{{ free()
  867.  
  868.     /**
  869.      * Free the internal resources associated with result.
  870.      *
  871.      * @return boolean true on success, false if result is invalid
  872.      * @access public
  873.      */
  874.     function free()
  875.     {
  876.         $free @pg_free_result($this->result);
  877.         if (!$free{
  878.             if (is_null($this->result)) {
  879.                 return MDB2_OK;
  880.             }
  881.             return $this->db->raiseError();
  882.         }
  883.         $this->result = null;
  884.         return MDB2_OK;
  885.     }
  886. }
  887.  
  888. {
  889.     // {{{ seek()
  890.  
  891.     /**
  892.      * seek to a specific row in a result set
  893.      *
  894.      * @param int    $rownum    number of the row where the data can be found
  895.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  896.      * @access public
  897.      */
  898.     function seek($rownum = 0)
  899.     {
  900.         if ($this->rownum != ($rownum - 1&& !@pg_result_seek($this->result$rownum)) {
  901.             if (is_null($this->result)) {
  902.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  903.                     'seek: resultset has already been freed');
  904.             }
  905.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  906.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  907.         }
  908.         $this->rownum $rownum - 1;
  909.         return MDB2_OK;
  910.     }
  911.  
  912.     // }}}
  913.     // {{{ valid()
  914.  
  915.     /**
  916.      * check if the end of the result set has been reached
  917.      *
  918.      * @return mixed true or false on sucess, a MDB2 error on failure
  919.      * @access public
  920.      */
  921.     function valid()
  922.     {
  923.         $numrows $this->numRows();
  924.         if (PEAR::isError($numrows)) {
  925.             return $numrows;
  926.         }
  927.         return $this->rownum ($numrows - 1);
  928.     }
  929.  
  930.     // }}}
  931.     // {{{ numRows()
  932.  
  933.     /**
  934.      * returns the number of rows in a result object
  935.      *
  936.      * @return mixed MDB2 Error Object or the number of rows
  937.      * @access public
  938.      */
  939.     function numRows()
  940.     {
  941.         $rows @pg_num_rows($this->result);
  942.         if (is_null($rows)) {
  943.             if (is_null($this->result)) {
  944.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  945.                     'numRows: resultset has already been freed');
  946.             }
  947.             return $this->raiseError();
  948.         }
  949.         return $rows;
  950.     }
  951. }
  952.  
  953. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  954. {
  955.     // {{{ _execute()
  956.  
  957.     /**
  958.      * Execute a prepared query statement helper method.
  959.      *
  960.      * @param mixed $result_class string which specifies which result class to use
  961.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  962.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  963.      * @access private
  964.      */
  965.     function &_execute($result_class = true$result_wrap_class = false)
  966.     {
  967.         $this->db->last_query = $this->query;
  968.         $this->db->debug($this->query'execute');
  969.         if ($this->db->getOption('disable_query')) {
  970.             if ($this->is_manip{
  971.                 $return = 0;
  972.                 return $return;
  973.             }
  974.             $null = null;
  975.             return $null;
  976.         }
  977.  
  978.         $connection $this->db->getConnection();
  979.         if (PEAR::isError($connection)) {
  980.             return $connection;
  981.         }
  982.  
  983.         $query 'EXECUTE '.$this->statement;
  984.         if (!empty($this->values)) {
  985.             $parameters = array();
  986.             foreach ($this->values as $parameter => $value{
  987.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  988.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  989.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  990.                         if ($match[1== 'file://'{
  991.                             $value $match[2];
  992.                         }
  993.                         $value @fopen($value'r');
  994.                         $close = true;
  995.                     }
  996.                     if (is_resource($value)) {
  997.                         $data '';
  998.                         while (!@feof($value)) {
  999.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  1000.                         }
  1001.                         if ($close{
  1002.                             @fclose($value);
  1003.                         }
  1004.                         $value $data;
  1005.                     }
  1006.                 }
  1007.                 $parameters[$this->db->quote($value$type);
  1008.             }
  1009.             $query.= ' ('.implode(', '$parameters).')';
  1010.         }
  1011.  
  1012.         $result $this->db->_doQuery($query$this->is_manip$connection);
  1013.         if (PEAR::isError($result)) {
  1014.             return $result;
  1015.         }
  1016.  
  1017.         if ($this->is_manip{
  1018.             $affected_rows $this->db->_affectedRows($connection$result);
  1019.             return $affected_rows;
  1020.         }
  1021.  
  1022.         $result =$this->db->_wrapResult($result$this->result_types$result_class$result_wrap_class);
  1023.         return $result;
  1024.     }
  1025.  
  1026.     // }}}
  1027.  
  1028.     // }}}
  1029.  
  1030.     // }}}
  1031.     // {{{ free()
  1032.  
  1033.     /**
  1034.      * Release resources allocated for the specified prepared query.
  1035.      *
  1036.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1037.      * @access public
  1038.      */
  1039.     function free()
  1040.     {
  1041.         $connection $this->db->getConnection();
  1042.         if (PEAR::isError($connection)) {
  1043.             return $connection;
  1044.         }
  1045.  
  1046.         $query 'DEALLOCATE PREPARE '.$this->statement;
  1047.         return $this->db->_doQuery($querytrue$connection);
  1048.     }
  1049. }
  1050. ?>

Documentation generated on Mon, 11 Mar 2019 14:32:23 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.