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

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