Location: PHPKode > scripts > RC4PHP class > rc4php-class/rc4php_db_postgresql.php
<?PHP
/**
*
* RC4PHP :  Raul's Classes For PHP <http://rc4php.sourceforge.net/>
* Copyright (c) 2006, Raul IONESCU
*                     Bucharest, ROMANIA
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package      RC4PHP
* @copyright 	Copyright (c) 2006, Raul IONESCU.
* @author 	Raul IONESCU <hide@address.com>
* @license      http://www.opensource.org/licenses/mit-license.php The MIT License
* @version 	0.6.3 (development)
* @category 	PostgreSQL implementation
* @access 	public
*
* PHP versions 5.1 or greater
*/
//////////////////////////////////////////////////////////////////
require_once('rc4php_autoload.php');
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_PostgreSQL
*
* It's the MySQL SQL class.
* 
* GET PROPERTIES
* ---------------------------------------------------------------------------
* (Note: get properties  marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* type			= object's type: 'PostgreSQL'	[]
* version		= server version				[]
* database		= database's name				[]
* server 		= server's name					[] 		
* user			= user's name					[]		
* password		= user's password				[]		
* connection		= sql connection resource
* databases		= databases from server (array)
* tables		= database's tables (array)
* views			= current database's views (array)
* 
* SET PROPERTIES
* ---------------------------------------------------------------------------
* (Note: set properties  marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* database		= database's name		[]
* server		= server's name			[]		
* user			= user's name			[]		
* password		= user's password		[]		
* 
* PUBLIC METHODS
* ----------------------------
* escapeString($string);                    -> returns escaped string of $string.
* &escapeBinaryString(&$binaryString);      -> returns escaped string for binary data.
* &unescapeSQLBinaryString(&$binaryString); -> returns binary string from SQL server.
* isConnected();                            -> returns state of connection: boolean true for connected else it returns false.
* connect();                                -> try to connects to SQL server.
* disconnect();                             -> disconnect from SQL server.
* query($sql);                              -> send a query to the SQL server; it returns an SQL Result object.
* getDatabases();                           -> get array of databases
* getTables($database='');                  -> get array of tables from $database; if $database is empty then it will use current database.
* getViews($database='');                   -> get array of views from $database; if $database is empty then it will use current database.
* DATE2MIDAS($date);                        -> convert date into MIDAS date.
* MIDAS2DATE($MIDASdate);                   -> convert MIDAS date into date.
* 
* @access public
*/
class RC4PHP_DB_PostgreSQL extends RC4PHP_DB_SQL
{
protected $RC4PHP_DB_QUOTE_PATTERN='%s';
protected $dbSQLServerPort=5432;
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_PostgreSQL object
*
* Initialize object's properties.
* It doesn't establish connection to the PostgreSQL database. The connection
* it's established only when it's needed.
*
* @param string $dbSQLDBName
* @return RC4PHP_DB_PostgreSQL
*/
public function __construct($dbSQLDBName='',$dbSQLServer='localhost:5432',$dbSQLUser='',$dbSQLPassword='')
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
self::_checkPHPExtension('pdo');
self::_checkPHPExtension('pdo_pgsql');
self::_checkPHPExtension('pgsql');

$dbSQLDBName=$this->quoteName($this->_escape($dbSQLDBName));
$dbSQLUser=$this->_escape($dbSQLUser);
$dbSQLPassword=$this->_escape($dbSQLPassword);

parent::__construct($dbSQLDBName,$dbSQLServer,$dbSQLUser,$dbSQLPassword);
$srvAndPort=@split(':',$dbSQLServer);
switch(count($srvAndPort))
	{
	 case 0:
		$srvAndPort=array('',5432);
		break;

	 case 1:
		$srvAndPort[]=5432;
		break;
	}
@list($this->dbSQLServer,$this->dbSQLServerPort)=$srvAndPort;
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_PostgreSQL object
*
* When object it's destroyed, the database connection will be closed.
*
* @return void
*/
public function __destruct()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
parent::__destruct();
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns an escaped string for database name, user and password.
* 
* @access protected
* @return string
*/
protected function _escape($string)
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
$searchArray=array('\'','\\');
$replaceArray=array('\\\'','\\\\');
return @str_replace($searchArray,$replaceArray,$string);
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'MySQL'.
* 
* @access protected
* @return string
*/
protected function _getType()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return 'PostgreSQL';
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns SQL server's version. 
*
* @access protected
* @return string
*/
protected function _getVersion()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
$this->connect();
$version=@pg_version($this->dbSQLConnection);
return $version['client'];
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns escaped version of string $string.
*
* @access public
* @param string $string
* @return string
*/
public function escapeString($string)
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return @pg_escape_string($string);
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns escaped version of binary string $binaryString.
*
* @access public
* @param string $binartString
* @return string
*/
public function &escapeBinaryString(&$binaryString)
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
$escapedBinaryString=@pg_escape_bytea($binaryString);
return $escapedBinaryString;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns unescaped version of binary string $binaryString
* returned by the SQL server.
*
* @access public
* @param string $binaryString
* @return string
*/
public function &unescapeSQLBinaryString(&$binaryString)
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
$unescapedSQLBinaryString=@pg_unescape_bytea($binaryString);
return $unescapedSQLBinaryString;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returned boolean TRUE if connection to SQL server is 
* established, otherwise it returns FALSE.
*
* @access public
* @return bool
*/
public function isConnected()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
static $isValidConnection=false;
if(($isValidConnection==false) && $this->_isResourceConnection()) $isValidConnection=($this->_isResourceConnection() && @pg_ping($this->dbSQLConnection));
return ($isValidConnection && @pg_ping($this->dbSQLConnection));
}
//////////////////////////////////////////////////////////////////
/**
*
*
* If the connection wasn't made yet, then establish connection to PostgreSQL database.
*
* @access public
* @return bool
*/
public function connect()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
if(($this->isConnected()==false) && (($this->dbSQLConnection=@pg_connect('host=\''.$this->dbSQLServer.'\' port=\''.$this->dbSQLServerPort.'\' dbname=\''.$this->dbSQLDBName.'\' user=\''.$this->dbSQLUser.'\' password=\''.$this->dbSQLPassword.'\'',PGSQL_CONNECT_FORCE_NEW))===false)) throw new RC4PHP_DB_PostgreSQL_Exception($this->dbSQLConnection,"SQL server connect failure.",-1);
return true;	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* If the connection was made, then disconnects object from SQL server.
*
* @access public
* @return bool
*/
public function disconnect()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
if($this->isConnected()) return @pg_close($this->dbSQLConnection);	
else return false;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Sends a query to be executed by the SQL engine and returns an result
* object. If the SQL instruction it's not generating a result that would
* be used , then it's mandatory to execute recorset's method execute().
*
* @access public
* @param string $sql
* @return RC4PHP_DB_PostgreSQL_Result
*/
public function query($sql)
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
try { return new RC4PHP_DB_PostgreSQL_Result($this,$sql); }
catch(Exception $e) { $this->disconnect(); throw $e; }
}
//////////////////////////////////////////////////////////////////
/**
*
*
* @access public
* Returns an array with databases from SQL server.
* @return array
*/
public function getDatabases()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return $this->_get('SELECT datname FROM pg_database ORDER BY datname');
}	
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns an array with tables from specified database. 
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return array
*/
public function getTables($database='')
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return $this->_get('SELECT catalogClass.relname as "tables" FROM pg_catalog.pg_class AS catalogClass LEFT JOIN pg_catalog.pg_namespace AS catalogNameSpace ON (catalogNameSpace.oid = catalogClass.relnamespace) WHERE ((catalogClass.relkind IN (\'r\',\'\')) AND (catalogNameSpace.nspname NOT IN (\'pg_catalog\', \'pg_toast\')) AND (pg_catalog.pg_table_is_visible(catalogClass.oid))) ORDER BY catalogClass.relname',$database);
}	
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns an array with views from specified database. 
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return array
*/
public function getViews($database='')
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return $this->_get('SELECT catalogClass.relname as "views" FROM pg_catalog.pg_class AS catalogClass LEFT JOIN pg_catalog.pg_namespace AS catalogNameSpace ON (catalogNameSpace.oid = catalogClass.relnamespace) WHERE ((catalogClass.relkind IN (\'v\',\'\')) AND (catalogNameSpace.nspname NOT IN (\'pg_catalog\', \'pg_toast\')) AND (pg_catalog.pg_table_is_visible(catalogClass.oid))) ORDER BY catalogClass.relname',$database);
}
//////////////////////////////////////////////////////////////////
public function createSQLFunctionDATE2MIDAS($database='')
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
//2DO 
}
//////////////////////////////////////////////////////////////////
public function createSQLFunctionMIDAS2DATE($database='')
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
//2DO 		 
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_PostgreSQL_Result
*
* It's the base result class who will be extended by other SQL result classes.
* 
* ------------------------------------------------------------------------------
* (Note: the result's rows and columns can also be accessed as array elements
* 		Example: $result[0][0] 		-> first columnn from 1st row
* 			 $result[1]['Foo']	-> column 'Foo' from 2nd row)
* ------------------------------------------------------------------------------
* 
* GET PROPERTIES
* -------------------------------------------------------------
* type			= object's type: 'PostgreSQLResult'
* maxPageSize		= limit maximum page size
* pageSize		= number of rows for page
* pages			= number of pages
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* rows			= number of rows from current page or total number of rows if pagination is not used
* totalRows             = total number of rows, no matter pagination is set or not
* fields		= number of fields
* affectedRows  	= number of affected rows
* lastInsertedID        = last inserted ID
* executionTime         = execution time for the SQL query in msec
* 
* SET PROPERTIES
* -------------------------------------------------------------
* maxPageSize		= limit maximum page size
* pageSize		= number of rows for page
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* 
* PUBLIC METHODS
* -------------------------------------------------------------
* execute();				-> execute the sql querry.
* fetchField($fieldOffset=NULL);
* fetchRow();			        -> fetch row from current row position as an array. each result column is stored in an array offset, starting at offset 0.
* fetchRowAssociative();		-> fetch row from current row position as an associative array of column's names.
* fetchRowArray();			-> fetch row from current row position as an array. the array offsets can be colum's name or column's number (starting from 0).
* fetchObject();			-> fetch row from current row position as an object with properties that correspond to the fetched row.
* fetchAllRows();			-> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension is column (starting from 0).
* fetchAllRowsAssociative();		-> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension is column's name.
* fetchAllRowsArray();			-> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension can be colum's name or column's number (starting from 0).
* fetchAllObjectsArray();		-> fetch all rows from current row position as an  array of objects. the array offsets are row numbers (starting from 0).
* nextResult();
* freeResult();				-> free all memory associated with the result.
* 
* @access public
*/
class RC4PHP_DB_PostgreSQL_Result extends RC4PHP_DB_SQL_Result
{
protected $dbSQLResultCurrentPageOffset=0;
protected $dbSQLCommandLIMIT='';
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_PostgreSQL_Result object
*
* Initialize object's properties.
* It doesn't query SQL server until execute() method or a property 
* of the result object (such as fetchRow() method or rows property,
* for example) it's called.
*
* @param RC4PHP_DB_PostgreSQL $RC4PHP_DB_PostgreSQLObject
* @param string $dbSQLCommand
* @return RC4PHP_DB_PostgreSQL_Result
*/
public function __construct(RC4PHP_DB_PostgreSQL &$RC4PHP_DB_PostgreSQLObject,&$dbSQLCommand)
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
parent::__construct($RC4PHP_DB_PostgreSQLObject,$dbSQLCommand);
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_PostgreSQL_Result object
*
* When object it's destroyed, the associated memory with the result
* it's freed.
*
* @return void
*/
public function __destruct()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
parent::__destruct();
}
//////////////////////////////////////////////////////////////////
/**
* Clonning RC4PHP_DB_PostgreSQL_Result object
*
* When object it's cloned, the internal $dbSQLObject it's clonned
* and the result it's cleared. When needed, a new connection to
* the SQL server will be established and a new result will be 
* retrived.
*
* @return RC4PHP_DB_PostgreSQL_Result
*/
public function __clone()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
parent::__clone();
$this->dbSQLResultCurrentPageOffset=$that->dbSQLResultCurrentPageOffset;
$this->dbSQLCommandLIMIT=$that->dbSQLCommandLIMIT;
}
//////////////////////////////////////////////////////////////////
public function __sleep()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
$sleepArray=parent::__sleep();
$sleepArray[]='dbSQLResultCurrentPageOffset';
$sleepArray[]='dbSQLCommandLIMIT';
return $sleepArray;
}
//////////////////////////////////////////////////////////////////
/**
* Getting RC4PHP_DB_PostgreSQL_Result properties
*
* type			= object's type: 'PostgreSQLResult'
* pageSize		= number of rows for page
* pages			= number of pages
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* rows			= number of rows from current page or total number of rows if pagination is not used
* totalRows             = total number of rows, no matter pagination is set or not
* fields		= number of fields
* affectedRows  	= number of affected rows
* lastInsertedID        = last inserted ID
* executionTime         = execution time for the SQL query in msec
*
* @param string $varname
* @return mixed
*/
public function __get($varname)
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
$varname=@strtoupper($varname);
switch($varname)
	{
		case 'TYPE':    return 'PostgreSQL.Result';
		default:	return parent::__get($varname);
	}
}
//////////////////////////////////////////////////////////////////
/**
* Setting RC4PHP_DB_PostgreSQL_Result properties
*
* pageSize	= number of rows for page
* page		= current page number (starting from 1)
* row		= current row number (from current page, if pageSize is set) (starting from 0)
*
* @param string $varname
* @param string $value
*/
public function __set($varname,$value)
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try
	{
	 $varname=@strtoupper($varname);
	 $value=@intval($value);
	 parent::__set($varname,$value);
	 switch($varname)
		{
			case 'PAGE':
				$this->dbSQLResultCurrentPageOffset=($this->dbSQLResultCurrentPage==1)?(0):(($this->dbSQLResultCurrentPage*$this->dbSQLResultPageSize)-$this->dbSQLResultPageSize);
				//change sql limit
				$this->dbSQLCommandLIMIT=($this->dbSQLResultPageSize==0)?(''):(($this->dbSQLResultCurrentPage==1)?('LIMIT '.$this->dbSQLResultPageSize):('LIMIT '.$this->dbSQLResultPageSize.' OFFSET  '.$this->dbSQLResultCurrentPageOffset));
				return true;

			case 'ROW':
				$this->_checkConnectionAndResult();
                                $value=($value<0)?(0):($value>($this->rows-1)?($this->rows-1):($value));
				$this->dbSQLResultCurrentRow=$value;
				return @pg_result_seek($this->dbSQLResult,$this->dbSQLResultCurrentRow);
		}
	}		
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}		
}	
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'PostgreSQL.Result'.
* 
* @access protected
* @return string
*/
protected function _getType()
///class RC4PHP_DB_PostgreSQL/////////////////////////////////////
{
return 'PostgreSQL.Result';
}
//////////////////////////////////////////////////////////////////
/**
*
*
* It checks if the connection was already established and the SQL command
* was sended to the server. If not, try to connect to the PostgreSQL database 
* and sends command to server.
*
* @access protected
*/
protected function _checkConnectionAndResult($acceptRC4PHP_DB_SQL_ResultAsBooleanTrue=false)
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
$this->_checkConnection();

if(($this->dbSQLResult===false) || ($this->dbSQLResultPreviousPage!=$this->dbSQLResultCurrentPage))
	{
	 $startTime=microtime(true);
	 $this->dbSQLResultPreviousPage=$this->dbSQLResultCurrentPage;
 	 $this->freeResult();
	 if(strlen($this->dbSQLCommandLIMIT))
	 	{
		 if(substr_count($this->dbSQLCommand,';')>1) throw new RC4PHP_DB_SQL_Exception('Pagination feature is supported only for single queryes. '.self::_ErrorMessageHeader_.trim($this->dbSQLCommand).self::_ErrorMessageFooter_);
 		 /* current SQL command should be a SELECT command */ 
		 if(($this->dbSQLResult=@pg_query($this->_getConnection(),'SELECT __rc4php__.* FROM ('.$this->dbSQLCommand.') AS __rc4php__ '.$this->dbSQLCommandLIMIT))===false)
			{ if(($this->dbSQLResult=@pg_query($this->_getConnection(),$this->dbSQLCommand.' '.$this->dbSQLCommandLIMIT))===false) { throw new RC4PHP_DB_PostgreSQL_Exception($this->_getConnection()); } }		
		}
	 else
	 	{ /* current SQL command shouldn't be a SELECT command or a SELECT command without pagination */ 
		 if(($this->dbSQLResult=@pg_query($this->_getConnection(),$this->dbSQLCommand))===false) { throw new RC4PHP_DB_PostgreSQL_Exception($this->_getConnection()); }	 	 
		}
	 $this->dbSQLQueryTime=microtime(true)-$startTime;		
 	 //at this point I have to recheck if it's a resource result
 	 $this->_isResourceResult(true);	
 	 if($this->dbSQLResult===false) $this->dbSQLResult=true;
	}	
//at this point	dbSQLResult can be only a resource or boolean 'true'
if($acceptRC4PHP_DB_SQL_ResultAsBooleanTrue) { if(($this->dbSQLResult!==true) && ($this->_isResourceResult()==false)) { throw new RC4PHP_DB_PostgreSQL_Exception($this->_getConnection(),'Invalid result.',-1); } }	
else { if($this->_isResourceResult()==false) { throw new RC4PHP_DB_PostgreSQL_Exception($this->_getConnection(),'Invalid result.',-1); } }
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of rows from result.
*
* @access protected
* @return integer | boolean
*/
protected function _getRows()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     if($this->dbSQLResultRows==0)
        {
	 $this->_checkConnectionAndResult();
	 $this->dbSQLResultRows=@pg_num_rows($this->dbSQLResult);
	} 
     return $this->dbSQLResultRows;
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of affected rows by the SQL command.
*
* @access protected
* @return integer | boolean
*/
protected function _getAffectedRows()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult(true);
     return @pg_affected_rows($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the last inserted ID.
*
* @access protected
* @return integer | boolean
*/
protected function _getLastInsertedID()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
//2DO
/*
SELECT pg_get_serial_sequence('test', 'identity'); -> return Sequence name
SELECT CURRVAL('$seq_name') AS seq

try
	{
	 $this->_checkConnectionAndResult(true);
	 return $this->_getConnection()->lastInsertRowid();
	}
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	
*/
return false;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of fields(columns) from result.
*
* @access protected
* @return integer | boolean
*/
protected function _getFields()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult();
     $this->dbSQLResultRows=@pg_num_fields($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of total rows not just the number of rows from
* current page for result.
*
* @access protected
* @return integer
*/
protected function _getTotalRows()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
if($this->dbSQLResultTotalRows==0)
	{
	 $this->_checkConnection();
	 if($this->dbSQLResult===true) { $this->dbSQLResultTotalRows=0; return 0; }
	 
	 if($rs=@pg_query($this->_getConnection(),'SELECT COUNT(*) FROM ('.$this->dbSQLCommand.') AS __rc4php__'))
	 	{
		 $this->dbSQLResultTotalRows=@pg_fetch_result($rs,0,0);
		 unset($rs);
		}
	 else 
	 	{
	 	 if($rs=@pg_query($this->_getConnection(),$this->dbSQLCommand))
	 		{
			 $this->dbSQLResultTotalRows=@pg_num_rows($rs);
			 unset($rs);
			}
		 else $this->dbSQLResultTotalRows=0;	
		}	
	} 
return $this->dbSQLResultTotalRows;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Send the SQL command to the SQL engine.
*
* @access public
* @return boolean | boolean
*/
public function execute()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try { 
     $this->_checkConnectionAndResult(true); 
     return true;
    } 
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch field or returns FALSE.
*
* @access public
* @return mixed | boolean
*/
public function fetchField($fieldOffset=NULL)
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
/*
$this->_checkConnectionAndResult();
return (($fieldOffset!==NULL)?($this->dbSQLResult->fetch_field_direct($fieldOffset)):($this->dbSQLResult->fetch_field()));
*/
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an array. The method returns FALSE 
* when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRow()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult();
     ++$this->dbSQLResultCurrentRow;
     return @pg_fetch_row($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	 
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an associative array. The method 
* returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRowAssociative()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult();
     ++$this->dbSQLResultCurrentRow;
     return @pg_fetch_assoc($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	 
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an associative and numerical array.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRowArray()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult();
     ++$this->dbSQLResultCurrentRow;
     return @pg_fetch_array($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	 
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as object.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return object | boolean
*/
public function fetchObject()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
try {
     $this->_checkConnectionAndResult();
     ++$this->dbSQLResultCurrentRow;
     return @pg_fetch_object($this->dbSQLResult);
    }
catch(Exception $e)
	{
	 $this->freeResult();
	 if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
	 throw $e;
	}	 
}
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
*
*
* When sending more than one SQL statement to the server or executing
* a stored procedure with multiple results, it will cause the server 
* to return multiple result sets. This function will test for additional
* results available form the server. If an additional result set exists 
* it will free the existing result set and prepare to fetch the rows from
* the new result set. The function will return TRUE if an additional result
* set was available or FALSE otherwise. 
*
* @access public
* @return boolean
*/
public function nextResult()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
return false;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* When sending more than one SQL statement to the server or executing
* a stored procedure with multiple results, it will cause the server 
* to return multiple result sets. This function will test for additional
* results available form the server. If an additional result set exists 
* it will free the existing result set and prepare to fetch the rows from
* the new result set. The function will return TRUE if an additional result
* set was available or FALSE otherwise. 
*
* @access public
* @return boolean
*/
public function freeResult()
///class RC4PHP_DB_PostgreSQL_Result//////////////////////////////
{
if($this->_isResourceResult(true)) return @pg_free_result($this->dbSQLResult);
else return false;
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY
*
* It's a MySQL dictionary class.
* 
* GET PROPERTIES
* ---------------------------------------------------------------------------
* DATA TYPES
* ==========
* boolean
* binary
* char	
* unicodeChar
* varChar
* unicodeVarChar
* float			
* integer
* numeric
* date
* 
* PUBLIC METHODS
* ---------------------------------------------------------------------------
* DATA TYPES
* ==========
* char($size=self::DB_DEFAULT_CHAR_SIZE)
* unicodeChar($size=self::DB_DEFAULT_CHAR_SIZE);
* varchar($size=self::DB_DEFAULT_VARCHAR_SIZE);
* unicodeVarChar($size=self::DB_DEFAULT_VARCHAR_SIZE);
* float($size=self::DB_DEFAULT_FLOAT_SIZE);
* integer($size=self::DB_DEFAULT_INTEGER_SIZE);
* numeric($fieldDefinition=array(self::DB_DEFAULT_NUMERIC_PRECISION,self::DB_DEFAULT_NUMERIC_SCALE),$optionalScale=self::DB_DEFAULT_NUMERIC_SCALE);
* 
* @access public
*/
class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY extends RC4PHP_DB_SQL_DATA_DICTIONARY
{
//////////////////////////////////////////////////////////////////
public function __construct($dbSQLcommand='')
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ parent::__construct($dbSQLcommand); }
//////////////////////////////////////////////////////////////////
protected function _boolean()
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ return 'boolean'; }
//////////////////////////////////////////////////////////////////
protected function _char($size=self::DB_DEFAULT_CHAR_SIZE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ 
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_CHAR_SIZE))):(abs(intval($size)));
return "char($size)"; 
}
//////////////////////////////////////////////////////////////////
protected function _unicodeChar($size=self::DB_DEFAULT_UNICODE_CHAR_SIZE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_UNICODE_CHAR_SIZE))):(abs(intval($size))))>255) $size=255;
return "char($size)"; 
}
//////////////////////////////////////////////////////////////////
protected function _varChar($size=self::DB_DEFAULT_VARCHAR_SIZE) 
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ 
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_VARCHAR_SIZE))):(abs(intval($size)));
return "varchar($size)"; 
}
//////////////////////////////////////////////////////////////////
protected function _unicodeVarChar($size=self::DB_DEFAULT_UNICODE_VARCHAR_SIZE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{//2do
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_UNICODE_VARCHAR_SIZE))):(abs(intval($size)));
return "varchar($size)"; 
}
//////////////////////////////////////////////////////////////////
protected function _binary()
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ return 'bytea'; }
//////////////////////////////////////////////////////////////////
protected function _float($size=self::DB_DEFAULT_FLOAT_SIZE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_FLOAT_SIZE))):(abs(intval($size))))>53) $size=53;
return "float($size)";
}
//////////////////////////////////////////////////////////////////
protected function _integer($size=self::DB_DEFAULT_INTEGER_SIZE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_INTEGER_SIZE))):(abs(intval($size)));
if($size>8) $size=8;
switch($size)
	{
		case 1:  return 'smallint';
		case 2:  return 'smallint';
		case 4:  return 'integer';
		case 8:  return 'bigint';
		default: return '';
	}
}
//////////////////////////////////////////////////////////////////
protected function _numeric($fieldDefinition=array(self::DB_DEFAULT_NUMERIC_PRECISION,self::DB_DEFAULT_NUMERIC_SCALE),$optionalScale=self::DB_DEFAULT_NUMERIC_SCALE)
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{
$precision=(is_array($fieldDefinition))?((isset($fieldDefinition[0]))?(abs(intval($fieldDefinition[0]))):(self::DB_DEFAULT_NUMERIC_PRECISION)):(abs(intval($fieldDefinition)));
if(($scale=(is_array($fieldDefinition))?((isset($fieldDefinition[1]))?(abs(intval($fieldDefinition[1]))):(self::DB_DEFAULT_NUMERIC_SCALE)):((empty($optionalScale)?(self::DB_DEFAULT_NUMERIC_SCALE):(abs(intval($optionalScale))))))>$precision) $scale=$precision;
return "numeric($precision,$scale)";
}
//////////////////////////////////////////////////////////////////
protected function _dateTime()
///class RC4PHP_DB_PostgreSQL_DATA_DICTIONARY/////////////////////
{ return 'timestamp'; }
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_PostgreSQL_Exception
*
* It's the PostgreSQL exception class.
* 
* PUBLIC METHODS
* -------------------------------------------------------------
* getMessage();			-> returns message of exception 
* getCode();			-> returns code of exception
* getFile();			-> returns source filename
* getLine();			-> returns source line
* getTrace();			-> returns an array of the backtrace()
* getTraceAsString();	-> returns formated string of trace
* getBacktrace();		-> returns an array of the backtrace
* 
* @access public
*/
class RC4PHP_DB_PostgreSQL_Exception extends RC4PHP_DB_SQL_Exception
{
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_PostgreSQL_Exception object
*
* Initialize object's properties.
*
* @param object $dbSQLConnection
* @param string $message
* @param integer $code
* @return RC4PHP_DB_SQL_Exception
*/
public function __construct(&$dbSQLConnection=false,$SQLErrorMessage=self::_ExceptionDefaultMessage_,$SQLErrorCode=self::_ExceptionDefaultCode_)
///class RC4PHP_DB_PostgreSQL_Exception///////////////////////////////
{
parent::__construct($SQLErrorMessage, $SQLErrorCode);
if(@is_resource($dbSQLConnection))
    {
     if($errorMessage=@pg_last_error($dbSQLConnection)) $this->message=@trim($SQLErrorMessage.' '.RC4PHP_DB_SQL_Result::_ServerErrorMessageHeader_.$errorMessage.RC4PHP_DB_SQL_Result::_ServerErrorMessageFooter_);
     else $this->message=@trim($SQLErrorMessage);   
    } 
else 
    {
     if($errorMessage=@pg_last_error()) $this->message=@trim($SQLErrorMessage.' '.RC4PHP_DB_SQL_Result::_ServerErrorMessageHeader_.$errorMessage.RC4PHP_DB_SQL_Result::_ServerErrorMessageFooter_);
     else $this->message=@trim($SQLErrorMessage);   
    } 


//$this->message=trim($SQLErrorMessage.' '.RC4PHP_DB_SQL_Result::hide@address.com().RC4PHP_DB_SQL_Result::_ServerErrorMessageFooter_);	
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
?>
Return current item: RC4PHP class