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.94 2006/01/22 18:30:16 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->offset;
  416.         $limit $this->limit;
  417.         $this->offset $this->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/string with version information or MDB2 error object
  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_info3);
  541.             if (!array_key_exists(2$tmp)
  542.                 && isset($tmp[1])
  543.                 && preg_match('/(\d+)(.*)/'$tmp[1]$tmp2)
  544.             {
  545.                 $server_info = array(
  546.                     'major' => $tmp[0],
  547.                     'minor' => $tmp2[1],
  548.                     'patch' => null,
  549.                     'extra' => $tmp2[2],
  550.                     'native' => $server_info,
  551.                 );
  552.             else {
  553.                 $server_info = array(
  554.                     'major' => isset($tmp[0]$tmp[0: null,
  555.                     'minor' => isset($tmp[1]$tmp[1: null,
  556.                     'patch' => isset($tmp[2]$tmp[2: null,
  557.                     'extra' => null,
  558.                     'native' => $server_info,
  559.                 );
  560.             }
  561.         }
  562.         return $server_info;
  563.     }
  564.  
  565.     // }}}
  566.     // {{{ prepare()
  567.  
  568.     /**
  569.      * Prepares a query for multiple execution with execute().
  570.      * With some database backends, this is emulated.
  571.      * prepare() requires a generic query as string like
  572.      * 'INSERT INTO numbers VALUES(?,?)' or
  573.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  574.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  575.      * bindParam() and the query can be send off using the execute() method.
  576.      *
  577.      * @param string $query the query to prepare
  578.      * @param mixed   $types  array that contains the types of the placeholders
  579.      * @param mixed   $result_types  array that contains the types of the columns in
  580.      *                         the result set, if set to MDB2_PREPARE_MANIP the
  581.                               query is handled as a manipulation query
  582.      * @return mixed resource handle for the prepared query on success, a MDB2
  583.      *         error on failure
  584.      * @access public
  585.      * @see bindParam, execute
  586.      */
  587.     function &prepare($query$types = null$result_types = null)
  588.     {
  589.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  590.         $offset $this->offset;
  591.         $limit $this->limit;
  592.         $this->offset $this->limit = 0;
  593.         $this->debug($query'prepare');
  594.         if (!empty($types)) {
  595.             $this->loadModule('Datatype'nulltrue);
  596.         }
  597.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  598.         $placeholder_type_guess $placeholder_type = null;
  599.         $question '?';
  600.         $colon ':';
  601.         $positions = array();
  602.         $position $parameter = 0;
  603.         while ($position strlen($query)) {
  604.             $q_position strpos($query$question$position);
  605.             $c_position strpos($query$colon$position);
  606.             if ($q_position && $c_position{
  607.                 $p_position min($q_position$c_position);
  608.             elseif ($q_position{
  609.                 $p_position $q_position;
  610.             elseif ($c_position{
  611.                 $p_position $c_position;
  612.             else {
  613.                 break;
  614.             }
  615.             if (is_null($placeholder_type)) {
  616.                 $placeholder_type_guess $query[$p_position];
  617.             }
  618.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  619.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  620.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  621.                         'prepare: query with an unterminated text string specified');
  622.                     return $err;
  623.                 }
  624.                 switch ($this->escape_quotes{
  625.                 case '':
  626.                 case "'":
  627.                     $position $end_quote + 1;
  628.                     break;
  629.                 default:
  630.                     if ($end_quote == $quote + 1{
  631.                         $position $end_quote + 1;
  632.                     else {
  633.                         if ($query[$end_quote-1== $this->escape_quotes{
  634.                             $position $end_quote;
  635.                         else {
  636.                             $position $end_quote + 1;
  637.                         }
  638.                     }
  639.                     break;
  640.                 }
  641.             elseif ($query[$position== $placeholder_type_guess{
  642.                 if (is_null($placeholder_type)) {
  643.                     $placeholder_type $query[$p_position];
  644.                     $question $colon $placeholder_type;
  645.                     if (is_array($types&& !empty($types)) {
  646.                         if ($placeholder_type == ':'{
  647.                         else {
  648.                             $types array_values($types);
  649.                         }
  650.                     }
  651.                 }
  652.                 if ($placeholder_type_guess == '?'{
  653.                     $length = 1;
  654.                     $name $parameter;
  655.                 else {
  656.                     $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  657.                     if ($name === ''{
  658.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  659.                             'prepare: named parameter with an empty name');
  660.                         return $err;
  661.                     }
  662.                     $length strlen($name+ 1;
  663.                 }
  664.                 if (array_key_exists($name$types)) {
  665.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$name]);
  666.                 elseif (array_key_exists($parameter$types)) {
  667.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$parameter]);
  668.                 else {
  669.                     $pgtypes['text';
  670.                 }
  671.                 $positions[$name$p_position;
  672.                 $query substr_replace($query'$'.++$parameter$position$length);
  673.                 $position $p_position strlen($parameter);
  674.             else {
  675.                 $position $p_position;
  676.             }
  677.         }
  678.         $connection $this->getConnection();
  679.         if (PEAR::isError($connection)) {
  680.             return $connection;
  681.         }
  682.  
  683.         $types_string '';
  684.         if ($pgtypes{
  685.             $types_string ' ('.implode(', '$pgtypes).') ';
  686.         }
  687.         $statement_name 'MDB2_Statement_'.$this->phptype.md5(time());
  688.         $query 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  689.         $statement $this->_doQuery($query$is_manip$connection);
  690.         if (PEAR::isError($statement)) {
  691.             return $statement;
  692.         }
  693.  
  694.         $class_name 'MDB2_Statement_'.$this->phptype;
  695.         $obj =new $class_name($this$statement_name$positions$query$types$result_types$is_manip$limit$offset);
  696.         return $obj;
  697.     }
  698.  
  699.     // }}}
  700.     // {{{ nextID()
  701.  
  702.     /**
  703.      * returns the next free id of a sequence
  704.      *
  705.      * @param string $seq_name name of the sequence
  706.      * @param boolean $ondemand when true the seqence is
  707.      *                           automatic created, if it
  708.      *                           not exists
  709.      * @return mixed MDB2 Error Object or id
  710.      * @access public
  711.      */
  712.     function nextID($seq_name$ondemand = true)
  713.     {
  714.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  715.         $query = "SELECT NEXTVAL('$sequence_name')";
  716.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  717.         $result $this->queryOne($query'integer');
  718.         $this->popExpect();
  719.         if (PEAR::isError($result)) {
  720.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  721.                 $this->loadModule('Manager'nulltrue);
  722.                 $result $this->manager->createSequence($seq_name1);
  723.                 if (PEAR::isError($result)) {
  724.                     return $this->raiseError(MDB2_ERRORnullnull,
  725.                         'nextID: on demand sequence could not be created');
  726.                 }
  727.                 return $this->nextId($seq_namefalse);
  728.             }
  729.         }
  730.         return $result;
  731.     }
  732.  
  733.     // }}}
  734.     // {{{ currID()
  735.  
  736.     /**
  737.      * returns the current id of a sequence
  738.      *
  739.      * @param string $seq_name name of the sequence
  740.      * @return mixed MDB2 Error Object or id
  741.      * @access public
  742.      */
  743.     function currID($seq_name)
  744.     {
  745.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  746.         return $this->queryOne("SELECT last_value FROM $sequence_name"'integer');
  747.     }
  748. }
  749.  
  750. class MDB2_Result_pgsql extends MDB2_Result_Common
  751. {
  752.     // }}}
  753.     // {{{ fetchRow()
  754.  
  755.     /**
  756.      * Fetch a row and insert the data into an existing array.
  757.      *
  758.      * @param int       $fetchmode  how the array data should be indexed
  759.      * @param int    $rownum    number of the row where the data can be found
  760.      * @return int data array on success, a MDB2 error on failure
  761.      * @access public
  762.      */
  763.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  764.     {
  765.         if (!is_null($rownum)) {
  766.             $seek $this->seek($rownum);
  767.             if (PEAR::isError($seek)) {
  768.                 return $seek;
  769.             }
  770.         }
  771.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  772.             $fetchmode $this->db->fetchmode;
  773.         }
  774.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  775.             $row @pg_fetch_array($this->resultnullPGSQL_ASSOC);
  776.             if (is_array($row)
  777.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  778.             {
  779.                 $row array_change_key_case($row$this->db->options['field_case']);
  780.             }
  781.         else {
  782.             $row @pg_fetch_row($this->result);
  783.         }
  784.         if (!$row{
  785.             if (is_null($this->result)) {
  786.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  787.                     'fetchRow: resultset has already been freed');
  788.                 return $err;
  789.             }
  790.             $null = null;
  791.             return $null;
  792.         }
  793.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  794.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  795.         }
  796.         if (!empty($this->values)) {
  797.             $this->_assignBindColumns($row);
  798.         }
  799.         if (!empty($this->types)) {
  800.             $row $this->db->datatype->convertResultRow($this->types$row);
  801.         }
  802.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  803.             $object_class $this->db->options['fetch_class'];
  804.             if ($object_class == 'stdClass'{
  805.                 $row = (object) $row;
  806.             else {
  807.                 $row &new $object_class($row);
  808.             }
  809.         }
  810.         ++$this->rownum;
  811.         return $row;
  812.     }
  813.  
  814.     // }}}
  815.     // {{{ _getColumnNames()
  816.  
  817.     /**
  818.      * Retrieve the names of columns returned by the DBMS in a query result.
  819.      *
  820.      * @return mixed                an associative array variable
  821.      *                               that will hold the names of columns. The
  822.      *                               indexes of the array are the column names
  823.      *                               mapped to lower case and the values are the
  824.      *                               respective numbers of the columns starting
  825.      *                               from 0. Some DBMS may not return any
  826.      *                               columns when the result set does not
  827.      *                               contain any rows.
  828.      *
  829.      *                               a MDB2 error on failure
  830.      * @access private
  831.      */
  832.     function _getColumnNames()
  833.     {
  834.         $columns = array();
  835.         $numcols $this->numCols();
  836.         if (PEAR::isError($numcols)) {
  837.             return $numcols;
  838.         }
  839.         for ($column = 0; $column $numcols$column++{
  840.             $column_name @pg_field_name($this->result$column);
  841.             $columns[$column_name$column;
  842.         }
  843.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  844.             $columns array_change_key_case($columns$this->db->options['field_case']);
  845.         }
  846.         return $columns;
  847.     }
  848.  
  849.     // }}}
  850.     // {{{ numCols()
  851.  
  852.     /**
  853.      * Count the number of columns returned by the DBMS in a query result.
  854.      *
  855.      * @access public
  856.      * @return mixed integer value with the number of columns, a MDB2 error
  857.      *                        on failure
  858.      */
  859.     function numCols()
  860.     {
  861.         $cols @pg_num_fields($this->result);
  862.         if (is_null($cols)) {
  863.             if (is_null($this->result)) {
  864.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  865.                     'numCols: resultset has already been freed');
  866.             }
  867.             return $this->db->raiseError();
  868.         }
  869.         return $cols;
  870.     }
  871.  
  872.     // }}}
  873.     // {{{ free()
  874.  
  875.     /**
  876.      * Free the internal resources associated with result.
  877.      *
  878.      * @return boolean true on success, false if result is invalid
  879.      * @access public
  880.      */
  881.     function free()
  882.     {
  883.         $free @pg_free_result($this->result);
  884.         if (!$free{
  885.             if (is_null($this->result)) {
  886.                 return MDB2_OK;
  887.             }
  888.             return $this->db->raiseError();
  889.         }
  890.         $this->result = null;
  891.         return MDB2_OK;
  892.     }
  893. }
  894.  
  895. {
  896.     // {{{ seek()
  897.  
  898.     /**
  899.      * seek to a specific row in a result set
  900.      *
  901.      * @param int    $rownum    number of the row where the data can be found
  902.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  903.      * @access public
  904.      */
  905.     function seek($rownum = 0)
  906.     {
  907.         if ($this->rownum != ($rownum - 1&& !@pg_result_seek($this->result$rownum)) {
  908.             if (is_null($this->result)) {
  909.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  910.                     'seek: resultset has already been freed');
  911.             }
  912.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  913.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  914.         }
  915.         $this->rownum $rownum - 1;
  916.         return MDB2_OK;
  917.     }
  918.  
  919.     // }}}
  920.     // {{{ valid()
  921.  
  922.     /**
  923.      * check if the end of the result set has been reached
  924.      *
  925.      * @return mixed true or false on sucess, a MDB2 error on failure
  926.      * @access public
  927.      */
  928.     function valid()
  929.     {
  930.         $numrows $this->numRows();
  931.         if (PEAR::isError($numrows)) {
  932.             return $numrows;
  933.         }
  934.         return $this->rownum ($numrows - 1);
  935.     }
  936.  
  937.     // }}}
  938.     // {{{ numRows()
  939.  
  940.     /**
  941.      * returns the number of rows in a result object
  942.      *
  943.      * @return mixed MDB2 Error Object or the number of rows
  944.      * @access public
  945.      */
  946.     function numRows()
  947.     {
  948.         $rows @pg_num_rows($this->result);
  949.         if (is_null($rows)) {
  950.             if (is_null($this->result)) {
  951.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  952.                     'numRows: resultset has already been freed');
  953.             }
  954.             return $this->db->raiseError();
  955.         }
  956.         return $rows;
  957.     }
  958. }
  959.  
  960. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  961. {
  962.     // {{{ _execute()
  963.  
  964.     /**
  965.      * Execute a prepared query statement helper method.
  966.      *
  967.      * @param mixed $result_class string which specifies which result class to use
  968.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  969.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  970.      * @access private
  971.      */
  972.     function &_execute($result_class = true$result_wrap_class = false)
  973.     {
  974.         $this->db->last_query = $this->query;
  975.         $this->db->debug($this->query'execute');
  976.         if ($this->db->getOption('disable_query')) {
  977.             if ($this->is_manip{
  978.                 $return = 0;
  979.                 return $return;
  980.             }
  981.             $null = null;
  982.             return $null;
  983.         }
  984.  
  985.         $connection $this->db->getConnection();
  986.         if (PEAR::isError($connection)) {
  987.             return $connection;
  988.         }
  989.  
  990.         $query 'EXECUTE '.$this->statement;
  991.         if (!empty($this->positions)) {
  992.             $parameters = array();
  993.             foreach ($this->positions as $parameter => $current_position{
  994.                 if (!array_key_exists($parameter$this->values)) {
  995.                     return $this->db->raiseError();
  996.                 }
  997.                 $value $this->values[$parameter];
  998.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  999.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1000.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1001.                         if ($match[1== 'file://'{
  1002.                             $value $match[2];
  1003.                         }
  1004.                         $value @fopen($value'r');
  1005.                         $close = true;
  1006.                     }
  1007.                     if (is_resource($value)) {
  1008.                         $data '';
  1009.                         while (!@feof($value)) {
  1010.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  1011.                         }
  1012.                         if ($close{
  1013.                             @fclose($value);
  1014.                         }
  1015.                         $value $data;
  1016.                     }
  1017.                 }
  1018.                 $parameters[$this->db->quote($value$type);
  1019.             }
  1020.             $query.= ' ('.implode(', '$parameters).')';
  1021.         }
  1022.  
  1023.         $result $this->db->_doQuery($query$this->is_manip$connection);
  1024.         if (PEAR::isError($result)) {
  1025.             return $result;
  1026.         }
  1027.  
  1028.         if ($this->is_manip{
  1029.             $affected_rows $this->db->_affectedRows($connection$result);
  1030.             return $affected_rows;
  1031.         }
  1032.  
  1033.         $result =$this->db->_wrapResult($result$this->result_types$result_class$result_wrap_class);
  1034.         return $result;
  1035.     }
  1036.  
  1037.     // }}}
  1038.  
  1039.     // }}}
  1040.  
  1041.     // }}}
  1042.     // {{{ free()
  1043.  
  1044.     /**
  1045.      * Release resources allocated for the specified prepared query.
  1046.      *
  1047.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1048.      * @access public
  1049.      */
  1050.     function free()
  1051.     {
  1052.         $connection $this->db->getConnection();
  1053.         if (PEAR::isError($connection)) {
  1054.             return $connection;
  1055.         }
  1056.  
  1057.         $query 'DEALLOCATE PREPARE '.$this->statement;
  1058.         return $this->db->_doQuery($querytrue$connection);
  1059.     }
  1060. }
  1061. ?>

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