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

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