Add new directory structure. Tags will contain current and past releases, and stable will contain any bug fixes to the current stable release so users won't have to get the potentially broken trunk build to fix a screwup in stable.

Trunk updated to 0.9

git-svn-id: http://kusabax.cultnet.net/svn/repo/stable@176 73d99b7e-4f53-4972-b7b7-2ecd3c4d89ee
This commit is contained in:
Sazpaimon committed 2009-05-27 06:37:50 +00:00
commit 88bacfad9c
316 files changed
+79806

No files matched your search

@@ -0,0 +1,112 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_mysql extends ADODB_DataDict {
var $dbtype = 'mysql';
var $alterCol = ' MODIFY COLUMN';
var $alterTableAddIndex = true;
var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later
var $dropIndex = 'DROP INDEX %s ON %s';
var $renameColumn = 'ALTER TABLE %s CHANGE COLUMN %s %s %s'; // needs column-definition!
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':return 'LONGTEXT';
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'LONGTEXT';
case 'B': return 'LONGBLOB';
case 'D': return 'DATE';
case 'DT': return 'DATETIME';
case 'T': return 'TIME';
case 'TS': return 'TIMESTAMP';
case 'L': return 'TINYINT';
case 'R':
case 'I4':
case 'I': return 'INTEGER';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
if ($fnotnull) $suffix .= ' NOT NULL';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";
else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
if (isset($idxoptions['FULLTEXT'])) {
$unique = ' FULLTEXT';
} elseif (isset($idxoptions['UNIQUE'])) {
$unique = ' UNIQUE';
} else {
$unique = '';
}
if ( is_array($flds) ) $flds = implode(', ',$flds);
if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";
else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;
$s .= ' (' . $flds . ')';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
?>
@@ -0,0 +1,321 @@
<?php
/**
* ADOdb Lite Date Module for Mysql
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class mysql_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysql_date_ADOConnection extends mysql_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $isoDates = true; // accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
else return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
$fraction = $dayFraction * 24 * 3600;
return "from_unixtime(unix_timestamp($date)+$fraction)";
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate, $date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
return adodb_date($this->fmtTimeStamp, $this->UnixTimeStamp($timestamp));
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt, $v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function SQLDate($fmt, $col=false)
{
if (!$col)
$col = $this->sysTimeStamp;
$s = 'DATE_FORMAT('.$col.",'";
$concat = false;
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt, $i, 1);
}
/** FALL THROUGH */
case '-':
case '/':
$s .= $ch;
break;
case 'Y':
case 'y':
$s .= '%Y';
break;
case 'M':
$s .= '%b';
break;
case 'm':
$s .= '%m';
break;
case 'D':
case 'd':
$s .= '%d';
break;
case 'Q':
case 'q':
$s .= "'),Quarter($col)";
if ($len > $i+1)
$s .= ",DATE_FORMAT($col,'";
else $s .= ",('";
$concat = true;
break;
case 'H':
$s .= '%H';
break;
case 'h':
$s .= '%I';
break;
case 'i':
$s .= '%i';
break;
case 's':
$s .= '%s';
break;
case 'a':
case 'A':
$s .= '%p';
break;
case 'w':
$s .= '%w';
break;
case 'l':
$s .= '%W';
break;
}
}
$s.="')";
if ($concat)
$s = "CONCAT($s)";
return $s;
}
}
eval('class mysql_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysql_date_ResultSet extends mysql_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt, $v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt, $tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt, $tt);
}
function UnixDate($v)
{
return mysql_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return mysql_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,660 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, SqLite and Sybase.
*
*/
class mysql_driver_ADOConnection extends ADOConnection
{
var $nameQuote = '`';
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
function mysql_driver_ADOConnection()
{
$this->dbtype = 'mysql';
$this->dataProvider = 'mysql';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('mysql_connect')) {
echo "ERROR: Function 'mysql_connect' not found! Check if MySQL is properly set up. And that PHP has the MySQL extension installed.";
return false;
}
$this->host = $host;
if (!empty($this->port)) $this->host .= ":" . $this->port;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
if($this->persistent == 1)
{
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0)
$this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password, $this->clientFlags );
else
$this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password );
}
else
{
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0)
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection, $this->clientFlags );
else if (strnatcmp(PHP_VERSION, '4.2.0') >= 0)
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection );
else
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password );
}
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return false;
}
if (!empty($this->database))
{
if($this->SelectDB( $this->database ) == false)
{
$this->connectionId = false;
return false;
}
}
return true;
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
$result = @mysql_select_db( $this->database, $this->connectionId );
if($result === false)
{
if($this->createdatabase == true)
{
$result = @mysql_query( "CREATE DATABASE IF NOT EXISTS " . $this->database, $this->connectionId );
if ($result === false) { // error handling if query fails
return false;
}
$result = @mysql_select_db( $this->database, $this->connectionId );
if($result === false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
if ($this->connectionId === false)
{
return @mysql_error();
}
else
{
return @mysql_error($this->connectionId);
}
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
if ($this->connectionId === false)
{
return @mysql_errno();
}
else
{
return @mysql_errno($this->connectionId);
}
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @mysql_affected_rows($this->connectionId);
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @mysql_insert_id($this->connectionId);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
if (!$magic_quotes) {
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) {
return "'" . mysql_real_escape_string($string, $this->connectionId) . "'";
}
$string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
$list = implode(', ', $arr);
if (strlen($list) > 0) return "CONCAT($list)";
else return '';
}
function IfNull( $field, $ifNull )
{
return " IFNULL($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@mysql_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$false = false;
$limit = '';
if ($offset >= 0 || $nrows >= 0)
{
$offset = ($offset >= 0) ? $offset . "," : '';
$nrows = ($nrows >= 0) ? $nrows : '18446744073709551615';
$limit = ' LIMIT ' . $offset . ' ' . $nrows;
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? 1 : 0;
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @mysql_query( $this->sql, $this->connectionId );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql . $limit;
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @mysql_query( $this->sql, $this->connectionId );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC: $recordset->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH: $recordset->fetchMode = MYSQL_BOTH; break;
}
$recordset->_numOfRows = @mysql_num_rows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @mysql_num_fields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class mysql_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* mysqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function mysql_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function Close()
{
@mysql_free_result( $this->resultId );
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = mysql_fetch_array($this->resultId,$this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @mysql_data_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @mysql_fetch_array($this->resultId,$this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$fieldObject = @mysql_fetch_field($this->resultId, $fieldOffset);
$fieldObject->max_length = @mysql_field_len($this->resultId,$fieldOffset);
}
else
{
$fieldObject = @mysql_fetch_field($this->resultId);
$fieldObject->max_length = @mysql_field_len($this->resultId);
}
return $fieldObject;
}
}
?>
@@ -0,0 +1,150 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class mysql_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysql_extend_ADOConnection extends mysql_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $genID = 0;
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table %s";
function GenID($seqname='adodbseq', $startID=1)
{
$getnext = sprintf($this->_genIDSQL, $seqname);
$holdtransOK = $this->transaction_status;
$result = @$this->Execute($getnext);
if (!$result) {
if ($holdtransOK)
$this->transaction_status = true;
// $u = strtoupper($seqname);
$this->Execute(sprintf($this->_genSeqSQL, $seqname));
$this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID-1));
$result = $this->Execute($getnext);
}
$this->genID = mysql_insert_id($this->connectionId);
if ($result)
$result->Close();
return $this->genID;
}
function CreateSequence($seqname='adodbseq',$startID=1)
{
$u = strtoupper($seqname);
$ok = $this->Execute(sprintf($this->_genSeqSQL, $seqname));
if (!$ok)
return false;
return $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID-1));
}
function DropSequence($seqname='adodbseq')
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class mysql_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysql_extend_ResultSet extends mysql_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,623 @@
<?php
/**
* ADOdb Lite Meta Module for Mysql
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class mysql_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysql_meta_ADOConnection extends mysql_meta_EXTENDER
{
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p))
return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
{
if ( !empty($owner) ) {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
$matches = array();
if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
$foreign_keys = array();
$num_keys = count($matches[0]);
for ( $i = 0; $i < $num_keys; $i ++ ) {
$my_field = explode('`, `', $matches[1][$i]);
$ref_table = $matches[2][$i];
$ref_field = explode('`, `', $matches[3][$i]);
if ( $upper ) {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
}
}
}
return $foreign_keys;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false,$this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function &MetaDatabases()
{
$qid = mysql_list_dbs($this->connectionId);
$arr = array();
$i = 0;
$max = mysql_num_rows($qid);
while ($i < $max) {
$db = mysql_tablename($qid,$i);
if ($db != 'mysql') $arr[] = $db;
$i += 1;
}
return $arr;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
$this->metaTablesSQL .= " from $showSchema";
}
if ($mask) {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " like $mask";
}
$ret =& $this->_MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
function &_MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function MetaColumns($table)
{
$this->_findschema($table,$schema);
if ($schema) {
$dbName = $this->database;
$this->connection->SelectDB($schema);
}
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($schema) {
$this->SelectDB($dbName);
}
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
// split type into type(length):
$fld->scale = null;
if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
$fld->type = $query_array[1];
$arr = explode(",",$query_array[2]);
$fld->enums = $arr;
$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
$fld->max_length = ($zlen > 0) ? $zlen : 1;
} else {
$fld->type = $type;
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($type,'blob') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != '' && $d != 'NULL') {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->has_default = false;
}
}
if ($save == ADODB_FETCH_NUM) {
$retarr[] = $fld;
} else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
// get index details
$rs =& $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
// restore fetchmode
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return $false;
}
$indexes = array ();
// parse index data into array
while (!$rs->EOF)
{
if ($primary == FALSE AND $rs->fields[2] == 'PRIMARY') {
$rs->MoveNext();
continue;
}
if (!isset($indexes[$rs->fields[2]])) {
$indexes[$rs->fields[2]] = array(
'unique' => ($rs->fields[1] == 0),
'columns' => array()
);
}
$indexes[$rs->fields[2]]['columns'][$rs->fields[3] - 1] = $rs->fields[4];
$rs->MoveNext();
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index )
{
ksort ($indexes[$index]['columns']);
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class mysql_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysql_meta_ResultSet extends mysql_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
return $tmap;
}
}
}
?>
@@ -0,0 +1,426 @@
<?php
/*
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Library for basic performance monitoring and tuning.
Modified 17 March 2006 for use with ADOdb Lite by Pádraic Brady
Such modifications as listed (c) 2006 Pádraic Brady (maugrimtr@hotmail.com)
Modifications:
- Moved adodb_perf class to $dbtype_perfmon_module.inc as the $dbtype_perfmon_ADOConnection class
- restricted adodb_perf class to tracking table name to use (for BC) - it's an alias for perfmon_parent_ADOConnection::table()
- Added LogSQL() method, and _logsql property
- general formatting changes and replacement of htmlspecialchars() woth htmlentities()
- parent class for specific driver modules added in adodb-perf-module.inc.php
*/
// required to allow a common parent for all perfmon dbtype specific modules to extend
$thisDBType = 'mysql';
require_once(ADODB_DIR . '/adodb-perf.inc.php');
require_once(ADODB_DIR . '/adodb-perf-module.inc.php');
// not really needed, we already know the parent class name?
eval('class mysql_perfmon_EXTENDER extends perfmon_parent_ADOConnection { }');
class mysql_perfmon_ADOConnection extends mysql_perfmon_EXTENDER
{
var $upperCase = 'upper';
var $substr = "substring";
var $tablesSQL = 'show table status';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 text NOT NULL,
params text NOT NULL,
tracer text NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'MyISAM cache hit ratio' => array('RATIO',
'=GetKeyHitRatio',
'=WarnCacheRatio'),
'InnoDB cache hit ratio' => array('RATIO',
'=GetInnoDBHitRatio',
'=WarnCacheRatio'),
'data cache hit ratio' => array('HIDE', # only if called
'=FindDBHitRatio',
'=WarnCacheRatio'),
'sql cache hit ratio' => array('RATIO',
'=GetQHitRatio',
''),
'IO',
'data reads' => array('IO',
'=GetReads',
'Number of selects (Key_reads is not accurate)'),
'data writes' => array('IO',
'=GetWrites',
'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
'Data Cache',
'MyISAM data cache size' => array('DATAC',
array("show variables", 'key_buffer_size'),
'' ),
'BDB data cache size' => array('DATAC',
array("show variables", 'bdb_cache_size'),
'' ),
'InnoDB data cache size' => array('DATAC',
array("show variables", 'innodb_buffer_pool_size'),
'' ),
'Memory Usage',
'read buffer size' => array('CACHE',
array("show variables", 'read_buffer_size'),
'(per session)'),
'sort buffer size' => array('CACHE',
array("show variables", 'sort_buffer_size'),
'Size of sort buffer (per session)' ),
'table cache' => array('CACHE',
array("show variables", 'table_cache'),
'Number of tables to keep open'),
'Connections',
'current connections' => array('SESS',
array('show status','Threads_connected'),
''),
'max connections' => array( 'SESS',
array("show variables",'max_connections'),
''),
false
);
/**
Get server version info...
@returns An array with 2 elements: $arr['description'] is the description string,
and $arr['version'] is the version (also a string).
*/
function ServerInfo()
{
$arr = array();
$result = $this->do_query('select version()', -1, -1, false);
if (!$result->EOF) $data = $result->fields;
else $data = array();
$arr['version'] = $arr['description'] = $data[0];
//****// Where does $arr come from in ADOdb - doesn't appear global, maybe null? A possible bug?
return $arr;
}
/*
Explain Plan for $sql.
If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
actual sql.
*/
function Explain($sql,$partial=false)
{
$perf_table = perfmon_parent_ADOConnection::table(); // this was missing in the original ADOdb perf class - bug?
if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN a non-select statement</p>';
$save = $this->LogSQL(false);
if ($partial) {
$sqlq = $this->qstr($sql.'%');
$arr = $this->GetArray("select distinct sql1 from $perf_table where sql1 like $sqlq");
if ($arr)
{
foreach($arr as $row)
{
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$sql = str_replace('?',"''",$sql);
if ($partial)
{
$sqlq = $this->qstr($sql.'%');
$sql = $this->GetOne("select sql1 from $perf_table where sql1 like $sqlq");
}
$s = '<p><strong>Explain</strong>: '.htmlentities($sql, ENT_QUOTES, 'UTF-8').'</p>';
$rs = $this->Execute('EXPLAIN '.$sql);
$s .= rs2html($rs,false,false,false,false);
$this->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
if (!$this->tablesSQL) return false;
$rs = $this->Execute($this->tablesSQL);
if (!$rs) return false;
$html = rs2html($rs,false,false,false,false);
return $html;
}
function CreateLogTable()
{
if (!$this->createTableSQL) return false;
$savelog = $this->LogSQL(false);
$ok = $this->Execute($this->createTableSQL);
$this->LogSQL($savelog);
return ($ok) ? true : false;
}
function GetReads()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$val = 0;
while (!$rs->EOF)
{
switch($rs->fields[0])
{
case 'Com_select':
$val = $rs->fields[1];
$rs->Close();
return $val;
}
$rs->MoveNext();
}
$rs->Close();
return $val;
}
function GetWrites()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$val = 0.0;
while (!$rs->EOF)
{
switch($rs->fields[0])
{
case 'Com_insert':
$val += $rs->fields[1];
break;
case 'Com_delete':
$val += $rs->fields[1];
break;
case 'Com_update':
$val += $rs->fields[1]/2;
$rs->Close();
return $val;
}
$rs->MoveNext();
}
$rs->Close();
return $val;
}
function FindDBHitRatio()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show table status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return '';
$type = strtoupper($rs->fields[1]);
$rs->Close();
switch($type)
{
case 'MYISAM':
case 'ISAM':
return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';
case 'INNODB':
return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';
default:
return $type.' not supported';
}
}
function GetQHitRatio()
{
//Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached
$hits = $this->_DBParameter(array("show status","Qcache_hits"));
$total = $this->_DBParameter(array("show status","Qcache_inserts"));
$total += $this->_DBParameter(array("show status","Qcache_not_cached"));
$total += $hits;
if ($total) return round(($hits*100)/$total,2);
return 0;
}
/*
Use session variable to store Hit percentage, because MySQL
does not remember last value of SHOW INNODB STATUS hit ratio
# 1st query to SHOW INNODB STATUS
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
Buffer pool hit rate 1000 / 1000
# 2nd query to SHOW INNODB STATUS
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
No buffer pool activity since the last printout
*/
function GetInnoDBHitRatio()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show innodb status');
;
$ADODB_FETCH_MODE = $save;
if (!$rs || $rs->EOF) return 0;
$stat = $rs->fields[0];
$rs->Close();
$at = strpos($stat,'Buffer pool hit rate');
$stat = substr($stat,$at,200);
if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr))
{
$val = 100*$arr[1]/$arr[2];
$_SESSION['INNODB_HIT_PCT'] = $val;
return round($val,2);
}
else
{
if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
return 0;
}
return 0;
}
function GetKeyHitRatio()
{
$hits = $this->_DBParameter(array("show status","Key_read_requests"));
$reqs = $this->_DBParameter(array("show status","Key_reads"));
if ($reqs == 0) return 0;
return round(($hits/($reqs+$hits))*100,2);
}
// start hack
var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK';
var $optimizeTableHigh = 'OPTIMIZE TABLE %s';
/**
* @see adodb_perf#optimizeTable
*/
function optimizeTable( $table, $mode = ADODB_OPT_LOW)
{
if ( !is_string( $table)) return false;
$sql = '';
switch( $mode)
{
case ADODB_OPT_LOW:
$sql = $this->optimizeTableLow;
break;
case ADODB_OPT_HIGH:
$sql = $this->optimizeTableHigh;
break;
default:
{
// May dont use __FUNCTION__ constant for BC (__FUNCTION__ Added in PHP 4.3.0)
trigger_error(sprintf( "<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, __FUNCTION__, $mode), E_USER_ERROR);
return false;
}
}
$sql = sprintf( $sql, $table);
return $this->Execute( $sql) !== false;
}
}
eval('class mysql_perfmon_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysql_perfmon_ResultSet extends mysql_perfmon_resultset_EXTENDER
{
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
}
}
}
?>
@@ -0,0 +1,113 @@
<?php
/**
* ADOdb Lite Transaction Module for Mysql
*
*/
eval('class mysql_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysql_transaction_ADOConnection extends mysql_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
return false;
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->transaction_status = false;
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
return true;
}
function RollbackTrans()
{
return false;
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($table,$where)
{
return false;
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class mysql_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysql_transaction_ResultSet extends mysql_transaction_resultset_EXTENDER
{
}
?>
@@ -0,0 +1,112 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_mysqli extends ADODB_DataDict {
var $dbtype = 'mysqli';
var $alterCol = ' MODIFY COLUMN';
var $alterTableAddIndex = true;
var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later
var $dropIndex = 'DROP INDEX %s ON %s';
var $renameColumn = 'ALTER TABLE %s CHANGE COLUMN %s %s %s'; // needs column-definition!
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':return 'LONGTEXT';
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'LONGTEXT';
case 'B': return 'LONGBLOB';
case 'D': return 'DATE';
case 'DT': return 'DATETIME';
case 'T': return 'TIME';
case 'TS': return 'TIMESTAMP';
case 'L': return 'TINYINT';
case 'R':
case 'I4':
case 'I': return 'INTEGER';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
if ($fnotnull) $suffix .= ' NOT NULL';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";
else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
if (isset($idxoptions['FULLTEXT'])) {
$unique = ' FULLTEXT';
} elseif (isset($idxoptions['UNIQUE'])) {
$unique = ' UNIQUE';
} else {
$unique = '';
}
if ( is_array($flds) ) $flds = implode(', ',$flds);
if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";
else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;
$s .= ' (' . $flds . ')';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
?>
@@ -0,0 +1,321 @@
<?php
/**
* ADOdb Lite Date Module for Mysql
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class mysqli_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysqli_date_ADOConnection extends mysqli_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $isoDates = true; // accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
else return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
$fraction = $dayFraction * 24 * 3600;
return "from_unixtime(unix_timestamp($date)+$fraction)";
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate, $date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
return adodb_date($this->fmtTimeStamp, $this->UnixTimeStamp($timestamp));
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt, $v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function SQLDate($fmt, $col=false)
{
if (!$col)
$col = $this->sysTimeStamp;
$s = 'DATE_FORMAT('.$col.",'";
$concat = false;
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt, $i, 1);
}
/** FALL THROUGH */
case '-':
case '/':
$s .= $ch;
break;
case 'Y':
case 'y':
$s .= '%Y';
break;
case 'M':
$s .= '%b';
break;
case 'm':
$s .= '%m';
break;
case 'D':
case 'd':
$s .= '%d';
break;
case 'Q':
case 'q':
$s .= "'),Quarter($col)";
if ($len > $i+1)
$s .= ",DATE_FORMAT($col,'";
else $s .= ",('";
$concat = true;
break;
case 'H':
$s .= '%H';
break;
case 'h':
$s .= '%I';
break;
case 'i':
$s .= '%i';
break;
case 's':
$s .= '%s';
break;
case 'a':
case 'A':
$s .= '%p';
break;
case 'w':
$s .= '%w';
break;
case 'l':
$s .= '%W';
break;
}
}
$s.="')";
if ($concat)
$s = "CONCAT($s)";
return $s;
}
}
eval('class mysqli_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysqli_date_ResultSet extends mysqli_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt, $v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt, $tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt, $tt);
}
function UnixDate($v)
{
return mysqli_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return mysqli_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,641 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, SqLite and Sybase.
*
*/
class mysqli_driver_ADOConnection extends ADOConnection
{
var $nameQuote = '`';
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
function mysqli_driver_ADOConnection()
{
$this->dbtype = 'mysqli';
$this->dataProvider = 'mysql';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('mysqli_real_connect')) {
echo "ERROR: Function 'mysqli_real_connect' not found! Check if MySQL is properly set up. And that PHP has the MySQLi extension installed. If MySQLi is not installed, try setting KU_DBTYPE to 'mysql' and try again.";
return false;
}
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
$this->connectionId = @mysqli_init();
@mysqli_real_connect( $this->connectionId, $this->host, $this->username, $this->password, $this->database, $this->port, $this->socket, $this->clientFlags );
if (mysqli_connect_errno() != 0)
{
$this->connectionId = false;
}
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return false;
}
if (!empty($this->database))
{
if($this->SelectDB( $this->database ) == false)
{
$this->connectionId = false;
return false;
}
}
return true;
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
$result = @mysqli_select_db( $this->connectionId, $this->database );
if($result === false)
{
if($this->createdatabase == true)
{
$result = @mysqli_query( $this->connectionId, "CREATE DATABASE IF NOT EXISTS " . $this->database );
if ($result === false) { // error handling if query fails
return false;
}
$result = @mysqli_select_db( $this->connectionId, $this->database );
if($result === false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
if ($this->connectionId === false)
{
return @mysqli_connect_error();
}
else
{
return @mysqli_error($this->connectionId);
}
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
if ($this->connectionId === false)
{
return @mysqli_connect_errno();
}
else
{
return @mysqli_errno($this->connectionId);
}
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @mysqli_affected_rows($this->connectionId);
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @mysqli_insert_id($this->connectionId);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
if (!$magic_quotes) {
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0 && function_exists('mysqli_real_escape_string')) {
return "'" . mysqli_real_escape_string($this->connectionId, $string) . "'";
}
$string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
$list = implode(', ', $arr);
if (strlen($list) > 0) return "CONCAT($list)";
else return '';
}
function IfNull( $field, $ifNull )
{
return " IFNULL($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@mysqli_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$false = false;
$limit = '';
if ($offset >= 0 || $nrows >= 0)
{
$offset = ($offset >= 0) ? $offset . "," : '';
$nrows = ($nrows >= 0) ? $nrows : '18446744073709551615';
$limit = ' LIMIT ' . $offset . ' ' . $nrows;
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? 1 : 0;
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @mysqli_query($this->connectionId, $this->sql );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @mysqli_query($this->connectionId, $this->sql );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQLI_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQLI_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQLI_BOTH; break;
}
$recordset->_numOfRows = @mysqli_num_rows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @mysqli_num_fields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class mysqli_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* mysqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function mysqli_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function Close()
{
@mysqli_free_result( $this->resultId );
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = mysqli_fetch_array($this->resultId,$this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @mysqli_data_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
// $fieldOffset not supported by mysqli
$fieldObject = @mysqli_fetch_field($this->resultId);
return $fieldObject;
}
}
?>
@@ -0,0 +1,150 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class mysqli_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysqli_extend_ADOConnection extends mysqli_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table %s";
var $genID = 0;
function GenID($seqname='adodbseq', $startID=1)
{
$getnext = sprintf($this->_genIDSQL, $seqname);
$holdtransOK = $this->transaction_status;
$result = @$this->Execute($getnext);
if (!$result) {
if ($holdtransOK)
$this->transaction_status = true;
// $u = strtoupper($seqname);
$this->Execute(sprintf($this->_genSeqSQL, $seqname));
$this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID-1));
$result = $this->Execute($getnext);
}
$this->genID = mysqli_insert_id($this->connectionId);
if ($result)
$result->Close();
return $this->genID;
}
function CreateSequence($seqname='adodbseq',$startID=1)
{
$u = strtoupper($seqname);
$ok = $this->Execute(sprintf($this->_genSeqSQL, $seqname));
if (!$ok)
return false;
return $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID-1));
}
function DropSequence($seqname='adodbseq')
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class mysqli_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysqli_extend_ResultSet extends mysqli_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,624 @@
<?php
/**
* ADOdb Lite Meta Module for Mysql
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class mysqli_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysqli_meta_ADOConnection extends mysqli_meta_EXTENDER
{
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
function MetaError($err=false)
{
include_once(ADODB_DIR . "/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR . "/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p))
return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
{
if ( !empty($owner) ) {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
$matches = array();
if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
$foreign_keys = array();
$num_keys = count($matches[0]);
for ( $i = 0; $i < $num_keys; $i ++ ) {
$my_field = explode('`, `', $matches[1][$i]);
$ref_table = $matches[2][$i];
$ref_field = explode('`, `', $matches[3][$i]);
if ( $upper ) {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
}
}
}
return $foreign_keys;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false, $this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function &MetaDatabases()
{
$qid = mysql_list_dbs($this->connectionId);
$arr = array();
$i = 0;
$max = mysql_num_rows($qid);
while ($i < $max) {
$db = mysql_tablename($qid,$i);
if ($db != 'mysql') $arr[] = $db;
$i += 1;
}
return $arr;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
$this->metaTablesSQL .= " from $showSchema";
}
if ($mask) {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " like $mask";
}
$ret =& $this->_MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
function &_MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function MetaColumns($table)
{
$this->_findschema($table,$schema);
if ($schema) {
$dbName = $this->database;
$this->connection->SelectDB($schema);
}
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($schema) {
$this->SelectDB($dbName);
}
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
// split type into type(length):
$fld->scale = null;
if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
$fld->type = $query_array[1];
$arr = explode(",",$query_array[2]);
$fld->enums = $arr;
$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
$fld->max_length = ($zlen > 0) ? $zlen : 1;
} else {
$fld->type = $type;
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($type,'blob') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != '' && $d != 'NULL') {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->has_default = false;
}
}
if ($save == ADODB_FETCH_NUM) {
$retarr[] = $fld;
} else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
// get index details
$rs =& $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
// restore fetchmode
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return $false;
}
$indexes = array ();
// parse index data into array
while (!$rs->EOF)
{
if ($primary == FALSE AND $rs->fields[2] == 'PRIMARY') {
$rs->MoveNext();
continue;
}
if (!isset($indexes[$rs->fields[2]])) {
$indexes[$rs->fields[2]] = array(
'unique' => ($rs->fields[1] == 0),
'columns' => array()
);
}
$indexes[$rs->fields[2]]['columns'][$rs->fields[3] - 1] = $rs->fields[4];
$rs->MoveNext();
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index )
{
ksort ($indexes[$index]['columns']);
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class mysqli_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysqli_meta_ResultSet extends mysqli_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
}
?>
@@ -0,0 +1,468 @@
<?php
/*
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Library for basic performance monitoring and tuning.
Modified 17 March 2006 for use with ADOdb Lite by Pádraic Brady
Such modifications as listed (c) 2006 Pádraic Brady (maugrimtr@hotmail.com)
Modifications:
- Moved adodb_perf class to $dbtype_perfmon_module.inc as the $dbtype_perfmon_ADOConnection class
- restricted adodb_perf class to tracking table name to use (for BC) - it's an alias for perfmon_parent_ADOConnection::table()
- Added LogSQL() method, and _logsql property
- general formatting changes and replacement of htmlspecialchars() woth htmlentities()
- parent class for specific driver modules added in adodb-perf-module.inc.php
*/
// required to allow a common parent for all perfmon dbtype specific modules to extend
$thisDBType = 'mysqli';
require_once(ADODB_DIR . '/adodb-perf.inc.php');
require_once(ADODB_DIR . '/adodb-perf-module.inc.php');
// not really needed, we already know the parent class name?
eval('class mysqli_perfmon_EXTENDER extends perfmon_parent_ADOConnection { }');
class mysqli_perfmon_ADOConnection extends mysqli_perfmon_EXTENDER
{
var $upperCase = 'upper';
var $substr = "substring";
var $tablesSQL = 'show table status';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 text NOT NULL,
params text NOT NULL,
tracer text NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'MyISAM cache hit ratio' => array('RATIO',
'=GetKeyHitRatio',
'=WarnCacheRatio'),
'InnoDB cache hit ratio' => array('RATIO',
'=GetInnoDBHitRatio',
'=WarnCacheRatio'),
'data cache hit ratio' => array('HIDE', # only if called
'=FindDBHitRatio',
'=WarnCacheRatio'),
'sql cache hit ratio' => array('RATIO',
'=GetQHitRatio',
''),
'IO',
'data reads' => array('IO',
'=GetReads',
'Number of selects (Key_reads is not accurate)'),
'data writes' => array('IO',
'=GetWrites',
'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
'Data Cache',
'MyISAM data cache size' => array('DATAC',
array("show variables", 'key_buffer_size'),
'' ),
'BDB data cache size' => array('DATAC',
array("show variables", 'bdb_cache_size'),
'' ),
'InnoDB data cache size' => array('DATAC',
array("show variables", 'innodb_buffer_pool_size'),
'' ),
'Memory Usage',
'read buffer size' => array('CACHE',
array("show variables", 'read_buffer_size'),
'(per session)'),
'sort buffer size' => array('CACHE',
array("show variables", 'sort_buffer_size'),
'Size of sort buffer (per session)' ),
'table cache' => array('CACHE',
array("show variables", 'table_cache'),
'Number of tables to keep open'),
'Connections',
'current connections' => array('SESS',
array('show status','Threads_connected'),
''),
'max connections' => array( 'SESS',
array("show variables",'max_connections'),
''),
false
);
/**
Get server version info...
@returns An array with 2 elements: $arr['description'] is the description string,
and $arr['version'] is the version (also a string).
*/
function ServerInfo()
{
$arr = array();
$result = $this->do_query('select version()', -1, -1, false);
if (!$result->EOF) $data = $result->fields;
else $data = array();
$arr['version'] = $arr['description'] = $data[0];
//****// Where does $arr come from in ADOdb - doesn't appear global, maybe null? A possible bug?
return $arr;
}
/*
Explain Plan for $sql.
If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
actual sql.
*/
function Explain($sql,$partial=false)
{
$perf_table = perfmon_parent_ADOConnection::table(); // this was missing in the original ADOdb perf class - bug?
if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN a non-select statement</p>';
$save = $this->LogSQL(false);
if ($partial) {
$sqlq = $this->qstr($sql.'%');
$arr = $this->GetArray("select distinct sql1 from $perf_table where sql1 like $sqlq");
if ($arr)
{
foreach($arr as $row)
{
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$sql = str_replace('?',"''",$sql);
if ($partial)
{
$sqlq = $this->qstr($sql.'%');
$sql = $this->GetOne("select sql1 from $perf_table where sql1 like $sqlq");
}
$s = '<p><strong>Explain</strong>: '.htmlentities($sql, ENT_QUOTES, 'UTF-8').'</p>';
$rs = $this->Execute('EXPLAIN '.$sql);
$s .= rs2html($rs,false,false,false,false);
$this->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
if (!$this->tablesSQL) return false;
$rs = $this->Execute($this->tablesSQL);
if (!$rs) return false;
$html = rs2html($rs,false,false,false,false);
return $html;
}
function CreateLogTable()
{
if (!$this->createTableSQL) return false;
$savelog = $this->LogSQL(false);
$ok = $this->Execute($this->createTableSQL);
$this->LogSQL($savelog);
return ($ok) ? true : false;
}
function GetReads()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$val = 0;
while (!$rs->EOF)
{
switch($rs->fields[0])
{
case 'Com_select':
$val = $rs->fields[1];
$rs->Close();
return $val;
}
$rs->MoveNext();
}
$rs->Close();
return $val;
}
function GetWrites()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$val = 0.0;
while (!$rs->EOF)
{
switch($rs->fields[0])
{
case 'Com_insert':
$val += $rs->fields[1];
break;
case 'Com_delete':
$val += $rs->fields[1];
break;
case 'Com_update':
$val += $rs->fields[1]/2;
$rs->Close();
return $val;
}
$rs->MoveNext();
}
$rs->Close();
return $val;
}
function FindDBHitRatio()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show table status');
$ADODB_FETCH_MODE = $save;
if (!$rs) return '';
$type = strtoupper($rs->fields[1]);
$rs->Close();
switch($type)
{
case 'MYISAM':
case 'ISAM':
return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';
case 'INNODB':
return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';
default:
return $type.' not supported';
}
}
function GetQHitRatio()
{
//Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached
$hits = $this->_DBParameter(array("show status","Qcache_hits"));
$total = $this->_DBParameter(array("show status","Qcache_inserts"));
$total += $this->_DBParameter(array("show status","Qcache_not_cached"));
$total += $hits;
if ($total) return round(($hits*100)/$total,2);
return 0;
}
/*
Use session variable to store Hit percentage, because MySQL
does not remember last value of SHOW INNODB STATUS hit ratio
# 1st query to SHOW INNODB STATUS
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
Buffer pool hit rate 1000 / 1000
# 2nd query to SHOW INNODB STATUS
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
No buffer pool activity since the last printout
*/
function GetInnoDBHitRatio()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute('show innodb status');
;
$ADODB_FETCH_MODE = $save;
if (!$rs || $rs->EOF) return 0;
$stat = $rs->fields[0];
$rs->Close();
$at = strpos($stat,'Buffer pool hit rate');
$stat = substr($stat,$at,200);
if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr))
{
$val = 100*$arr[1]/$arr[2];
$_SESSION['INNODB_HIT_PCT'] = $val;
return round($val,2);
}
else
{
if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
return 0;
}
return 0;
}
function GetKeyHitRatio()
{
$hits = $this->_DBParameter(array("show status","Key_read_requests"));
$reqs = $this->_DBParameter(array("show status","Key_reads"));
if ($reqs == 0) return 0;
return round(($hits/($reqs+$hits))*100,2);
}
// start hack
var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK';
var $optimizeTableHigh = 'OPTIMIZE TABLE %s';
/**
* @see adodb_perf#optimizeTable
*/
function optimizeTable( $table, $mode = ADODB_OPT_LOW)
{
if ( !is_string( $table)) return false;
$sql = '';
switch( $mode)
{
case ADODB_OPT_LOW:
$sql = $this->optimizeTableLow;
break;
case ADODB_OPT_HIGH:
$sql = $this->optimizeTableHigh;
break;
default:
{
// May dont use __FUNCTION__ constant for BC (__FUNCTION__ Added in PHP 4.3.0)
trigger_error(sprintf( "<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, __FUNCTION__, $mode), E_USER_ERROR);
return false;
}
}
$sql = sprintf( $sql, $table);
return $this->Execute( $sql) !== false;
}
}
eval('class mysqli_perfmon_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysqli_perfmon_ResultSet extends mysqli_perfmon_resultset_EXTENDER
{
function MetaType($t, $len = -1, $fieldobj = false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
case MYSQLI_TYPE_TINY_BLOB :
case MYSQLI_TYPE_CHAR :
case MYSQLI_TYPE_STRING :
case MYSQLI_TYPE_ENUM :
case MYSQLI_TYPE_SET :
case 253 :
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
case MYSQLI_TYPE_BLOB :
case MYSQLI_TYPE_LONG_BLOB :
case MYSQLI_TYPE_MEDIUM_BLOB :
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE':
case MYSQLI_TYPE_DATE :
case MYSQLI_TYPE_YEAR :
return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case MYSQLI_TYPE_DATETIME :
case MYSQLI_TYPE_NEWDATE :
case MYSQLI_TYPE_TIME :
case MYSQLI_TYPE_TIMESTAMP :
return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
case MYSQLI_TYPE_INT24 :
case MYSQLI_TYPE_LONG :
case MYSQLI_TYPE_LONGLONG :
case MYSQLI_TYPE_SHORT :
case MYSQLI_TYPE_TINY :
if (!empty($fieldobj->primary_key)) return 'R';
return 'I';
// Added floating-point types
// Maybe not necessery.
case 'FLOAT':
case 'DOUBLE':
// case 'DOUBLE PRECISION':
case 'DECIMAL':
case 'DEC':
case 'FIXED':
default:
//if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
return 'N';
}
} // function
}
?>
@@ -0,0 +1,138 @@
<?php
/**
* ADOdb Lite Transaction Module for Mysqli
*
*/
eval('class mysqli_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class mysqli_transaction_ADOConnection extends mysqli_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$this->transCnt += 1;
$this->Execute('SET AUTOCOMMIT=0');
$this->Execute('BEGIN');
return true;
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok) return
$this->RollbackTrans();
if ($this->transCnt)
$this->transCnt -= 1;
$this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RollbackTrans()
{
if ($this->transOff)
return true;
if ($this->transCnt)
$this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
if ($this->transCnt==0)
$this->BeginTrans();
return $this->GetOne("select $flds from $tables where $where for update");
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class mysqli_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class mysqli_transaction_ResultSet extends mysqli_transaction_resultset_EXTENDER
{
}
?>
@@ -0,0 +1,211 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_postgres64 extends ADODB_DataDict {
var $dbtype = 'postgres';
var $seqField = false;
var $seqPrefix = 'SEQ_';
var $addCol = ' ADD COLUMN';
var $quote = '"';
var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BYTEA';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
case 'I4': return 'INT4';
case 'I8': return 'INT8';
case 'F': return 'FLOAT8';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
foreach($lines as $v) {
if (($not_null = preg_match('/NOT NULL/i',$v))) {
$v = preg_replace('/NOT NULL/i','',$v);
}
if (preg_match('/^([^ ]+) .*(DEFAULT [^ ]+)/',$v,$matches)) {
list(,$colname,$default) = $matches;
$sql[] = $alter . str_replace($default,'',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET ' . $default;
} else {
$sql[] = $alter . $v;
}
if ($not_null) {
list($colname) = explode(' ',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
}
}
return $sql;
}
function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
if (!$tableflds) {
if ($this->debug) $this->outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
return array();
}
return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
}
function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
$has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
if (!$has_drop_column && !$tableflds) {
if ($this->debug) $this->outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
return array();
}
if ($has_drop_column) {
return ADODB_DataDict::DropColumnSQL($tabname, $flds);
}
return $this->_recreate_copy_table($tabname,$flds,$tableflds,$tableoptions);
}
function DropTableSQL($tabname)
{
$sql = ADODB_DataDict::DropTableSQL($tabname);
$drop_seq = $this->_DropAutoIncrement($tabname);
if ($drop_seq) $sql[] = $drop_seq;
return $sql;
}
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _DropAutoIncrement($tabname)
{
$tabname = $this->connection->qstr('%'.$tabname.'%');
$seq = $this->connection->GetOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'");
// check if a tables depends on the sequenz and it therefor cant and dont need to be droped separatly
if (!$seq || $this->connection->GetOne("SELECT relname FROM pg_class JOIN pg_depend ON pg_class.relfilenode=pg_depend.objid WHERE relname='$seq' AND relkind='S' AND deptype='i'")) {
return False;
}
return "DROP SEQUENCE ".$seq;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
if (isset($idxoptions['HASH']))
$s .= 'USING HASH ';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
if ( is_array($flds) )
$flds = implode(', ',$flds);
$s .= '(' . $flds . ')';
$sql[] = $s;
return $sql;
}
function _recreate_copy_table($tabname,$dropflds,$tableflds,$tableoptions='')
{
if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds);
$copyflds = array();
foreach($this->MetaColumns($tabname) as $fld) {
if (!$dropflds || !in_array($fld->name,$dropflds)) {
// we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one
if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) &&
in_array($fld->type,array('varchar','char','text','bytea'))) {
$copyflds[] = "to_number($fld->name,'S99D99')";
} else {
$copyflds[] = $fld->name;
}
// identify the sequence name and the fld its on
if ($fld->primary_key && $fld->has_default &&
preg_match("/nextval\('([^']+)'::text\)/",$fld->default_value,$matches)) {
$seq_name = $matches[1];
$seq_fld = $fld->name;
}
}
}
$copyflds = implode(', ',$copyflds);
$tempname = $tabname.'_tmp';
$aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table
$aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname";
$aSql = array_merge($aSql,$this->DropTableSQL($tabname));
$aSql = array_merge($aSql,$this->CreateTableSQL($tabname,$tableflds,$tableoptions));
$aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname";
if ($seq_name && $seq_fld) { // if we have a sequence we need to set it again
$seq_name = $tabname.'_'.$seq_fld.'_seq'; // has to be the name of the new implicit sequence
$aSql[] = "SELECT setval('$seq_name',MAX($seq_fld)) FROM $tabname";
}
$aSql[] = "DROP TABLE $tempname";
// recreate the indexes, if they not contain one of the droped columns
foreach($this->MetaIndexes($tabname) as $idx_name => $idx_data)
{
if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) {
$aSql = array_merge($aSql,$this->CreateIndexSQL($idx_name,$tabname,$idx_data['columns'],
$idx_data['unique'] ? array('UNIQUE') : False));
}
}
$aSql[] = 'COMMIT';
return $aSql;
}
}
?>
@@ -0,0 +1,316 @@
<?php
/**
* ADOdb Lite Date Module for Postgres 64
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class postgres64_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres64_date_ADOConnection extends postgres64_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
var $isoDates = true; /// accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
else if (strncmp($date,"'",1) == 0) {
$len = strlen($date);
if (10 <= $len && $len <= 12)
$date = 'date ' . $date;
else $date = 'timestamp ' . $date;
}
return "($date+interval'$dayFraction days')";
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate,$date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
$timestamp = $this->UnixTimeStamp($timestamp);
return adodb_date($this->fmtTimeStamp, $timestamp);
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
else return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
else return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
}
function SQLDate($fmt, $col=false)
{
if (!$col)
$col = $this->sysTimeStamp;
$s = 'TO_CHAR('.$col.",'";
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= 'YYYY';
break;
case 'Q':
case 'q':
$s .= 'Q';
break;
case 'M':
$s .= 'Mon';
break;
case 'm':
$s .= 'MM';
break;
case 'D':
case 'd':
$s .= 'DD';
break;
case 'H':
$s.= 'HH24';
break;
case 'h':
$s .= 'HH';
break;
case 'i':
$s .= 'MI';
break;
case 's':
$s .= 'SS';
break;
case 'a':
case 'A':
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
default:
// handle escape characters...
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
if (strpos('-/.:;, ',$ch) !== false)
$s .= $ch;
else $s .= '"'.$ch.'"';
}
}
return $s. "')";
}
}
eval('class postgres64_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres64_date_ResultSet extends postgres64_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt,$tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
function UnixDate($v)
{
return postgres64_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return postgres64_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,659 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, SqLite and Sybase.
*
*/
class postgres64_driver_ADOConnection extends ADOConnection
{
var $connect_string;
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
function postgres64_driver_ADOConnection()
{
$this->dbtype = 'postgres64';
$this->dataProvider = 'postgres';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('pg_connect')) return false;
$this->host = $host;
$this->username = $this->query_addslashes($username);
$this->password = $this->query_addslashes($password);
if (strlen($database) == 0) $database = 'template1';
$this->database = $this->query_addslashes($database);
if ($this->username || $this->password || $this->database) {
$this->connect_string = $this->host;
if ($this->connect_string) {
$host = split(":", $this->connect_string);
if ($host[0]) $this->connect_string = "host=" . $this->query_addslashes($host[0]);
else $this->connect_string = 'host=localhost';
if (isset($host[1])) $this->connect_string .= " port=$host[1]";
else if (!empty($this->port)) $this->connect_string .= " port=" . $this->port;
}
if ($this->username) $this->connect_string .= " user=" . $this->username;
if ($this->password) $this->connect_string .= " password=" . $this->password;
if ($this->database) $this->connect_string .= " dbname=" . $this->database;
}
else
{
$this->connect_string = $this->host;
}
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
$this->_makeconnection();
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return $this->SelectDB( $this->database );
}
return true;
}
function _makeconnection()
{
if($this->persistent == 1)
{
$this->connectionId = @pg_pconnect( $this->connect_string );
}
else
{
if(!$this->forcenewconnection)
{
$this->connectionId = @pg_connect( $this->connect_string );
}
else
{
$this->connectionId = @pg_connect( $this->connect_string, PGSQL_CONNECT_FORCE_NEW );
}
}
}
function query_addslashes($query)
{
$len = strlen($query);
if ($len == 0)
return "''";
if (strncmp($query,"'",1) === 0 && substr($query,$len-1) == "'")
return $s;
return "'".addslashes($query)."'";
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
if($this->createdatabase == true)
{
$this->connectionId = @pg_pconnect( "host=$this->host user=$this->username password=$this->password" );
$result = @pg_query($this->connectionId, "CREATE DATABASE " . $this->database );
if ($result === false) { // error handling if query fails
$this->connectionId = false;
return false;
}
$this->_makeconnection();
if($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
return @pg_last_error($this->connectionId);
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
$error = @pg_last_error( $this->connectionId );
return strlen($error) ? $error : 0;
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @pg_affected_rows($this->record_set);
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @pg_getlastoid($this->record_set);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
// Ugly hack alert! Repalce backticks with some arbitrary character
$string = str_replace('`', "\x1C", $string);
if (!$magic_quotes) {
$string = str_replace("'", "\\'", str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
return implode("||", $arr);
}
function IfNull( $field, $ifNull )
{
return " coalesce($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@pg_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$sql = str_replace('`', '"', $sql);
$sql = str_replace("\x1C", "`", $sql);
$sql = str_replace('IS_DELETED', 'is_deleted', $sql);
$sql = str_replace("HIGH_PRIORITY", "", $sql);
$false = false;
// $limit = '';
// if ($offset != -1 || $nrows != -1)
// {
// $offset = ($offset>=0) ? $offset . "," : '';
// $limit = ' LIMIT ' . $offset . ' ' . $nrows;
// }
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? "'t'" : "'f'";
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql);
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql);
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql);
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if (@pg_numfields( $resultId ) <= 0) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
$this->record_set = $recordset;
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$this->record_set = $recordset;
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = PGSQL_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = PGSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = PGSQL_BOTH; break;
}
$recordset->_numOfRows = @pg_numrows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @pg_numfields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class postgres64_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* pgsqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function postgres64_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function Close()
{
pg_free_result( $this->resultId );
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = pg_fetch_array($this->resultId, NULL, $this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @pg_result_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @pg_fetch_array($this->resultId, NULL, $this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
$fieldObject= new ADOFieldObject();
$fieldObject->name = @pg_fieldname($this->resultId, $fieldOffset);
$fieldObject->type = @pg_fieldtype($this->resultId, $fieldOffset);
$fieldObject->max_length = @pg_fieldsize($this->resultId, $fieldOffset);
return $fieldObject;
}
}
?>
@@ -0,0 +1,147 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class postgres64_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres64_extend_ADOConnection extends postgres64_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $_genIDSQL = "SELECT NEXTVAL('%s')";
var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $genID = 0;
function GenID($seqname='adodbseq', $startID=1)
{
$getnext = sprintf($this->_genIDSQL, $seqname);
$holdtransOK = $this->transaction_status;
$save_handler = $this->raiseErrorFn;
$this->raiseErrorFn = '';
@($result = $this->Execute($getnext));
$this->raiseErrorFn = $save_handler;
if (!$result) {
$this->transaction_status = $holdtransOK;
$createseq = $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
$result = $this->Execute($getnext);
}
if ($result && !$result->EOF)
$this->genID = reset($result->fields);
else $this->genID = 0;
if ($result)
$result->Close();
return $this->genID;
}
function CreateSequence($seqname='adodbseq', $startID=1)
{
return $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
}
function DropSequence($seqname='adodbseq')
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class postgres64_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres64_extend_ResultSet extends postgres64_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,684 @@
<?php
/**
* ADOdb Lite Meta Module for Postgres64
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class postgres64_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres64_meta_ADOConnection extends postgres64_meta_EXTENDER
{
var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%'";
var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
FROM pg_class c, pg_attribute a,pg_type t
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// used when schema defined
var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
and c.relnamespace=n.oid and n.nspname='%s'
and a.attname not like '....%%' AND a.attnum > 0
AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// get primary key etc -- from Freek Dijkstra
var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p)) return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
return false;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false,$this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function MetaDatabases()
{
global $ADODB_FETCH_MODE;
if ($this->metaDatabasesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$arr = $this->GetCol($this->metaDatabasesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $arr;
}
return false;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$info = $this->ServerInfo();
if ($info['version'] >= 7.3) {
$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
}
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtolower($mask));
if ($info['version']>=7.3)
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
else
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask
union
select viewname,'V' from pg_views where viewname like $mask";
}
$ret =& $this->_MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
function &_MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function &MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
$schema = false;
$false = false;
$this->_findschema($table,$schema);
if ($normalize) $table = strtolower($table);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) {
return $false;
}
if (!empty($this->metaKeySQL)) {
// If we want the primary keys, we have to issue a separate query
// Of course, a modified version of the metaColumnsSQL query using a
// LEFT JOIN would have been much more elegant, but postgres does
// not support OUTER JOINS. So here is the clumsy way.
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
// fetch all result in once for performance.
$keys =& $rskey->GetArray();
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
$rskey->Close();
unset($rskey);
}
$rsdefa = array();
if (!empty($this->metaDefaultsSQL)) {
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$sql = sprintf($this->metaDefaultsSQL, ($table));
$rsdef = $this->Execute($sql);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rsdef) {
while (!$rsdef->EOF) {
$num = $rsdef->fields['num'];
$s = $rsdef->fields['def'];
if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
$s = substr($s, 1);
$s = substr($s, 0, strlen($s) - 1);
}
$rsdefa[$num] = $s;
$rsdef->MoveNext();
}
} else {
ADOConnection::outp( "==> SQL => " . $sql);
}
unset($rsdef);
}
$retarr = array();
while (!$rs->EOF) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->attnum = $rs->fields[6];
if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
if ($fld->max_length <= 0) $fld->max_length = -1;
if ($fld->type == 'numeric') {
$fld->scale = $fld->max_length & 0xFFFF;
$fld->max_length >>= 16;
}
// dannym
// 5 hasdefault; 6 num-of-column
$fld->has_default = ($rs->fields[5] == 't');
if ($fld->has_default) {
$fld->default_value = $rsdefa[$rs->fields[6]];
}
//Freek
$fld->not_null = $rs->fields[4] == 't';
// Freek
if (is_array($keys)) {
foreach($keys as $key) {
if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
$fld->primary_key = true;
if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
$fld->unique = true; // What name is more compatible?
}
}
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
$rs->MoveNext();
}
$rs->Close();
if (empty($retarr))
return $false;
else
return $retarr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function &MetaIndexes ($table, $primary = FALSE)
{
global $ADODB_FETCH_MODE;
$schema = false;
$this->_findschema($table,$schema);
if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
,pg_namespace n
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
} else {
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
}
if ($primary == FALSE) {
$sql .= ' AND i.indisprimary=false;';
}
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$rs = $this->Execute(sprintf($sql,$table,$table,$schema));
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$col_names = $this->MetaColumnNames($table,true,true);
//3rd param is use attnum,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
$indexes = array();
while ($row = $rs->FetchRow()) {
$columns = array();
foreach (explode(' ', $row[2]) as $col) {
$columns[] = $col_names[$col];
}
$indexes[$row[0]] = array(
'unique' => ($row[1] == 't'),
'columns' => $columns
);
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
if ($useattnum) {
foreach($objarr as $v)
$arr[$v->attnum] = $v->name;
} else
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class postgres64_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres64_meta_ResultSet extends postgres64_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->unique && $fieldobj->has_default && substr($fieldobj->default_value,0,8) == 'nextval(';
switch (strtoupper($t)) {
case 'MONEY': // stupid, postgres expects money to be a string
case 'INTERVAL':
case 'CHAR':
case 'CHARACTER':
case 'VARCHAR':
case 'NAME':
case 'BPCHAR':
case '_VARCHAR':
case 'INET':
case 'MACADDR':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
return 'X';
case 'IMAGE': // user defined type
case 'BLOB': // user defined type
case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
case 'VARBIT':
case 'BYTEA':
return 'B';
case 'BOOL':
case 'BOOLEAN':
return 'L';
case 'DATE':
return 'D';
case 'TIMESTAMP WITHOUT TIME ZONE':
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case 'TIMESTAMPTZ':
return 'T';
case 'INTEGER': return !$is_serial ? 'I' : 'R';
case 'SMALLINT':
case 'INT2': return !$is_serial ? 'I2' : 'R';
case 'INT4': return !$is_serial ? 'I4' : 'R';
case 'BIGINT':
case 'INT8': return !$is_serial ? 'I8' : 'R';
case 'OID':
case 'SERIAL':
return 'R';
case 'FLOAT4':
case 'FLOAT8':
case 'DOUBLE PRECISION':
case 'REAL':
return 'F';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
}
?>
@@ -0,0 +1,128 @@
<?php
/**
* ADOdb Lite Transaction Module for Postgres
*
*/
eval('class postgres64_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres64_transaction_ADOConnection extends postgres64_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$this->transCnt += 1;
return @pg_Exec($this->connectionId, "begin");
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok)
return $this->RollbackTrans();
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "commit");
}
function RollbackTrans()
{
if ($this->transOff)
return true;
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "rollback");
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
if (!$this->transCnt)
$this->BeginTrans();
return $this->GetOne("select $flds from $tables where $where for update");
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class postgres64_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres64_transaction_ResultSet extends postgres64_transaction_resultset_EXTENDER
{
}
?>
@@ -0,0 +1,211 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_postgres7 extends ADODB_DataDict {
var $dbtype = 'postgres';
var $seqField = false;
var $seqPrefix = 'SEQ_';
var $addCol = ' ADD COLUMN';
var $quote = '"';
var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BYTEA';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
case 'I4': return 'INT4';
case 'I8': return 'INT8';
case 'F': return 'FLOAT8';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
foreach($lines as $v) {
if (($not_null = preg_match('/NOT NULL/i',$v))) {
$v = preg_replace('/NOT NULL/i','',$v);
}
if (preg_match('/^([^ ]+) .*(DEFAULT [^ ]+)/',$v,$matches)) {
list(,$colname,$default) = $matches;
$sql[] = $alter . str_replace($default,'',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET ' . $default;
} else {
$sql[] = $alter . $v;
}
if ($not_null) {
list($colname) = explode(' ',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
}
}
return $sql;
}
function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
if (!$tableflds) {
if ($this->debug) $this->outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
return array();
}
return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
}
function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
$has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
if (!$has_drop_column && !$tableflds) {
if ($this->debug) $this->outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
return array();
}
if ($has_drop_column) {
return ADODB_DataDict::DropColumnSQL($tabname, $flds);
}
return $this->_recreate_copy_table($tabname,$flds,$tableflds,$tableoptions);
}
function DropTableSQL($tabname)
{
$sql = ADODB_DataDict::DropTableSQL($tabname);
$drop_seq = $this->_DropAutoIncrement($tabname);
if ($drop_seq) $sql[] = $drop_seq;
return $sql;
}
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _DropAutoIncrement($tabname)
{
$tabname = $this->connection->qstr('%'.$tabname.'%');
$seq = $this->connection->GetOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'");
// check if a tables depends on the sequenz and it therefor cant and dont need to be droped separatly
if (!$seq || $this->connection->GetOne("SELECT relname FROM pg_class JOIN pg_depend ON pg_class.relfilenode=pg_depend.objid WHERE relname='$seq' AND relkind='S' AND deptype='i'")) {
return False;
}
return "DROP SEQUENCE ".$seq;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
if (isset($idxoptions['HASH']))
$s .= 'USING HASH ';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
if ( is_array($flds) )
$flds = implode(', ',$flds);
$s .= '(' . $flds . ')';
$sql[] = $s;
return $sql;
}
function _recreate_copy_table($tabname,$dropflds,$tableflds,$tableoptions='')
{
if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds);
$copyflds = array();
foreach($this->MetaColumns($tabname) as $fld) {
if (!$dropflds || !in_array($fld->name,$dropflds)) {
// we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one
if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) &&
in_array($fld->type,array('varchar','char','text','bytea'))) {
$copyflds[] = "to_number($fld->name,'S99D99')";
} else {
$copyflds[] = $fld->name;
}
// identify the sequence name and the fld its on
if ($fld->primary_key && $fld->has_default &&
preg_match("/nextval\('([^']+)'::text\)/",$fld->default_value,$matches)) {
$seq_name = $matches[1];
$seq_fld = $fld->name;
}
}
}
$copyflds = implode(', ',$copyflds);
$tempname = $tabname.'_tmp';
$aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table
$aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname";
$aSql = array_merge($aSql,$this->DropTableSQL($tabname));
$aSql = array_merge($aSql,$this->CreateTableSQL($tabname,$tableflds,$tableoptions));
$aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname";
if ($seq_name && $seq_fld) { // if we have a sequence we need to set it again
$seq_name = $tabname.'_'.$seq_fld.'_seq'; // has to be the name of the new implicit sequence
$aSql[] = "SELECT setval('$seq_name',MAX($seq_fld)) FROM $tabname";
}
$aSql[] = "DROP TABLE $tempname";
// recreate the indexes, if they not contain one of the droped columns
foreach($this->MetaIndexes($tabname) as $idx_name => $idx_data)
{
if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) {
$aSql = array_merge($aSql,$this->CreateIndexSQL($idx_name,$tabname,$idx_data['columns'],
$idx_data['unique'] ? array('UNIQUE') : False));
}
}
$aSql[] = 'COMMIT';
return $aSql;
}
}
?>
@@ -0,0 +1,316 @@
<?php
/**
* ADOdb Lite Date Module for Postgres 7
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class postgres7_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres7_date_ADOConnection extends postgres7_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
var $isoDates = true; /// accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
else if (strncmp($date,"'",1) == 0) {
$len = strlen($date);
if (10 <= $len && $len <= 12)
$date = 'date ' . $date;
else $date = 'timestamp ' . $date;
}
return "($date+interval'$dayFraction days')";
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate,$date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
$timestamp = $this->UnixTimeStamp($timestamp);
return adodb_date($this->fmtTimeStamp, $timestamp);
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
else return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
else return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
}
function SQLDate($fmt, $col=false)
{
if (!$col)
$col = $this->sysTimeStamp;
$s = 'TO_CHAR('.$col.",'";
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= 'YYYY';
break;
case 'Q':
case 'q':
$s .= 'Q';
break;
case 'M':
$s .= 'Mon';
break;
case 'm':
$s .= 'MM';
break;
case 'D':
case 'd':
$s .= 'DD';
break;
case 'H':
$s.= 'HH24';
break;
case 'h':
$s .= 'HH';
break;
case 'i':
$s .= 'MI';
break;
case 's':
$s .= 'SS';
break;
case 'a':
case 'A':
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
default:
// handle escape characters...
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
if (strpos('-/.:;, ',$ch) !== false)
$s .= $ch;
else $s .= '"'.$ch.'"';
}
}
return $s. "')";
}
}
eval('class postgres7_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres7_date_ResultSet extends postgres7_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt,$tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
function UnixDate($v)
{
return postgres7_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return postgres7_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,680 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, SqLite and Sybase.
*
*/
class postgres7_driver_ADOConnection extends ADOConnection
{
var $connect_string;
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
var $pg_escape_enable = false;
function postgres7_driver_ADOConnection()
{
$this->dbtype = 'postgres7';
$this->dataProvider = 'postgres';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('pg_connect')) return false;
$this->host = $host;
$this->username = $this->query_addslashes($username);
$this->password = $this->query_addslashes($password);
if (strlen($database) == 0) $database = 'template1';
$this->database = $this->query_addslashes($database);
if ($this->username || $this->password || $this->database) {
$this->connect_string = $this->host;
if ($this->connect_string) {
$host = split(":", $this->connect_string);
if ($host[0]) $this->connect_string = "host=" . $this->query_addslashes($host[0]);
else $this->connect_string = 'host=localhost';
if (isset($host[1])) $this->connect_string .= " port=$host[1]";
else if (!empty($this->port)) $this->connect_string .= " port=" . $this->port;
}
if ($this->username) $this->connect_string .= " user=" . $this->username;
if ($this->password) $this->connect_string .= " password=" . $this->password;
if ($this->database) $this->connect_string .= " dbname=" . $this->database;
}
else
{
$this->connect_string = $this->host;
}
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
$this->_makeconnection();
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return $this->SelectDB( $this->database );
}
return true;
}
function _makeconnection()
{
if($this->persistent == 1)
{
$this->connectionId = @pg_pconnect( $this->connect_string );
}
else
{
if(!$this->forcenewconnection)
{
$this->connectionId = @pg_connect( $this->connect_string );
}
else
{
$this->connectionId = @pg_connect( $this->connect_string, PGSQL_CONNECT_FORCE_NEW );
}
}
}
function query_addslashes($query)
{
$len = strlen($query);
if ($len == 0)
return "''";
if (strncmp($query,"'",1) === 0 && substr($query,$len-1) == "'")
return $s;
return "'".addslashes($query)."'";
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
if($this->createdatabase == true)
{
$this->connectionId = @pg_pconnect( "host=$this->host user=$this->username password=$this->password" );
$result = @pg_query($this->connectionId, "CREATE DATABASE " . $this->database );
if ($result === false) { // error handling if query fails
$this->connectionId = false;
return false;
}
$this->_makeconnection();
if($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
return @pg_last_error($this->connectionId);
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
$error = @pg_last_error( $this->connectionId );
return strlen($error) ? $error : 0;
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @pg_affected_rows( $this->record_set );
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @pg_getlastoid($this->record_set);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
// Ugly hack alert! Repalce backticks with some arbitrary character
$string = str_replace('`', "\x1C", $string);
if (!$magic_quotes) {
if (strnatcmp(PHP_VERSION, '4.2.0') >= 0 && $this->pg_escape_enable) {
return "'" . pg_escape_string($string) . "'";
}
$string = str_replace("'", "\\'", str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
return implode("||", $arr);
}
function IfNull( $field, $ifNull )
{
return " coalesce($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@pg_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$sql = str_replace('`', '"', $sql);
$sql = str_replace("\x1C", "`", $sql);
$sql = str_replace('IS_DELETED', 'is_deleted', $sql);
$sql = str_replace("HIGH_PRIORITY", "", $sql);
$false = false;
$offsetStr = '';
$limitStr = '';
if ($offset != -1 || $nrows != -1)
{
$offsetStr = ($offset >= 0) ? " OFFSET " . ((integer)$offset) : '';
$limitStr = ($nrows >= 0) ? " LIMIT " . ((integer)$nrows) : '';
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? "'t'" : "'f'";
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql);
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql);
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if (@pg_numfields( $resultId ) <= 0) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
$this->record_set = $recordset;
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$this->record_set = $recordset;
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = PGSQL_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = PGSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = PGSQL_BOTH; break;
}
$recordset->_numOfRows = @pg_numrows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @pg_numfields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class postgres7_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* pgsqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function postgres7_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function Close()
{
pg_free_result( $this->resultId );
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* PEAR DB Compatable Command
*/
function NumRows()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* PEAR DB Compatable Command
*/
function NumCols()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = pg_fetch_array($this->resultId, NULL, $this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @pg_result_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @pg_fetch_array($this->resultId, NULL, $this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
$fieldObject= new ADOFieldObject();
$fieldObject->name = @pg_fieldname($this->resultId, $fieldOffset);
$fieldObject->type = @pg_fieldtype($this->resultId, $fieldOffset);
$fieldObject->max_length = @pg_fieldsize($this->resultId, $fieldOffset);
return $fieldObject;
}
}
?>
@@ -0,0 +1,147 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class postgres7_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres7_extend_ADOConnection extends postgres7_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $_genIDSQL = "SELECT NEXTVAL('%s')";
var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $genID = 0;
function GenID($seqname='adodbseq', $startID=1)
{
$getnext = sprintf($this->_genIDSQL, $seqname);
$holdtransOK = $this->transaction_status;
$save_handler = $this->raiseErrorFn;
$this->raiseErrorFn = '';
@($result = $this->Execute($getnext));
$this->raiseErrorFn = $save_handler;
if (!$result) {
$this->transaction_status = $holdtransOK;
$createseq = $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
$result = $this->Execute($getnext);
}
if ($result && !$result->EOF)
$this->genID = reset($result->fields);
else $this->genID = 0;
if ($result)
$result->Close();
return $this->genID;
}
function CreateSequence($seqname='adodbseq', $startID=1)
{
return $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
}
function DropSequence($seqname='adodbseq')
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class postgres7_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres7_extend_ResultSet extends postgres7_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,712 @@
<?php
/**
* ADOdb Lite Meta Module for Postgres7
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class postgres7_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres7_meta_ADOConnection extends postgres7_meta_EXTENDER
{
var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%'";
var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
FROM pg_class c, pg_attribute a,pg_type t
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// used when schema defined
var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
and c.relnamespace=n.oid and n.nspname='%s'
and a.attname not like '....%%' AND a.attnum > 0
AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// get primary key etc -- from Freek Dijkstra
var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p)) return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = 'SELECT t.tgargs as args
FROM
pg_trigger t,pg_class c,pg_proc p
WHERE
t.tgenabled AND
t.tgrelid = c.oid AND
t.tgfoid = p.oid AND
p.proname = \'RI_FKey_check_ins\' AND
c.relname = \''.strtolower($table).'\'
ORDER BY
t.tgrelid';
$rs =& $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr =& $rs->GetArray();
$a = array();
foreach($arr as $v) {
$data = explode(chr(0), $v['args']);
$size = count($data)-1; //-1 because the last node is empty
for($i = 4; $i < $size; $i++) {
if ($upper)
$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
else
$a[$data[2]][] = $data[$i].'='.$data[++$i];
}
}
return $a;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false,$this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function MetaDatabases()
{
global $ADODB_FETCH_MODE;
if ($this->metaDatabasesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$arr = $this->GetCol($this->metaDatabasesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $arr;
}
return false;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$info = $this->ServerInfo();
if ($info['version'] >= 7.3) {
$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
}
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtolower($mask));
if ($info['version']>=7.3)
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
else
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask
union
select viewname,'V' from pg_views where viewname like $mask";
}
$ret =& $this->_MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
function &_MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function &MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
$schema = false;
$false = false;
$this->_findschema($table,$schema);
if ($normalize) $table = strtolower($table);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) {
return $false;
}
if (!empty($this->metaKeySQL)) {
// If we want the primary keys, we have to issue a separate query
// Of course, a modified version of the metaColumnsSQL query using a
// LEFT JOIN would have been much more elegant, but postgres does
// not support OUTER JOINS. So here is the clumsy way.
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
// fetch all result in once for performance.
$keys =& $rskey->GetArray();
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
$rskey->Close();
unset($rskey);
}
$rsdefa = array();
if (!empty($this->metaDefaultsSQL)) {
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$sql = sprintf($this->metaDefaultsSQL, ($table));
$rsdef = $this->Execute($sql);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rsdef) {
while (!$rsdef->EOF) {
$num = $rsdef->fields['num'];
$s = $rsdef->fields['def'];
if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
$s = substr($s, 1);
$s = substr($s, 0, strlen($s) - 1);
}
$rsdefa[$num] = $s;
$rsdef->MoveNext();
}
} else {
ADOConnection::outp( "==> SQL => " . $sql);
}
unset($rsdef);
}
$retarr = array();
while (!$rs->EOF) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->attnum = $rs->fields[6];
if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
if ($fld->max_length <= 0) $fld->max_length = -1;
if ($fld->type == 'numeric') {
$fld->scale = $fld->max_length & 0xFFFF;
$fld->max_length >>= 16;
}
// dannym
// 5 hasdefault; 6 num-of-column
$fld->has_default = ($rs->fields[5] == 't');
if ($fld->has_default) {
$fld->default_value = $rsdefa[$rs->fields[6]];
}
//Freek
$fld->not_null = $rs->fields[4] == 't';
// Freek
if (is_array($keys)) {
foreach($keys as $key) {
if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
$fld->primary_key = true;
if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
$fld->unique = true; // What name is more compatible?
}
}
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
$rs->MoveNext();
}
$rs->Close();
if (empty($retarr))
return $false;
else
return $retarr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function &MetaIndexes ($table, $primary = FALSE)
{
global $ADODB_FETCH_MODE;
$schema = false;
$this->_findschema($table,$schema);
if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
,pg_namespace n
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
} else {
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
}
if ($primary == FALSE) {
$sql .= ' AND i.indisprimary=false;';
}
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$rs = $this->Execute(sprintf($sql,$table,$table,$schema));
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$col_names = $this->MetaColumnNames($table,true,true);
//3rd param is use attnum,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
$indexes = array();
while ($row = $rs->FetchRow()) {
$columns = array();
foreach (explode(' ', $row[2]) as $col) {
$columns[] = $col_names[$col];
}
$indexes[$row[0]] = array(
'unique' => ($row[1] == 't'),
'columns' => $columns
);
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
if ($useattnum) {
foreach($objarr as $v)
$arr[$v->attnum] = $v->name;
} else
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class postgres7_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres7_meta_ResultSet extends postgres7_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->unique && $fieldobj->has_default && substr($fieldobj->default_value,0,8) == 'nextval(';
switch (strtoupper($t)) {
case 'MONEY': // stupid, postgres expects money to be a string
case 'INTERVAL':
case 'CHAR':
case 'CHARACTER':
case 'VARCHAR':
case 'NAME':
case 'BPCHAR':
case '_VARCHAR':
case 'INET':
case 'MACADDR':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
return 'X';
case 'IMAGE': // user defined type
case 'BLOB': // user defined type
case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
case 'VARBIT':
case 'BYTEA':
return 'B';
case 'BOOL':
case 'BOOLEAN':
return 'L';
case 'DATE':
return 'D';
case 'TIMESTAMP WITHOUT TIME ZONE':
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case 'TIMESTAMPTZ':
return 'T';
case 'INTEGER': return !$is_serial ? 'I' : 'R';
case 'SMALLINT':
case 'INT2': return !$is_serial ? 'I2' : 'R';
case 'INT4': return !$is_serial ? 'I4' : 'R';
case 'BIGINT':
case 'INT8': return !$is_serial ? 'I8' : 'R';
case 'OID':
case 'SERIAL':
return 'R';
case 'FLOAT4':
case 'FLOAT8':
case 'DOUBLE PRECISION':
case 'REAL':
return 'F';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
}
?>
@@ -0,0 +1,128 @@
<?php
/**
* ADOdb Lite Transaction Module for Postgres
*
*/
eval('class postgres7_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres7_transaction_ADOConnection extends postgres7_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$this->transCnt += 1;
return @pg_Exec($this->connectionId, "begin");
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok)
return $this->RollbackTrans();
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "commit");
}
function RollbackTrans()
{
if ($this->transOff)
return true;
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "rollback");
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
if (!$this->transCnt)
$this->BeginTrans();
return $this->GetOne("select $flds from $tables where $where for update");
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class postgres7_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres7_transaction_ResultSet extends postgres7_transaction_resultset_EXTENDER
{
}
?>
@@ -0,0 +1,211 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_postgres8 extends ADODB_DataDict {
var $dbtype = 'postgres';
var $seqField = false;
var $seqPrefix = 'SEQ_';
var $addCol = ' ADD COLUMN';
var $quote = '"';
var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BYTEA';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
case 'I4': return 'INT4';
case 'I8': return 'INT8';
case 'F': return 'FLOAT8';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
foreach($lines as $v) {
if (($not_null = preg_match('/NOT NULL/i',$v))) {
$v = preg_replace('/NOT NULL/i','',$v);
}
if (preg_match('/^([^ ]+) .*(DEFAULT [^ ]+)/',$v,$matches)) {
list(,$colname,$default) = $matches;
$sql[] = $alter . str_replace($default,'',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET ' . $default;
} else {
$sql[] = $alter . $v;
}
if ($not_null) {
list($colname) = explode(' ',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
}
}
return $sql;
}
function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
if (!$tableflds) {
if ($this->debug) $this->outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
return array();
}
return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
}
function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
$has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
if (!$has_drop_column && !$tableflds) {
if ($this->debug) $this->outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
return array();
}
if ($has_drop_column) {
return ADODB_DataDict::DropColumnSQL($tabname, $flds);
}
return $this->_recreate_copy_table($tabname,$flds,$tableflds,$tableoptions);
}
function DropTableSQL($tabname)
{
$sql = ADODB_DataDict::DropTableSQL($tabname);
$drop_seq = $this->_DropAutoIncrement($tabname);
if ($drop_seq) $sql[] = $drop_seq;
return $sql;
}
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _DropAutoIncrement($tabname)
{
$tabname = $this->connection->qstr('%'.$tabname.'%');
$seq = $this->connection->GetOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'");
// check if a tables depends on the sequenz and it therefor cant and dont need to be droped separatly
if (!$seq || $this->connection->GetOne("SELECT relname FROM pg_class JOIN pg_depend ON pg_class.relfilenode=pg_depend.objid WHERE relname='$seq' AND relkind='S' AND deptype='i'")) {
return False;
}
return "DROP SEQUENCE ".$seq;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
if (isset($idxoptions['HASH']))
$s .= 'USING HASH ';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
if ( is_array($flds) )
$flds = implode(', ',$flds);
$s .= '(' . $flds . ')';
$sql[] = $s;
return $sql;
}
function _recreate_copy_table($tabname,$dropflds,$tableflds,$tableoptions='')
{
if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds);
$copyflds = array();
foreach($this->MetaColumns($tabname) as $fld) {
if (!$dropflds || !in_array($fld->name,$dropflds)) {
// we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one
if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) &&
in_array($fld->type,array('varchar','char','text','bytea'))) {
$copyflds[] = "to_number($fld->name,'S99D99')";
} else {
$copyflds[] = $fld->name;
}
// identify the sequence name and the fld its on
if ($fld->primary_key && $fld->has_default &&
preg_match("/nextval\('([^']+)'::text\)/",$fld->default_value,$matches)) {
$seq_name = $matches[1];
$seq_fld = $fld->name;
}
}
}
$copyflds = implode(', ',$copyflds);
$tempname = $tabname.'_tmp';
$aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table
$aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname";
$aSql = array_merge($aSql,$this->DropTableSQL($tabname));
$aSql = array_merge($aSql,$this->CreateTableSQL($tabname,$tableflds,$tableoptions));
$aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname";
if ($seq_name && $seq_fld) { // if we have a sequence we need to set it again
$seq_name = $tabname.'_'.$seq_fld.'_seq'; // has to be the name of the new implicit sequence
$aSql[] = "SELECT setval('$seq_name',MAX($seq_fld)) FROM $tabname";
}
$aSql[] = "DROP TABLE $tempname";
// recreate the indexes, if they not contain one of the droped columns
foreach($this->MetaIndexes($tabname) as $idx_name => $idx_data)
{
if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) {
$aSql = array_merge($aSql,$this->CreateIndexSQL($idx_name,$tabname,$idx_data['columns'],
$idx_data['unique'] ? array('UNIQUE') : False));
}
}
$aSql[] = 'COMMIT';
return $aSql;
}
}
?>
@@ -0,0 +1,316 @@
<?php
/**
* ADOdb Lite Date Module for Postgres 8
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class postgres8_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres8_date_ADOConnection extends postgres8_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
var $isoDates = true; /// accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
else if (strncmp($date,"'",1) == 0) {
$len = strlen($date);
if (10 <= $len && $len <= 12)
$date = 'date ' . $date;
else $date = 'timestamp ' . $date;
}
return "($date+interval'$dayFraction days')";
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate,$date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
$timestamp = $this->UnixTimeStamp($timestamp);
return adodb_date($this->fmtTimeStamp, $timestamp);
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
else return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
else return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
}
function SQLDate($fmt, $col=false)
{
if (!$col)
$col = $this->sysTimeStamp;
$s = 'TO_CHAR('.$col.",'";
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= 'YYYY';
break;
case 'Q':
case 'q':
$s .= 'Q';
break;
case 'M':
$s .= 'Mon';
break;
case 'm':
$s .= 'MM';
break;
case 'D':
case 'd':
$s .= 'DD';
break;
case 'H':
$s.= 'HH24';
break;
case 'h':
$s .= 'HH';
break;
case 'i':
$s .= 'MI';
break;
case 's':
$s .= 'SS';
break;
case 'a':
case 'A':
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
default:
// handle escape characters...
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
if (strpos('-/.:;, ',$ch) !== false)
$s .= $ch;
else $s .= '"'.$ch.'"';
}
}
return $s. "')";
}
}
eval('class postgres8_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres8_date_ResultSet extends postgres8_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt,$tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
function UnixDate($v)
{
return postgres8_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return postgres8_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,663 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, PostgresSQL8, SqLite and Sybase.
*
*/
class postgres8_driver_ADOConnection extends ADOConnection
{
var $connect_string;
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
function postgres8_driver_ADOConnection()
{
$this->dbtype = 'postgres8';
$this->dataProvider = 'postgres';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('pg_connect')) return false;
$this->host = $host;
$this->username = $this->query_addslashes($username);
$this->password = $this->query_addslashes($password);
if (strlen($database) == 0) $database = 'template1';
$this->database = $this->query_addslashes($database);
if ($this->username || $this->password || $this->database) {
$this->connect_string = $this->host;
if ($this->connect_string) {
$host = split(":", $this->connect_string);
if ($host[0]) $this->connect_string = "host=" . $this->query_addslashes($host[0]);
else $this->connect_string = 'host=localhost';
if (isset($host[1])) $this->connect_string .= " port=$host[1]";
else if (!empty($this->port)) $this->connect_string .= " port=" . $this->port;
}
if ($this->username) $this->connect_string .= " user=" . $this->username;
if ($this->password) $this->connect_string .= " password=" . $this->password;
if ($this->database) $this->connect_string .= " dbname=" . $this->database;
}
else
{
$this->connect_string = $this->host;
}
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
$this->_makeconnection();
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return $this->SelectDB( $this->database );
}
return true;
}
function _makeconnection()
{
if($this->persistent == 1)
{
$this->connectionId = @pg_pconnect( $this->connect_string );
}
else
{
if(!$this->forcenewconnection)
{
$this->connectionId = @pg_connect( $this->connect_string );
}
else
{
$this->connectionId = @pg_connect( $this->connect_string, PGSQL_CONNECT_FORCE_NEW );
}
}
}
function query_addslashes($query)
{
$len = strlen($query);
if ($len == 0)
return "''";
if (strncmp($query,"'",1) === 0 && substr($query,$len-1) == "'")
return $s;
return "'".addslashes($query)."'";
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
if($this->createdatabase == true)
{
$this->connectionId = @pg_pconnect( "host=$this->host user=$this->username password=$this->password" );
$result = @pg_query($this->connectionId, "CREATE DATABASE " . $this->database );
if ($result === false) { // error handling if query fails
$this->connectionId = false;
return false;
}
$this->_makeconnection();
if($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
$this->connectionId = false;
return false;
}
else
{
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
return @pg_last_error($this->connectionId);
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
$error = @pg_last_error( $this->connectionId );
return strlen($error) ? $error : 0;
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @pg_affected_rows( $this->record_set );
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @pg_getlastoid($this->record_set);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
// Ugly hack alert! Repalce backticks with some arbitrary character
$string = str_replace('`', "\x1C", $string);
if (!$magic_quotes) {
if (strnatcmp(PHP_VERSION, '4.2.0') >= 0) {
return "'" . pg_escape_string($string) . "'";
}
$string = str_replace("'", "\\'", str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
return implode("||", $arr);
}
function IfNull( $field, $ifNull )
{
return " coalesce($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@pg_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$sql = str_replace('`', '"', $sql);
$sql = str_replace("\x1C", "`", $sql);
$sql = str_replace('IS_DELETED', 'is_deleted', $sql);
$sql = str_replace("HIGH_PRIORITY", "", $sql);
$false = false;
$offsetStr = '';
$limitStr = '';
if ($offset != -1 || $nrows != -1)
{
$offsetStr = ($offset >= 0) ? " OFFSET " . ((integer)$offset) : '';
$limitStr = ($nrows >= 0) ? " LIMIT " . ((integer)$nrows) : '';
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? "'t'" : "'f'";
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql);
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @pg_query( $this->sql);
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if (@pg_numfields( $resultId ) <= 0) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
$this->record_set = $recordset;
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$this->record_set = $recordset;
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = PGSQL_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = PGSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = PGSQL_BOTH; break;
}
$recordset->_numOfRows = @pg_numrows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @pg_numfields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class postgres8_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* pgsqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function postgres8_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function close()
{
pg_free_result( $this->resultId );
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = pg_fetch_array($this->resultId, NULL, $this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @pg_result_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @pg_fetch_array($this->resultId, NULL, $this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
$fieldObject= new ADOFieldObject();
$fieldObject->name = @pg_fieldname($this->resultId, $fieldOffset);
$fieldObject->type = @pg_fieldtype($this->resultId, $fieldOffset);
$fieldObject->max_length = @pg_fieldsize($this->resultId, $fieldOffset);
return $fieldObject;
}
}
?>
@@ -0,0 +1,147 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class postgres8_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres8_extend_ADOConnection extends postgres8_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $_genIDSQL = "SELECT NEXTVAL('%s')";
var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $genID = 0;
function GenID($seqname='adodbseq', $startID=1)
{
$getnext = sprintf($this->_genIDSQL, $seqname);
$holdtransOK = $this->transaction_status;
$save_handler = $this->raiseErrorFn;
$this->raiseErrorFn = '';
@($result = $this->Execute($getnext));
$this->raiseErrorFn = $save_handler;
if (!$result) {
$this->transaction_status = $holdtransOK;
$createseq = $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
$result = $this->Execute($getnext);
}
if ($result && !$result->EOF)
$this->genID = reset($result->fields);
else $this->genID = 0;
if ($result)
$result->Close();
return $this->genID;
}
function CreateSequence($seqname='adodbseq', $startID=1)
{
return $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID));
}
function DropSequence($seqname='adodbseq')
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class postgres8_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres8_extend_ResultSet extends postgres8_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,712 @@
<?php
/**
* ADOdb Lite Meta Module for Postgres8
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class postgres7_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres8_meta_ADOConnection extends postgres8_meta_EXTENDER
{
var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%'";
var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
FROM pg_class c, pg_attribute a,pg_type t
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// used when schema defined
var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
and c.relnamespace=n.oid and n.nspname='%s'
and a.attname not like '....%%' AND a.attnum > 0
AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// get primary key etc -- from Freek Dijkstra
var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p)) return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = 'SELECT t.tgargs as args
FROM
pg_trigger t,pg_class c,pg_proc p
WHERE
t.tgenabled AND
t.tgrelid = c.oid AND
t.tgfoid = p.oid AND
p.proname = \'RI_FKey_check_ins\' AND
c.relname = \''.strtolower($table).'\'
ORDER BY
t.tgrelid';
$rs =& $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr =& $rs->GetArray();
$a = array();
foreach($arr as $v) {
$data = explode(chr(0), $v['args']);
$size = count($data)-1; //-1 because the last node is empty
for($i = 4; $i < $size; $i++) {
if ($upper)
$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
else
$a[$data[2]][] = $data[$i].'='.$data[++$i];
}
}
return $a;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false,$this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function MetaDatabases()
{
global $ADODB_FETCH_MODE;
if ($this->metaDatabasesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$arr = $this->GetCol($this->metaDatabasesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $arr;
}
return false;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$info = $this->ServerInfo();
if ($info['version'] >= 7.3) {
$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
}
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtolower($mask));
if ($info['version']>=7.3)
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
union
select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
else
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask
union
select viewname,'V' from pg_views where viewname like $mask";
}
$ret =& $this->_MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
function &_MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function &MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
$schema = false;
$false = false;
$this->_findschema($table,$schema);
if ($normalize) $table = strtolower($table);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) {
return $false;
}
if (!empty($this->metaKeySQL)) {
// If we want the primary keys, we have to issue a separate query
// Of course, a modified version of the metaColumnsSQL query using a
// LEFT JOIN would have been much more elegant, but postgres does
// not support OUTER JOINS. So here is the clumsy way.
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
// fetch all result in once for performance.
$keys =& $rskey->GetArray();
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
$rskey->Close();
unset($rskey);
}
$rsdefa = array();
if (!empty($this->metaDefaultsSQL)) {
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$sql = sprintf($this->metaDefaultsSQL, ($table));
$rsdef = $this->Execute($sql);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rsdef) {
while (!$rsdef->EOF) {
$num = $rsdef->fields['num'];
$s = $rsdef->fields['def'];
if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
$s = substr($s, 1);
$s = substr($s, 0, strlen($s) - 1);
}
$rsdefa[$num] = $s;
$rsdef->MoveNext();
}
} else {
ADOConnection::outp( "==> SQL => " . $sql);
}
unset($rsdef);
}
$retarr = array();
while (!$rs->EOF) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->attnum = $rs->fields[6];
if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
if ($fld->max_length <= 0) $fld->max_length = -1;
if ($fld->type == 'numeric') {
$fld->scale = $fld->max_length & 0xFFFF;
$fld->max_length >>= 16;
}
// dannym
// 5 hasdefault; 6 num-of-column
$fld->has_default = ($rs->fields[5] == 't');
if ($fld->has_default) {
$fld->default_value = $rsdefa[$rs->fields[6]];
}
//Freek
$fld->not_null = $rs->fields[4] == 't';
// Freek
if (is_array($keys)) {
foreach($keys as $key) {
if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
$fld->primary_key = true;
if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
$fld->unique = true; // What name is more compatible?
}
}
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
$rs->MoveNext();
}
$rs->Close();
if (empty($retarr))
return $false;
else
return $retarr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function &MetaIndexes ($table, $primary = FALSE)
{
global $ADODB_FETCH_MODE;
$schema = false;
$this->_findschema($table,$schema);
if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
,pg_namespace n
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
} else {
$sql = '
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
}
if ($primary == FALSE) {
$sql .= ' AND i.indisprimary=false;';
}
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$rs = $this->Execute(sprintf($sql,$table,$table,$schema));
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$col_names = $this->MetaColumnNames($table,true,true);
//3rd param is use attnum,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
$indexes = array();
while ($row = $rs->FetchRow()) {
$columns = array();
foreach (explode(' ', $row[2]) as $col) {
$columns[] = $col_names[$col];
}
$indexes[$row[0]] = array(
'unique' => ($row[1] == 't'),
'columns' => $columns
);
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
if ($useattnum) {
foreach($objarr as $v)
$arr[$v->attnum] = $v->name;
} else
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class postgres8_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres8_meta_ResultSet extends postgres8_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->unique && $fieldobj->has_default && substr($fieldobj->default_value,0,8) == 'nextval(';
switch (strtoupper($t)) {
case 'MONEY': // stupid, postgres expects money to be a string
case 'INTERVAL':
case 'CHAR':
case 'CHARACTER':
case 'VARCHAR':
case 'NAME':
case 'BPCHAR':
case '_VARCHAR':
case 'INET':
case 'MACADDR':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
return 'X';
case 'IMAGE': // user defined type
case 'BLOB': // user defined type
case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
case 'VARBIT':
case 'BYTEA':
return 'B';
case 'BOOL':
case 'BOOLEAN':
return 'L';
case 'DATE':
return 'D';
case 'TIMESTAMP WITHOUT TIME ZONE':
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case 'TIMESTAMPTZ':
return 'T';
case 'INTEGER': return !$is_serial ? 'I' : 'R';
case 'SMALLINT':
case 'INT2': return !$is_serial ? 'I2' : 'R';
case 'INT4': return !$is_serial ? 'I4' : 'R';
case 'BIGINT':
case 'INT8': return !$is_serial ? 'I8' : 'R';
case 'OID':
case 'SERIAL':
return 'R';
case 'FLOAT4':
case 'FLOAT8':
case 'DOUBLE PRECISION':
case 'REAL':
return 'F';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
}
?>
@@ -0,0 +1,128 @@
<?php
/**
* ADOdb Lite Transaction Module for Postgres
*
*/
eval('class postgres8_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class postgres8_transaction_ADOConnection extends postgres8_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$this->transCnt += 1;
return @pg_Exec($this->connectionId, "begin");
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok)
return $this->RollbackTrans();
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "commit");
}
function RollbackTrans()
{
if ($this->transOff)
return true;
$this->transCnt -= 1;
return @pg_Exec($this->connectionId, "rollback");
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
if (!$this->transCnt)
$this->BeginTrans();
return $this->GetOne("select $flds from $tables where $where for update");
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class postgres8_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class postgres8_transaction_ResultSet extends postgres8_transaction_resultset_EXTENDER
{
}
?>
@@ -0,0 +1,67 @@
<?php
/**
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified 28 August, 2005 for use with ADOdb Lite by Mark Dickenson
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_sqlite extends ADODB_DataDict {
var $dbtype = 'sqlite';
var $seqField = false;
var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'VARCHAR(250)';
case 'C2': return 'VARCHAR';
case 'X2': return 'VARCHAR(250)';
case 'B': return 'VARCHAR';
case 'D': return 'DATE';
case 'T': return 'DATE';
case 'L': return 'DECIMAL(1)';
case 'I': return 'DECIMAL(10)';
case 'I1': return 'DECIMAL(3)';
case 'I2': return 'DECIMAL(5)';
case 'I4': return 'DECIMAL(10)';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'DECIMAL(32,8)';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) $this->outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) $this->outp("DropColumnSQL not supported");
return array();
}
}
?>
@@ -0,0 +1,241 @@
<?php
/**
* ADOdb Lite Date Module for SQLite
*
*/
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
@include(ADODB_DIR . '/adodb-time.inc.php');
eval('class sqlite_date_EXTENDER extends '. $last_module . '_ADOConnection { }');
class sqlite_date_ADOConnection extends sqlite_date_EXTENDER
{
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $emptyDate = '&nbsp;';
var $emptyTimeStamp = '&nbsp;';
var $sysDate = "adodb_date('Y-m-d')";
var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
var $isoDates = false; /// accepts dates in ISO format
function Time()
{
$rs =& $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF)
return $this->UnixTimeStamp(reset($rs->fields));
return false;
}
function OffsetDate($dayFraction, $date=false)
{
if (!$date)
$date = $this->sysDate;
return '('.$date.'+'.$dayFraction.')';
}
function SetDateLocale($locale = 'En')
{
$this->locale = $locale;
switch (strtoupper($locale))
{
case 'EN':
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
case 'US':
$this->fmtDate = "'m-d-Y'";
$this->fmtTimeStamp = "'m-d-Y H:i:s'";
break;
case 'NL':
case 'FR':
case 'RO':
case 'IT':
$this->fmtDate="'d-m-Y'";
$this->fmtTimeStamp = "'d-m-Y H:i:s'";
break;
case 'GE':
$this->fmtDate="'d.m.Y'";
$this->fmtTimeStamp = "'d.m.Y H:i:s'";
break;
default:
$this->fmtDate="'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
break;
}
}
function DBDate($date)
{
if (empty($date) && $date !== 0)
return 'null';
if (is_string($date) && !is_numeric($date)) {
if ($date === 'null' || strncmp($date, "'", 1) === 0)
return $date;
if ($this->isoDates)
return "'$date'";
$date = $this->UnixDate($date);
}
return adodb_date($this->fmtDate,$date);
}
function DBTimeStamp($timestamp)
{
if (empty($timestamp) && $timestamp !== 0)
return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($timestamp) || (is_numeric($timestamp) && strlen($timestamp)<14))
return adodb_date($this->fmtTimeStamp, $timestamp);
if ($timestamp === 'null')
return $timestamp;
if ($this->isoDates && strlen($timestamp) !== 14)
return "'$timestamp'";
$timestamp = $this->UnixTimeStamp($timestamp);
return adodb_date($this->fmtTimeStamp, $timestamp);
}
function UnixDate($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (is_numeric($v) && strlen($v) !== 8)
return $v;
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR)
return 0;
// h-m-s-MM-DD-YY
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
}
function UnixTimeStamp($v)
{
if (is_object($v)) {
// odbtp support
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour, $v->minute, $v->second, $v->month, $v->day, $v->year);
}
if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr))
return false;
if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1)
return 0;
// h-m-s-MM-DD-YY
if (!isset($rr[5]))
return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]);
else return adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]);
}
function UserDate($v, $fmt='Y-m-d', $gmt=false)
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return ($gmt) ? adodb_gmdate($fmt, $tt) : adodb_date($fmt, $tt);
}
function UserTimeStamp($v, $fmt='Y-m-d H:i:s', $gmt=false)
{
if (!isset($v))
return $this->emptyTimeStamp;
# strlen(14) allows YYYYMMDDHHMMSS format
if (is_numeric($v) && strlen($v)<14)
return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt == 0)
return $this->emptyTimeStamp;
else return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
}
function SQLDate($fmt, $col=false)
{
$fmt = $this->qstr($fmt);
return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";
}
}
eval('class sqlite_date_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class sqlite_date_ResultSet extends sqlite_date_resultset_EXTENDER
{
var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
var $emptyDate = '&nbsp;'; /// what to display when $time==0
var $datetime = false;
function UserTimeStamp($v, $fmt='Y-m-d H:i:s')
{
if (is_numeric($v) && strlen($v)<14)
return adodb_date($fmt,$v);
$tt = $this->UnixTimeStamp($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
if ($tt === 0)
return $this->emptyTimeStamp;
else return adodb_date($fmt,$tt);
}
function UserDate($v,$fmt='Y-m-d')
{
$tt = $this->UnixDate($v);
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == -1) && $v != false)
return $v;
else if ($tt == 0)
return $this->emptyDate;
else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
}
return adodb_date($fmt,$tt);
}
function UnixDate($v)
{
return sqlite_date_ADOConnection::UnixDate($v);
}
function UnixTimeStamp($v)
{
return sqlite_date_ADOConnection::UnixTimeStamp($v);
}
}
?>
@@ -0,0 +1,614 @@
<?php
/**
* ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
* a subset of the ADODB Command Syntax.
* Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
* PostgresSQL64, PostgresSQL7, SqLite and Sybase.
*
*/
class sqlite_driver_ADOConnection extends ADOConnection
{
var $sysDate = "date('Y-m-d')";
var $sysTimeStamp = "date('Y-m-d H:i:s')";
function sqlite_driver_ADOConnection()
{
$this->dbtype = 'sqlite';
$this->dataProvider = 'sqlite';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (!function_exists('sqlite_factory')) return false;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = ($database == "") ? $host : $database;
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
if($this->persistent == 1)
{
$this->connectionId = @sqlite_popen( $this->database );
}
else
{
$this->connectionId = @sqlite_open( $this->database );
}
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return false;
}
return true;
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
$this->connectionId = sqlite_close( $this->connectionId );
if($this->persistent == 1)
{
$this->connectionId = @sqlite_popen( $this->database );
}
else
{
$this->connectionId = @sqlite_open( $this->database );
}
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return false;
}
return true;
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
$errorno = @sqlite_last_error( $this->connectionId );
$error = ($errorno) ? sqlite_error_string($errorno) : '';
return $error;
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
return @sqlite_last_error($this->connectionId);
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
return @sqlite_changes( $this->connectionId );
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
return @sqlite_last_insert_rowid($this->connectionId);
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
// Ugly hack alert! Repalce backticks with some arbitrary character
$string = str_replace('`', "\x1C", $string);
if (!$magic_quotes) {
return "'".str_replace("'", "''", $string)."'";
}
$string = str_replace("\\'", "''", str_replace('\\\\', '\\', str_replace('\\"', '"', $string)));
return "'" . $string . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
return implode("||", $arr);
}
function IfNull( $field, $ifNull )
{
return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
@sqlite_close( $this->connectionId );
$this->connectionId = false;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$sql = str_replace('`by`', "'by'", $sql);
$sql = str_replace('`order`', '"order"', $sql);
$sql = str_replace('`when`', '"when"', $sql);
$sql = str_replace('`desc`', "'desc'", $sql);
$sql = str_replace('`', '', $sql);
$sql = str_replace("\x1C", "`", $sql);
if (strpos($sql, "(DISTINCT ipmd5)")) {
$sql = str_replace("(DISTINCT ipmd5) FROM " . KU_DBPREFIX . "posts", "(ipmd5) FROM (SELECT DISTINCT ipmd5 FROM " . KU_DBPREFIX . "posts", $sql);
$sql .= ")";
}
$sql = str_replace('IS_DELETED', 'is_deleted', $sql);
$sql = str_replace("HIGH_PRIORITY", "", $sql);
$false = false;
$offsetStr = '';
$limitStr = '';
if ($offset != -1 || $nrows != -1)
{
$offsetStr = ($offset>=0) ? " OFFSET " . $offset . "," : '';
$limitStr = ($nrows >= 0) ? " LIMIT ". $nrows : ($offset >= 0 ? ' LIMIT 999999999' : '');
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? 1 : 0;
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @sqlite_query( $this->sql, $this->connectionId );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
}
}
else
{
$this->sql = $sql . "$limitStr$offsetStr";
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
$resultId = @sqlite_query( $this->sql, $this->connectionId );
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . "$limitStr$offsetStr");
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$recordset->_currentRow = 0;
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = SQLITE_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = SQLITE_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = SQLITE_BOTH; break;
}
$recordset->_numOfRows = @sqlite_num_rows( $resultId );
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
$recordset->_numOfFields = @sqlite_num_fields( $resultId );
$recordset->_fetch();
return $recordset;
}
}
class sqlite_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* sqliteResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function sqlite_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function close()
{
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (@$this->fields = sqlite_fetch_array($this->resultId,$this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @sqlite_seek($this->resultId,$row);
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
$this->fields = @sqlite_fetch_array($this->resultId,$this->fetchMode);
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
$fieldObject = new ADOFieldObject;
$fieldObject->name = sqlite_field_name($this->resultId, $fieldOffset);
$fieldObject->type = 'VARCHAR';
$fieldObject->max_length = -1;
return $fieldObject;
}
}
?>
@@ -0,0 +1,153 @@
<?php
/**
* ADOdb Lite Extend Module for Mysqlt
*
*/
eval('class sqlite_extend_EXTENDER extends '. $last_module . '_ADOConnection { }');
class sqlite_extend_ADOConnection extends sqlite_extend_EXTENDER
{
function &GetAssoc($sql, $inputarr=false, $force_array = false, $first2cols = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result) {
$data =& $result->GetAssoc($force_array, $first2cols);
$result->Close();
}
return $data;
}
/**
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
*
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
var $_genSeqSQL = "create table %s (id integer)";
var $_dropSeqSQL = 'drop table %s';
var $genID = 0;
function GenID($seqname='adodbseq', $startID=1)
{
$MAXLOOPS = 100;
while (--$MAXLOOPS>=0) {
@($num = $this->GetOne("select id from $seq"));
if ($num === false) {
$this->Execute(sprintf($this->_genSeqSQL, $seq));
$start -= 1;
$num = '0';
$result = $this->Execute("insert into $seq values($start)");
if (!$result)
return false;
}
$this->Execute("update $seq set id=id+1 where id=$num");
if ($this->affected_rows() > 0) {
$num += 1;
$this->genID = $num;
return $num;
}
}
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType, 'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts", $seq, $num);
}
return false;
}
function CreateSequence($seqname='adodbseq', $start=1)
{
$ok = $this->Execute(sprintf($this->_genSeqSQL, $seqname));
if (!$ok)
return false;
$start -= 1;
return $this->Execute("insert into $seqname values($start)");
}
function DropSequence($seqname)
{
return $this->Execute(sprintf($this->_dropSeqSQL, $seqname));
}
}
eval('class sqlite_extend_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class sqlite_extend_ResultSet extends sqlite_extend_resultset_EXTENDER
{
function &GetAssoc($force_array = false, $first2cols = false)
{
$results = false;
if ($this->_numOfFields > 1) {
$numIndex = isset($this->fields[0]);
$results = array();
if (!$first2cols && ($this->_numOfFields > 2 || $force_array)) {
if ($numIndex) {
while (!$this->EOF) {
$results[trim($this->fields[0])] = array_slice($this->fields, 1);
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
$this->MoveNext();
}
}
} else {
if ($numIndex) {
while (!$this->EOF) {
$results[trim(($this->fields[0]))] = $this->fields[1];
$this->MoveNext();
}
} else {
while (!$this->EOF) {
$v1 = trim(reset($this->fields));
$v2 = ''.next($this->fields);
$results[$v1] = $v2;
$this->MoveNext();
}
}
}
}
return $results;
}
function PO_RecordCount($table="", $condition="")
{
$lnumrows = $this->_numOfRows;
if($lnumrows == -1 && $this->connectionId)
{
if($table)
{
if ($condition)
$condition = " WHERE " . $condition;
$resultrows = &$this->connectionId->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows)
$lnumrows = reset($resultrows->fields);
}
}
return $lnumrows;
}
function CurrentRow()
{
return $this->_currentRow;
}
function AbsolutePosition()
{
return $this->_currentRow;
}
function NextRecordSet()
{
return false;
}
}
?>
@@ -0,0 +1,533 @@
<?php
/**
* ADOdb Lite Meta Module for SQlite
*
* Portions of the Meta Coding came from ADOdb
*/
/*
(c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
*/
eval('class sqlite_meta_EXTENDER extends '. $last_module . '_ADOConnection { }');
class sqlite_meta_ADOConnection extends sqlite_meta_EXTENDER
{
var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
function MetaError($err=false)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
if ($err === false)
$err = $this->ErrorNo();
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
function MetaErrorMsg($errno)
{
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
function MetaPrimaryKeys($table, $owner=false)
{
// owner not used in base class - see oci8
$p = array();
$objs =& $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
if (!empty($v->primary_key))
$p[] = $v->name;
}
}
if (sizeof($p)) return $p;
if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
return false;
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=-1,$fieldobj=false)
{
if (empty($this->_metars)) {
$rsclass = $this->last_module_name . "_ResultSet";
$this->_metars =& new $rsclass(false,$this->fetchMode);
}
return $this->_metars->MetaType($t,$len,$fieldobj);
}
/**
* return the databases that the driver can connect to.
* Some databases will return an empty array.
*
* @return an array of database names.
*/
function MetaDatabases()
{
global $ADODB_FETCH_MODE;
if ($this->metaDatabasesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$arr = $this->GetCol($this->metaDatabasesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $arr;
}
return false;
}
/**
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
*
* @return array of tables for current database.
*/
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
$false = false;
if ($mask) {
return $false;
}
if ($this->metaTablesSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute($this->metaTablesSQL);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
$arr =& $rs->GetArray();
$arr2 = array();
if ($hast = ($ttype && isset($arr[0][1]))) {
$showt = strncmp($ttype,'T',1);
}
for ($i=0; $i < sizeof($arr); $i++) {
if ($hast) {
if ($showt == 0) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
} else {
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
}
} else
$arr2[] = trim($arr[$i][0]);
}
$rs->Close();
return $arr2;
}
return $false;
}
function _findschema(&$table,&$schema)
{
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+1);
}
}
/**
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
*
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
*
* @return array of ADOFieldObjects for current table.
*/
function &MetaColumns($tab)
{
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute("PRAGMA table_info('$tab')");
if (isset($savem)) $this->SetFetchMode($savem);
if (!$rs) {
$ADODB_FETCH_MODE = $save;
return $false;
}
$arr = array();
while ($r = $rs->FetchRow()) {
$type = explode('(',$r['type']);
$size = '';
if (sizeof($type)==2)
$size = trim($type[1],')');
$fn = strtoupper($r['name']);
$fld = new ADOFieldObject;
$fld->name = $r['name'];
$fld->type = $type[0];
$fld->max_length = $size;
$fld->not_null = $r['notnull'];
$fld->default_value = $r['dflt_value'];
$fld->scale = 0;
if ($save == ADODB_FETCH_NUM) $arr[] = $fld;
else $arr[strtoupper($fld->name)] = $fld;
}
$rs->Close();
$ADODB_FETCH_MODE = $save;
return $arr;
}
/**
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
*
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
Array (
[name_of_index] => Array
(
[unique] => true or false
[columns] => Array
(
[0] => firstname
[1] => lastname
)
)
*/
function &MetaIndexes($table, $primary = FALSE, $owner=false)
{
$false = false;
// save old fetch mode
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table));
$rs = $this->Execute($SQL);
if (!is_object($rs)) {
if (isset($savem))
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $false;
}
$indexes = array ();
while ($row = $rs->FetchRow()) {
if ($primary && preg_match("/primary/i",$row[1]) == 0) continue;
if (!isset($indexes[$row[0]])) {
$indexes[$row[0]] = array(
'unique' => preg_match("/unique/i",$row[1]),
'columns' => array());
}
/**
* There must be a more elegant way of doing this,
* the index elements appear in the SQL statement
* in cols[1] between parentheses
* e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse)
*/
$cols = explode("(",$row[1]);
$cols = explode(")",$cols[1]);
array_pop($cols);
$indexes[$row[0]]['columns'] = $cols;
}
if (isset($savem)) {
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
}
return $indexes;
}
/**
* List columns names in a table as an array.
* @param table table name to query
*
* @return array of column names for current table.
*/
function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
{
$objarr =& $this->MetaColumns($table);
if (!is_array($objarr)) {
$false = false;
return $false;
}
$arr = array();
if ($numIndexes) {
$i = 0;
if ($useattnum) {
foreach($objarr as $v)
$arr[$v->attnum] = $v->name;
} else
foreach($objarr as $v) $arr[$i++] = $v->name;
} else
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
return $arr;
}
function MetaTransaction($mode,$db)
{
$mode = strtoupper($mode);
$mode = str_replace('ISOLATION LEVEL ','',$mode);
switch($mode) {
case 'READ UNCOMMITTED':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL READ COMMITTED';
default:
return 'ISOLATION LEVEL READ UNCOMMITTED';
}
break;
case 'READ COMMITTED':
return 'ISOLATION LEVEL READ COMMITTED';
break;
case 'REPEATABLE READ':
switch($db) {
case 'oci8':
case 'oracle':
return 'ISOLATION LEVEL SERIALIZABLE';
default:
return 'ISOLATION LEVEL REPEATABLE READ';
}
break;
case 'SERIALIZABLE':
return 'ISOLATION LEVEL SERIALIZABLE';
break;
default:
return $mode;
}
}
}
eval('class sqlite_meta_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class sqlite_meta_ResultSet extends sqlite_meta_resultset_EXTENDER
{
/**
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
*
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
*
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* B for Binary
* N for numeric or floating point
* D for date
* T for timestamp
* L for logical/Boolean
* I for integer
* R for autoincrement counter/integer
*
*
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default:
static $typeMap = array(
'VARCHAR' => 'C',
'VARCHAR2' => 'C',
'CHAR' => 'C',
'C' => 'C',
'STRING' => 'C',
'NCHAR' => 'C',
'NVARCHAR' => 'C',
'VARYING' => 'C',
'BPCHAR' => 'C',
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
'NTEXT' => 'X',
'M' => 'X',
'X' => 'X',
'CLOB' => 'X',
'NCLOB' => 'X',
'LVARCHAR' => 'X',
##
'BLOB' => 'B',
'IMAGE' => 'B',
'BINARY' => 'B',
'VARBINARY' => 'B',
'LONGBINARY' => 'B',
'B' => 'B',
##
'YEAR' => 'D', // mysql
'DATE' => 'D',
'D' => 'D',
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
'BOOL' => 'L',
'BOOLEAN' => 'L',
'BIT' => 'L',
'L' => 'L',
##
'COUNTER' => 'R',
'R' => 'R',
'SERIAL' => 'R', // ifx
'INT IDENTITY' => 'R',
##
'INT' => 'I',
'INT2' => 'I',
'INT4' => 'I',
'INT8' => 'I',
'INTEGER' => 'I',
'INTEGER UNSIGNED' => 'I',
'SHORT' => 'I',
'TINYINT' => 'I',
'SMALLINT' => 'I',
'I' => 'I',
##
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DECIMAL' => 'N',
'DEC' => 'N',
'REAL' => 'N',
'DOUBLE' => 'N',
'DOUBLE PRECISION' => 'N',
'SMALLFLOAT' => 'N',
'FLOAT' => 'N',
'NUMBER' => 'N',
'NUM' => 'N',
'NUMERIC' => 'N',
'MONEY' => 'N',
## informix 9.2
'SQLINT' => 'I',
'SQLSERIAL' => 'I',
'SQLSMINT' => 'I',
'SQLSMFLOAT' => 'N',
'SQLFLOAT' => 'N',
'SQLMONEY' => 'N',
'SQLDECIMAL' => 'N',
'SQLDATE' => 'D',
'SQLVCHAR' => 'C',
'SQLCHAR' => 'C',
'SQLDTIME' => 'T',
'SQLINTERVAL' => 'N',
'SQLBYTES' => 'B',
'SQLTEXT' => 'X',
## informix 10
"SQLINT8" => 'I8',
"SQLSERIAL8" => 'I8',
"SQLNCHAR" => 'C',
"SQLNVCHAR" => 'C',
"SQLLVARCHAR" => 'X',
"SQLBOOL" => 'L'
);
$tmap = false;
$t = strtoupper($t);
$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
return $tmap;
}
}
}
?>
@@ -0,0 +1,132 @@
<?php
/**
* ADOdb Lite Transaction Module for Sqlite
*
*/
eval('class sqlite_transaction_EXTENDER extends '. $last_module . '_ADOConnection { }');
class sqlite_transaction_ADOConnection extends sqlite_transaction_EXTENDER
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$ret = $this->Execute("BEGIN TRANSACTION");
$this->transCnt += 1;
return true;
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok)
return $this->RollbackTrans();
$ret = $this->Execute("COMMIT");
if ($this->transCnt>0)
$this->transCnt -= 1;
return !empty($ret);
}
function RollbackTrans()
{
if ($this->transOff)
return true;
$ret = $this->Execute("ROLLBACK");
if ($this->transCnt>0)
$this->transCnt -= 1;
return !empty($ret);
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
return false;
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
}
eval('class sqlite_transaction_resultset_EXTENDER extends '. $last_module . '_ResultSet { }');
class sqlite_transaction_ResultSet extends sqlite_transaction_resultset_EXTENDER
{
}
?>