Source for file pgsql.php
Documentation is available at pgsql.php
// vim: set et ts=4 sw=4 fdm=marker:
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox, |
// | Stig. S. Bakken, Lukas Smith |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Author: Paul Cooper <pgc@ucecom.com> |
// +----------------------------------------------------------------------+
// $Id: pgsql.php,v 1.13 2004/04/23 17:06:46 lsmith Exp $
* @author Paul Cooper <pgc@ucecom.com>
$this->phptype = 'pgsql';
$this->dbsyntax = 'pgsql';
$this->supported['summary_functions'] = true;
* This method is used to collect information about an error
$native_msg = @pg_result_error ($error);
$native_msg = @pg_errormessage ($this->connection);
// Fall back to MDB2_ERROR if there was no mapping.
if (empty ($error_regexps)) {
'/([Tt]able does not exist\.|[Rr]elation [\"\'].*[\"\'] does not exist|[Ss]equence does not exist|[Cc]lass ".+" not found)$/' => MDB2_ERROR_NOSUCHTABLE,
'/[Rr]elation [\"\'].*[\"\'] already exists|[Cc]annot insert a duplicate key into (a )?unique index.*/' => MDB2_ERROR_ALREADY_EXISTS,
'/ttribute [\"\'].*[\"\'] not found$|[Rr]elation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => MDB2_ERROR_NOSUCHFIELD,
foreach ($error_regexps as $regexp => $code) {
return array ($error, null , $native_msg);
* Define whether database changes done on the database be automatically
* committed. This function may also implicitly start or end a transaction.
* @param boolean $auto_commit flag that indicates whether the database
* changes should be committed right after executing every query
* statement. If this argument is 0 a transaction implicitly started.
* Otherwise, if a transaction is in progress it is ended by committing
* any database changes that were pending.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug(($auto_commit ? 'On' : 'Off'), 'autoCommit');
$result = $this->_doQuery ($auto_commit ? 'END' : 'BEGIN');
$this->in_transaction = !$auto_commit;
* Commit the database changes done during a transaction that is in
* progress. This function may only be called when auto-committing is
* disabled, otherwise it will fail. Therefore, a new transaction is
* implicitly started after committing the pending changes.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('commit transaction', 'commit');
'commit: transaction changes are being auto commited');
$result = $this->_doQuery ('COMMIT');
return $this->_doQuery ('BEGIN');
* Cancel any database changes done during a transaction that is in
* progress. This function may only be called when auto-committing is
* disabled, otherwise it will fail. Therefore, a new transaction is
* implicitly started after canceling the pending changes.
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('rolling back transaction', 'rollback');
'rollback: transactions can not be rolled back when changes are auto commited');
$result = $this->_doQuery ('ROLLBACK');
return $this->_doQuery ('BEGIN');
* Does the grunt work of connecting to the database
* @return mixed connection resource on success, MDB2 Error Object on failure
function _doConnect ($database_name, $persistent)
if ($database_name == '') {
$database_name = 'template1';
$protocol = (isset ($dsninfo['protocol'])) ? $dsninfo['protocol'] : 'tcp';
if ($protocol == 'tcp') {
if (!empty ($dsninfo['hostspec'])) {
$connstr = 'host=' . $dsninfo['hostspec'];
if (!empty ($dsninfo['port'])) {
$connstr .= ' port=' . $dsninfo['port'];
if (isset ($database_name)) {
$connstr .= ' dbname=\'' . addslashes($database_name) . '\'';
if (!empty ($dsninfo['username'])) {
$connstr .= ' user=\'' . addslashes($dsninfo['username']) . '\'';
if (!empty ($dsninfo['password'])) {
$connstr .= ' password=\'' . addslashes($dsninfo['password']) . '\'';
if (!empty ($dsninfo['options'])) {
$connstr .= ' options=' . $dsninfo['options'];
if (!empty ($dsninfo['tty'])) {
$connstr .= ' tty=' . $dsninfo['tty'];
$function = ($persistent ? 'pg_pconnect' : 'pg_connect');
$connection = @$function($connstr);
$error_msg = 'Could not connect to PostgreSQL server';
* Connect to the database
* @return true on success, MDB2 Error Object on failure
if ($this->connection != 0 ) {
&& !strcmp($this->connected_database_name, $this->database_name)
&& ($this->opened_persistent == $this->options['persistent']))
@pg_close ($this->connection);
$this->affected_rows = -1;
if (!PEAR ::loadExtension ($this->phptype)) {
'connect: extension '. $this->phptype. ' is not compiled into PHP');
if ($this->database_name) {
$connection = $this->_doConnect ('template1', 0 );
if (($result = @pg_exec ($connection, 'BEGIN'))) {
if (!isset ($php_errormsg)
|| strcmp($php_errormsg, 'This compilation does not support pg_cmdtuples()')
'connect: could not execute BEGIN');
$connection = $this->_doConnect ($this->database_name, $this->options['persistent']);
$this->connection = $connection;
$this->connected_dsn = $this->dsn;
$this->connected_database_name = $this->database_name;
$this->opened_persistent = $this->options['persistent'];
&& MDB2::isError($trans_result = $this->_doQuery ('BEGIN'))
@pg_close ($this->connection);
$this->affected_rows = -1;
* Close the database connection
if ($this->connection != 0 ) {
$result = $this->_doQuery ('END');
@pg_close ($this->connection);
$this->affected_rows = -1;
unset ($GLOBALS['_MDB2_databases'][$this->db_index]);
* @param string $query the SQL query
* @return mixed result identifier if query executed, else MDB2_error
function _doQuery ($query)
$result = @pg_exec ($this->connection, $query);
$this->affected_rows = (isset ($this->supported['affected_rows']) ? @pg_cmdtuples ($result) : -1 );
* @param string $query the SQL query
* @return mixed MDB2_OK on success, a MDB2 error on failure
if (($connection = $this->_doConnect ('template1', 0 )) == 0 ) {
'Cannot connect to template1');
if (!($result = @pg_exec ($connection, $query))) {
* Send a query to the database and return any results
* @param string $query the SQL query
* @param array $types array that contains the types of the columns in
* @param mixed $result_class string which specifies which result class to use
* @param mixed $result_wrap_class string which specifies which class to wrap results in
* @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
function &query($query, $types = null , $result_class = false , $result_wrap_class = false )
$offset = $this->row_offset;
$limit = $this->row_limit;
$this->row_offset = $this->row_limit = 0;
$this->debug($query, 'query');
if (!$ismanip && $limit > 0 ) {
$result = $this->_doQuery ('DECLARE select_cursor SCROLL CURSOR FOR '. $query);
&& MDB2::isError($result = $this->_doQuery (" MOVE FORWARD $offset FROM select_cursor" ))
@pg_free_result ($result);
$result = $this->_doQuery (" FETCH FORWARD $limit FROM select_cursor" );
@pg_free_result ($result);
@pg_free_result ($result);
$result = $this->_doQuery ($query);
$this->affected_rows = @pg_cmdtuples ($result);
} elseif ((preg_match('/^\s*\(?\s*SELECT\s+/si', $query)
&& !preg_match('/^\s*\(?\s*SELECT\s+INTO\s/si', $query))
$result_class = $this->options['result_buffering']
? $this->options['buffered_result_class'] : $this->options['result_class'];
$class_name = sprintf($result_class, $this->phptype);
$result = & new $class_name($this, $result);
$err = $result->setResultTypes ($types);
if (!$result_wrap_class) {
$result_wrap_class = $this->options['result_wrap_class'];
if ($result_wrap_class) {
$result = & new $result_wrap_class($result);
$this->affected_rows = 0;
* returns the next free id of a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true the seqence is
* automatic created, if it
* @return mixed MDB2 Error Object or id
function nextID($seq_name, $ondemand = true )
$result = $this->queryOne(" SELECT NEXTVAL('$sequence_name')" , 'integer');
$result = $this->manager->createSequence ($seq_name, 1 );
'nextID: on demand sequence could not be created');
return $this->nextId ($seq_name, false );
* returns the current id of a sequence
* @param string $seq_name name of the sequence
* @return mixed MDB2 Error Object or id
return $this->queryOne(" SELECT last_value FROM $seqname" , 'integer');
class MDB2_Result_pgsql extends MDB2_Result_Common
function MDB2_Result_pgsql (&$mdb, &$result)
parent ::MDB2_Result_Common ($mdb, $result);
* fetch value from a result set
* @param int $rownum number of the row where the data can be found
* @param int $colnum field number where the data can be found
* @return mixed string on success, a MDB2 error on failure
function fetch ($rownum = 0 , $colnum = 0 )
$value = @pg_result ($this->result, $rownum, $colnum);
'fetch: resultset has already been freed');
if (isset ($this->types[$colnum])) {
$value = $this->mdb->datatype ->convertResult ($value, $this->types[$colnum]);
* Fetch a row and insert the data into an existing array.
* @param int $fetchmode how the array data should be indexed
* @return int data array on success, a MDB2 error on failure
function fetchRow ($fetchmode = MDB2_FETCHMODE_DEFAULT )
$fetchmode = $this->mdb->fetchmode;
$row = @pg_fetch_array ($this->result, null , PGSQL_ASSOC );
$row = @pg_fetch_row ($this->result);
'fetchRow: resultset has already been freed');
if (isset ($this->types)) {
$row = $this->mdb->datatype ->convertResultRow ($this->types, $row);
$this->mdb->_convertEmptyArrayValuesToNull ($row);
* Retrieve the names of columns returned by the DBMS in a query result.
* @return mixed an associative array variable
* that will hold the names of columns. The
* indexes of the array are the column names
* mapped to lower case and the values are the
* respective numbers of the columns starting
* from 0. Some DBMS may not return any
* columns when the result set does not
* a MDB2 error on failure
function getColumnNames ()
$numcols = $this->numCols ();
for ($column = 0; $column < $numcols; $column++ ) {
$column_name = @pg_field_name ($this->result, $column);
$columns[$column_name] = $column;
* Count the number of columns returned by the DBMS in a query result.
* @return mixed integer value with the number of columns, a MDB2 error
$cols = @pg_num_fields ($this->result);
'numCols: resultset has already been freed');
return $this->mdb->raiseError ();
* Determine whether the value of a query result located in given row and
* @param int $rownum number of the row where the data can be found
* @param int $colnum field number where the data can be found
* @return mixed true or false on success, a MDB2 error on failure
function resultIsNull ($rownum, $colnum)
return parent ::resultIsNull ($rownum, $colnum);
$value = pg_field_is_null ($this->result, $rownum, $colnum);
'fetch: resultset has already been freed');
* Free the internal resources associated with result.
* @return boolean true on success, false if result is invalid
$free = @pg_free_result ($this->result);
return $this->mdb->raiseError ();
class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
function MDB2_BufferedResult_pgsql (&$mdb, &$result)
parent ::MDB2_Result_pgsql ($mdb, $result);
* seek to a specific row in a result set
* @param int $rownum number of the row where the data can be found
* @return mixed MDB2_OK on success, a MDB2 error on failure
function seek ($rownum = 0 )
if (!@pg_result_seek ($this->result, $rownum)) {
'seek: resultset has already been freed');
'seek: tried to seek to an invalid row number ('. $rownum. ')');
$this->rownum = $rownum - 1;
* check if the end of the result set has been reached
* @return mixed true or false on sucess, a MDB2 error on failure
$numrows = $this->numRows ();
return $this->rownum < ($numrows - 1 );
* returns the number of rows in a result object
* @return mixed MDB2 Error Object or the number of rows
$rows = @pg_num_rows ($this->result);
'numRows: resultset has already been freed');
return $this->raiseError ();
Documentation generated on Mon, 11 Mar 2019 10:15:54 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|