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.87 2005/12/28 10:14:57 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.                 }
  640.                 if ($placeholder_type_guess == '?'{
  641.                     $length = 1;
  642.                     $name $parameter;
  643.                 else {
  644.                     $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  645.                     if ($name === ''{
  646.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  647.                             'prepare: named parameter with an empty name');
  648.                         return $err;
  649.                     }
  650.                     $length strlen($name+ 1;
  651.                 }
  652.                 $query substr_replace($query'$'.++$parameter$position$length);
  653.                 $position $p_position strlen($parameter);
  654.                 if (isset($types[$name])) {
  655.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$name]);
  656.                 else {
  657.                     $pgtypes['text';
  658.                 }
  659.             else {
  660.                 $position $p_position;
  661.             }
  662.         }
  663.         $connection $this->getConnection();
  664.         if (PEAR::isError($connection)) {
  665.             return $connection;
  666.         }
  667.  
  668.         $types_string '';
  669.         if ($pgtypes{
  670.             $types_string ' ('.implode(', '$pgtypes).') ';
  671.         }
  672.         $statement_name 'MDB2_Statement_'.$this->phptype.md5(time());
  673.         $query 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  674.         $statement $this->_doQuery($query$is_manip$connection);
  675.         if (PEAR::isError($statement)) {
  676.             return $statement;
  677.         }
  678.  
  679.         $class_name 'MDB2_Statement_'.$this->phptype;
  680.         $obj =new $class_name($this$statement_name$query$types$result_types$is_manip$this->row_limit$this->row_offset);
  681.         return $obj;
  682.     }
  683.  
  684.     // }}}
  685.     // {{{ nextID()
  686.  
  687.     /**
  688.      * returns the next free id of a sequence
  689.      *
  690.      * @param string $seq_name name of the sequence
  691.      * @param boolean $ondemand when true the seqence is
  692.      *                           automatic created, if it
  693.      *                           not exists
  694.      * @return mixed MDB2 Error Object or id
  695.      * @access public
  696.      */
  697.     function nextID($seq_name$ondemand = true)
  698.     {
  699.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  700.         $query = "SELECT NEXTVAL('$sequence_name')";
  701.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  702.         $result $this->queryOne($query'integer');
  703.         $this->popExpect();
  704.         if (PEAR::isError($result)) {
  705.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  706.                 $this->loadModule('Manager');
  707.                 $result $this->manager->createSequence($seq_name1);
  708.                 if (PEAR::isError($result)) {
  709.                     return $this->raiseError(MDB2_ERRORnullnull,
  710.                         'nextID: on demand sequence could not be created');
  711.                 }
  712.                 return $this->nextId($seq_namefalse);
  713.             }
  714.         }
  715.         return $result;
  716.     }
  717.  
  718.     // }}}
  719.     // {{{ currID()
  720.  
  721.     /**
  722.      * returns the current id of a sequence
  723.      *
  724.      * @param string $seq_name name of the sequence
  725.      * @return mixed MDB2 Error Object or id
  726.      * @access public
  727.      */
  728.     function currID($seq_name)
  729.     {
  730.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  731.         return $this->queryOne("SELECT last_value FROM $sequence_name"'integer');
  732.     }
  733. }
  734.  
  735. class MDB2_Result_pgsql extends MDB2_Result_Common
  736. {
  737.     // }}}
  738.     // {{{ fetchRow()
  739.  
  740.     /**
  741.      * Fetch a row and insert the data into an existing array.
  742.      *
  743.      * @param int       $fetchmode  how the array data should be indexed
  744.      * @param int    $rownum    number of the row where the data can be found
  745.      * @return int data array on success, a MDB2 error on failure
  746.      * @access public
  747.      */
  748.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  749.     {
  750.         if (!is_null($rownum)) {
  751.             $seek $this->seek($rownum);
  752.             if (PEAR::isError($seek)) {
  753.                 return $seek;
  754.             }
  755.         }
  756.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  757.             $fetchmode $this->db->fetchmode;
  758.         }
  759.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  760.             $row @pg_fetch_array($this->resultnullPGSQL_ASSOC);
  761.             if (is_array($row)
  762.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  763.             {
  764.                 $row array_change_key_case($row$this->db->options['field_case']);
  765.             }
  766.         else {
  767.             $row @pg_fetch_row($this->result);
  768.         }
  769.         if (!$row{
  770.             if (is_null($this->result)) {
  771.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  772.                     'fetchRow: resultset has already been freed');
  773.                 return $err;
  774.             }
  775.             $null = null;
  776.             return $null;
  777.         }
  778.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  779.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  780.         }
  781.         if (!empty($this->values)) {
  782.             $this->_assignBindColumns($row);
  783.         }
  784.         if (!empty($this->types)) {
  785.             $row $this->db->datatype->convertResultRow($this->types$row);
  786.         }
  787.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  788.             $object_class $this->db->options['fetch_class'];
  789.             if ($object_class == 'stdClass'{
  790.                 $row = (object) $row;
  791.             else {
  792.                 $row &new $object_class($row);
  793.             }
  794.         }
  795.         ++$this->rownum;
  796.         return $row;
  797.     }
  798.  
  799.     // }}}
  800.     // {{{ _getColumnNames()
  801.  
  802.     /**
  803.      * Retrieve the names of columns returned by the DBMS in a query result.
  804.      *
  805.      * @return mixed                an associative array variable
  806.      *                               that will hold the names of columns. The
  807.      *                               indexes of the array are the column names
  808.      *                               mapped to lower case and the values are the
  809.      *                               respective numbers of the columns starting
  810.      *                               from 0. Some DBMS may not return any
  811.      *                               columns when the result set does not
  812.      *                               contain any rows.
  813.      *
  814.      *                               a MDB2 error on failure
  815.      * @access private
  816.      */
  817.     function _getColumnNames()
  818.     {
  819.         $columns = array();
  820.         $numcols $this->numCols();
  821.         if (PEAR::isError($numcols)) {
  822.             return $numcols;
  823.         }
  824.         for ($column = 0; $column $numcols$column++{
  825.             $column_name @pg_field_name($this->result$column);
  826.             $columns[$column_name$column;
  827.         }
  828.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  829.             $columns array_change_key_case($columns$this->db->options['field_case']);
  830.         }
  831.         return $columns;
  832.     }
  833.  
  834.     // }}}
  835.     // {{{ numCols()
  836.  
  837.     /**
  838.      * Count the number of columns returned by the DBMS in a query result.
  839.      *
  840.      * @access public
  841.      * @return mixed integer value with the number of columns, a MDB2 error
  842.      *                        on failure
  843.      */
  844.     function numCols()
  845.     {
  846.         $cols @pg_num_fields($this->result);
  847.         if (is_null($cols)) {
  848.             if (is_null($this->result)) {
  849.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  850.                     'numCols: resultset has already been freed');
  851.             }
  852.             return $this->db->raiseError();
  853.         }
  854.         return $cols;
  855.     }
  856.  
  857.     // }}}
  858.     // {{{ free()
  859.  
  860.     /**
  861.      * Free the internal resources associated with result.
  862.      *
  863.      * @return boolean true on success, false if result is invalid
  864.      * @access public
  865.      */
  866.     function free()
  867.     {
  868.         $free @pg_free_result($this->result);
  869.         if (!$free{
  870.             if (is_null($this->result)) {
  871.                 return MDB2_OK;
  872.             }
  873.             return $this->db->raiseError();
  874.         }
  875.         $this->result = null;
  876.         return MDB2_OK;
  877.     }
  878. }
  879.  
  880. {
  881.     // {{{ seek()
  882.  
  883.     /**
  884.      * seek to a specific row in a result set
  885.      *
  886.      * @param int    $rownum    number of the row where the data can be found
  887.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  888.      * @access public
  889.      */
  890.     function seek($rownum = 0)
  891.     {
  892.         if ($this->rownum != ($rownum - 1&& !@pg_result_seek($this->result$rownum)) {
  893.             if (is_null($this->result)) {
  894.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  895.                     'seek: resultset has already been freed');
  896.             }
  897.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  898.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  899.         }
  900.         $this->rownum $rownum - 1;
  901.         return MDB2_OK;
  902.     }
  903.  
  904.     // }}}
  905.     // {{{ valid()
  906.  
  907.     /**
  908.      * check if the end of the result set has been reached
  909.      *
  910.      * @return mixed true or false on sucess, a MDB2 error on failure
  911.      * @access public
  912.      */
  913.     function valid()
  914.     {
  915.         $numrows $this->numRows();
  916.         if (PEAR::isError($numrows)) {
  917.             return $numrows;
  918.         }
  919.         return $this->rownum ($numrows - 1);
  920.     }
  921.  
  922.     // }}}
  923.     // {{{ numRows()
  924.  
  925.     /**
  926.      * returns the number of rows in a result object
  927.      *
  928.      * @return mixed MDB2 Error Object or the number of rows
  929.      * @access public
  930.      */
  931.     function numRows()
  932.     {
  933.         $rows @pg_num_rows($this->result);
  934.         if (is_null($rows)) {
  935.             if (is_null($this->result)) {
  936.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  937.                     'numRows: resultset has already been freed');
  938.             }
  939.             return $this->raiseError();
  940.         }
  941.         return $rows;
  942.     }
  943. }
  944.  
  945. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  946. {
  947.     // {{{ _execute()
  948.  
  949.     /**
  950.      * Execute a prepared query statement helper method.
  951.      *
  952.      * @param mixed $result_class string which specifies which result class to use
  953.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  954.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  955.      * @access private
  956.      */
  957.     function &_execute($result_class = true$result_wrap_class = false)
  958.     {
  959.         $this->db->last_query = $this->query;
  960.         $this->db->debug($this->query'execute');
  961.         if ($this->db->getOption('disable_query')) {
  962.             if ($this->is_manip{
  963.                 $return = 0;
  964.                 return $return;
  965.             }
  966.             $null = null;
  967.             return $null;
  968.         }
  969.  
  970.         $connection $this->db->getConnection();
  971.         if (PEAR::isError($connection)) {
  972.             return $connection;
  973.         }
  974.  
  975.         $query 'EXECUTE '.$this->statement;
  976.         if (!empty($this->values)) {
  977.             $parameters = array();
  978.             foreach ($this->values as $parameter => $value{
  979.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  980.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  981.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  982.                         if ($match[1== 'file://'{
  983.                             $value $match[2];
  984.                         }
  985.                         $value @fopen($value'r');
  986.                         $close = true;
  987.                     }
  988.                     if (is_resource($value)) {
  989.                         $data '';
  990.                         while (!@feof($value)) {
  991.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  992.                         }
  993.                         if ($close{
  994.                             @fclose($value);
  995.                         }
  996.                         $value $data;
  997.                     }
  998.                 }
  999.                 $parameters[$this->db->quote($value$type);
  1000.             }
  1001.             $query.= ' ('.implode(', '$parameters).')';
  1002.         }
  1003.  
  1004.         $result $this->db->_doQuery($query$this->is_manip$connection);
  1005.         if (PEAR::isError($result)) {
  1006.             return $result;
  1007.         }
  1008.  
  1009.         if ($this->is_manip{
  1010.             $affected_rows $this->db->_affectedRows($connection$result);
  1011.             return $affected_rows;
  1012.         }
  1013.  
  1014.         $result =$this->db->_wrapResult($result$this->result_types$result_class$result_wrap_class);
  1015.         return $result;
  1016.     }
  1017.  
  1018.     // }}}
  1019.  
  1020.     // }}}
  1021.  
  1022.     // }}}
  1023.     // {{{ free()
  1024.  
  1025.     /**
  1026.      * Release resources allocated for the specified prepared query.
  1027.      *
  1028.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1029.      * @access public
  1030.      */
  1031.     function free()
  1032.     {
  1033.         $connection $this->db->getConnection();
  1034.         if (PEAR::isError($connection)) {
  1035.             return $connection;
  1036.         }
  1037.  
  1038.         $query 'DEALLOCATE PREPARE '.$this->statement;
  1039.         return $this->db->_doQuery($querytrue$connection);
  1040.     }
  1041. }
  1042. ?>

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