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

Source for file pgsql.php

Documentation is available at pgsql.php

  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5                                                 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
  7. // | Stig. S. Bakken, Lukas Smith                                         |
  8. // | All rights reserved.                                                 |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  11. // | API as well as database abstraction for PHP applications.            |
  12. // | This LICENSE is in the BSD license style.                            |
  13. // |                                                                      |
  14. // | Redistribution and use in source and binary forms, with or without   |
  15. // | modification, are permitted provided that the following conditions   |
  16. // | are met:                                                             |
  17. // |                                                                      |
  18. // | Redistributions of source code must retain the above copyright       |
  19. // | notice, this list of conditions and the following disclaimer.        |
  20. // |                                                                      |
  21. // | Redistributions in binary form must reproduce the above copyright    |
  22. // | notice, this list of conditions and the following disclaimer in the  |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // |                                                                      |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission.                                                  |
  29. // |                                                                      |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  41. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Paul Cooper <pgc@ucecom.com>                                 |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: pgsql.php,v 1.132 2006/06/14 08:10:49 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.     var $escape_identifier = '"';
  61.  
  62.     // }}}
  63.     // {{{ constructor
  64.  
  65.     /**
  66.      * Constructor
  67.      */
  68.     function __construct()
  69.     {
  70.         parent::__construct();
  71.  
  72.         $this->phptype 'pgsql';
  73.         $this->dbsyntax 'pgsql';
  74.  
  75.         $this->supported['sequences'= true;
  76.         $this->supported['indexes'= true;
  77.         $this->supported['affected_rows'= true;
  78.         $this->supported['summary_functions'= true;
  79.         $this->supported['order_by_text'= true;
  80.         $this->supported['transactions'= true;
  81.         $this->supported['current_id'= true;
  82.         $this->supported['limit_queries'= true;
  83.         $this->supported['LOBs'= true;
  84.         $this->supported['replace''emulated';
  85.         $this->supported['sub_selects'= true;
  86.         $this->supported['auto_increment''emulated';
  87.         $this->supported['primary_key'= true;
  88.         $this->supported['result_introspection'= true;
  89.         $this->supported['prepared_statements'= true;
  90.  
  91.         $this->options['multi_query'= false;
  92.     }
  93.  
  94.     // }}}
  95.     // {{{ errorInfo()
  96.  
  97.     /**
  98.      * This method is used to collect information about an error
  99.      *
  100.      * @param integer $error 
  101.      * @return array 
  102.      * @access public
  103.      */
  104.     function errorInfo($error = null)
  105.     {
  106.         // Fall back to MDB2_ERROR if there was no mapping.
  107.         $error_code = MDB2_ERROR;
  108.  
  109.         $native_msg '';
  110.         if (is_resource($error)) {
  111.             $native_msg @pg_result_error($error);
  112.         elseif ($this->connection{
  113.             $native_msg @pg_last_error($this->connection);
  114.             if (!$native_msg && @pg_connection_status($this->connection=== PGSQL_CONNECTION_BAD{
  115.                 $native_msg 'Database connection has been lost.';
  116.                 $error_code = MDB2_ERROR_CONNECT_FAILED;
  117.             }
  118.         }
  119.  
  120.         static $error_regexps;
  121.         if (empty($error_regexps)) {
  122.             $error_regexps = array(
  123.                 '/column .* (of relation .*)?does not exist/i'
  124.                     => MDB2_ERROR_NOSUCHFIELD,
  125.                 '/(relation|sequence|table).*does not exist|class .* not found/i'
  126.                     => MDB2_ERROR_NOSUCHTABLE,
  127.                 '/index .* does not exist/'
  128.                     => MDB2_ERROR_NOT_FOUND,
  129.                 '/relation .* already exists/i'
  130.                     => MDB2_ERROR_ALREADY_EXISTS,
  131.                 '/(divide|division) by zero$/i'
  132.                     => MDB2_ERROR_DIVZERO,
  133.                 '/pg_atoi: error in .*: can\'t parse /i'
  134.                     => MDB2_ERROR_INVALID_NUMBER,
  135.                 '/invalid input syntax for( type)? (integer|numeric)/i'
  136.                     => MDB2_ERROR_INVALID_NUMBER,
  137.                 '/value .* is out of range for type \w*int/i'
  138.                     => MDB2_ERROR_INVALID_NUMBER,
  139.                 '/integer out of range/i'
  140.                     => MDB2_ERROR_INVALID_NUMBER,
  141.                 '/value too long for type character/i'
  142.                     => MDB2_ERROR_INVALID,
  143.                 '/attribute .* not found|relation .* does not have attribute/i'
  144.                     => MDB2_ERROR_NOSUCHFIELD,
  145.                 '/column .* specified in USING clause does not exist in (left|right) table/i'
  146.                     => MDB2_ERROR_NOSUCHFIELD,
  147.                 '/parser: parse error at or near/i'
  148.                     => MDB2_ERROR_SYNTAX,
  149.                 '/syntax error at/'
  150.                     => MDB2_ERROR_SYNTAX,
  151.                 '/column reference .* is ambiguous/i'
  152.                     => MDB2_ERROR_SYNTAX,
  153.                 '/permission denied/'
  154.                     => MDB2_ERROR_ACCESS_VIOLATION,
  155.                 '/violates not-null constraint/'
  156.                     => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  157.                 '/violates [\w ]+ constraint/'
  158.                     => MDB2_ERROR_CONSTRAINT,
  159.                 '/referential integrity violation/'
  160.                     => MDB2_ERROR_CONSTRAINT,
  161.                 '/more expressions than target columns/i'
  162.                     => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  163.             );
  164.         }
  165.         if (is_numeric($error&& $error < 0{
  166.             $error_code $error;
  167.         else {
  168.             foreach ($error_regexps as $regexp => $code{
  169.                 if (preg_match($regexp$native_msg)) {
  170.                     $error_code $code;
  171.                     break;
  172.                 }
  173.             }
  174.         }
  175.         return array($error_codenull$native_msg);
  176.     }
  177.  
  178.     // }}}
  179.     // {{{ escape()
  180.  
  181.     /**
  182.      * Quotes a string so it can be safely used in a query. It will quote
  183.      * the text so it can safely be used within a query.
  184.      *
  185.      * @param string $text the input string to quote
  186.      * @return string quoted string
  187.      * @access public
  188.      */
  189.     function escape($text)
  190.     {
  191.         return @pg_escape_string($text);
  192.     }
  193.  
  194.     // }}}
  195.     // {{{ beginTransaction()
  196.  
  197.     /**
  198.      * Start a transaction.
  199.      *
  200.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  201.      * @access public
  202.      */
  203.     function beginTransaction()
  204.     {
  205.         $this->debug('starting transaction''beginTransaction'false);
  206.         if ($this->in_transaction{
  207.             return MDB2_OK;  //nothing to do
  208.         }
  209.         if (!$this->destructor_registered && $this->opened_persistent{
  210.             $this->destructor_registered = true;
  211.             register_shutdown_function('MDB2_closeOpenTransactions');
  212.         }
  213.         $result =$this->_doQuery('BEGIN'true);
  214.         if (PEAR::isError($result)) {
  215.             return $result;
  216.         }
  217.         $this->in_transaction = true;
  218.         return MDB2_OK;
  219.     }
  220.  
  221.     // }}}
  222.     // {{{ commit()
  223.  
  224.     /**
  225.      * Commit the 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 commit()
  232.     {
  233.         $this->debug('commit transaction''commit'false);
  234.         if (!$this->in_transaction{
  235.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  236.                 'commit: transaction changes are being auto committed');
  237.         }
  238.         $result =$this->_doQuery('COMMIT'true);
  239.         if (PEAR::isError($result)) {
  240.             return $result;
  241.         }
  242.         $this->in_transaction = false;
  243.         return MDB2_OK;
  244.     }
  245.  
  246.     // }}}
  247.     // {{{ rollback()
  248.  
  249.     /**
  250.      * Cancel any database changes done during a transaction that is in
  251.      * progress.
  252.      *
  253.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  254.      * @access public
  255.      */
  256.     function rollback()
  257.     {
  258.         $this->debug('rolling back transaction''rollback'false);
  259.         if (!$this->in_transaction{
  260.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  261.                 'rollback: transactions can not be rolled back when changes are auto committed');
  262.         }
  263.         $result =$this->_doQuery('ROLLBACK'true);
  264.         if (PEAR::isError($result)) {
  265.             return $result;
  266.         }
  267.         $this->in_transaction = false;
  268.         return MDB2_OK;
  269.     }
  270.  
  271.     // }}}
  272.     // {{{ _doConnect()
  273.  
  274.     /**
  275.      * Does the grunt work of connecting to the database
  276.      *
  277.      * @return mixed connection resource on success, MDB2 Error Object on failure
  278.      * @access protected
  279.      ***/
  280.     function _doConnect($database_name$persistent = false)
  281.     {
  282.         if ($database_name == ''{
  283.             $database_name 'template1';
  284.         }
  285.  
  286.         $protocol $this->dsn['protocol'$this->dsn['protocol''tcp';
  287.  
  288.         $params = array('');
  289.         if ($protocol == 'tcp'{
  290.             if ($this->dsn['hostspec']{
  291.                 $params[0].= 'host=' $this->dsn['hostspec'];
  292.             }
  293.             if ($this->dsn['port']{
  294.                 $params[0].= ' port=' $this->dsn['port'];
  295.             }
  296.         elseif ($protocol == 'unix'{
  297.             // Allow for pg socket in non-standard locations.
  298.             if ($this->dsn['socket']{
  299.                 $params[0].= 'host=' $this->dsn['socket'];
  300.             }
  301.             if ($this->dsn['port']{
  302.                 $params[0].= ' port=' $this->dsn['port'];
  303.             }
  304.         }
  305.         if ($database_name{
  306.             $params[0].= ' dbname=\'' addslashes($database_name'\'';
  307.         }
  308.         if ($this->dsn['username']{
  309.             $params[0].= ' user=\'' addslashes($this->dsn['username']'\'';
  310.         }
  311.         if ($this->dsn['password']{
  312.             $params[0].= ' password=\'' addslashes($this->dsn['password']'\'';
  313.         }
  314.         if (!empty($this->dsn['options'])) {
  315.             $params[0].= ' options=' $this->dsn['options'];
  316.         }
  317.         if (!empty($this->dsn['tty'])) {
  318.             $params[0].= ' tty=' $this->dsn['tty'];
  319.         }
  320.         if (!empty($this->dsn['connect_timeout'])) {
  321.             $params[0].= ' connect_timeout=' $this->dsn['connect_timeout'];
  322.         }
  323.         if (!empty($this->dsn['sslmode'])) {
  324.             $params[0].= ' sslmode=' $this->dsn['sslmode'];
  325.         }
  326.         if (!empty($this->dsn['service'])) {
  327.             $params[0].= ' service=' $this->dsn['service'];
  328.         }
  329.  
  330.         if (!empty($this->dsn['new_link'])
  331.             && ($this->dsn['new_link'== 'true' || $this->dsn['new_link'=== true))
  332.         {
  333.             if (version_compare(phpversion()'4.3.0''>=')) {
  334.                 $params[= PGSQL_CONNECT_FORCE_NEW;
  335.             }
  336.         }
  337.  
  338.         $connect_function $persistent 'pg_pconnect' 'pg_connect';
  339.  
  340.         @ini_set('track_errors'true);
  341.         $php_errormsg '';
  342.         $connection @call_user_func_array($connect_function$params);
  343.         @ini_restore('track_errors');
  344.         if (!$connection{
  345.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED,
  346.                 nullnullstrip_tags($php_errormsg));
  347.         }
  348.  
  349.         if (!@pg_query($connection"SET SESSION DATESTYLE = 'ISO'")) {
  350.             return $this->raiseError(nullnullnull,
  351.                 'Unable to set connection charset: '.$this->dsn['charset']);
  352.         }
  353.  
  354.         if (!empty($this->dsn['charset'])) {
  355.             $result $this->setCharset($this->dsn['charset']$connection);
  356.             if (PEAR::isError($result)) {
  357.                 return $result;
  358.             }
  359.         }
  360.  
  361.         return $connection;
  362.     }
  363.  
  364.     // }}}
  365.     // {{{ connect()
  366.  
  367.     /**
  368.      * Connect to the database
  369.      *
  370.      * @return true on success, MDB2 Error Object on failure
  371.      * @access public
  372.      ***/
  373.     function connect()
  374.     {
  375.         if (is_resource($this->connection)) {
  376.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0
  377.                 && $this->connected_database_name == $this->database_name
  378.                 && ($this->opened_persistent == $this->options['persistent'])
  379.             {
  380.                 return MDB2_OK;
  381.             }
  382.             $this->disconnect(false);
  383.         }
  384.  
  385.         if (!PEAR::loadExtension($this->phptype)) {
  386.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  387.                 'connect: extension '.$this->phptype.' is not compiled into PHP');
  388.         }
  389.  
  390.         if ($this->database_name{
  391.             $connection $this->_doConnect($this->database_name$this->options['persistent']);
  392.             if (PEAR::isError($connection)) {
  393.                 return $connection;
  394.             }
  395.             $this->connection $connection;
  396.             $this->connected_dsn $this->dsn;
  397.             $this->connected_database_name $this->database_name;
  398.             $this->opened_persistent $this->options['persistent'];
  399.             $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  400.         }
  401.         return MDB2_OK;
  402.     }
  403.  
  404.     // }}}
  405.     // {{{ setCharset()
  406.  
  407.     /**
  408.      * Set the charset on the current connection
  409.      *
  410.      * @param string    charset
  411.      * @param resource  connection handle
  412.      *
  413.      * @return true on success, MDB2 Error Object on failure
  414.      */
  415.     function setCharset($charset$connection = null)
  416.     {
  417.         if (is_null($connection)) {
  418.             $connection $this->getConnection();
  419.             if (PEAR::isError($connection)) {
  420.                 return $connection;
  421.             }
  422.         }
  423.  
  424.         $result @pg_set_client_encoding($connection$charset);
  425.  
  426.         if (!$result{
  427.             return $this->raiseError(nullnullnull,
  428.                 'setCharset: Unable to set client charset: '.$charset);
  429.         }
  430.         return MDB2_OK;
  431.     }
  432.  
  433.     // }}}
  434.     // {{{ disconnect()
  435.  
  436.     /**
  437.      * Log out and disconnect from the database.
  438.      *
  439.      * @param  boolean $force if the disconnect should be forced even if the
  440.      *                         connection is opened persistently
  441.      * @return mixed true on success, false if not connected and error
  442.      *                 object on error
  443.      * @access public
  444.      */
  445.     function disconnect($force = true)
  446.     {
  447.         if (is_resource($this->connection)) {
  448.             if ($this->in_transaction{
  449.                 $this->rollback();
  450.             }
  451.             if (!$this->opened_persistent || $force{
  452.                 @pg_close($this->connection);
  453.             }
  454.         }
  455.         return parent::disconnect($force);
  456.     }
  457.  
  458.     // }}}
  459.     // {{{ standaloneQuery()
  460.  
  461.    /**
  462.      * execute a query as DBA
  463.      *
  464.      * @param string $query the SQL query
  465.      * @param mixed   $types  array that contains the types of the columns in
  466.      *                         the result set
  467.      * @param boolean $is_manip  if the query is a manipulation query
  468.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  469.      * @access public
  470.      */
  471.     function &standaloneQuery($query$types = null$is_manip = false)
  472.     {
  473.         $connection $this->_doConnect('template1'false);
  474.         if (PEAR::isError($connection)) {
  475.             $err =$this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  476.                 'Cannot connect to template1');
  477.             return $err;
  478.         }
  479.  
  480.         $offset $this->offset;
  481.         $limit $this->limit;
  482.         $this->offset $this->limit = 0;
  483.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  484.  
  485.         $result =$this->_doQuery($query$is_manip$connectionfalse);
  486.         @pg_close($connection);
  487.         if (PEAR::isError($result)) {
  488.             return $result;
  489.         }
  490.  
  491.         if ($is_manip{
  492.             $affected_rows =  $this->_affectedRows($connection$result);
  493.             return $affected_rows;
  494.         }
  495.         $result =$this->_wrapResult($result$typestruefalse$limit$offset);
  496.         return $result;
  497.     }
  498.  
  499.     // }}}
  500.     // {{{ _doQuery()
  501.  
  502.     /**
  503.      * Execute a query
  504.      * @param string $query  query
  505.      * @param boolean $is_manip  if the query is a manipulation query
  506.      * @param resource $connection 
  507.      * @param string $database_name 
  508.      * @return result or error object
  509.      * @access protected
  510.      */
  511.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  512.     {
  513.         $this->last_query $query;
  514.         $result $this->debug($query'query'$is_manip);
  515.         if ($result{
  516.             if (PEAR::isError($result)) {
  517.                 return $result;
  518.             }
  519.             $query $result;
  520.         }
  521.         if ($this->options['disable_query']{
  522.             if ($is_manip{
  523.                 return 0;
  524.             }
  525.             return null;
  526.         }
  527.  
  528.         if (is_null($connection)) {
  529.             $connection $this->getConnection();
  530.             if (PEAR::isError($connection)) {
  531.                 return $connection;
  532.             }
  533.         }
  534.  
  535.         $function $this->options['multi_query''pg_send_query' 'pg_query';
  536.         $result @$function($connection$query);
  537.         if (!$result{
  538.             $err =$this->raiseError(nullnullnull,
  539.                 '_doQuery: Could not execute statement');
  540.             return $err;
  541.         }
  542.  
  543.         if ($this->options['multi_query']{
  544.             if (!($result @pg_get_result($connection))) {
  545.                 $err =$this->raiseError(nullnullnull,
  546.                         '_doQuery: Could not get the first result from a multi query');
  547.                 return $err;
  548.             }
  549.         }
  550.  
  551.         return $result;
  552.     }
  553.  
  554.     // }}}
  555.     // {{{ _affectedRows()
  556.  
  557.     /**
  558.      * Returns the number of rows affected
  559.      *
  560.      * @param resource $result 
  561.      * @param resource $connection 
  562.      * @return mixed MDB2 Error Object or the number of rows affected
  563.      * @access private
  564.      */
  565.     function _affectedRows($connection$result = null)
  566.     {
  567.         if (is_null($connection)) {
  568.             $connection $this->getConnection();
  569.             if (PEAR::isError($connection)) {
  570.                 return $connection;
  571.             }
  572.         }
  573.         return @pg_affected_rows($result);
  574.     }
  575.  
  576.     // }}}
  577.     // {{{ _modifyQuery()
  578.  
  579.     /**
  580.      * Changes a query string for various DBMS specific reasons
  581.      *
  582.      * @param string $query  query to modify
  583.      * @param boolean $is_manip  if it is a DML query
  584.      * @param integer $limit  limit the number of rows
  585.      * @param integer $offset  start reading from given offset
  586.      * @return string modified query
  587.      * @access protected
  588.      */
  589.     function _modifyQuery($query$is_manip$limit$offset)
  590.     {
  591.         if ($limit > 0
  592.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  593.         {
  594.             $query rtrim($query);
  595.             if (substr($query-1== ';'{
  596.                 $query substr($query0-1);
  597.             }
  598.             if ($is_manip{
  599.                 $manip preg_replace('/^(DELETE FROM|UPDATE).*$/''\\1'$query);
  600.                 $from $match[2];
  601.                 $where $match[3];
  602.                 $query $manip.' '.$from.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
  603.             else {
  604.                 $query.= " LIMIT $limit OFFSET $offset";
  605.             }
  606.         }
  607.         return $query;
  608.     }
  609.  
  610.     // }}}
  611.     // {{{ getServerVersion()
  612.  
  613.     /**
  614.      * return version information about the server
  615.      *
  616.      * @param string     $native  determines if the raw version string should be returned
  617.      * @return mixed array/string with version information or MDB2 error object
  618.      * @access public
  619.      */
  620.     function getServerVersion($native = false)
  621.     {
  622.         $query 'SHOW SERVER_VERSION';
  623.         if ($this->connected_server_info{
  624.             $server_info $this->connected_server_info;
  625.         else {
  626.             $server_info $this->queryOne($query'text');
  627.             if (PEAR::isError($server_info)) {
  628.                 return $server_info;
  629.             }
  630.         }
  631.         // cache server_info
  632.         $this->connected_server_info $server_info;
  633.         if (!$native && !PEAR::isError($server_info)) {
  634.             $tmp explode('.'$server_info3);
  635.             if (empty($tmp[2])
  636.                 && isset($tmp[1])
  637.                 && preg_match('/(\d+)(.*)/'$tmp[1]$tmp2)
  638.             {
  639.                 $server_info = array(
  640.                     'major' => $tmp[0],
  641.                     'minor' => $tmp2[1],
  642.                     'patch' => null,
  643.                     'extra' => $tmp2[2],
  644.                     'native' => $server_info,
  645.                 );
  646.             else {
  647.                 $server_info = array(
  648.                     'major' => isset($tmp[0]$tmp[0: null,
  649.                     'minor' => isset($tmp[1]$tmp[1: null,
  650.                     'patch' => isset($tmp[2]$tmp[2: null,
  651.                     'extra' => null,
  652.                     'native' => $server_info,
  653.                 );
  654.             }
  655.         }
  656.         return $server_info;
  657.     }
  658.  
  659.     // }}}
  660.     // {{{ prepare()
  661.  
  662.     /**
  663.      * Prepares a query for multiple execution with execute().
  664.      * With some database backends, this is emulated.
  665.      * prepare() requires a generic query as string like
  666.      * 'INSERT INTO numbers VALUES(?,?)' or
  667.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  668.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  669.      * bindParam() and the query can be send off using the execute() method.
  670.      *
  671.      * @param string $query the query to prepare
  672.      * @param mixed   $types  array that contains the types of the placeholders
  673.      * @param mixed   $result_types  array that contains the types of the columns in
  674.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  675.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  676.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  677.      * @return mixed resource handle for the prepared query on success, a MDB2
  678.      *         error on failure
  679.      * @access public
  680.      * @see bindParam, execute
  681.      */
  682.     function &prepare($query$types = null$result_types = null$lobs = array())
  683.     {
  684.         if ($this->options['emulate_prepared']{
  685.             $obj =parent::prepare($query$types$result_types$lobs);
  686.             return $obj;
  687.         }
  688.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  689.         $offset $this->offset;
  690.         $limit $this->limit;
  691.         $this->offset $this->limit = 0;
  692.         $result $this->debug($query'prepare'$is_manip);
  693.         if ($result{
  694.             if (PEAR::isError($result)) {
  695.                 return $result;
  696.             }
  697.             $query $result;
  698.         }
  699.         if (!empty($types)) {
  700.             $this->loadModule('Datatype'nulltrue);
  701.         }
  702.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  703.         $placeholder_type_guess $placeholder_type = null;
  704.         $question '?';
  705.         $colon ':';
  706.         $positions $pgtypes = array();
  707.         $position $parameter = 0;
  708.         while ($position strlen($query)) {
  709.             $q_position strpos($query$question$position);
  710.             $c_position strpos($query$colon$position);
  711.             if ($q_position && $c_position{
  712.                 $p_position min($q_position$c_position);
  713.             elseif ($q_position{
  714.                 $p_position $q_position;
  715.             elseif ($c_position{
  716.                 $p_position $c_position;
  717.             else {
  718.                 break;
  719.             }
  720.             if (is_null($placeholder_type)) {
  721.                 $placeholder_type_guess $query[$p_position];
  722.             }
  723.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  724.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  725.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  726.                         'prepare: query with an unterminated text string specified');
  727.                     return $err;
  728.                 }
  729.                 switch ($this->escape_quotes{
  730.                 case '':
  731.                 case "'":
  732.                     $position $end_quote + 1;
  733.                     break;
  734.                 default:
  735.                     if ($end_quote == $quote + 1{
  736.                         $position $end_quote + 1;
  737.                     else {
  738.                         if ($query[$end_quote-1== $this->escape_quotes{
  739.                             $position $end_quote;
  740.                         else {
  741.                             $position $end_quote + 1;
  742.                         }
  743.                     }
  744.                     break;
  745.                 }
  746.             elseif ($query[$position== $placeholder_type_guess{
  747.                 if (is_null($placeholder_type)) {
  748.                     $placeholder_type $query[$p_position];
  749.                     $question $colon $placeholder_type;
  750.                     if (!empty($types&& is_array($types)) {
  751.                         if ($placeholder_type == ':'{
  752.                         else {
  753.                             $types array_values($types);
  754.                         }
  755.                     }
  756.                 }
  757.                 if ($placeholder_type_guess == '?'{
  758.                     $length = 1;
  759.                     $name $parameter;
  760.                 else {
  761.                     $name preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  762.                     if ($name === ''{
  763.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  764.                             'prepare: named parameter with an empty name');
  765.                         return $err;
  766.                     }
  767.                     $length strlen($name+ 1;
  768.                 }
  769.                 if (is_array($types&& array_key_exists($name$types)) {
  770.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$name]);
  771.                 elseif (is_array($types&& array_key_exists($parameter$types)) {
  772.                     $pgtypes[$this->datatype->mapPrepareDatatype($types[$parameter]);
  773.                 else {
  774.                     $pgtypes['text';
  775.                 }
  776.                 $positions[$name$p_position;
  777.                 $query substr_replace($query'$'.++$parameter$position$length);
  778.                 $position $p_position strlen($parameter);
  779.             else {
  780.                 $position $p_position;
  781.             }
  782.         }
  783.         $connection $this->getConnection();
  784.         if (PEAR::isError($connection)) {
  785.             return $connection;
  786.         }
  787.  
  788.         $types_string '';
  789.         if ($pgtypes{
  790.             $types_string ' ('.implode(', '$pgtypes).') ';
  791.         }
  792.         $statement_name strtolower('MDB2_Statement_'.$this->phptype.md5(time(rand()));
  793.         if (function_exists('pg_prepare')) {
  794.             $result @pg_prepare($connection$statement_name$query);
  795.             if (!$result{
  796.                 $err =$this->raiseError(nullnullnull,
  797.                     'prepare: Unable to create prepared statement handle');
  798.                 return $err;
  799.             }
  800.         else {
  801.             $query 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  802.             $statement =$this->_doQuery($querytrue$connection);
  803.             if (PEAR::isError($statement)) {
  804.                 return $statement;
  805.             }
  806.         }
  807.  
  808.         $class_name 'MDB2_Statement_'.$this->phptype;
  809.         $obj =new $class_name($this$statement_name$positions$query$types$result_types$is_manip$limit$offset);
  810.         return $obj;
  811.     }
  812.  
  813.     // }}}
  814.     // {{{ nextID()
  815.  
  816.     /**
  817.      * Returns the next free id of a sequence
  818.      *
  819.      * @param string $seq_name name of the sequence
  820.      * @param boolean $ondemand when true the sequence is
  821.      *                           automatic created, if it
  822.      *                           not exists
  823.      * @return mixed MDB2 Error Object or id
  824.      * @access public
  825.      */
  826.     function nextID($seq_name$ondemand = true)
  827.     {
  828.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  829.         $query = "SELECT NEXTVAL('$sequence_name')";
  830.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  831.         $result $this->queryOne($query'integer');
  832.         $this->popExpect();
  833.         if (PEAR::isError($result)) {
  834.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  835.                 $this->loadModule('Manager'nulltrue);
  836.                 $result $this->manager->createSequence($seq_name1);
  837.                 if (PEAR::isError($result)) {
  838.                     return $this->raiseError($resultnullnull,
  839.                         'nextID: on demand sequence could not be created');
  840.                 }
  841.                 return $this->nextId($seq_namefalse);
  842.             }
  843.         }
  844.         return $result;
  845.     }
  846.  
  847.     // }}}
  848.     // {{{ currID()
  849.  
  850.     /**
  851.      * Returns the current id of a sequence
  852.      *
  853.      * @param string $seq_name name of the sequence
  854.      * @return mixed MDB2 Error Object or id
  855.      * @access public
  856.      */
  857.     function currID($seq_name)
  858.     {
  859.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  860.         return $this->queryOne("SELECT last_value FROM $sequence_name"'integer');
  861.     }
  862. }
  863.  
  864. /**
  865.  * MDB2 PostGreSQL result driver
  866.  *
  867.  * @package MDB2
  868.  * @category Database
  869.  * @author  Paul Cooper <pgc@ucecom.com>
  870.  */
  871. class MDB2_Result_pgsql extends MDB2_Result_Common
  872. {
  873.     // }}}
  874.     // {{{ fetchRow()
  875.  
  876.     /**
  877.      * Fetch a row and insert the data into an existing array.
  878.      *
  879.      * @param int       $fetchmode  how the array data should be indexed
  880.      * @param int    $rownum    number of the row where the data can be found
  881.      * @return int data array on success, a MDB2 error on failure
  882.      * @access public
  883.      */
  884.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  885.     {
  886.         if (!is_null($rownum)) {
  887.             $seek $this->seek($rownum);
  888.             if (PEAR::isError($seek)) {
  889.                 return $seek;
  890.             }
  891.         }
  892.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  893.             $fetchmode $this->db->fetchmode;
  894.         }
  895.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  896.             $row @pg_fetch_array($this->resultnullPGSQL_ASSOC);
  897.             if (is_array($row)
  898.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  899.             {
  900.                 $row array_change_key_case($row$this->db->options['field_case']);
  901.             }
  902.         else {
  903.             $row @pg_fetch_row($this->result);
  904.         }
  905.         if (!$row{
  906.             if ($this->result === false{
  907.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  908.                     'fetchRow: resultset has already been freed');
  909.                 return $err;
  910.             }
  911.             $null = null;
  912.             return $null;
  913.         }
  914.         if ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL{
  915.             $this->db->_fixResultArrayValues($rowMDB2_PORTABILITY_EMPTY_TO_NULL);
  916.         }
  917.         if (!empty($this->values)) {
  918.             $this->_assignBindColumns($row);
  919.         }
  920.         if (!empty($this->types)) {
  921.             $row $this->db->datatype->convertResultRow($this->types$row);
  922.         }
  923.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  924.             $object_class $this->db->options['fetch_class'];
  925.             if ($object_class == 'stdClass'{
  926.                 $row = (object) $row;
  927.             else {
  928.                 $row &new $object_class($row);
  929.             }
  930.         }
  931.         ++$this->rownum;
  932.         return $row;
  933.     }
  934.  
  935.     // }}}
  936.     // {{{ _getColumnNames()
  937.  
  938.     /**
  939.      * Retrieve the names of columns returned by the DBMS in a query result.
  940.      *
  941.      * @return  mixed   Array variable that holds the names of columns as keys
  942.      *                   or an MDB2 error on failure.
  943.      *                   Some DBMS may not return any columns when the result set
  944.      *                   does not contain any rows.
  945.      * @access private
  946.      */
  947.     function _getColumnNames()
  948.     {
  949.         $columns = array();
  950.         $numcols $this->numCols();
  951.         if (PEAR::isError($numcols)) {
  952.             return $numcols;
  953.         }
  954.         for ($column = 0; $column $numcols$column++{
  955.             $column_name @pg_field_name($this->result$column);
  956.             $columns[$column_name$column;
  957.         }
  958.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  959.             $columns array_change_key_case($columns$this->db->options['field_case']);
  960.         }
  961.         return $columns;
  962.     }
  963.  
  964.     // }}}
  965.     // {{{ numCols()
  966.  
  967.     /**
  968.      * Count the number of columns returned by the DBMS in a query result.
  969.      *
  970.      * @access public
  971.      * @return mixed integer value with the number of columns, a MDB2 error
  972.      *                        on failure
  973.      */
  974.     function numCols()
  975.     {
  976.         $cols @pg_num_fields($this->result);
  977.         if (is_null($cols)) {
  978.             if ($this->result === false{
  979.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  980.                     'numCols: resultset has already been freed');
  981.             elseif (is_null($this->result)) {
  982.                 return count($this->types);
  983.             }
  984.             return $this->db->raiseError(nullnullnull,
  985.                 'numCols: Could not get column count');
  986.         }
  987.         return $cols;
  988.     }
  989.  
  990.     // }}}
  991.     // {{{ nextResult()
  992.  
  993.     /**
  994.      * Move the internal result pointer to the next available result
  995.      *
  996.      * @param valid result resource
  997.      * @return true on success, false if there is no more result set or an error object on failure
  998.      * @access public
  999.      */
  1000.     function nextResult()
  1001.     {
  1002.         $connection $this->db->getConnection();
  1003.         if (PEAR::isError($connection)) {
  1004.             return $connection;
  1005.         }
  1006.  
  1007.         if (!($this->result @pg_get_result($connection))) {
  1008.             return false;
  1009.         }
  1010.         return MDB2_OK;
  1011.     }
  1012.  
  1013.     // }}}
  1014.     // {{{ free()
  1015.  
  1016.     /**
  1017.      * Free the internal resources associated with result.
  1018.      *
  1019.      * @return boolean true on success, false if result is invalid
  1020.      * @access public
  1021.      */
  1022.     function free()
  1023.     {
  1024.         if (is_resource($this->result&& $this->db->connection{
  1025.             $free @pg_free_result($this->result);
  1026.             if ($free === false{
  1027.                 return $this->db->raiseError(nullnullnull,
  1028.                     'free: Could not free result');
  1029.             }
  1030.         }
  1031.         $this->result = false;
  1032.         return MDB2_OK;
  1033.     }
  1034. }
  1035.  
  1036. /**
  1037.  * MDB2 PostGreSQL buffered result driver
  1038.  *
  1039.  * @package MDB2
  1040.  * @category Database
  1041.  * @author  Paul Cooper <pgc@ucecom.com>
  1042.  */
  1043. {
  1044.     // {{{ seek()
  1045.  
  1046.     /**
  1047.      * Seek to a specific row in a result set
  1048.      *
  1049.      * @param int    $rownum    number of the row where the data can be found
  1050.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1051.      * @access public
  1052.      */
  1053.     function seek($rownum = 0)
  1054.     {
  1055.         if ($this->rownum != ($rownum - 1&& !@pg_result_seek($this->result$rownum)) {
  1056.             if ($this->result === false{
  1057.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1058.                     'seek: resultset has already been freed');
  1059.             elseif (is_null($this->result)) {
  1060.                 return MDB2_OK;
  1061.             }
  1062.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1063.                 'seek: tried to seek to an invalid row number ('.$rownum.')');
  1064.         }
  1065.         $this->rownum $rownum - 1;
  1066.         return MDB2_OK;
  1067.     }
  1068.  
  1069.     // }}}
  1070.     // {{{ valid()
  1071.  
  1072.     /**
  1073.      * Check if the end of the result set has been reached
  1074.      *
  1075.      * @return mixed true or false on sucess, a MDB2 error on failure
  1076.      * @access public
  1077.      */
  1078.     function valid()
  1079.     {
  1080.         $numrows $this->numRows();
  1081.         if (PEAR::isError($numrows)) {
  1082.             return $numrows;
  1083.         }
  1084.         return $this->rownum ($numrows - 1);
  1085.     }
  1086.  
  1087.     // }}}
  1088.     // {{{ numRows()
  1089.  
  1090.     /**
  1091.      * Returns the number of rows in a result object
  1092.      *
  1093.      * @return mixed MDB2 Error Object or the number of rows
  1094.      * @access public
  1095.      */
  1096.     function numRows()
  1097.     {
  1098.         $rows @pg_num_rows($this->result);
  1099.         if (is_null($rows)) {
  1100.             if ($this->result === false{
  1101.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1102.                     'numRows: resultset has already been freed');
  1103.             elseif (is_null($this->result)) {
  1104.                 return 0;
  1105.             }
  1106.             return $this->db->raiseError(nullnullnull,
  1107.                 'numRows: Could not get row count');
  1108.         }
  1109.         return $rows;
  1110.     }
  1111. }
  1112.  
  1113. /**
  1114.  * MDB2 PostGreSQL statement driver
  1115.  *
  1116.  * @package MDB2
  1117.  * @category Database
  1118.  * @author  Paul Cooper <pgc@ucecom.com>
  1119.  */
  1120. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  1121. {
  1122.     // {{{ _execute()
  1123.  
  1124.     /**
  1125.      * Execute a prepared query statement helper method.
  1126.      *
  1127.      * @param mixed $result_class string which specifies which result class to use
  1128.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1129.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1130.      * @access private
  1131.      */
  1132.     function &_execute($result_class = true$result_wrap_class = false)
  1133.     {
  1134.         if (is_null($this->statement)) {
  1135.             $result =parent::_execute($result_class$result_wrap_class);
  1136.             return $result;
  1137.         }
  1138.         $this->db->last_query = $this->query;
  1139.         $this->db->debug($this->query'execute'$this->is_manip);
  1140.         $this->db->debug($this->values'parameters'$this->is_manip);
  1141.         if ($this->db->getOption('disable_query')) {
  1142.             if ($this->is_manip{
  1143.                 $return = 0;
  1144.                 return $return;
  1145.             }
  1146.             $null = null;
  1147.             return $null;
  1148.         }
  1149.  
  1150.         $connection $this->db->getConnection();
  1151.         if (PEAR::isError($connection)) {
  1152.             return $connection;
  1153.         }
  1154.  
  1155.         $query = false;
  1156.         $parameters = array();
  1157.         // todo: disabled until pg_execute() bytea issues are cleared up
  1158.         if (true || !function_exists('pg_execute')) {
  1159.             $query 'EXECUTE '.$this->statement;
  1160.         }
  1161.         if (!empty($this->positions)) {
  1162.             foreach ($this->positions as $parameter => $current_position{
  1163.                 if (!array_key_exists($parameter$this->values)) {
  1164.                     return $this->db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  1165.                         '_execute: Unable to bind to missing placeholder: '.$parameter);
  1166.                 }
  1167.                 $value $this->values[$parameter];
  1168.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1169.                 if (is_resource($value|| $type == 'clob' || $type == 'blob'{
  1170.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1171.                         if ($match[1== 'file://'{
  1172.                             $value $match[2];
  1173.                         }
  1174.                         $value @fopen($value'r');
  1175.                         $close = true;
  1176.                     }
  1177.                     if (is_resource($value)) {
  1178.                         $data '';
  1179.                         while (!@feof($value)) {
  1180.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  1181.                         }
  1182.                         if ($close{
  1183.                             @fclose($value);
  1184.                         }
  1185.                         $value $data;
  1186.                     }
  1187.                 }
  1188.                 $parameters[$this->db->quote($value$type$query);
  1189.             }
  1190.             if ($query{
  1191.                 $query.= ' ('.implode(', '$parameters).')';
  1192.             }
  1193.         }
  1194.  
  1195.         if (!$query{
  1196.             $result @pg_execute($connection$this->statement$parameters);
  1197.             if (!$result{
  1198.                 $err =$this->db->raiseError(nullnullnull,
  1199.                     '_execute: Unable to execute statement');
  1200.                 return $err;
  1201.             }
  1202.         else {
  1203.             $result $this->db->_doQuery($query$this->is_manip$connection);
  1204.             if (PEAR::isError($result)) {
  1205.                 return $result;
  1206.             }
  1207.         }
  1208.  
  1209.         if ($this->is_manip{
  1210.             $affected_rows $this->db->_affectedRows($connection$result);
  1211.             return $affected_rows;
  1212.         }
  1213.  
  1214.         $result =$this->db->_wrapResult($result$this->result_types,
  1215.             $result_class$result_wrap_class$this->limit$this->offset);
  1216.         return $result;
  1217.     }
  1218.  
  1219.     // }}}
  1220.     // {{{ free()
  1221.  
  1222.     /**
  1223.      * Release resources allocated for the specified prepared query.
  1224.      *
  1225.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1226.      * @access public
  1227.      */
  1228.     function free()
  1229.     {
  1230.         if (is_null($this->positions)) {
  1231.             return $this->db->raiseError(MDB2_ERRORnullnull,
  1232.                 'free: Prepared statement has already been freed');
  1233.         }
  1234.         $result = MDB2_OK;
  1235.  
  1236.         if (!is_null($this->statement)) {
  1237.             $connection $this->db->getConnection();
  1238.             if (PEAR::isError($connection)) {
  1239.                 return $connection;
  1240.             }
  1241.             $query 'DEALLOCATE PREPARE '.$this->statement;
  1242.             $result $this->db->_doQuery($querytrue$connection);
  1243.         }
  1244.  
  1245.         parent::free();
  1246.         return $result;
  1247.     }
  1248. }
  1249. ?>

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