imported adodb 4.65

This commit is contained in:
Ralf Becker 2005-09-26 10:12:10 +00:00
parent e7179a8977
commit 4e5cb1786e
131 changed files with 8364 additions and 4114 deletions

View File

@ -7,7 +7,8 @@ global $ADODB_INCLUDED_CSV;
$ADODB_INCLUDED_CSV = 1;
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -66,10 +67,15 @@ $ADODB_INCLUDED_CSV = 1;
$o =& $rs->FetchField($i);
$flds[] = $o;
}
$rs =& new ADORecordSet_array();
$rs->InitArrayFields($rows,$flds);
return $line.serialize($rs);
$savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
$class = $rs->connection->arrayClass;
$rs2 = new $class();
$rs2->sql = $rs->sql;
$rs2->oldProvider = $rs->dataProvider;
$rs2->InitArrayFields($rows,$flds);
$rs2->fetchMode = $savefetch;
return $line.serialize($rs2);
}
@ -84,15 +90,16 @@ $ADODB_INCLUDED_CSV = 1;
* error occurred in sql INSERT/UPDATE/DELETE,
* empty recordset is returned
*/
function &csv2rs($url,&$err,$timeout=0)
function &csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
{
$false = false;
$err = false;
$fp = @fopen($url,'rb');
if (!$fp) {
$err = $url.' file/URL not found';
return false;
return $false;
}
flock($fp, LOCK_SH);
@flock($fp, LOCK_SH);
$arr = array();
$ttl = 0;
@ -101,7 +108,7 @@ $ADODB_INCLUDED_CSV = 1;
if (strncmp($meta[0],'****',4) === 0) {
$err = trim(substr($meta[0],4,1024));
fclose($fp);
return false;
return $false;
}
// check for meta data
// $meta[0] is -1 means return an empty recordset
@ -113,19 +120,20 @@ $ADODB_INCLUDED_CSV = 1;
if (sizeof($meta) < 5) {
$err = "Corrupt first line for format -1";
fclose($fp);
return false;
return $false;
}
fclose($fp);
if ($timeout > 0) {
$err = " Illegal Timeout $timeout ";
return false;
return $false;
}
$rs = new $rsclass($val=true);
$rs->fields = array();
$rs->timeCreated = $meta[1];
$rs =& new ADORecordSet($val=true);
$rs->EOF = true;
$rs->_numOfFields=0;
$rs->_numOfFields = 0;
$rs->sql = urldecode($meta[2]);
$rs->affectedrows = (integer)$meta[3];
$rs->insertid = $meta[4];
@ -149,27 +157,27 @@ $ADODB_INCLUDED_CSV = 1;
if ((rand() & 31) == 0) {
fclose($fp);
$err = "Timeout 3";
return false;
return $false;
}
break;
case 2:
if ((rand() & 15) == 0) {
fclose($fp);
$err = "Timeout 2";
return false;
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
fclose($fp);
$err = "Timeout 1";
return false;
return $false;
}
break;
default:
fclose($fp);
$err = "Timeout 0";
return false;
return $false;
} // switch
} // if check flush cache
@ -203,7 +211,7 @@ $ADODB_INCLUDED_CSV = 1;
if (!$meta) {
fclose($fp);
$err = "Unexpected EOF 1";
return false;
return $false;
}
}
@ -216,7 +224,7 @@ $ADODB_INCLUDED_CSV = 1;
$flds = false;
break;
}
$fld =& new ADOFieldObject();
$fld = new ADOFieldObject();
$fld->name = urldecode($o2[0]);
$fld->type = $o2[1];
$fld->max_length = $o2[2];
@ -225,7 +233,7 @@ $ADODB_INCLUDED_CSV = 1;
} else {
fclose($fp);
$err = "Recordset had unexpected EOF 2";
return false;
return $false;
}
// slurp in the data
@ -242,9 +250,9 @@ $ADODB_INCLUDED_CSV = 1;
if (!is_array($arr)) {
$err = "Recordset had unexpected EOF (in serialized recordset)";
if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
return false;
return $false;
}
$rs =& new ADORecordSet_array();
$rs = new $rsclass();
$rs->timeCreated = $ttl;
$rs->InitArrayFields($arr,$flds);
return $rs;
@ -272,7 +280,7 @@ $ADODB_INCLUDED_CSV = 1;
$mtime = substr(str_replace(' ','_',microtime()),2);
// getmypid() actually returns 0 on Win98 - never mind!
$tmpname = $filename.uniqid($mtime).getmypid();
if (!($fd = fopen($tmpname,'a'))) return false;
if (!($fd = @fopen($tmpname,'a'))) return false;
$ok = ftruncate($fd,0);
if (!fwrite($fd,$contents)) $ok = false;
fclose($fd);
@ -288,7 +296,7 @@ $ADODB_INCLUDED_CSV = 1;
}
return $ok;
}
if (!($fd = fopen($filename, 'a'))) return false;
if (!($fd = @fopen($filename, 'a'))) return false;
if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
$ok = fwrite( $fd, $contents );
fclose($fd);

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -22,7 +22,7 @@ if (!defined('ADODB_DIR')) die();
function Lens_ParseTest()
{
$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";
$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
print "<p>$str</p>";
$a= Lens_ParseArgs($str);
print "<pre>";
@ -30,6 +30,7 @@ print_r($a);
print "</pre>";
}
if (!function_exists('ctype_alnum')) {
function ctype_alnum($text) {
return preg_match('/^[a-z0-9]*$/i', $text);
@ -153,6 +154,7 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
}
$pos += 1;
}
if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
return $tokens;
}
@ -169,10 +171,12 @@ class ADODB_DataDict {
var $dropCol = ' DROP COLUMN';
var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s'; // table, old-column, new-column, column-definitions (not used by default)
var $nameRegex = '\w';
var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
var $schema = false;
var $serverInfo = array();
var $autoIncrement = false;
var $dataProvider;
var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
/// in other words, we use a text area for editting.
@ -186,23 +190,27 @@ class ADODB_DataDict {
return false;
}
function &MetaTables()
function MetaTables()
{
if (!$this->connection->IsConnected()) return array();
return $this->connection->MetaTables();
}
function &MetaColumns($tab, $upper=true, $schema=false)
function MetaColumns($tab, $upper=true, $schema=false)
{
if (!$this->connection->IsConnected()) return array();
return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
}
function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
{
if (!$this->connection->IsConnected()) return array();
return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
}
function &MetaIndexes($table, $primary = false, $owner = false)
function MetaIndexes($table, $primary = false, $owner = false)
{
if (!$this->connection->IsConnected()) return array();
return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
}
@ -211,7 +219,7 @@ class ADODB_DataDict {
return ADORecordSet::MetaType($t,$len,$fieldobj);
}
function NameQuote($name = NULL)
function NameQuote($name = NULL,$allowBrackets=false)
{
if (!is_string($name)) {
return FALSE;
@ -231,7 +239,9 @@ class ADODB_DataDict {
}
// if name contains special characters, quote it
if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {
$regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
return $quote . $name . $quote;
}
@ -312,7 +322,8 @@ class ADODB_DataDict {
}
foreach($flds as $key => $fld) {
$flds[$key] = $this->NameQuote($fld);
# some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
$flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
}
return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
@ -424,7 +435,7 @@ class ADODB_DataDict {
{
if (!$tableoptions) $tableoptions = array();
list($lines,$pkey) = $this->_GenFields($flds);
list($lines,$pkey) = $this->_GenFields($flds, true);
$taboptions = $this->_Options($tableoptions);
$tabname = $this->TableName ($tabname);
@ -436,7 +447,7 @@ class ADODB_DataDict {
return $sql;
}
function _GenFields($flds)
function _GenFields($flds,$widespacing=false)
{
if (is_string($flds)) {
$padding = ' ';
@ -558,7 +569,7 @@ class ADODB_DataDict {
} else {
$fdefault = $this->connection->sysDate;
}
} else if (strlen($fdefault) && !$fnoquote)
} else if ($fdefault !== false && !$fnoquote)
if ($ty == 'C' or $ty == 'X' or
( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
@ -567,7 +578,7 @@ class ADODB_DataDict {
$fdefault = $this->connection->qstr($fdefault);
$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
$fname = str_pad($fname,16);
if ($widespacing) $fname = str_pad($fname,24);
$lines[$fid] = $fname.' '.$ftype.$suffix;
if ($fautoinc) $this->autoIncrement = true;
@ -692,26 +703,69 @@ class ADODB_DataDict {
}
/*
"Florian Buzin [ easywe ]" <florian.buzin@easywe.de>
"Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
This function changes/adds new fields to your table. You don't
have to know if the col is new or not. It will check on its own.
*/
function ChangeTableSQL($tablename, $flds, $tableoptions = false)
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
// check table exists
$cols = &$this->MetaColumns($tablename);
$save_handler = $this->connection->raiseErrorFn;
$this->connection->raiseErrorFn = '';
$cols = $this->MetaColumns($tablename);
$this->connection->raiseErrorFn = $save_handler;
if (isset($savem)) $this->connection->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ( empty($cols)) {
return $this->CreateTableSQL($tablename, $flds, $tableoptions);
}
if (is_array($flds)) {
// Cycle through the update fields, comparing
// existing fields to fields to update.
// if the Metatype and size is exactly the
// same, ignore - by Mark Newham
$holdflds = array();
foreach($flds as $k=>$v) {
if ( isset($cols[$k]) && is_object($cols[$k]) ) {
$c = $cols[$k];
$ml = $c->max_length;
$mt = &$this->MetaType($c->type,$ml);
if ($ml == -1) $ml = '';
if ($mt == 'X') $ml = $v['SIZE'];
if (($mt != $v['TYPE']) || $ml != $v['SIZE']) {
$holdflds[$k] = $v;
}
} else {
$holdflds[$k] = $v;
}
}
$flds = $holdflds;
}
// already exists, alter table instead
list($lines,$pkey) = $this->_GenFields($flds);
$alter = 'ALTER TABLE ' . $this->TableName($tablename);
$sql = array();
foreach ( $lines as $id => $v ) {
if ( isset($cols[$id]) && is_object($cols[$id]) ) {
$flds = Lens_ParseArgs($v,',');
// We are trying to change the size of the field, if not allowed, simply ignore the request.
if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) continue;
$sql[] = $alter . $this->alterCol . ' ' . $v;
} else {
$sql[] = $alter . $this->addCol . ' ' . $v;
@ -721,4 +775,4 @@ class ADODB_DataDict {
return $sql;
}
} // class
?>
?>

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -249,7 +249,8 @@ static $MAP = array(
1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
1146 => DB_ERROR_NOSUCHTABLE,
1048 => DB_ERROR_CONSTRAINT,
2002 => DB_ERROR_CONNECT_FAILED
2002 => DB_ERROR_CONNECT_FAILED,
2005 => DB_ERROR_CONNECT_FAILED
);
return $MAP;

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -15,7 +15,7 @@
// added Claudio Bustos clbustos#entelchile.net
if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
/**
* Default Error Handler. This will be called with the following params

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -12,7 +12,7 @@
*/
include_once('PEAR.php');
define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
/*
* Enabled the following if you want to terminate scripts when an error occurs

View File

@ -1,7 +1,7 @@
<?php
/**
* @version V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -69,7 +69,8 @@ var $database = '';
function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
{
global $ADODB_EXCEPTION;
if (error_reporting() == 0) return; // obey @ protocol
if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
else $errfn = 'ADODB_EXCEPTION';
throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -73,6 +73,7 @@ class ADODB_BASE_RS implements IteratorAggregate {
return new ADODB_Iterator($this);
}
/* this is experimental - i don't really know what to return... */
function __toString()
{
include_once(ADODB_DIR.'/toexport.inc.php');

View File

@ -7,7 +7,7 @@ global $ADODB_INCLUDED_LIB;
$ADODB_INCLUDED_LIB = 1;
/*
@version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.
@version 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.
@ -22,6 +22,7 @@ $ADODB_INCLUDED_LIB = 1;
function _array_change_key_case($an_array)
{
if (is_array($an_array)) {
$new_array = array();
foreach($an_array as $key=>$value)
$new_array[strtoupper($key)] = $value;
@ -80,7 +81,6 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
$cnt = $zthis->GetOne("select count(*) from $table where $where");
if ($cnt > 0) return 1; // record already exists
} else {
if (($zthis->Affected_Rows()>0)) return 1;
}
} else
@ -114,12 +114,12 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = " multiple size=$size";
$attr = ' multiple size="'.$size.'"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = " size=$size";
} else if ($size) $attr = ' size="'.$size.'"';
else $attr ='';
$s = "<select name=\"$name\"$attr $selectAttr>";
$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
@ -131,9 +131,18 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
else $compareFields0 = true;
$value = '';
$optgroup = null;
$firstgroup = true;
$fieldsize = $zthis->FieldCount();
while(!$zthis->EOF) {
$zval = rtrim(reset($zthis->fields));
if (sizeof($zthis->fields) > 1) {
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($fieldsize > 1) {
if (isset($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
else
@ -141,67 +150,176 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
}
$selected = ($compareFields0) ? $zval : $zval2;
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
$group = '';
if ($fieldsize > 2) {
$group = rtrim($zthis->fields[2]);
}
if ($optgroup != $group) {
$optgroup = $group;
if ($firstgroup) {
$firstgroup = false;
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
} else {
$s .="\n</optgroup>";
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
}
}
if ($hasvalue)
$value = " value='".htmlspecialchars($zval2)."'";
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} // while
// closing last optgroup
if($optgroup != null) {
$s .= "\n</optgroup>";
}
return $s ."\n</select>\n";
}
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
$hasvalue = false;
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = ' multiple size="'.$size.'"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = ' size="'.$size.'"';
else $attr ='';
$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue=true;
else $compareFields0 = true;
$value = '';
$optgroup = null;
$firstgroup = true;
$fieldsize = sizeof($zthis->fields);
while(!$zthis->EOF) {
$zval = rtrim(reset($zthis->fields));
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($fieldsize > 1) {
if (isset($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
else
$zval2 = rtrim(next($zthis->fields));
}
$selected = ($compareFields0) ? $zval : $zval2;
$group = '';
if (isset($zthis->fields[2])) {
$group = rtrim($zthis->fields[2]);
}
if ($optgroup != $group) {
$optgroup = $group;
if ($firstgroup) {
$firstgroup = false;
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
} else {
$s .="\n</optgroup>";
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
}
}
if ($hasvalue)
$value = " value='".htmlspecialchars($zval2)."'";
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} // while
// closing last optgroup
if($optgroup != null) {
$s .= "\n</optgroup>";
}
return $s ."\n</select>\n";
}
/*
Count the number of records this sql statement will return by using
query rewriting techniques...
Does not work with UNIONs.
Does not work with UNIONs, except with postgresql and oracle.
*/
function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
{
$qryRecs = 0;
if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
preg_match('/\s+GROUP\s+BY\s+/is',$sql) ||
preg_match('/\s+UNION\s+/is',$sql)) {
// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
// but this is only supported by oracle and postgresql...
if ($zthis->dataProvider == 'oci8') {
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
} else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') {
// Allow Oracle hints to be used for query optimization, Chris Wrye
if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
$rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")";
} else
$rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")";
} else if (strncmp($zthis->databaseType,'postgres',8) == 0) {
$info = $zthis->ServerInfo();
if (substr($info['version'],0,3) >= 7.1) { // good till version 999
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
}
}
} else {
} else {
// now replace SELECT ... FROM with SELECT COUNT(*) FROM
$rewritesql = preg_replace(
'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
// fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
// with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql);
}
if (isset($rewritesql) && $rewritesql != $sql) {
@ -218,11 +336,14 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
//--------------------------------------------
// query rewrite failed - so try slower way...
// strip off unneeded ORDER BY if no UNION
if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rstest = &$zthis->Execute($rewritesql,$inputarr);
if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
if ($rstest) {
$qryRecs = $rstest->RecordCount();
if ($qryRecs == -1) {
@ -249,7 +370,7 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
/*
Code originally from "Cornel G" <conyg@fx.ro>
This code will not work with SQL that has UNION in it
This code might not work with SQL that has UNION in it
Also if you are using CachePageExecute(), there is a strong possibility that
data will get out of synch. use CachePageExecute() only with tables that
@ -416,9 +537,9 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
// is_null requires php 4.0.4
//********************************************************//
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === 'null'
|| $arrFields[$upperfname] === ''
|| empty($arrFields[$upperfname]))
)
{
switch ($force) {
@ -462,8 +583,11 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
// If there were any modified fields then build the rest of the update query.
if ($fieldUpdatedCount > 0 || $forceUpdate) {
// Get the table name from the existing query.
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
if (!empty($rs->tableName)) $tableName = $rs->tableName;
else {
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
$tableName = $tableName[1];
}
// Get the full where clause excluding the word "WHERE" from
// the existing query.
preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
@ -472,18 +596,19 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
// not a good hack, improvements?
if ($whereClause) {
if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
else preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
else preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard);
} else
$whereClause = array(false,false);
if ($discard)
$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
$sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2);
if (strlen($whereClause[1]) > 0)
$sql .= ' WHERE '.$whereClause[1];
$sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2);
if (strlen($whereClause[1]) > 0)
$sql .= ' WHERE '.$whereClause[1];
return $sql;
return $sql;
} else {
return false;
@ -512,6 +637,10 @@ function adodb_key_exists($key, &$arr,$force=2)
*/
function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
{
static $cacheRS = false;
static $cacheSig = 0;
static $cacheCols;
$tableName = '';
$values = '';
$fields = '';
@ -528,13 +657,26 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
//because we have to call MetaType.
//php can't do a $rsclass::MetaType()
$rsclass = $zthis->rsPrefix.$zthis->databaseType;
$recordSet =& new $rsclass(-1,$zthis->fetchMode);
$recordSet = new $rsclass(-1,$zthis->fetchMode);
$recordSet->connection = &$zthis;
$columns = $zthis->MetaColumns( $tableName );
if (is_string($cacheRS) && $cacheRS == $rs) {
$columns =& $cacheCols;
} else {
$columns = $zthis->MetaColumns( $tableName );
$cacheRS = $tableName;
$cacheCols = $columns;
}
} else if (is_subclass_of($rs, 'adorecordset')) {
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
$columns[] = $rs->FetchField($i);
if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
$columns =& $cacheCols;
} else {
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
$columns[] = $rs->FetchField($i);
$cacheRS = $cacheSig;
$cacheCols = $columns;
$rs->insertSig = $cacheSig++;
}
$recordSet =& $rs;
} else {
@ -556,9 +698,9 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
/********************************************************/
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === 'null'
|| $arrFields[$upperfname] === ''
|| empty($arrFields[$upperfname]))
)
{
switch ($force) {
@ -613,7 +755,8 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
// Get the table name from the existing query.
if (!$tableName) {
if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
if (!empty($rs->tableName)) $tableName = $rs->tableName;
else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
$tableName = $tableName[1];
else
return false;
@ -724,58 +867,39 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
}
}
$sql = '';
switch($type) {
case "C":
case "X":
case 'B':
if ($action == 'I') {
$sql = $zthis->qstr($arrFields[$fname],$magicq) . ", ";
} else {
$sql .= $fnameq . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", ";
}
break;
$val = $zthis->qstr($arrFields[$fname],$magicq);
break;
case "D":
if ($action == 'I') {
$sql = $zthis->DBDate($arrFields[$fname]) . ", ";
} else {
$sql .= $fnameq . "=" . $zthis->DBDate($arrFields[$fname]) . ", ";
}
$val = $zthis->DBDate($arrFields[$fname]);
break;
case "T":
if ($action == 'I') {
$sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
} else {
$sql .= $fnameq . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
}
$val = $zthis->DBTimeStamp($arrFields[$fname]);
break;
default:
$val = $arrFields[$fname];
if (empty($val)) $val = '0';
if ($action == 'I') {
$sql .= $val . ", ";
} else {
$sql .= $fnameq . "=" . $val . ", ";
}
break;
}
return $sql;
if ($action == 'I') return $val . ", ";
return $fnameq . "=" . $val . ", ";
}
function _adodb_debug_execute(&$zthis, $sql, $inputarr)
{
global $HTTP_SERVER_VARS;
$ss = '';
if ($inputarr) {
foreach($inputarr as $kk=>$vv) {
@ -784,21 +908,26 @@ global $HTTP_SERVER_VARS;
}
$ss = "[ $ss ]";
}
$sqlTxt = str_replace(',',', ',is_array($sql) ? $sql[0] : $sql);
$sqlTxt = is_array($sql) ? $sql[0] : $sql;
/*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql);
$sqlTxt = str_replace(',',', ',$sqlTxt);
$sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt);
*/
// check if running from browser or command-line
$inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
$dbt = $zthis->databaseType;
if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType;
if ($inBrowser) {
$ss = htmlspecialchars($ss);
if ($zthis->debug === -1)
ADOConnection::outp( "<br>\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
ADOConnection::outp( "<br>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
else
ADOConnection::outp( "<hr>\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr>\n",false);
ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr>\n",false);
} else {
ADOConnection::outp("-----\n($zthis->databaseType): ".$sqlTxt."\n-----\n",false);
ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false);
}
$qID = $zthis->_query($sql,$inputarr);
/*
@ -814,18 +943,19 @@ global $HTTP_SERVER_VARS;
ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
}
if ($zthis->debug === 99) _adodb_backtrace(true,9999,2);
return $qID;
}
function _adodb_backtrace($printOrArr=true,$levels=9999)
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
{
if (PHPVERSION() < 4.3) return '';
if ((float) PHPVERSION() < 4.3) return '';
$html = (isset($_SERVER['HTTP_USER_AGENT']));
$fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
$MAXSTRLEN = 64;
$MAXSTRLEN = 128;
$s = ($html) ? '<pre align=left>' : '';
@ -836,6 +966,7 @@ function _adodb_backtrace($printOrArr=true,$levels=9999)
$tabs = sizeof($traceArr)-2;
foreach ($traceArr as $arr) {
if ($skippy) {$skippy -= 1; continue;}
$levels -= 1;
if ($levels < 0) break;

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -57,10 +57,10 @@ class ADODB_Pager {
//
function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
{
global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
global $PHP_SELF;
$curr_page = $id.'_curr_page';
if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
if (empty($PHP_SELF)) $PHP_SELF = $_SERVER['PHP_SELF'];
$this->sql = $sql;
$this->id = $id;
@ -69,12 +69,12 @@ class ADODB_Pager {
$next_page = $id.'_next_page';
if (isset($HTTP_GET_VARS[$next_page])) {
$HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
if (isset($_GET[$next_page])) {
$_SESSION[$curr_page] = $_GET[$next_page];
}
if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page
$this->curr_page = $HTTP_SESSION_VARS[$curr_page];
$this->curr_page = $_SESSION[$curr_page];
}
@ -242,6 +242,8 @@ class ADODB_Pager {
$this->rows = $rows;
if ($this->db->dataProvider == 'informix') $this->db->cursorType = IFX_SCROLL;
$savec = $ADODB_COUNTRECS;
if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
if ($this->cache)

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -51,6 +51,11 @@ include_once ADODB_PEAR."/adodb.inc.php";
if (!defined('DB_OK')) {
define("DB_OK", 1);
define("DB_ERROR",-1);
// autoExecute constants
define('DB_AUTOQUERY_INSERT', 1);
define('DB_AUTOQUERY_UPDATE', 2);
/**
* This is a special constant that tells DB the user hasn't specified
* any particular get mode, so the default should be used.
@ -160,6 +165,7 @@ class DB
if (is_array($options)) {
foreach($options as $k => $v) {
switch(strtolower($k)) {
case 'persist':
case 'persistent': $persist = $v; break;
#ibase
case 'dialect': $obj->dialect = $v; break;
@ -204,9 +210,10 @@ class DB
*/
function isError($value)
{
return (is_object($value) &&
(get_class($value) == 'db_error' ||
is_subclass_of($value, 'db_error')));
if (!is_object($value)) return false;
$class = get_class($value);
return $class == 'pear_error' || is_subclass_of($value, 'pear_error') ||
$class == 'db_error' || is_subclass_of($value, 'db_error');
}
@ -221,9 +228,11 @@ class DB
*/
function isWarning($value)
{
return false;
/*
return is_object($value) &&
(get_class( $value ) == "db_warning" ||
is_subclass_of($value, "db_warning"));
is_subclass_of($value, "db_warning"));*/
}
/**

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -19,6 +19,33 @@ V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese
if (!defined(ADODB_DIR)) include_once(dirname(__FILE__).'/adodb.inc.php');
include_once(ADODB_DIR.'/tohtml.inc.php');
define( 'ADODB_OPT_HIGH', 2);
define( 'ADODB_OPT_LOW', 1);
// returns in K the memory of current process, or 0 if not known
function adodb_getmem()
{
if (function_exists('memory_get_usage'))
return (integer) ((memory_get_usage()+512)/1024);
$pid = getmypid();
if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
$output = array();
exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output);
return substr($output[5], strpos($output[5], ':') + 1);
}
/* Hopefully UNIX */
exec("ps --pid $pid --no-headers -o%mem,size", $output);
if (sizeof($output) == 0) return 0;
$memarr = explode(' ',$output[0]);
if (sizeof($memarr)>=2) return (integer) $memarr[1];
return 0;
}
// avoids localization problems where , is used instead of .
function adodb_round($n,$prec)
@ -37,7 +64,6 @@ function adodb_microtime()
/* sql code timing */
function& adodb_log_sql(&$conn,$sql,$inputarr)
{
global $HTTP_SERVER_VARS;
$perf_table = adodb_perf::table();
$conn->fnExecute = false;
@ -73,20 +99,26 @@ global $HTTP_SERVER_VARS;
$conn->lastInsID = @$conn->Insert_ID();
$conn->debug = $dbg;
}
if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {
$tracer .= '<br>'.$HTTP_SERVER_VARS['HTTP_HOST'];
if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF'];
if (isset($_SERVER['HTTP_HOST'])) {
$tracer .= '<br>'.$_SERVER['HTTP_HOST'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
} else
if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '<br>'.$HTTP_SERVER_VARS['PHP_SELF'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
//$tracer .= (string) adodb_backtrace(false);
$tracer = substr($tracer,0,500);
$tracer = (string) substr($tracer,0,500);
if (is_array($inputarr)) {
if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
else {
$params = '';
$params = implode(', ',$inputarr);
// Quote string parameters so we can see them in the
// performance stats. This helps spot disabled indexes.
$xar_params = $inputarr;
foreach ($xar_params as $xar_param_key => $xar_param) {
if (gettype($xar_param) == 'string')
$xar_params[$xar_param_key] = '"' . $xar_param . '"';
}
$params = implode(', ', $xar_params);
if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
}
} else {
@ -94,14 +126,16 @@ global $HTTP_SERVER_VARS;
}
if (is_array($sql)) $sql = $sql[0];
$arr = array('b'=>trim(substr($sql,0,230)),
$arr = array('b'=>strlen($sql).'.'.crc32($sql),
'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
//var_dump($arr);
$saved = $conn->debug;
$conn->debug = 0;
$d = $conn->sysTimeStamp;
if (empty($d)) $d = date("'Y-m-d H:i:s'");
if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
$isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)";
$isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
} else if ($dbT == 'odbc_mssql' || $dbT == 'informix') {
$timer = $arr['f'];
if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
@ -111,12 +145,13 @@ global $HTTP_SERVER_VARS;
$params = $conn->qstr($arr['d']);
$tracer = $conn->qstr($arr['e']);
$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)";
$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
$arr = false;
} else {
$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)";
$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
}
$ok = $conn->Execute($isql,$arr);
$conn->debug = $saved;
@ -138,7 +173,7 @@ global $HTTP_SERVER_VARS;
timer decimal(16,6))");
}
if (!$ok) {
ADOConnection::outp( "<b>LOGSQL Insert Failed</b>: $isql<br>$err2</br>");
ADOConnection::outp( "<p><b>LOGSQL Insert Failed</b>: $isql<br>$err2</p>");
$conn->_logsql = false;
}
}
@ -208,6 +243,12 @@ processes 69293
// Algorithm is taken from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
if (strncmp(PHP_OS,'WIN',3)==0) {
if (PHP_VERSION == '5.0.0') return false;
if (PHP_VERSION == '5.0.1') return false;
if (PHP_VERSION == '5.0.2') return false;
if (PHP_VERSION == '5.0.3') return false;
if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
@$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
if (!$c) return false;
@ -310,7 +351,12 @@ Committed_AS: 348732 kB
$perf_table = adodb_perf::table();
$saveE = $this->conn->fnExecute;
$this->conn->fnExecute = false;
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$sqlq = $this->conn->qstr($sql);
$arr = $this->conn->GetArray(
"select count(*),tracer
@ -324,6 +370,9 @@ Committed_AS: 348732 kB
$s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
}
}
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_CACHE_MODE = $save;
$this->conn->fnExecute = $saveE;
return $s;
}
@ -340,9 +389,8 @@ Committed_AS: 348732 kB
function InvalidSQL($numsql = 10)
{
global $HTTP_GET_VARS;
if (isset($HTTP_GET_VARS['sql'])) return;
if (isset($_GET['sql'])) return;
$s = '<h3>Invalid SQL</h3>';
$saveE = $this->conn->fnExecute;
$this->conn->fnExecute = false;
@ -363,22 +411,23 @@ Committed_AS: 348732 kB
*/
function _SuspiciousSQL($numsql = 10)
{
global $ADODB_FETCH_MODE,$HTTP_GET_VARS;
global $ADODB_FETCH_MODE;
$perf_table = adodb_perf::table();
$saveE = $this->conn->fnExecute;
$this->conn->fnExecute = false;
if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) {
$partial = !empty($HTTP_GET_VARS['part']);
echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
if (isset($_GET['exps']) && isset($_GET['sql'])) {
$partial = !empty($_GET['part']);
echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
}
if (isset($HTTP_GET_VARS['sql'])) return;
if (isset($_GET['sql'])) return;
$sql1 = $this->sql1;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
//$this->conn->debug=1;
$rs =& $this->conn->SelectLimit(
"select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
@ -387,6 +436,7 @@ Committed_AS: 348732 kB
and (tracer is null or tracer not like 'ERROR:%')
group by sql1
order by 1 desc",$numsql);
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
$this->conn->fnExecute = $saveE;
@ -440,35 +490,38 @@ Committed_AS: 348732 kB
*/
function _ExpensiveSQL($numsql = 10)
{
global $HTTP_GET_VARS,$ADODB_FETCH_MODE;
global $ADODB_FETCH_MODE;
$perf_table = adodb_perf::table();
$saveE = $this->conn->fnExecute;
$this->conn->fnExecute = false;
if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) {
$partial = !empty($HTTP_GET_VARS['part']);
echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
if (isset($_GET['expe']) && isset($_GET['sql'])) {
$partial = !empty($_GET['part']);
echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
}
if (isset($HTTP_GET_VARS['sql'])) return;
if (isset($_GET['sql'])) return;
$sql1 = $this->sql1;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs =& $this->conn->SelectLimit(
"select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
from $perf_table
where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
and (tracer is null or tracer not like 'ERROR:%')
group by sql1
having count(*)>1
order by 1 desc",$numsql);
if (isset($savem)) $this->conn->SetFetchMode($savem);
$this->conn->fnExecute = $saveE;
$ADODB_FETCH_MODE = $save;
if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
$s = "<h3>Expensive SQL</h3>
<font size=1>Tuning the following SQL will reduce the server load substantially</font><br>
<font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
$max = $this->maxLength;
while (!$rs->EOF) {
@ -531,7 +584,11 @@ Committed_AS: 348732 kB
$ret = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute($sql1);
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs) {
while (!$rs->EOF) {
@ -577,7 +634,6 @@ Committed_AS: 348732 kB
function UI($pollsecs=5)
{
global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS;
$perf_table = adodb_perf::table();
$conn = $this->conn;
@ -589,15 +645,15 @@ Committed_AS: 348732 kB
if ($app) $app .= ', ';
$savelog = $this->conn->LogSQL(false);
$info = $conn->ServerInfo();
if (isset($HTTP_GET_VARS['clearsql'])) {
if (isset($_GET['clearsql'])) {
$this->conn->Execute("delete from $perf_table");
}
$this->conn->LogSQL($savelog);
// magic quotes
if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) {
$_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']);
if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
$_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
}
if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
@ -606,13 +662,13 @@ Committed_AS: 348732 kB
$app .= $info['description'];
if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do'];
else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do'];
else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql';
if (isset($_GET['do'])) $do = $_GET['do'];
else if (isset($_POST['do'])) $do = $_POST['do'];
else if (isset($_GET['sql'])) $do = 'viewsql';
else $do = 'stats';
if (isset($HTTP_GET_VARS['nsql'])) {
if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql'];
if (isset($_GET['nsql'])) {
if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
}
echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
@ -620,7 +676,7 @@ Committed_AS: 348732 kB
$allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
if (empty($HTTP_GET_VARS['hidem']))
if (empty($_GET['hidem']))
echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
<b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
<a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
@ -639,7 +695,7 @@ Committed_AS: 348732 kB
break;
case 'poll':
echo "<iframe width=720 height=80%
src=\"{$HTTP_SERVER_VARS['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
break;
case 'poll2':
echo "<pre>";
@ -652,7 +708,7 @@ Committed_AS: 348732 kB
$this->DoSQLForm();
break;
case 'viewsql':
if (empty($HTTP_GET_VARS['hidem']))
if (empty($_GET['hidem']))
echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
echo($this->SuspiciousSQL($nsql));
echo($this->ExpensiveSQL($nsql));
@ -679,6 +735,7 @@ Committed_AS: 348732 kB
set_time_limit(0);
sleep($secs);
while (1) {
$arr =& $this->PollParameters();
$hits = sprintf('%2.2f',$arr[0]);
@ -699,6 +756,8 @@ Committed_AS: 348732 kB
echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n";
flush();
if (connection_aborted()) return;
sleep($secs);
$arro = $arr;
}
@ -809,24 +868,22 @@ Committed_AS: 348732 kB
function DoSQLForm()
{
global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS;
$HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS);
$PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
$sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : '';
$PHP_SELF = $_SERVER['PHP_SELF'];
$sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows'];
if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
else $rows = 3;
if (isset($HTTP_VARS['SMALLER'])) {
if (isset($_REQUEST['SMALLER'])) {
$rows /= 2;
if ($rows < 3) $rows = 3;
$HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
$_SESSION['phplens_sqlrows'] = $rows;
}
if (isset($HTTP_VARS['BIGGER'])) {
if (isset($_REQUEST['BIGGER'])) {
$rows *= 2;
$HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
$_SESSION['phplens_sqlrows'] = $rows;
}
?>
@ -846,7 +903,7 @@ Committed_AS: 348732 kB
</form>
<?php
if (!isset($HTTP_VARS['sql'])) return;
if (!isset($_REQUEST['sql'])) return;
$sql = $this->undomq(trim($sql));
if (substr($sql,strlen($sql)-1) === ';') {
@ -902,8 +959,95 @@ Committed_AS: 348732 kB
}
return $m;
}
/************************************************************************/
/**
* Reorganise multiple table-indices/statistics/..
* OptimizeMode could be given by last Parameter
*
* @example
* <pre>
* optimizeTables( 'tableA');
* </pre>
* <pre>
* optimizeTables( 'tableA', 'tableB', 'tableC');
* </pre>
* <pre>
* optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
* </pre>
*
* @param string table name of the table to optimize
* @param int mode optimization-mode
* <code>ADODB_OPT_HIGH</code> for full optimization
* <code>ADODB_OPT_LOW</code> for CPU-less optimization
* Default is LOW <code>ADODB_OPT_LOW</code>
* @author Markus Staab
* @return Returns <code>true</code> on success and <code>false</code> on error
*/
function OptimizeTables()
{
$args = func_get_args();
$numArgs = func_num_args();
if ( $numArgs == 0) return false;
$mode = ADODB_OPT_LOW;
$lastArg = $args[ $numArgs - 1];
if ( !is_string($lastArg)) {
$mode = $lastArg;
unset( $args[ $numArgs - 1]);
}
foreach( $args as $table) {
$this->optimizeTable( $table, $mode);
}
}
/**
* Reorganise the table-indices/statistics/.. depending on the given mode.
* Default Implementation throws an error.
*
* @param string table name of the table to optimize
* @param int mode optimization-mode
* <code>ADODB_OPT_HIGH</code> for full optimization
* <code>ADODB_OPT_LOW</code> for CPU-less optimization
* Default is LOW <code>ADODB_OPT_LOW</code>
* @author Markus Staab
* @return Returns <code>true</code> on success and <code>false</code> on error
*/
function OptimizeTable( $table, $mode = ADODB_OPT_LOW)
{
ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
return false;
}
/**
* Reorganise current database.
* Default implementation loops over all <code>MetaTables()</code> and
* optimize each using <code>optmizeTable()</code>
*
* @author Markus Staab
* @return Returns <code>true</code> on success and <code>false</code> on error
*/
function optimizeDatabase()
{
$conn = $this->conn;
if ( !$conn) return false;
$tables = $conn->MetaTables( 'TABLES');
if ( !$tables ) return false;
foreach( $tables as $table) {
if ( !$this->optimizeTable( $table)) {
return false;
}
}
return true;
}
// end hack
}
?>

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -24,6 +24,8 @@ This library replaces native functions as follows:
gmdate() with adodb_gmdate()
mktime() with adodb_mktime()
gmmktime() with adodb_gmmktime()
strftime() with adodb_strftime()
strftime() with adodb_gmstrftime()
</pre>
The parameters are identical, except that adodb_date() accepts a subset
@ -55,8 +57,8 @@ adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)
COPYRIGHT
(c) 2003 John Lim and released under BSD-style license except for code by jackbbs,
which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year
(c) 2003-2005 John Lim and released under BSD-style license except for code by
jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year
and originally found at http://www.php.net/manual/en/function.mktime.php
=============================================================================
@ -72,13 +74,14 @@ These should be posted to the ADOdb forums at
FUNCTION DESCRIPTIONS
FUNCTION adodb_getdate($date=false)
** FUNCTION adodb_getdate($date=false)
Returns an array containing date information, as getdate(), but supports
dates greater than 1901 to 2038.
FUNCTION adodb_date($fmt, $timestamp = false)
dates greater than 1901 to 2038. The local date/time format is derived from a
heuristic the first time adodb_getdate is called.
** FUNCTION adodb_date($fmt, $timestamp = false)
Convert a timestamp to a formatted local date. If $timestamp is not defined, the
current timestamp is used. Unlike the function date(), it supports dates
@ -87,72 +90,139 @@ outside the 1901 to 2038 range.
The format fields that adodb_date supports:
<pre>
a - "am" or "pm"
A - "AM" or "PM"
d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"
D - day of the week, textual, 3 letters; e.g. "Fri"
F - month, textual, long; e.g. "January"
g - hour, 12-hour format without leading zeros; i.e. "1" to "12"
G - hour, 24-hour format without leading zeros; i.e. "0" to "23"
h - hour, 12-hour format; i.e. "01" to "12"
H - hour, 24-hour format; i.e. "00" to "23"
i - minutes; i.e. "00" to "59"
j - day of the month without leading zeros; i.e. "1" to "31"
l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"
L - boolean for whether it is a leap year; i.e. "0" or "1"
m - month; i.e. "01" to "12"
M - month, textual, 3 letters; e.g. "Jan"
n - month without leading zeros; i.e. "1" to "12"
O - Difference to Greenwich time in hours; e.g. "+0200"
Q - Quarter, as in 1, 2, 3, 4
r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200"
s - seconds; i.e. "00" to "59"
S - English ordinal suffix for the day of the month, 2 characters;
i.e. "st", "nd", "rd" or "th"
t - number of days in the given month; i.e. "28" to "31"
T - Timezone setting of this machine; e.g. "EST" or "MDT"
U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
Y - year, 4 digits; e.g. "1999"
y - year, 2 digits; e.g. "99"
z - day of the year; i.e. "0" to "365"
Z - timezone offset in seconds (i.e. "-43200" to "43200").
The offset for timezones west of UTC is always negative,
and for those east of UTC is always positive.
a - "am" or "pm"
A - "AM" or "PM"
d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"
D - day of the week, textual, 3 letters; e.g. "Fri"
F - month, textual, long; e.g. "January"
g - hour, 12-hour format without leading zeros; i.e. "1" to "12"
G - hour, 24-hour format without leading zeros; i.e. "0" to "23"
h - hour, 12-hour format; i.e. "01" to "12"
H - hour, 24-hour format; i.e. "00" to "23"
i - minutes; i.e. "00" to "59"
j - day of the month without leading zeros; i.e. "1" to "31"
l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"
L - boolean for whether it is a leap year; i.e. "0" or "1"
m - month; i.e. "01" to "12"
M - month, textual, 3 letters; e.g. "Jan"
n - month without leading zeros; i.e. "1" to "12"
O - Difference to Greenwich time in hours; e.g. "+0200"
Q - Quarter, as in 1, 2, 3, 4
r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200"
s - seconds; i.e. "00" to "59"
S - English ordinal suffix for the day of the month, 2 characters;
i.e. "st", "nd", "rd" or "th"
t - number of days in the given month; i.e. "28" to "31"
T - Timezone setting of this machine; e.g. "EST" or "MDT"
U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
Y - year, 4 digits; e.g. "1999"
y - year, 2 digits; e.g. "99"
z - day of the year; i.e. "0" to "365"
Z - timezone offset in seconds (i.e. "-43200" to "43200").
The offset for timezones west of UTC is always negative,
and for those east of UTC is always positive.
</pre>
Unsupported:
<pre>
B - Swatch Internet time
I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
W - ISO-8601 week number of year, weeks starting on Monday
B - Swatch Internet time
I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
W - ISO-8601 week number of year, weeks starting on Monday
</pre>
FUNCTION adodb_date2($fmt, $isoDateString = false)
** FUNCTION adodb_date2($fmt, $isoDateString = false)
Same as adodb_date, but 2nd parameter accepts iso date, eg.
adodb_date2('d-M-Y H:i','2003-12-25 13:01:34');
FUNCTION adodb_gmdate($fmt, $timestamp = false)
** FUNCTION adodb_gmdate($fmt, $timestamp = false)
Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the
current timestamp is used. Unlike the function date(), it supports dates
outside the 1901 to 2038 range.
FUNCTION adodb_mktime($hr, $min, $sec [, $month, $day, $year])
** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year])
Converts a local date to a unix timestamp. Unlike the function mktime(), it supports
dates outside the 1901 to 2038 range. Differs from mktime() in that all parameters
are currently compulsory.
dates outside the 1901 to 2038 range. All parameters are optional.
FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year])
** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year])
Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports
dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters
are currently compulsory.
** FUNCTION adodb_gmstrftime($fmt, $timestamp = false)
Convert a timestamp to a formatted GMT date.
** FUNCTION adodb_strftime($fmt, $timestamp = false)
Convert a timestamp to a formatted local date. Internally converts $fmt into
adodb_date format, then echo result.
For best results, you can define the local date format yourself. Define a global
variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using
adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax.
eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s');
Supported format codes:
<pre>
%a - abbreviated weekday name according to the current locale
%A - full weekday name according to the current locale
%b - abbreviated month name according to the current locale
%B - full month name according to the current locale
%c - preferred date and time representation for the current locale
%d - day of the month as a decimal number (range 01 to 31)
%D - same as %m/%d/%y
%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
%h - same as %b
%H - hour as a decimal number using a 24-hour clock (range 00 to 23)
%I - hour as a decimal number using a 12-hour clock (range 01 to 12)
%m - month as a decimal number (range 01 to 12)
%M - minute as a decimal number
%n - newline character
%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second as a decimal number
%t - tab character
%T - current time, equal to %H:%M:%S
%x - preferred date representation for the current locale without the time
%X - preferred time representation for the current locale without the date
%y - year as a decimal number without a century (range 00 to 99)
%Y - year as a decimal number including the century
%Z - time zone or name or abbreviation
%% - a literal `%' character
</pre>
Unsupported codes:
<pre>
%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
%g - like %G, but without the century.
%G - The 4-digit year corresponding to the ISO week number (see %V).
This has the same format and value as %Y, except that if the ISO week number belongs
to the previous or next year, that year is used instead.
%j - day of the year as a decimal number (range 001 to 366)
%u - weekday as a decimal number [1,7], with 1 representing Monday
%U - week number of the current year as a decimal number, starting
with the first Sunday as the first day of the first week
%V - The ISO 8601:1988 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least 4 days in the
current year, and with Monday as the first day of the week. (Use %G or %g for
the year component that corresponds to the week number for the specified timestamp.)
%w - day of the week as a decimal, Sunday being 0
%W - week number of the current year as a decimal number, starting with the
first Monday as the first day of the first week
</pre>
=============================================================================
NOTES
@ -166,17 +236,31 @@ a. Using an algorithm similar to Plauger's in "The Standard C Library"
(page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not
work outside 32-bit signed range, so i decided not to implement it.
b. Iterate over a block of years (say 12) when searching for the
correct year.
c. Implement daylight savings, which looks awfully complicated, see
b. Implement daylight savings, which looks awfully complicated, see
http://webexhibits.org/daylightsaving/
CHANGELOG
- 18 July 2005 0.21
- In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat.
- Added support for negative months in adodb_mktime().
- 24 Feb 2005 0.20
Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date().
- 21 Dec 2004 0.17
In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false.
Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro.
- 17 Nov 2004 0.16
Removed intval typecast in adodb_mktime() for secs, allowing:
adodb_mktime(0,0,0 + 2236672153,1,1,1934);
Suggested by Ryan.
- 18 July 2004 0.15
All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. This
brings it more in line with mktime (still not identical).
All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory.
This brings it more in line with mktime (still not identical).
- 23 June 2004 0.14
@ -275,12 +359,11 @@ First implementation.
/*
Version Number
*/
define('ADODB_DATE_VERSION',0.15);
define('ADODB_DATE_VERSION',0.21);
/*
We check for Windows as only +ve ints are accepted as dates on Windows.
Apparently this problem happens also with Linux, RH 7.3 and later!
This code was originally for windows. But apparently this problem happens
also with Linux, RH 7.3 and later!
glibc-2.2.5-34 and greater has been changed to return -1 for dates <
1970. This used to work. The problem exists with RedHat 7.3 and 8.0
@ -293,16 +376,28 @@ define('ADODB_DATE_VERSION',0.15);
if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
function adodb_date_test_date($y1,$m)
function adodb_date_test_date($y1,$m,$d=13)
{
//print " $y1/$m ";
$t = adodb_mktime(0,0,0,$m,13,$y1);
if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s',$t)) {
print "<b>$y1 error</b><br>";
$t = adodb_mktime(0,0,0,$m,$d,$y1);
$rez = adodb_date('Y-n-j H:i:s',$t);
if ("$y1-$m-$d 00:00:00" != $rez) {
print "<b>$y1 error, expected=$y1-$m-$d 00:00:00, adodb=$rez</b><br>";
return false;
}
return true;
}
function adodb_date_test_strftime($fmt)
{
$s1 = strftime($fmt);
$s2 = adodb_strftime($fmt);
if ($s1 == $s2) return true;
echo "error for $fmt, strftime=$s1, $adodb=$s2<br>";
return false;
}
/**
Test Suite
*/
@ -310,13 +405,17 @@ function adodb_date_test()
{
error_reporting(E_ALL);
print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION. "</h4>";
print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."</h4>";
@set_time_limit(0);
$fail = false;
// This flag disables calling of PHP native functions, so we can properly test the code
if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);
adodb_date_test_strftime('%Y %m %x %X');
adodb_date_test_strftime("%A %d %B %Y");
adodb_date_test_strftime("%H %M S");
$t = adodb_mktime(0,0,0);
if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'<br>';
@ -485,13 +584,13 @@ Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 1
$year--;
}
$day = ( floor((13 * $month - 1) / 5) +
$day = floor((13 * $month - 1) / 5) +
$day + ($year % 100) +
floor(($year % 100) / 4) +
floor(($year / 100) / 4) - 2 *
floor($year / 100) + 77);
floor($year / 100) + 77 + $greg_correction;
return (($day - 7 * floor($day / 7))) + $greg_correction;
return $day - 7 * floor($day / 7);
}
@ -513,6 +612,7 @@ function _adodb_is_leap_year($year)
return true;
}
/**
checks for leap year, returns true if it is. Has 2-digit year check
*/
@ -575,6 +675,26 @@ function adodb_getdate($d=false,$fast=false)
return _adodb_getdate($d);
}
/*
// generate $YRS table for _adodb_getdate()
function adodb_date_gentable($out=true)
{
for ($i=1970; $i >= 1600; $i-=10) {
$s = adodb_gmmktime(0,0,0,1,1,$i);
echo "$i => $s,<br>";
}
}
adodb_date_gentable();
for ($i=1970; $i > 1500; $i--) {
echo "<hr>$i ";
adodb_date_test_date($i,1,1);
}
*/
/**
Low-level function that returns the getdate() array. We have a special
$fast flag, which if set to true, will return fewer array values,
@ -582,6 +702,8 @@ function adodb_getdate($d=false,$fast=false)
*/
function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
{
static $YRS;
$d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff());
$_day_power = 86400;
@ -597,9 +719,57 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
$d365 = $_day_power * 365;
if ($d < 0) {
$origd = $d;
if (empty($YRS)) $YRS = array(
1970 => 0,
1960 => -315619200,
1950 => -631152000,
1940 => -946771200,
1930 => -1262304000,
1920 => -1577923200,
1910 => -1893456000,
1900 => -2208988800,
1890 => -2524521600,
1880 => -2840140800,
1870 => -3155673600,
1860 => -3471292800,
1850 => -3786825600,
1840 => -4102444800,
1830 => -4417977600,
1820 => -4733596800,
1810 => -5049129600,
1800 => -5364662400,
1790 => -5680195200,
1780 => -5995814400,
1770 => -6311347200,
1760 => -6626966400,
1750 => -6942499200,
1740 => -7258118400,
1730 => -7573651200,
1720 => -7889270400,
1710 => -8204803200,
1700 => -8520336000,
1690 => -8835868800,
1680 => -9151488000,
1670 => -9467020800,
1660 => -9782640000,
1650 => -10098172800,
1640 => -10413792000,
1630 => -10729324800,
1620 => -11044944000,
1610 => -11360476800,
1600 => -11676096000);
if ($is_gmt) $origd = $d;
// The valid range of a 32bit signed timestamp is typically from
// Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT
//
# old algorithm iterates through all years. new algorithm does it in
# 10 year blocks
/*
# old algo
for ($a = 1970 ; --$a >= 0;) {
$lastd = $d;
@ -611,6 +781,36 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
break;
}
}
*/
$lastsecs = 0;
$lastyear = 1970;
foreach($YRS as $year => $secs) {
if ($d >= $secs) {
$a = $lastyear;
break;
}
$lastsecs = $secs;
$lastyear = $year;
}
$d -= $lastsecs;
if (!isset($a)) $a = $lastyear;
//echo ' yr=',$a,' ', $d,'.';
for (; --$a >= 0;) {
$lastd = $d;
if ($leaf = _adodb_is_leap_year($a)) $d += $d366;
else $d += $d365;
if ($d >= 0) {
$year = $a;
break;
}
}
/**/
$secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd;
@ -738,6 +938,7 @@ static $daylight;
$_day_power = 86400;
$arr = _adodb_getdate($d,true,$is_gmt);
if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv');
if ($daylight) adodb_daylight_sv($arr, $is_gmt);
@ -762,8 +963,10 @@ static $daylight;
case 'L': $dates .= $arr['leap'] ? '1' : '0'; break;
case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
// 4.3.11 uses '04 Jun 2004'
// 4.3.8 uses ' 4 Jun 2004'
$dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', '
. ($day<10?' '.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
. ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour;
@ -877,33 +1080,46 @@ function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=
function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false)
{
if (!defined('ADODB_TEST_DATES')) {
if ($mon === false) {
return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec);
}
// for windows, we don't check 1970 because with timezone differences,
// 1 Jan 1970 could generate negative timestamp, which is illegal
if (1971 < $year && $year < 2038
|| $mon === false
|| !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038)
)
return $is_gmt?
) {
return $is_gmt ?
@gmmktime($hr,$min,$sec,$mon,$day,$year):
@mktime($hr,$min,$sec,$mon,$day,$year);
}
}
$gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff();
/*
# disabled because some people place large values in $sec.
# however we need it for $mon because we use an array...
$hr = intval($hr);
$min = intval($min);
$sec = intval($sec);
*/
$mon = intval($mon);
$day = intval($day);
$year = intval($year);
$year = adodb_year_digit_check($year);
if ($mon > 12) {
$y = floor($mon / 12);
$year += $y;
$mon -= $y*12;
} else if ($mon < 1) {
$y = ceil((1-$mon) / 12);
$year -= $y;
$mon += $y*12;
}
$_day_power = 86400;
@ -964,4 +1180,108 @@ function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=fa
return $ret;
}
function adodb_gmstrftime($fmt, $ts=false)
{
return adodb_strftime($fmt,$ts,true);
}
// hack - convert to adodb_date
function adodb_strftime($fmt, $ts=false,$is_gmt=false)
{
global $ADODB_DATE_LOCALE;
if (!defined('ADODB_TEST_DATES')) {
if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer
return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
}
}
if (empty($ADODB_DATE_LOCALE)) {
$tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am
$sep = substr($tstr,2,1);
$hasAM = strrpos($tstr,'M') !== false;
$ADODB_DATE_LOCALE = array();
$ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y';
$ADODB_DATE_LOCALE[] = ($hasAM) ? 'h:i:s a' : 'H:i:s';
}
$inpct = false;
$fmtdate = '';
for ($i=0,$max = strlen($fmt); $i < $max; $i++) {
$ch = $fmt[$i];
if ($ch == '%') {
if ($inpct) {
$fmtdate .= '%';
$inpct = false;
} else
$inpct = true;
} else if ($inpct) {
$inpct = false;
switch($ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'E':
case 'O':
/* ignore format modifiers */
$inpct = true;
break;
case 'a': $fmtdate .= 'D'; break;
case 'A': $fmtdate .= 'l'; break;
case 'h':
case 'b': $fmtdate .= 'M'; break;
case 'B': $fmtdate .= 'F'; break;
case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break;
case 'C': $fmtdate .= '\C?'; break; // century
case 'd': $fmtdate .= 'd'; break;
case 'D': $fmtdate .= 'm/d/y'; break;
case 'e': $fmtdate .= 'j'; break;
case 'g': $fmtdate .= '\g?'; break; //?
case 'G': $fmtdate .= '\G?'; break; //?
case 'H': $fmtdate .= 'H'; break;
case 'I': $fmtdate .= 'h'; break;
case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd
case 'm': $fmtdate .= 'm'; break;
case 'M': $fmtdate .= 'i'; break;
case 'n': $fmtdate .= "\n"; break;
case 'p': $fmtdate .= 'a'; break;
case 'r': $fmtdate .= 'h:i:s a'; break;
case 'R': $fmtdate .= 'H:i:s'; break;
case 'S': $fmtdate .= 's'; break;
case 't': $fmtdate .= "\t"; break;
case 'T': $fmtdate .= 'H:i:s'; break;
case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-basde
case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based
case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break;
case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break;
case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-basde
case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based
case 'y': $fmtdate .= 'y'; break;
case 'Y': $fmtdate .= 'Y'; break;
case 'Z': $fmtdate .= 'T'; break;
}
} else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' ))
$fmtdate .= "\\".$ch;
else
$fmtdate .= $ch;
}
//echo "fmt=",$fmtdate,"<br>";
if ($ts === false) $ts = time();
$ret = adodb_date($fmtdate, $ts, $is_gmt);
return $ret;
}
?>

Binary file not shown.

View File

@ -921,9 +921,10 @@ class dbData extends dbObject {
// check that no required columns are missing
if( count( $fields ) < $table_field_count ) {
foreach( $table_fields as $field ) {
if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
continue(2);
}
if (isset( $field['OPTS'] ))
if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
continue(2);
}
}
}
@ -1917,7 +1918,7 @@ class adoSchema {
$schema .= ' <table name="' . $table . '">' . "\n";
// grab details from database
$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' );
$fields = $this->db->MetaColumns( $table );
$indexes = $this->db->MetaIndexes( $table );
@ -1983,7 +1984,7 @@ class adoSchema {
while( $row = $rs->FetchRow() ) {
foreach( $row as $key => $val ) {
$row[$key] = htmlentities($row);
$row[$key] = htmlentities($val);
}
$schema .= ' <row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -16,29 +16,29 @@ class ADODB2_db2 extends ADODB_DataDict {
var $databaseType = 'db2';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL': return 'CLOB';
case 'X': return 'VARCHAR(3600)';
case 'C2': return 'VARCHAR'; // up to 32K
case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'DECIMAL';
default:
@ -70,6 +70,73 @@ class ADODB2_db2 extends ADODB_DataDict {
return array();
}
function xChangeTableSQL($tablename, $flds, $tableoptions = false)
{
/**
Allow basic table changes to DB2 databases
DB2 will fatally reject changes to non character columns
*/
$validTypes = array("CHAR","VARC");
$invalidTypes = array("BIGI","BLOB","CLOB","DATE", "DECI","DOUB", "INTE", "REAL","SMAL", "TIME");
// check table exists
$cols = &$this->MetaColumns($tablename);
if ( empty($cols)) {
return $this->CreateTableSQL($tablename, $flds, $tableoptions);
}
// already exists, alter table instead
list($lines,$pkey) = $this->_GenFields($flds);
$alter = 'ALTER TABLE ' . $this->TableName($tablename);
$sql = array();
foreach ( $lines as $id => $v ) {
if ( isset($cols[$id]) && is_object($cols[$id]) ) {
/**
If the first field of $v is the fieldname, and
the second is the field type/size, we assume its an
attempt to modify the column size, so check that it is allowed
$v can have an indeterminate number of blanks between the
fields, so account for that too
*/
$vargs = explode(' ' , $v);
// assume that $vargs[0] is the field name.
$i=0;
// Find the next non-blank value;
for ($i=1;$i<sizeof($vargs);$i++)
if ($vargs[$i] != '')
break;
// if $vargs[$i] is one of the following, we are trying to change the
// size of the field, if not allowed, simply ignore the request.
if (in_array(substr($vargs[$i],0,4),$invalidTypes))
continue;
// insert the appropriate DB2 syntax
if (in_array(substr($vargs[$i],0,4),$validTypes)) {
array_splice($vargs,$i,0,array('SET','DATA','TYPE'));
}
// Now Look for the NOT NULL statement as this is not allowed in
// the ALTER table statement. If it is in there, remove it
if (in_array('NOT',$vargs) && in_array('NULL',$vargs)) {
for ($i=1;$i<sizeof($vargs);$i++)
if ($vargs[$i] == 'NOT')
break;
array_splice($vargs,$i,2,'');
}
$v = implode(' ',$vargs);
$sql[] = $alter . $this->alterCol . ' ' . $v;
} else {
$sql[] = $alter . $this->addCol . ' ' . $v;
}
}
return $sql;
}
}

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -10,9 +10,9 @@
*/
class ADODB2_firebird15 extends ADODB_DataDict {
class ADODB2_firebird extends ADODB_DataDict {
var $databaseType = 'firebird15';
var $databaseType = 'firebird';
var $seqField = false;
var $seqPrefix = 'gen_';
var $blobSize = 40000;
@ -21,7 +21,7 @@ class ADODB2_firebird15 extends ADODB_DataDict {
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'XL': return 'VARCHAR(32000)';
case 'X': return 'VARCHAR(4000)';
case 'C2': return 'VARCHAR'; // up to 32K

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -15,10 +15,14 @@ if (!defined('ADODB_DIR')) die();
class ADODB2_mssql extends ADODB_DataDict {
var $databaseType = 'mssql';
var $dropIndex = 'DROP INDEX %2$s.%1$s';
var $renameTable = "EXEC sp_rename '%s','%s'";
var $renameColumn = "EXEC sp_rename '%s.%s','%s'";
var $typeX = 'TEXT'; ## Alternatively, set it to VARCHAR(4000)
var $typeXL = 'TEXT';
//var $alterCol = ' ALTER COLUMN ';
function MetaType($t,$len=-1,$fieldobj=false)
{
@ -30,7 +34,7 @@ class ADODB2_mssql extends ADODB_DataDict {
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'R':
case 'INT':
case 'INTEGER': return 'I';
case 'BIT':
@ -47,10 +51,10 @@ class ADODB2_mssql extends ADODB_DataDict {
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'XL': return (isset($this)) ? $this->typeXL : 'TEXT';
case 'X': return (isset($this)) ? $this->typeX : 'TEXT'; ## could be varchar(8000), but we want compat with oracle
case 'C2': return 'NVARCHAR';
case 'X2': return 'NTEXT';
@ -60,6 +64,7 @@ class ADODB2_mssql extends ADODB_DataDict {
case 'T': return 'DATETIME';
case 'L': return 'BIT';
case 'R':
case 'I': return 'INT';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
@ -83,7 +88,7 @@ class ADODB2_mssql extends ADODB_DataDict {
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f);
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
@ -110,9 +115,9 @@ class ADODB2_mssql extends ADODB_DataDict {
$f = array();
$s = 'ALTER TABLE ' . $tabname;
foreach($flds as $v) {
$f[] = "\n$this->dropCol $v";
$f[] = "\n$this->dropCol ".$this->NameQuote($v);
}
$s .= implode(',',$f);
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
@ -241,12 +246,9 @@ CREATE TABLE
case 'BIGINT':
return $ftype;
}
if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
$ftype .= "(".$fsize;
if (strlen($fprec)) $ftype .= ",".$fprec;
$ftype .= ')';
}
return $ftype;
if ($ty == 'T') return $ftype;
return parent::_GetSize($ftype, $ty, $fsize, $fprec);
}
}
?>
?>

View File

@ -1,7 +1,7 @@
<?php
/**
V4.54 5 Nov 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -80,8 +80,8 @@ class ADODB2_mysql extends ADODB_DataDict {
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'LONGTEXT';
case 'XL':return 'LONGTEXT';
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'LONGTEXT';
@ -157,8 +157,6 @@ class ADODB2_mysql extends ADODB_DataDict {
if (isset($idxoptions['FULLTEXT'])) {
$unique = ' FULLTEXT';
// fulltext indexes are only allowed for MyISAM tables (changing MyISAM tables to MyISAM does no harm)
$sql[] = "ALTER TABLE $tabname TYPE=MyISAM";
} elseif (isset($idxoptions['UNIQUE'])) {
$unique = ' UNIQUE';
} else {

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -20,6 +20,9 @@ class ADODB2_oci8 extends ADODB_DataDict {
var $seqPrefix = 'SEQ_';
var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
var $trigPrefix = 'TRIG_';
var $alterCol = ' MODIFY ';
var $typeX = 'VARCHAR(4000)';
var $typeXL = 'CLOB';
function MetaType($t,$len=-1)
{
@ -69,8 +72,8 @@ class ADODB2_oci8 extends ADODB_DataDict {
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'X': return 'VARCHAR(4000)';
case 'XL': return 'CLOB';
case 'X': return $this->typeX;
case 'XL': return $this->typeXL;
case 'C2': return 'NVARCHAR';
case 'X2': return 'NVARCHAR(2000)';
@ -113,7 +116,7 @@ class ADODB2_oci8 extends ADODB_DataDict {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$s .= implode(', ',$f).')';
$sql[] = $s;
return $sql;
}
@ -126,7 +129,7 @@ class ADODB2_oci8 extends ADODB_DataDict {
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$s .= implode(', ',$f).')';
$sql[] = $s;
return $sql;
}
@ -134,9 +137,11 @@ class ADODB2_oci8 extends ADODB_DataDict {
function DropColumnSQL($tabname, $flds)
{
if (!is_array($flds)) $flds = explode(',',$flds);
foreach ($flds as $k => $v) $flds[$k] = $this->NameQuote($v);
$sql = array();
$s = "ALTER TABLE $tabname DROP(";
$s .= implode(',',$flds).') CASCADE COSTRAINTS';
$s .= implode(', ',$flds).') CASCADE CONSTRAINTS';
$sql[] = $s;
return $sql;
}

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -101,7 +101,7 @@ class ADODB2_postgres extends ADODB_DataDict {
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
@ -134,11 +134,10 @@ class ADODB2_postgres extends ADODB_DataDict {
if (($not_null = preg_match('/NOT NULL/i',$v))) {
$v = preg_replace('/NOT NULL/i','',$v);
}
if (preg_match('/^([^ ]+) .*DEFAULT ([^ ]+)/',$v,$matches)) {
if (preg_match('/^([^ ]+) .*(DEFAULT [^ ]+)/',$v,$matches)) {
list(,$colname,$default) = $matches;
$sql[] = $alter . str_replace('DEFAULT '.$default,'',$v);
$sql[] = 'UPDATE '.$tabname.' SET '.$colname.'='.$default;
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
$sql[] = $alter . str_replace($default,'',$v);
$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET ' . $default;
} else {
$sql[] = $alter . $v;
}
@ -183,11 +182,11 @@ class ADODB2_postgres extends ADODB_DataDict {
*/
function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
$has_drop_column = 7.3 <= (float) $this->serverInfo['version'];
$has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
if (!$has_drop_column && !$tableflds) {
if ($this->debug) ADOConnection::outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
return array();
}
return array();
}
if ($has_drop_column) {
return ADODB_DataDict::DropColumnSQL($tabname, $flds);
}
@ -215,7 +214,7 @@ class ADODB2_postgres extends ADODB_DataDict {
// 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,'S9999999999999D99')";
$copyflds[] = "to_number($fld->name,'S99D99')";
} else {
$copyflds[] = $fld->name;
}
@ -227,7 +226,7 @@ class ADODB2_postgres extends ADODB_DataDict {
}
}
}
$copyflds = implode(',',$copyflds);
$copyflds = implode(', ',$copyflds);
$tempname = $tabname.'_tmp';
$aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table
@ -261,7 +260,7 @@ class ADODB2_postgres extends ADODB_DataDict {
return $sql;
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
@ -357,4 +356,4 @@ CREATE [ UNIQUE ] INDEX index_name ON table
return $sql;
}
}
?>
?>

View File

@ -1,7 +1,7 @@
<?php
/**
V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.50 6 July 2004 (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.
@ -96,7 +96,7 @@ class ADODB2_sapdb extends ADODB_DataDict {
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(',',$lines) . ')' );
return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(', ',$lines) . ')' );
}
function AlterColumnSQL($tabname, $flds)
@ -104,7 +104,7 @@ class ADODB2_sapdb extends ADODB_DataDict {
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(',',$lines) . ')' );
return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' );
}
function DropColumnSQL($tabname, $flds)
@ -114,7 +114,7 @@ class ADODB2_sapdb extends ADODB_DataDict {
foreach($flds as $k => $v) {
$flds[$k] = $this->NameQuote($v);
}
return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(',',$flds) . ')' );
return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(', ',$flds) . ')' );
}
}

View File

@ -1,7 +1,7 @@
<?php
/**
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -81,7 +81,7 @@ class ADODB2_sybase extends ADODB_DataDict {
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f);
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
@ -100,14 +100,14 @@ class ADODB2_sybase extends ADODB_DataDict {
function DropColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$tabname = $this->TableName($tabname);
if (!is_array($flds)) $flds = explode(',',$flds);
$f = array();
$s = "ALTER TABLE $tabname";
foreach($flds as $v) {
$f[] = "\n$this->dropCol $v";
$f[] = "\n$this->dropCol ".$this->NameQuote($v);
}
$s .= implode(',',$f);
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}

File diff suppressed because it is too large Load Diff

View File

@ -20,22 +20,13 @@
</head>
<body style="background-color: rgb(255, 255, 255);">
<h2>ADOdb Data Dictionary Library for PHP</h2>
<p>V4.50 6 July 2004 (c) 2000-2004 John Lim (<a
<p>V4.65 22 July 2005 (c) 2000-2005 John Lim (<a
href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>).<br>
AXMLS (c) 2004 ars Cognita, Inc</p>
<p><font size="1">This software is dual licensed using BSD-Style and
LGPL. This means you can use it in compiled proprietary and commercial
products.</font></p>
<table border="1">
<tbody>
<tr>
<td><font color="red">Kindly note that the ADOdb home page has
moved to <a href="http://adodb.sourceforge.net/">http://adodb.sourceforge.net/</a>
because of the persistent unreliability of http://php.weblogs.com. <b>Please
change your links</b>!</font></td>
</tr>
</tbody>
</table>
<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>
@ -57,7 +48,14 @@ generic ODBC.
color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.<br> # Field types use 1 character codes, and fields are separated by commas.<br> # The following example creates three fields: "col1", "col2" and "col3":</font><br> $flds = " <br> <font
color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',<br> col2 I DEFAULT 0,<br> col3 N(12.2)</strong></font><br> ";<br><br> <font
color="#006600"># We demonstrate creating tables and indexes</font><br> $sqlarray = $dict-&gt;<strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);<br> $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br><br> $idxflds = 'co11, col2';<br> $sqlarray = $dict-&gt;<strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);<br> $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br></pre>
<h3>Functions</h3>
<h3>Class Factory</h3>
<h4>NewDataDictionary($connection, $drivername=false)</h4>
<p>Creates a new data dictionary object. You pass a database connection object in $connection. The $connection does not have to be actually connected to the database. Some database connection objects are generic (eg. odbtp and odbc). Since 4.53, you can tell ADOdb the actual database with $drivername. E.g.</p>
<pre>
$db =& NewADOConnection('odbtp');
$datadict = NewDataDictionary($db, 'mssql'); # force mssql
</pre>
<h3>Class Functions</h3>
<h4>function CreateDatabase($dbname, $optionsarray=false)</h4>
<p>Create a database with the name $dbname;</p>
<h4>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</h4>
@ -76,7 +74,7 @@ field. Each row has this format:</p>
field type can be a portable type codes or the actual type for that
database.</p>
<p>Legal portable type codes include:</p>
<pre> C: varchar<br> X: Largest varchar size <br> XL: For Oracle, returns CLOB, otherwise same as 'X' above<br><br> C2: Multibyte varchar<br> X2: Multibyte varchar (largest size)<br><br> B: BLOB (binary large object)<br><br> D: Date (some databases do not support this, and we return a datetime type)<br> T: Datetime or Timestamp<br> L: Integer field suitable for storing booleans (0 or 1)<br> I: Integer (mapped to I4)<br> I1: 1-byte integer<br> I2: 2-byte integer<br> I4: 4-byte integer<br> I8: 8-byte integer<br> F: Floating point number<br> N: Numeric or decimal number<br></pre>
<pre> C: Varchar, capped to 255 characters.<br> X: Larger varchar, capped to 4000 characters (to be compatible with Oracle). <br> XL: For Oracle, returns CLOB, otherwise the largest varchar size.<br><br> C2: Multibyte varchar<br> X2: Multibyte varchar (largest size)<br><br> B: BLOB (binary large object)<br><br> D: Date (some databases do not support this, and we return a datetime type)<br> T: Datetime or Timestamp<br> L: Integer field suitable for storing booleans (0 or 1)<br> I: Integer (mapped to I4)<br> I1: 1-byte integer<br> I2: 2-byte integer<br> I4: 4-byte integer<br> I8: 8-byte integer<br> F: Floating point number<br> N: Numeric or decimal number<br></pre>
<p>The $colsize field represents the size of the field. If a decimal
number is used, then it is assumed that the number following the dot is
the precision, so 6.2 means a number of size 6 digits and 2 decimal
@ -104,7 +102,7 @@ Indicates that the previous table definition should be removed
Drop table. Useful for removing unused tables. </li>
<li><b>CONSTRAINTS</b><br>
Define this as the key, with the constraint as the value. See the
postgresql example below. Additional constraints defined for the whole
postgresql <a href="#foreignkey">example</a> below. Additional constraints defined for the whole
table. You will probably need to prefix this with a comma. </li>
</ul>
<p>Database specific table options can be defined also using the name
@ -113,7 +111,7 @@ the table as ISAM with MySQL, and store the table in the "users"
tablespace if using Oracle</em>. And because we specified REPLACE, drop
the table first.</p>
<pre> $taboptarray = array('mysql' =&gt; 'TYPE=ISAM', 'oci8' =&gt; 'tablespace users', 'REPLACE');</pre>
<p>You can also define foreignkey constraints. The following is syntax
<p><a name=foreignkey></a>You can also define foreign key constraints. The following is syntax
for postgresql:
</p>
<pre> $taboptarray = array('constraints' =&gt; ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');</pre>
@ -127,6 +125,10 @@ $column if field does not exist.</p>
<p>The class must be connected to the database for ChangeTableSQL to
detect the existence of the table. Idea and code contributed by Florian
Buzin.</p>
<h4>function RenameTableSQL($tabname,$newname)</h4>
<p>Rename a table. Returns the an array of strings, which is the SQL required to rename a table. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
<h4> function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')</h4>
<p>Rename a table field. Returns the an array of strings, which is the SQL required to rename a column. The optional $flds is a complete column-defintion-string like for AddColumnSQL, only used by mysql at the moment. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
<h4>function CreateIndexSQL($idxname, $tabname, $flds,
$idxoptarray=false)</h4>
<pre> RETURNS: an array of strings, the sql to be executed, or false<br> $idxname: name of index<br> $tabname: name of table<br> $flds: list of fields as a comma delimited string or an array of strings<br> $idxoptarray: array of index creation options<br></pre>

View File

@ -0,0 +1,542 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<style>
pre {
background-color: #eee;
padding: 0.75em 1.5em;
font-size: 12px;
border: 1px solid #ddd;
}
.greybg {
background-color: #eee;
padding: 0.75em 1.5em;
font-size: 12px;
border: 1px solid #ddd;
}
.style1 {color: #660000}
</style>
<title>ADOdb with PHP and Oracle</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</style>
</head>
<body>
<table width=100%><tr><td>
<h2>Using ADOdb with PHP and Oracle: an advanced tutorial</h2>
</td><td><div align="right"><img src=cute_icons_for_site/adodb.gif width="88" height="31"></div></tr></table>
<p><font size="1">(c)2004-2005 John Lim. All rights reserved.</font></p>
<h3>1. Introduction</h3>
<p>Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:</p>
<ul>
<li>The oracle extension</li>
<li>The oci8 extension</li>
<li>PEAR DB library</li>
<li>ADOdb library</li>
</ul>
<p>The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and show you the advantages of using <a href="http://adodb.sourceforge.net/">ADOdb</a>. </p>
<p>First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a <a href=http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html>guide to installing Oracle and PHP on Linux</a>.</p>
<table width="75%" border="1" align="center">
<tr valign="top">
<td nowrap><b>Oracle extension</b></td>
<td>Designed for Oracle 7 or earlier. This is obsolete.</td>
</tr>
<tr valign="top">
<td nowrap><b>Oci8 extension</b></td>
<td> Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).</td>
</tr>
</table>
<p>Here is an example of using the oci8 extension to query the <i>emp</i> table of the <i>scott</i> schema with bind parameters:
<pre>
$conn = OCILogon("scott","tiger", $tnsName);
$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno");
$emp = 7900;
OCIBindByName($stmt, ':emp', $emp);
$ok = OCIExecute($stmt);
while (OCIFetchInto($stmt,$arr)) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>This generates the following output:
<div class=greybg>
Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 )
<hr>
Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 )
</div>
<p>We also have many higher level PHP libraries that allow you to simplify the above code. The most popular are <a href="http://pear.php.net/">PEAR DB</a> and <a href="http://adodb.sourceforge.net/">ADOdb</a>. Here are some of the differences between these libraries:</p>
<table width="75%" border="1" align="center">
<tr>
<td><b>Feature</b></td>
<td><b>PEAR DB 1.6</b></td>
<td><b>ADOdb 4.52</b></td>
</tr>
<tr valign="top">
<td>General Style</td>
<td>Simple, easy to use. Lacks Oracle specific functionality.</td>
<td>Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.</td>
</tr>
<tr valign="top">
<td>Support for Prepare</td>
<td>Yes, but only on one statement, as the last prepare overwrites previous prepares.</td>
<td>Yes (multiple simultaneous prepare's allowed)</td>
</tr>
<tr valign="top">
<td>Support for LOBs</td>
<td>No</td>
<td>Yes, using update semantics</td>
</tr>
<tr valign="top">
<td>Support for REF Cursors</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Support for IN Parameters</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Support for OUT Parameters</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Schema creation using XML</td>
<td>No</td>
<td>Yes, including ability to define tablespaces and constraints</td>
</tr>
<tr valign="top">
<td>Provides database portability features</td>
<td>No</td>
<td>Yes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.</td>
</tr>
<tr valign="top">
<td>Performance monitoring and tracing</td>
<td>No</td>
<td>Yes. SQL can be traced and linked to web page it was executed on. Explain plan support included.</td>
</tr>
<tr valign="top">
<td>Recordset caching for frequently used queries</td>
<td>No</td>
<td>Yes. Provides great speedups for SQL involving complex <i>where, group-by </i>and <i>order-by</i> clauses.</td>
</tr>
<tr valign="top">
<td>Popularity</td>
<td>Yes, part of PEAR release</td>
<td>Yes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.</td>
</tr>
<tr valign="top">
<td>Speed</td>
<td>Medium speed.</td>
<td>Very high speed. Fastest database abstraction library available for PHP. <a href="http://phplens.com/lens/adodb/">Benchmarks are available</a>.</td>
</tr>
<tr valign="top">
<td>High Speed Extension available</td>
<td>No</td>
<td>Yes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.</td>
</tr>
</table>
<p> PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about <a href="#connecting">connecting to Oracle</a> later in this guide.</p>
<h4>ADOdb Example</h4>
<p>In ADOdb, the above oci8 example querying the <i>emp</i> table could be written as:</p>
<pre>
include "/path/to/adodb.inc.php";
$db = NewADOConnection("oci8");
$db->Connect($tnsName, "scott", "tiger");
$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset-&gt;FetchRow( ). </p>
<p>If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:</p>
<table width="100%" border="1">
<tr valign="top" bgcolor="#FFFFFF">
<td width="50%" bgcolor="#e0e0e0"><b>Oci8</b></td>
<td bgcolor="#e0e0e0"><b>ADOdb</b></td>
</tr>
<tr valign="top" bgcolor="#CCCCCC">
<td><pre><font size="1">$stmt = <b>OCIParse</b>($conn,
"select * from emp where empno > :emp");
$emp = 7900;
<b>OCIBindByName</b>($stmt, ':emp', $emp);
$ok = <b>OCIExecute</b>($stmt);
while (<b>OCIFetchInto</b>($stmt,$arr)) {
print_r($arr);
echo "&lt;hr>";
} </font></pre></td>
<td><pre><font size="1">$recordset = $db-><b>Execute</b>("select * from emp where empno>:emp",
array('emp' => 7900));
while ($arr = $recordset-><b>FetchRow</b>()) {
print_r($arr);
echo "&lt;hr>";
}</font></pre></td>
</tr>
</table>
<p>&nbsp;</p>
<h3>2. ADOdb Query Semantics</h3>
<p>You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the <i>fields</i> property of the recordset object, $rs.
MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:
<pre>
$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}
</pre>
<p>And if you are interested in having the data returned in a 2-dimensional array, you can use:
<pre>
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
</pre>
<p>Now to obtain only the first row as an array:
<pre>
$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));
</pre>
<p>Or to retrieve only the first field of the first row:
<pre>
$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));
</pre>
<p>For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 200:
<pre>
$offset = 200; $limitrows = 100;
$rs = $db->SelectLimit('select * from table', $offset, $limitrows);
</pre>
<p>The $limitrows parameter is optional.
<h4>Array Fetch Mode</h4>
<p>When data is being returned in an array, you can choose the type of array the data is returned in.
<ol>
<li> Numeric indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_NUM).</font></li>
<li>Associative indexes - the keys of the array are the names of the fields (in upper-case). Use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_ASSOC)</font><font face="Courier New, Courier, mono">.</font></li>
<li>Both numeric and associative indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_BOTH).</font></li>
</ol>
<p>The default is ADODB_FETCH_BOTH for Oracle.</p>
<h4><b>Caching</b></h4>
<p>You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.</p>
<p>This example will cache the following select statement for 3600 seconds (1 hour):</p>
<pre>
$ADODB_CACHE_DIR = '/var/adodb/tmp';
$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");
</pre>
There are analogous CacheGetArray(
), CacheGetRow( ), CacheGetOne( ) and CacheSelectLimit( ) functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above).
<p>There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs
property of the connection object:
<pre>
$ADODB_CACHE_DIR = '/var/adodb/tmp';
$connection->cacheSecs = 3600;
$rs = $connection->CacheExecute($sql, array('id' => 1));
</pre>
<h3>&nbsp;</h3>
<h3>3. Using Prepare( ) For Frequently Used Statements</h3>
<p>Prepare( ) is for compiling frequently used SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:</p>
<pre>
$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
foreach ($arrayToInsert as $key => $value) {
$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
}
</pre>
<p>&nbsp;</p>
<h3>4. Working With LOBs</h3>
<p>Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory. </p>
<p>ADOdb will transparently handle LOBs in <i>select</i> statements. The LOBs are automatically converted to PHP variables without any special coding.</p>
<p>For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory:
<pre>
$ok = $db->Execute("insert into aTable (id, name, ablob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db-&gt;ErrorMsg());
<font color="#006600"># params: $tableName, $blobFieldName, $blobValue, $whereClause</font>
$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');
</pre>
<p>and the analogous CLOB example:
<pre>
$ok = $db->Execute("insert into aTable (id, name, aclob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db-&gt;ErrorMsg());
$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');
</pre>
<p>Note that LogError( ) is a user-defined function, and not part of ADOdb.
<p>Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this
(assuming that the <em>photo</em> field is a BLOB, and we want to store $blob_data into
this field, and the primary key is the <em>id</em> field):
<pre>
$sql = <span class="style1">"INSERT INTO photos ( ID, photo) ".
"VALUES ( :id, empty_blob() )".
" RETURNING photo INTO :xx"</span>;
$stmt = $db->PrepareSP($sql);
$db->InParameter($stmt, $<strong>id</strong>, <span class="style1">'id'</span>);
$blob = $db->InParameter($stmt, $<strong>blob_data</strong>, <span class="style1">'xx'</span>,-1, OCI_B_BLOB);
$db->StartTrans();
$ok = $db->Execute($stmt);
$db->CompleteTrans();
</pre>
<p>
<h3>5. REF CURSORs</h3>
<p>Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function <i>open_tab</i> that returns a REF CURSOR in the first parameter:</p>
<pre>
TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
BEGIN
OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
END open_tab;
</pre>
<p>In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find
all table names that begin with 'A' in the current schema:
<pre>
$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
while ($arr = $rs->FetchRow()) print_r($arr);
</pre>
<p>The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor.
</p>
<p>&nbsp;</p>
<h3>6. In and Out Parameters</h3>
<p>The following PL/SQL
stored procedure requires an input variable, and returns a result into an output variable:
<pre>
PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
BEGIN
output := 'I love '||input;
END;
</pre>
<p>The following ADOdb code allows you to call the stored procedure:</p>
<pre>
$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
$input = 'Sophia Loren';
$db->InParameter($stmt,$input,'a1');
$db->OutParameter($stmt,$output,'a2');
$ok = $db->Execute($stmt);
if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';
</pre>
<p>PrepareSP( ) is a special function that knows about bind parameters.
The main limitation currently is that IN OUT parameters do not work.
<h4>Bind Parameters and REF CURSORs</h4>
<p>We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later):
<pre>
$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
$input = 'A%';
$db->InParameter($stmt,$input,'tabname');
$rs = $db->ExecuteCursor($stmt,'refc');
while ($arr = $rs->FetchRow()) print_r($arr);
</pre>
<h4>Bind Parameters and LOBs</h4>
<p>You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs.
<pre>
$text = 'test test test';
$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
$stmt = $conn -> PrepareSP($sql);
$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
$rs = '';
$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
$conn -> Execute($stmt);
echo "return = ".$rs."&lt;br>";
</pre>
<p>Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs.
<h4>Reusing Bind Parameters with CURSOR_SHARING=FORCE</h4>
<p>Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:</p>
<pre>
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
</pre>
<p>They prefer entering the values inside the SQL:
<pre>
$arr = $db->GetArray("select * from emp where empno>7900");
</pre>
<p>This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL
is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login:
<pre>
ALTER SESSION SET CURSOR_SHARING=FORCE
</pre>
<p>This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.</p>
<p>More <a href="http://phplens.com/adodb/code.initialization.html#speed">speedup tips</a>.</p>
<p>&nbsp;</p>
<h3>7. Dates and Datetime in ADOdb</h3>
<p>There are two things you need to know about dates in ADOdb. </p>
<p>First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).</p>
<p>Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:</p>
<pre>
$db = NewADOConnection('oci8');
$db->NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS';
$db->Connect($tns, $user, $pwd);
</pre>
<p>Or execute:</p>
<pre>$sql = &quot;ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'&quot;;
$db-&gt;Execute($sql);
</pre>
<p>If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead.
<p>
<h3>8. Database Portability Layer</h3>
<p>ADOdb provides the following functions for portably generating SQL functions
as strings to be merged into your SQL statements:</p>
<table width="75%" border="1" align=center>
<tr>
<td width=30%><b>Function</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>DBDate($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a date
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>DBTimeStamp($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>SQLDate($date, $fmt)</td>
<td>Portably generate a date formatted using $fmt mask, for use in SELECT
statements.</td>
</tr>
<tr>
<td>OffsetDate($date, $ndays)</td>
<td>Portably generate a $date offset by $ndays.</td>
</tr>
<tr>
<td>Concat($s1, $s2, ...)</td>
<td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver,
which allows || operator.</td>
</tr>
<tr>
<td>IfNull($fld, $replaceNull)</td>
<td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
</tr>
<tr>
<td>Param($name)</td>
<td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
</tr>
<tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
</tr>
<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
timestamp (date+time).
</td>
</tr>
<tr>
<td>$db->concat_operator</td><td>Property that holds the concatenation operator
</td>
</tr>
<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
</td></tr>
<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
</td></tr>
<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
</td>
</tr>
<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
</td></tr>
</table>
<p>ADOdb also provides multiple oracle oci8 drivers for different scenarios:</p>
<table width="75%" border="1" align="center">
<tr>
<td nowrap><b>Driver Name</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>oci805 </td>
<td>Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).</td>
</tr>
<tr>
<td>oci8</td>
<td>The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.</td>
</tr>
<tr>
<td>oci8po</td>
<td> The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :<i>bindvar</i> for binding variables, which is the standard for other databases. Also the keys of associative arrays are in lower-case like other databases.</td>
</tr>
</table>
<p>Here's an example of calling the <i>oci8po</i> driver. Note that the bind variables use question-mark:</p>
<pre>$db = NewADOConnection('oci8po');
$db-&gt;Connect($tns, $user, $pwd);
$db-&gt;Execute(&quot;insert into atable (f1, f2) values (?,?)&quot;, array(12, 'abc'));</pre>
<p>&nbsp;<a name=connecting></a>
<h3>9. Connecting to Oracle</h3>
<p>Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at <a href="http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html">oracle.com</a>. </p>
<h4>Should You Use Persistent Connections</h4>
<p>One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called <a href="http://www.cise.ufl.edu/help/database/oracle-docs/server.920/a96521/manproc.htm#13132">Shared Server</a> (also known as MTS).</p>
<p>The author's benchmarks suggest that using non-persistent connections and the Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.</p>
<h4>Connection Examples</h4>
<p>Just in case you are having problems connecting to Oracle, here are some examples:</p>
<p>a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:</p>
<pre> $conn = NewADOConnection('oci8');
$conn-&gt;Connect(false, 'scott', 'tiger');</pre>
<p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:</p>
<pre> $conn = NewADOConnection('oci8');
$conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');</pre>
<p>or</p>
<pre> $conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
<p>c. Host Address and SID</p>
<pre>
$conn->connectSID = true;
$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
<p>d. Host Address and Service Name</p>
<pre> $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
<p>e. Oracle connection string:
<pre> $cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
(CONNECT_DATA=(SID=$sid)))";
$conn-&gt;Connect($cstr, 'scott', 'tiger');
</pre>
<p>f. ADOdb data source names (dsn):
<pre>
$dsn = 'oci8://user:pwd@tnsname/?persist'; # persist is optional
$conn = ADONewConnection($dsn); # no need for Connect/PConnect
$dsn = 'oci8://user:pwd@host/sid';
$conn = ADONewConnection($dsn);
$dsn = 'oci8://user:pwd@/'; # oracle on local machine
$conn = ADONewConnection($dsn);</pre>
<p>With ADOdb data source names,
you don't have to call Connect( ) or PConnect( ).
</p>
<p>&nbsp;</p>
<h3>10. Error Checking</h3>
<p>The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is:
<pre>function InvokeErrorHandler()
{<br>global $db; ## assume global
MyLogFunction($db-&gt;ErrorNo(), $db-&gt;ErrorMsg());
}
if (!$db-&gt;Connect($tns, $usr, $pwd)) InvokeErrorHandler();
$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
if (!$rs) return InvokeErrorHandler();
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>You can retrieve the error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also <a href=http://phplens.com/adodb/using.custom.error.handlers.and.pear_error.html>define a custom error handler function</a>.
ADOdb also supports throwing exceptions in PHP5.
<p>&nbsp;</p>
<h3>Handling Large Recordsets (added 27 May 2005)</h3>
The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount()
is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default.
We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets.
Set $ADODB_COUNTRECS to false for the best performance.
<p>
This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.
<p>&nbsp;</p>
<h3>11. Other ADOdb Features</h3>
<p><a href="http://phplens.com/lens/adodb/docs-datadict.htm">Schema generation</a>. This allows you to define a schema using XML and import it into different RDBMS systems portably.</p>
<p><a href="http://phplens.com/lens/adodb/docs-perf.htm">Performance monitoring and tracing</a>. Highlights of performance monitoring include identification of poor and suspicious SQL, with explain plan support, and identifying which web pages the SQL ran on.</p>
<p>&nbsp;</p>
<h3>12. Download</h3>
<p>You can <a href="http://adodb.sourceforge.net/#download">download ADOdb from sourceforge</a>. ADOdb uses a BSD style license. That means that it is free for commercial use, and redistribution without source code is allowed.</p>
<p>&nbsp;</p>
<h3>13. Resources</h3>
<ul>
<li>Oracle's <a href="http://www.oracle.com/technology/pub/articles/php_experts/index.html">Hitchhiker Guide to PHP</a></li>
<li>OTN article on <a href=http://www.oracle.com/technology/pub/articles/deployphp/lim_deployphp.html>Optimizing PHP and Oracle</a> by this author.
<li>Oracle has an excellent <a href="http://www.oracle.com/technology/tech/opensource/php/php_troubleshooting_faq.html">FAQ on PHP</a></li>
<li>PHP <a href="http://php.net/oci8">oci8</a> manual pages</li>
<li><a href=http://phplens.com/lens/lensforum/topics.php?id=4>ADOdb forums</a>.
</ul>
</body>
</html>

View File

@ -18,20 +18,10 @@ font-size: 8pt;
</head>
<body>
<h3>The ADOdb Performance Monitoring Library</h3>
<p>V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)</p>
<p>V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my)</p>
<p><font size="1">This software is dual licensed using BSD-Style and
LGPL. This means you can use it in compiled proprietary and commercial
products.</font></p>
<table border="1">
<tbody>
<tr>
<td><font color="red">Kindly note that the ADOdb home page has
moved to <a href="http://adodb.sourceforge.net/">http://adodb.sourceforge.net/</a>
because of the persistent unreliability of http://php.weblogs.com. <b>Please
change your links</b>!</font></td>
</tr>
</tbody>
</table>
<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>

View File

@ -21,24 +21,11 @@ font-size: 8pt;
<body style="background-color: rgb(255, 255, 255);">
<h3>ADODB Session Management Manual</h3>
<p>
V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my)
</p>
<p> <font size="1">This software is dual licensed using BSD-Style and
LGPL. This means you can use it in compiled proprietary and commercial
products. </font>
<table border="1">
<tbody>
<tr>
<td><font color="red">Kindly note that the ADOdb home page has
moved to <a href="http://adodb.sourceforge.net/">http://adodb.sourceforge.net/</a>
because of the persistent unreliability of http://php.weblogs.com. <b>Please
change your links</b>!</font></td>
</tr>
<tr>
</tr>
</tbody>
</table>
</p>
<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>
@ -61,9 +48,12 @@ However if you have special needs such as you:
<li>Need to do special processing of each session</li>
<li>Require notification when a session expires</li>
</ul>
<p>Then the ADOdb session handler provides you with the above
<p>The ADOdb session handler provides you with the above
additional capabilities by storing the session information as records
in a database table that can be shared across multiple servers. </p>
<p>These records will be garbage collected based on the php.ini [session] timeout settings.
You can register a notification function to notify you when the record has expired and
is about to be freed by the garbage collector.</p>
<p><b>Important Upgrade Notice:</b> Since ADOdb 4.05, the session files
have been moved to its own folder, adodb/session. This is a rewrite
of the session code by Ross Smith. The old session code is in
@ -92,11 +82,40 @@ including adodb-cryptsession.inc.php instead of adodb-session.inc.php. </li>
<p><pre>
<font
color="#004040"> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';</b><br> <br> <b>include('adodb/session/adodb-session.php');</b><br> session_start();<br> <br> #<br> # Test session vars, the following should increment on refresh<br> #<br> $_SESSION['AVAR'] += 1;<br> print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";<br></font></pre>
<p>To force non-persistent connections, call adodb_session_open first before session_start():<p>
<p>To force non-persistent connections, call adodb_session_open() first before session_start():
<p>
<pre>
<font color="#004040"><br> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';</b><br> <br> <b>include('adodb/session/adodb-session.php');<br> adodb_sess_open(false,false,false);</b><br> session_start();<br> </font>
</pre>
<p> To use a encrypted sessions, simply replace the file adodb-session.php:</p>
<p> The 3rd parameter to adodb_sess_open($path, $sessname, $connectMode) sets the connection method. You can pass in the following:</p>
<table width="50%" border="1">
<tr>
<td><b>$connectMode</b></td>
<td><b>Connection Method</b></td>
</tr>
<tr>
<td>true</td>
<td><p>PConnect( )</p></td>
</tr>
<tr>
<td>false</td>
<td>Connect( )</td>
</tr>
<tr>
<td>'N'</td>
<td>NConnect( )</td>
</tr>
<tr>
<td>'P'</td>
<td>PConnect( )</td>
</tr>
<tr>
<td>'C'</td>
<td>Connect( )</td>
</tr>
</table>
<p>To use a encrypted sessions, simply replace the file adodb-session.php:</p>
<pre> <font
color="#004040"><br> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';<br> <br> include('adodb/session/adodb-cryptsession.php');</b><br> session_start();</font><br>
</pre>
@ -120,22 +139,35 @@ including adodb-cryptsession.inc.php instead of adodb-session.inc.php. </li>
</pre><p>
When the session is created, $<b>ADODB_SESS_CONN</b> holds the connection object.<br> <br> 3. Recommended is PHP 4.0.6 or later. There are documented session bugs in earlier versions of PHP.
<h3>Notifications</h3>
<p>If you want to receive notification when a session expires, then tag
the session record with a <a href="#sessiontab">EXPIREREF</a> tag (see
the definition of the sessions table above). Before any session record
is deleted, ADOdb will call a notification function, passing in the
EXPIREREF.
</p>
<p>When a session is first created, we check a global variable
$ADODB_SESSION_EXPIRE_NOTIFY. This is an array with 2 elements, the
<p>You can receive notification when your session is cleaned up by the session garbage collector or
when you call session_destroy().
<p>PHP's session extension will automatically run a special garbage collection function based on
your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
adodb's garbage collection function, which can be setup to do notification.
<p>
<pre>
PHP Session --> ADOdb Session --> Find all recs --> Send --> Delete queued
GC Function GC Function to be deleted notification records
executed at called by for all recs
random time Session Extension queued for deletion
</pre>
<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically
the userid of the session. Later when the session has expired, just before the record is deleted,
we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which
is the userid of the person being logged off.
<p>ADOdb use a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
start to store the notification configuratioin.
$ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the
first being the name of the session variable you would like to store in
the EXPIREREF field, and the 2nd is the notification function's name. </p>
<p> Suppose we want to be notified when a user's session has expired,
based on the userid. The user id in the global session variable
$USERID. The function name is 'NotifyFn'. So we define: </p>
<p>For example, suppose we want to be notified when a user's session has expired,
based on the userid. When the user logs in, we store the id in the global session variable
$USERID. The function name is 'NotifyFn'.
<p>
So we define (before session_start() is called): </p>
<pre> <font color="#004040"><br> $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');<br> </font></pre>
And when the NotifyFn is called (when the session expires), we pass the
$USERID as the first parameter, eg. NotifyFn($userid, $sesskey). The
And when the NotifyFn is called (when the session expires), the
$USERID is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The
session key (which is the primary key of the record in the sessions
table) is the 2nd parameter.
<p> Here is an example of a Notification function that deletes some
@ -173,6 +205,28 @@ compression schemes are supported. Currently, supported are:
<p>These are stackable. E.g.
<p><pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
will compress and then encrypt the record in the database.
<h3>adodb_session_regenerate_id()</h3>
<p>Dynamically change the current session id with a newly generated one and update database. Currently only
works with cookies. Useful to improve security by reducing the risk of session-hijacking.
See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session Fixation</a> for more info
on the theory behind this feature. Usage:
<pre>
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='abc';
$ADODB_SESSION_DB ='phplens';
include('path/to/adodb/session/adodb-session.php');
session_start();
# Every 10 page loads, reset cookie for safety.
# This is extremely simplistic example, better
# to regenerate only when the user logs in or changes
# user privilege levels.
if ((rand()%10) == 0) adodb_session_regenerate_id(); </pre>
<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
<h2>More Info</h2>
<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>.
</p>
</body>

View File

@ -1,4 +1,126 @@
<html><title>Old Changelog: ADOdb</title><body>
<h3>Old Changelog</h3>
</p><p><b>3.92 22 Sept 2003</b>
</p><p>Added GetAssoc and CacheGetAssoc to connection object.
</p><p>Removed TextMax and CharMax functions from adodb.inc.php.
</p><p>HasFailedTrans() returned false when trans failed. Fixed.
</p><p>Moved perf driver classes into adodb/perf/*.php.
</p><p>Misc improvements to performance monitoring, including UI().
</p><p>RETVAL in mssql Parameter(), we do not append @ now.
</p><p>Added Param($name) to connection class, returns '?' or ":$name", for defining
bind parameters portably.
</p><p>LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8
_stmt and _affectedrows() bugs.
</p><p>Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT
stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also
added new $conn-&gt;datetime field to oci8, controls whether MetaType() returns
'D' ($this-&gt;datetime==false) or 'T' ($this-&gt;datetime == true) for DATE type.
</p><p>Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php.
</p><p>Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL().
</p><p>Tuned include_once handling to reduce file-system checking overhead.
</p><p><b>3.91 9 Sept 2003</b>
</p><p>Only released to InterAkt
</p><p>Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory
for driver instantiation.
</p><p>Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com
</p><p>Added portable substr support.
</p><p>Now rs2html() has new parameter, $echo. Set to false to return $html instead
of echoing it.
</p><p><b>3.90 5 Sept 2003</b>
</p><p>First beta of performance monitoring released.
</p><p>MySQL supports MetaTable() masking.
</p><p>Fixed key_exists() bug in adodb-lib.inc.php
</p><p>Added sp_executesql Prepare() support to mssql.
</p><p>Added bind support to db2.
</p><p>Added swedish language file - Christian Tiberg" christian#commsoft.nu
</p><p>Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich.
</p><p>Left join setting for oci8 was wrong. Thx to johnwilk#juno.com
</p><p><b>3.80 27 Aug 2003</b>
</p><p>Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility.
</p><p>Added matching mask for MetaTables. Only for oci8, mssql and postgres currently.
</p><p>Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano.
</p><p>Added better debugging for Smart Transactions.
</p><p>Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP.
</p><p>ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define
it after including adodb.inc.php.
</p><p>Added portugese (brazilian) to languages. Thx to "Levi Fukumori".
</p><p>Removed arg3 parameter from Execute/SelectLimit/Cache* functions.
</p><p>Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute()
to note change in sql query counting with 2-d arrays.
</p><p>Added MONEY to MetaType in PostgreSQL.
</p><p>Added more debugging output to CacheFlush().
</p><p><b>3.72 9 Aug 2003</b>
</p><p>Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes
and does the right thing...
</p><p>Fixed CacheFlush() bug - Thx to martin#gmx.de
</p><p>Walt Boring contributed MetaForeignKeys for postgres7.
</p><p>_fetch() called _BlobDecode() wrongly in interbase. Fixed.
</p><p>adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980
</p><p><b>3.71 4 Aug 2003</b>
</p><p>The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner
== false.
</p><p>Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru.
</p><p>Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com.
</p><p>Error handling in oci8 bugfix - if there was an error in Execute(), then when
calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but
the 2nd call would return no error.
</p><p>Error handling in odbc bugfix. ODBC would always return the last error, even
if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to
0 everytime before CacheExecute() and Execute().
</p><p><b>3.70 29 July 2003</b>
</p><p>Added new SQLite driver. Tested on PHP 4.3 and PHP 5.
</p><p>Added limited "sapdb" driver support - mainly date support.
</p><p>The oci8 driver did not identify NUMBER with no defined precision correctly.
</p><p>Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls
in GetInsertSQL/GetUpdateSQL.
</p><p>DBDate() and DBTimeStamp() format for postgresql had problems. Fixed.
</p><p>Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit.
</p><p>Added charset support to postgresql. Thx to Julian Tarkhanov.
</p><p>Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS)
</p><p>Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn.
</p><p>adodb-cryptsession.php includes wrong. Fixed.
</p><p>Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8.
</p><p>Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring.
</p><p>adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking
in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn.
</p><p>Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring.
</p><p>Upgraded to adodb-xmlschema.inc.php 0.0.2.
</p><p>NConnect for mysql now returns value. Thx to Dennis Verspuij.
</p><p>ADODB_FETCH_BOTH support added to interbase/firebird.
</p><p>Czech language file contributed by Kamil Jakubovic jake#host.sk.
</p><p>PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec.
</p><p>Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it
</p><p>ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed.
</p><p><b>3.60 16 June 2003</b>
</p><p>We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with
mssql driver.
</p><p>The property $emptyDate missing from connection class. Also changed 1903 to
constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn.
</p><p>ADOdb speedup optimization - we now return all arrays by reference.
</p><p>Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter.
Suggested by vincent.
</p><p>Added GetArray() to connection class.
</p><p>Added not_null check in informix metacolumns().
</p><p>Connection parameters for postgresql did not work correctly when port was defined.
</p><p>DB2 is now a tested driver, making adodb 100% compatible. Extensive changes
to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching
to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit()
fixes.
</p><p>The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed.
</p><p>Some bugs in adodb_backtrace() fixed.
</p><p>Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql
properly.
</p><p>MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions
to odbc MetaColumns() for vfp and db2 compat.
</p><p>Added unsigned support to mysql datadict class. Thx to iamsure.
</p><p>Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to
Josh R, Night_Wulfe#hotmail.com.
</p><p>ChangeTableSQL contributed by Florian Buzin.
</p><p>The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with
mssql driver.
</p>
<p><b>3.50 19 May 2003</b></p>
<p>Fixed mssql compat with FreeTDS. FreeTDS does not implement mssql_fetch_assoc().
<p>Merged back connection and recordset code into adodb.inc.php.
@ -697,4 +819,4 @@ and Insert_ID. Added above functions to test.php.</p>
</p>
<p><b>0.10 Sept 9 2000</b></p>
<p>First release</p>
<p>
</body></html>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -172,7 +172,7 @@ class ADODB_ado extends ADOConnection {
function &MetaColumns($table)
{
$table = strtoupper($table);
$arr= array();
$arr = array();
$dbc = $this->_connectionID;
$adors=@$dbc->OpenSchema(4);//tables
@ -196,8 +196,8 @@ class ADODB_ado extends ADOConnection {
}
$adors->Close();
}
return $arr;
$false = false;
return empty($arr) ? $false : $arr;
}
@ -208,6 +208,7 @@ class ADODB_ado extends ADOConnection {
{
$dbc = $this->_connectionID;
$false = false;
// return rs
if ($inputarr) {
@ -230,21 +231,19 @@ class ADODB_ado extends ADOConnection {
$p = false;
$rs = $oCmd->Execute();
$e = $dbc->Errors;
if ($dbc->Errors->Count > 0) return false;
if ($dbc->Errors->Count > 0) return $false;
return $rs;
}
$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
/*
$rs = new COM('ADODB.Recordset');
if ($rs) {
$rs->Open ($sql, $dbc, $this->_cursor_type,$this->_lock_type, $this->_execute_option);
}
*/
if ($dbc->Errors->Count > 0) return false;
if (! $rs) return false;
if ($dbc->Errors->Count > 0) return $false;
if (! $rs) return $false;
if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned
if ($rs->State == 0) {
$true = true;
return $true; // 0 = adStateClosed means no records returned
}
return $rs;
}
@ -335,7 +334,7 @@ class ADORecordSet_ado extends ADORecordSet {
// returns the field object
function FetchField($fieldOffset = -1) {
function &FetchField($fieldOffset = -1) {
$off=$fieldOffset+1; // offsets begin at 1
$o= new ADOFieldObject();
@ -345,8 +344,7 @@ class ADORecordSet_ado extends ADORecordSet {
$t = $f->Type;
$o->type = $this->MetaType($t);
$o->max_length = $f->DefinedSize;
$o->ado_type = $t;
$o->ado_type = $t;
//print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
return $o;

View File

@ -0,0 +1,636 @@
<?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.
Latest version is available at http://adodb.sourceforge.net
Microsoft ADO data driver. Requires ADO. Works only on MS Windows. PHP5 compat version.
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
define("_ADODB_ADO_LAYER", 1 );
/*--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------*/
class ADODB_ado extends ADOConnection {
var $databaseType = "ado";
var $_bindInputArray = false;
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
var $replaceQuote = "''"; // string to use to replace quotes
var $dataProvider = "ado";
var $hasAffectedRows = true;
var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary
var $_affectedRows = false;
var $_thisTransactions;
var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic
var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;
var $_lock_type = -1;
var $_execute_option = -1;
var $poorAffectedRows = true;
var $charPage;
function ADODB_ado()
{
$this->_affectedRows = new VARIANT;
}
function ServerInfo()
{
if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;
return array('description' => $desc, 'version' => '');
}
function _affectedrows()
{
if (PHP_VERSION >= 5) return $this->_affectedRows;
return $this->_affectedRows->value;
}
// you can also pass a connection string like this:
//
// $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')
{
try {
$u = 'UID';
$p = 'PWD';
if (!empty($this->charPage))
$dbc = new COM('ADODB.Connection',null,$this->charPage);
else
$dbc = new COM('ADODB.Connection');
if (! $dbc) return false;
/* special support if provider is mssql or access */
if ($argProvider=='mssql') {
$u = 'User Id'; //User parameter name for OLEDB
$p = 'Password';
$argProvider = "SQLOLEDB"; // SQL Server Provider
// not yet
//if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";
//use trusted conection for SQL if username not specified
if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
} else if ($argProvider=='access')
$argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider
if ($argProvider) $dbc->Provider = $argProvider;
if ($argUsername) $argHostname .= ";$u=$argUsername";
if ($argPassword)$argHostname .= ";$p=$argPassword";
if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
// @ added below for php 4.0.1 and earlier
@$dbc->Open((string) $argHostname);
$this->_connectionID = $dbc;
$dbc->CursorLocation = $this->_cursor_location;
return $dbc->State > 0;
} catch (exception $e) {
}
return false;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')
{
return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);
}
/*
adSchemaCatalogs = 1,
adSchemaCharacterSets = 2,
adSchemaCollations = 3,
adSchemaColumns = 4,
adSchemaCheckConstraints = 5,
adSchemaConstraintColumnUsage = 6,
adSchemaConstraintTableUsage = 7,
adSchemaKeyColumnUsage = 8,
adSchemaReferentialContraints = 9,
adSchemaTableConstraints = 10,
adSchemaColumnsDomainUsage = 11,
adSchemaIndexes = 12,
adSchemaColumnPrivileges = 13,
adSchemaTablePrivileges = 14,
adSchemaUsagePrivileges = 15,
adSchemaProcedures = 16,
adSchemaSchemata = 17,
adSchemaSQLLanguages = 18,
adSchemaStatistics = 19,
adSchemaTables = 20,
adSchemaTranslations = 21,
adSchemaProviderTypes = 22,
adSchemaViews = 23,
adSchemaViewColumnUsage = 24,
adSchemaViewTableUsage = 25,
adSchemaProcedureParameters = 26,
adSchemaForeignKeys = 27,
adSchemaPrimaryKeys = 28,
adSchemaProcedureColumns = 29,
adSchemaDBInfoKeywords = 30,
adSchemaDBInfoLiterals = 31,
adSchemaCubes = 32,
adSchemaDimensions = 33,
adSchemaHierarchies = 34,
adSchemaLevels = 35,
adSchemaMeasures = 36,
adSchemaProperties = 37,
adSchemaMembers = 38
*/
function &MetaTables()
{
$arr= array();
$dbc = $this->_connectionID;
$adors=@$dbc->OpenSchema(20);//tables
if ($adors){
$f = $adors->Fields(2);//table/view name
$t = $adors->Fields(3);//table type
while (!$adors->EOF){
$tt=substr($t->value,0,6);
if ($tt!='SYSTEM' && $tt !='ACCESS')
$arr[]=$f->value;
//print $f->value . ' ' . $t->value.'<br>';
$adors->MoveNext();
}
$adors->Close();
}
return $arr;
}
function &MetaColumns($table)
{
$table = strtoupper($table);
$arr= array();
$dbc = $this->_connectionID;
$adors=@$dbc->OpenSchema(4);//tables
if ($adors){
$t = $adors->Fields(2);//table/view name
while (!$adors->EOF){
if (strtoupper($t->Value) == $table) {
$fld = new ADOFieldObject();
$c = $adors->Fields(3);
$fld->name = $c->Value;
$fld->type = 'CHAR'; // cannot discover type in ADO!
$fld->max_length = -1;
$arr[strtoupper($fld->name)]=$fld;
}
$adors->MoveNext();
}
$adors->Close();
}
return $arr;
}
/* returns queryID or false */
function &_query($sql,$inputarr=false)
{
try { // In PHP5, all COM errors are exceptions, so to maintain old behaviour...
$dbc = $this->_connectionID;
// return rs
if ($inputarr) {
if (!empty($this->charPage))
$oCmd = new COM('ADODB.Command',null,$this->charPage);
else
$oCmd = new COM('ADODB.Command');
$oCmd->ActiveConnection = $dbc;
$oCmd->CommandText = $sql;
$oCmd->CommandType = 1;
foreach($inputarr as $val) {
// name, type, direction 1 = input, len,
$this->adoParameterType = 130;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
//print $p->Type.' '.$p->value;
$oCmd->Parameters->Append($p);
}
$p = false;
$rs = $oCmd->Execute();
$e = $dbc->Errors;
if ($dbc->Errors->Count > 0) return false;
return $rs;
}
$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
if ($dbc->Errors->Count > 0) return false;
if (! $rs) return false;
if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned
return $rs;
} catch (exception $e) {
}
return false;
}
function BeginTrans()
{
if ($this->transOff) return true;
if (isset($this->_thisTransactions))
if (!$this->_thisTransactions) return false;
else {
$o = $this->_connectionID->Properties("Transaction DDL");
$this->_thisTransactions = $o ? true : false;
if (!$o) return false;
}
@$this->_connectionID->BeginTrans();
$this->transCnt += 1;
return true;
}
function CommitTrans($ok=true)
{
if (!$ok) return $this->RollbackTrans();
if ($this->transOff) return true;
@$this->_connectionID->CommitTrans();
if ($this->transCnt) @$this->transCnt -= 1;
return true;
}
function RollbackTrans() {
if ($this->transOff) return true;
@$this->_connectionID->RollbackTrans();
if ($this->transCnt) @$this->transCnt -= 1;
return true;
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
$errc = $this->_connectionID->Errors;
if ($errc->Count == 0) return '';
$err = $errc->Item($errc->Count-1);
return $err->Description;
}
function ErrorNo()
{
$errc = $this->_connectionID->Errors;
if ($errc->Count == 0) return 0;
$err = $errc->Item($errc->Count-1);
return $err->NativeError;
}
// returns true or false
function _close()
{
if ($this->_connectionID) $this->_connectionID->Close();
$this->_connectionID = false;
return true;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_ado extends ADORecordSet {
var $bind = false;
var $databaseType = "ado";
var $dataProvider = "ado";
var $_tarr = false; // caches the types
var $_flds; // and field objects
var $canSeek = true;
var $hideErrors = true;
function ADORecordSet_ado($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
}
// returns the field object
function &FetchField($fieldOffset = -1) {
$off=$fieldOffset+1; // offsets begin at 1
$o= new ADOFieldObject();
$rs = $this->_queryID;
$f = $rs->Fields($fieldOffset);
$o->name = $f->Name;
$t = $f->Type;
$o->type = $this->MetaType($t);
$o->max_length = $f->DefinedSize;
$o->ado_type = $t;
//print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
return $o;
}
/* Use associative array to get fields array */
function Fields($colname)
{
if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _initrs()
{
$rs = $this->_queryID;
$this->_numOfRows = $rs->RecordCount;
$f = $rs->Fields;
$this->_numOfFields = $f->Count;
}
// should only be used to move forward as we normally use forward-only cursors
function _seek($row)
{
$rs = $this->_queryID;
// absoluteposition doesn't work -- my maths is wrong ?
// $rs->AbsolutePosition->$row-2;
// return true;
if ($this->_currentRow > $row) return false;
@$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst
return true;
}
/*
OLEDB types
enum DBTYPEENUM
{ DBTYPE_EMPTY = 0,
DBTYPE_NULL = 1,
DBTYPE_I2 = 2,
DBTYPE_I4 = 3,
DBTYPE_R4 = 4,
DBTYPE_R8 = 5,
DBTYPE_CY = 6,
DBTYPE_DATE = 7,
DBTYPE_BSTR = 8,
DBTYPE_IDISPATCH = 9,
DBTYPE_ERROR = 10,
DBTYPE_BOOL = 11,
DBTYPE_VARIANT = 12,
DBTYPE_IUNKNOWN = 13,
DBTYPE_DECIMAL = 14,
DBTYPE_UI1 = 17,
DBTYPE_ARRAY = 0x2000,
DBTYPE_BYREF = 0x4000,
DBTYPE_I1 = 16,
DBTYPE_UI2 = 18,
DBTYPE_UI4 = 19,
DBTYPE_I8 = 20,
DBTYPE_UI8 = 21,
DBTYPE_GUID = 72,
DBTYPE_VECTOR = 0x1000,
DBTYPE_RESERVED = 0x8000,
DBTYPE_BYTES = 128,
DBTYPE_STR = 129,
DBTYPE_WSTR = 130,
DBTYPE_NUMERIC = 131,
DBTYPE_UDT = 132,
DBTYPE_DBDATE = 133,
DBTYPE_DBTIME = 134,
DBTYPE_DBTIMESTAMP = 135
ADO Types
adEmpty = 0,
adTinyInt = 16,
adSmallInt = 2,
adInteger = 3,
adBigInt = 20,
adUnsignedTinyInt = 17,
adUnsignedSmallInt = 18,
adUnsignedInt = 19,
adUnsignedBigInt = 21,
adSingle = 4,
adDouble = 5,
adCurrency = 6,
adDecimal = 14,
adNumeric = 131,
adBoolean = 11,
adError = 10,
adUserDefined = 132,
adVariant = 12,
adIDispatch = 9,
adIUnknown = 13,
adGUID = 72,
adDate = 7,
adDBDate = 133,
adDBTime = 134,
adDBTimeStamp = 135,
adBSTR = 8,
adChar = 129,
adVarChar = 200,
adLongVarChar = 201,
adWChar = 130,
adVarWChar = 202,
adLongVarWChar = 203,
adBinary = 128,
adVarBinary = 204,
adLongVarBinary = 205,
adChapter = 136,
adFileTime = 64,
adDBFileTime = 137,
adPropVariant = 138,
adVarNumeric = 139
*/
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
if (!is_numeric($t)) return $t;
switch ($t) {
case 0:
case 12: // variant
case 8: // bstr
case 129: //char
case 130: //wc
case 200: // varc
case 202:// varWC
case 128: // bin
case 204: // varBin
case 72: // guid
if ($len <= $this->blobSize) return 'C';
case 201:
case 203:
return 'X';
case 128:
case 204:
case 205:
return 'B';
case 7:
case 133: return 'D';
case 134:
case 135: return 'T';
case 11: return 'L';
case 16:// adTinyInt = 16,
case 2://adSmallInt = 2,
case 3://adInteger = 3,
case 4://adBigInt = 20,
case 17://adUnsignedTinyInt = 17,
case 18://adUnsignedSmallInt = 18,
case 19://adUnsignedInt = 19,
case 20://adUnsignedBigInt = 21,
return 'I';
default: return 'N';
}
}
// time stamp not supported yet
function _fetch()
{
$rs = $this->_queryID;
if (!$rs or $rs->EOF) {
$this->fields = false;
return false;
}
$this->fields = array();
if (!$this->_tarr) {
$tarr = array();
$flds = array();
for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
$f = $rs->Fields($i);
$flds[] = $f;
$tarr[] = $f->Type;
}
// bind types and flds only once
$this->_tarr = $tarr;
$this->_flds = $flds;
}
$t = reset($this->_tarr);
$f = reset($this->_flds);
if ($this->hideErrors) $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null
for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
//echo "<p>",$t,' ';var_dump($f->value); echo '</p>';
switch($t) {
case 135: // timestamp
if (!strlen((string)$f->value)) $this->fields[] = false;
else {
if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value);
else $val = $f->value;
$this->fields[] = adodb_date('Y-m-d H:i:s',$val);
}
break;
case 133:// A date value (yyyymmdd)
if ($val = $f->value) {
$this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);
} else
$this->fields[] = false;
break;
case 7: // adDate
if (!strlen((string)$f->value)) $this->fields[] = false;
else {
if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value);
else $val = $f->value;
if (($val % 86400) == 0) $this->fields[] = adodb_date('Y-m-d',$val);
else $this->fields[] = adodb_date('Y-m-d H:i:s',$val);
}
break;
case 1: // null
$this->fields[] = false;
break;
case 6: // currency is not supported properly;
ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
$this->fields[] = (float) $f->value;
break;
default:
$this->fields[] = $f->value;
break;
}
//print " $f->value $t, ";
$f = next($this->_flds);
$t = next($this->_tarr);
} // for
if ($this->hideErrors) error_reporting($olde);
@$rs->MoveNext(); // @ needed for some versions of PHP!
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}
function NextRecordSet()
{
$rs = $this->_queryID;
$this->_queryID = $rs->NextRecordSet();
//$this->_queryID = $this->_QueryId->NextRecordSet();
if ($this->_queryID == null) return false;
$this->_currentRow = -1;
$this->_currentPage = -1;
$this->bind = false;
$this->fields = false;
$this->_flds = false;
$this->_tarr = false;
$this->_inited = false;
$this->Init();
return true;
}
function _close() {
$this->_flds = false;
@$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
$this->_queryID = false;
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -15,7 +15,8 @@ Set tabs to 4 for best viewing.
if (!defined('ADODB_DIR')) die();
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
if (PHP_VERSION >= 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php");
else include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
class ADODB_ado_access extends ADODB_ado {
@ -33,6 +34,10 @@ class ADODB_ado_access extends ADODB_ado {
}
function BeginTrans() { return false;}
function CommitTrans() { return false;}
function RollbackTrans() { return false;}
}

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -19,7 +19,8 @@ Set tabs to 4 for best viewing.
if (!defined('ADODB_DIR')) die();
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
if (PHP_VERSION >= 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php");
else include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
@ -54,35 +55,36 @@ class ADODB_ado_mssql extends ADODB_ado {
function MetaColumns($table)
{
$table = strtoupper($table);
$arr= array();
$dbc = $this->_connectionID;
$osoptions = array();
$osoptions[0] = null;
$osoptions[1] = null;
$osoptions[2] = $table;
$osoptions[3] = null;
$adors=@$dbc->OpenSchema(4, $osoptions);//tables
$table = strtoupper($table);
$arr= array();
$dbc = $this->_connectionID;
$osoptions = array();
$osoptions[0] = null;
$osoptions[1] = null;
$osoptions[2] = $table;
$osoptions[3] = null;
$adors=@$dbc->OpenSchema(4, $osoptions);//tables
if ($adors){
while (!$adors->EOF){
$fld = new ADOFieldObject();
$c = $adors->Fields(3);
$fld->name = $c->Value;
$fld->type = 'CHAR'; // cannot discover type in ADO!
$fld->max_length = -1;
$arr[strtoupper($fld->name)]=$fld;
$adors->MoveNext();
}
$adors->Close();
}
$false = false;
return empty($arr) ? $false : $arr;
}
if ($adors){
while (!$adors->EOF){
$fld = new ADOFieldObject();
$c = $adors->Fields(3);
$fld->name = $c->Value;
$fld->type = 'CHAR'; // cannot discover type in ADO!
$fld->max_length = -1;
$arr[strtoupper($fld->name)]=$fld;
$adors->MoveNext();
}
$adors->Close();
}
return $arr;
}
}
} // end class
class ADORecordSet_ado_mssql extends ADORecordSet_ado {

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -128,10 +128,10 @@ class ADODB_DB2 extends ADODB_odbc {
return $this->GetOne($this->identitySQL);
}
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='1 as ignore')
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
return $this->GetOne("select $flds from $tables where $where for update");
}
function &MetaTables($ttype=false,$showSchema=false, $qtable="%", $qschema="%")
@ -145,8 +145,10 @@ class ADODB_DB2 extends ADODB_odbc {
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
if (!$rs) {
$false = false;
return $false;
}
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr =& $rs->GetArray();
@ -175,7 +177,45 @@ class ADODB_DB2 extends ADODB_odbc {
}
return $arr2;
}
function &MetaIndexes ($table, $primary = FALSE, $owner=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);
}
$false = false;
// get index details
$table = strtoupper($table);
$SQL="SELECT NAME, UNIQUERULE, COLNAMES FROM SYSIBM.SYSINDEXES WHERE TBNAME='$table'";
if ($primary)
$SQL.= " AND UNIQUERULE='P'";
$rs = $this->Execute($SQL);
if (!is_object($rs)) {
if (isset($savem))
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $false;
}
$indexes = array ();
// parse index data into array
while ($row = $rs->FetchRow()) {
$indexes[$row[0]] = array(
'unique' => ($row[1] == 'U' || $row[1] == 'P'),
'columns' => array()
);
$cols = ltrim($row[2],'+');
$indexes[$row[0]]['columns'] = explode('+', $cols);
}
if (isset($savem)) {
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
}
return $indexes;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
@ -274,12 +314,14 @@ class ADORecordSet_db2 extends ADORecordSet_odbc {
case 'VARCHAR':
case 'CHAR':
case 'CHARACTER':
case 'C':
if ($len <= $this->blobSize) return 'C';
case 'LONGCHAR':
case 'TEXT':
case 'CLOB':
case 'DBCLOB': // double-byte
case 'X':
return 'X';
case 'BLOB':
@ -288,10 +330,12 @@ class ADORecordSet_db2 extends ADORecordSet_odbc {
return 'B';
case 'DATE':
case 'D':
return 'D';
case 'TIME':
case 'TIMESTAMP':
case 'T':
return 'T';
//case 'BOOLEAN':
@ -305,6 +349,7 @@ class ADORecordSet_db2 extends ADORecordSet_odbc {
case 'INTEGER':
case 'BIGINT':
case 'SMALLINT':
case 'I':
return 'I';
default: return 'N';

View File

@ -1,6 +1,6 @@
<?php
/*
@version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
@version 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.
@ -170,9 +170,10 @@ class ADORecordSet_fbsql extends ADORecordSet{
}
switch ($mode) {
case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
default:
case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;
case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = FBSQL_BOTH; break;
}
return $this->ADORecordSet($queryID);
}

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -52,6 +52,7 @@ class ADODB_ibase extends ADOConnection {
var $hasAffectedRows = false;
var $poorAffectedRows = true;
var $blobEncodeType = 'C';
var $role = false;
function ADODB_ibase()
{
@ -65,7 +66,11 @@ class ADODB_ibase extends ADOConnection {
if (!function_exists('ibase_pconnect')) return null;
if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
$fn = ($persist) ? 'ibase_pconnect':'ibase_connect';
$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
if ($this->role)
$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
$this->charSet,$this->buffers,$this->dialect,$this->role);
else
$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
$this->charSet,$this->buffers,$this->dialect);
if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
@ -186,7 +191,7 @@ class ADODB_ibase extends ADOConnection {
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
@ -207,7 +212,7 @@ class ADODB_ibase extends ADOConnection {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
return FALSE;
return $false;
}
$indexes = array ();
@ -475,61 +480,61 @@ class ADODB_ibase extends ADOConnection {
{
global $ADODB_FETCH_MODE;
if ($this->metaColumnsSQL) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
$retarr = array();
//OPN STUFF start
$dialect3 = ($this->dialect==3 ? true : false);
//OPN STUFF end
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = trim($rs->fields[0]);
//OPN STUFF start
$this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3);
if (isset($rs->fields[1]) && $rs->fields[1]) {
$fld->not_null = true;
}
if (isset($rs->fields[2])) {
$fld->has_default = true;
$d = substr($rs->fields[2],strlen('default '));
switch ($fld->type)
{
case 'smallint':
case 'integer': $fld->default_value = (int) $d; break;
case 'char':
case 'blob':
case 'text':
case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
case 'double':
case 'float': $fld->default_value = (float) $d; break;
default: $fld->default_value = $d; break;
}
// case 35:$tt = 'TIMESTAMP'; break;
}
if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
$fld->sub_type = $rs->fields[5];
} else {
$fld->sub_type = null;
}
//OPN STUFF end
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
$ADODB_FETCH_MODE = $save;
$false = false;
if ($rs === false) {
return $false;
}
return false;
$retarr = array();
//OPN STUFF start
$dialect3 = ($this->dialect==3 ? true : false);
//OPN STUFF end
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = trim($rs->fields[0]);
//OPN STUFF start
$this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3);
if (isset($rs->fields[1]) && $rs->fields[1]) {
$fld->not_null = true;
}
if (isset($rs->fields[2])) {
$fld->has_default = true;
$d = substr($rs->fields[2],strlen('default '));
switch ($fld->type)
{
case 'smallint':
case 'integer': $fld->default_value = (int) $d; break;
case 'char':
case 'blob':
case 'text':
case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
case 'double':
case 'float': $fld->default_value = (float) $d; break;
default: $fld->default_value = $d; break;
}
// case 35:$tt = 'TIMESTAMP'; break;
}
if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
$fld->sub_type = $rs->fields[5];
} else {
$fld->sub_type = null;
}
//OPN STUFF end
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
if ( empty($retarr)) return $false;
else return $retarr;
}
function BlobEncode( $blob )

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -26,6 +26,7 @@ class ADODB_informix extends ADODB_informix72 {
class ADORecordset_informix extends ADORecordset_informix72 {
var $databaseType = "informix";
function ADORecordset_informix($id,$mode=false)
{
$this->ADORecordset_informix72($id,$mode);

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim. All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim. 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.
@ -28,7 +28,7 @@ class ADODB_informix72 extends ADOConnection {
var $hasInsertID = true;
var $hasAffectedRows = true;
var $substr = 'substr';
var $metaTablesSQL="select tabname from systables where tabtype!=' ' and owner!='informix'"; //Don't get informix tables and pseudo-tables
var $metaTablesSQL="select tabname,tabtype from systables where tabtype in ('T','V') and owner!='informix'"; //Don't get informix tables and pseudo-tables
var $metaColumnsSQL =
@ -74,7 +74,7 @@ class ADODB_informix72 extends ADOConnection {
if (isset($this->version)) return $this->version;
$arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1");
$arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1");
$arr['version'] = $this->GetOne("select DBINFO('version','major') || DBINFO('version','minor') from systables where tabid = 1");
$this->version = $arr;
return $arr;
}
@ -123,10 +123,10 @@ class ADODB_informix72 extends ADOConnection {
return true;
}
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='1 as ignore')
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
return $this->GetOne("select $flds from $tables where $where for update");
}
/* Returns: the last error message from previous database operation
@ -141,7 +141,7 @@ class ADODB_informix72 extends ADOConnection {
function ErrorNo()
{
preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS
preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse);
if (is_array($parse) && isset($parse[1])) return (int)$parse[1];
return 0;
}
@ -151,6 +151,7 @@ class ADODB_informix72 extends ADOConnection {
{
global $ADODB_FETCH_MODE;
$false = false;
if (!empty($this->metaColumnsSQL)) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
@ -158,16 +159,27 @@ class ADODB_informix72 extends ADOConnection {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
if ($rs === false) return $false;
$rspkey = $this->Execute(sprintf($this->metaPrimaryKeySQL,$table)); //Added to get primary key colno items
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
/* //!eos.
$rs->fields[1] is not the correct adodb type
$rs->fields[2] is not correct max_length, because can include not-null bit
$fld->type = $rs->fields[1];
$fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields); //Added to set primary key flag
$fld->max_length = $rs->fields[2];
$fld->max_length = $rs->fields[2];*/
$pr=ifx_props($rs->fields[1],$rs->fields[2]); //!eos
$fld->type = $pr[0] ;//!eos
$fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields);
$fld->max_length = $pr[1]; //!eos
$fld->precision = $pr[2] ;//!eos
$fld->not_null = $pr[3]=="N"; //!eos
if (trim($rs->fields[3]) != "AAAAAA 0") {
$fld->has_default = 1;
$fld->default_value = $rs->fields[3];
@ -180,10 +192,11 @@ class ADODB_informix72 extends ADOConnection {
}
$rs->Close();
$rspKey->Close(); //!eos
return $retarr;
}
return false;
return $false;
}
function &xMetaColumns($table)
@ -191,6 +204,38 @@ class ADODB_informix72 extends ADOConnection {
return ADOConnection::MetaColumns($table,false);
}
function MetaForeignKeys($table, $owner=false, $upper=false) //!Eos
{
$sql = "
select tr.tabname,updrule,delrule,
i.part1 o1,i2.part1 d1,i.part2 o2,i2.part2 d2,i.part3 o3,i2.part3 d3,i.part4 o4,i2.part4 d4,
i.part5 o5,i2.part5 d5,i.part6 o6,i2.part6 d6,i.part7 o7,i2.part7 d7,i.part8 o8,i2.part8 d8
from systables t,sysconstraints s,sysindexes i,
sysreferences r,systables tr,sysconstraints s2,sysindexes i2
where t.tabname='$table'
and s.tabid=t.tabid and s.constrtype='R' and r.constrid=s.constrid
and i.idxname=s.idxname and tr.tabid=r.ptabid
and s2.constrid=r.primary and i2.idxname=s2.idxname";
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr =& $rs->GetArray();
$a = array();
foreach($arr as $v) {
$coldest=$this->metaColumnNames($v["tabname"]);
$colorig=$this->metaColumnNames($table);
$colnames=array();
for($i=1;$i<=8 && $v["o$i"] ;$i++) {
$colnames[]=$coldest[$v["d$i"]-1]."=".$colorig[$v["o$i"]-1];
}
if($upper)
$a[strtoupper($v["tabname"])] = $colnames;
else
$a[$v["tabname"]] = $colnames;
}
return $a;
}
function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
{
$type = ($blobtype == 'TEXT') ? 1 : 0;
@ -331,7 +376,8 @@ class ADORecordset_informix72 extends ADORecordSet {
$o->not_null = $arr[4]=="N";
}
}
return $this->_fieldprops[$fieldOffset];
$ret = $this->_fieldprops[$fieldOffset];
return $ret;
}
function _initrs()
@ -342,7 +388,7 @@ class ADORecordset_informix72 extends ADORecordSet {
function _seek($row)
{
return @ifx_fetch_row($this->_queryID, $row);
return @ifx_fetch_row($this->_queryID, (int) $row);
}
function MoveLast()
@ -401,4 +447,29 @@ class ADORecordset_informix72 extends ADORecordSet {
}
}
/** !Eos
* Auxiliar function to Parse coltype,collength. Used by Metacolumns
* return: array ($mtype,$length,$precision,$nullable) (similar to ifx_fieldpropierties)
*/
function ifx_props($coltype,$collength){
$itype=fmod($coltype+1,256);
$nullable=floor(($coltype+1) /256) ?"N":"Y";
$mtype=substr(" CIIFFNNDN TBXCC ",$itype,1);
switch ($itype){
case 2:
$length=4;
case 6:
case 9:
case 14:
$length=floor($collength/256);
$precision=fmod($collength,256);
break;
default:
$precision=0;
$length=$collength;
}
return array($mtype,$length,$precision,$nullable);
}
?>

View File

@ -1,11 +1,15 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
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 8.
Revision 1: (02/25/2005) Updated codebase to include the _inject_bind_options function. This allows
users to access the options in the ldap_set_option function appropriately. Most importantly
LDAP Version 3 is now supported. See the examples for more information. Also fixed some minor
bugs that surfaced when PHP error levels were set high.
Joshua Eldridge (joshuae74#hotmail.com)
*/
@ -13,6 +17,12 @@
// security - hide paths
if (!defined('ADODB_DIR')) die();
if (!defined('LDAP_ASSOC')) {
define('LDAP_ASSOC',ADODB_FETCH_ASSOC);
define('LDAP_NUM',ADODB_FETCH_NUM);
define('LDAP_BOTH',ADODB_FETCH_BOTH);
}
class ADODB_ldap extends ADOConnection {
var $databaseType = 'ldap';
var $dataProvider = 'ldap';
@ -24,45 +34,124 @@ class ADODB_ldap extends ADOConnection {
# Used during searches
var $filter;
var $dn;
var $version;
var $port = 389;
# Options configuration information
var $LDAP_CONNECT_OPTIONS;
function ADODB_ldap()
{
}
// returns true or false
function _connect( $host, $username, $password, $ldapbase )
function _connect( $host, $username, $password, $ldapbase)
{
if ( !function_exists( 'ldap_connect' ) ) return null;
$conn_info = array( $host );
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
$this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] )
or die( 'Could not connect to ' . $this->_connectionID );
if ($username && $password) {
$bind = ldap_bind( $this->_connectionID, $username, $password )
or die( 'Could not bind to ' . $this->_connectionID . ' with $username & $password');
} else {
$bind = ldap_bind( $this->_connectionID )
or die( 'Could not bind anonymously to ' . $this->_connectionID );
}
return $this->_connectionID;
}
global $LDAP_CONNECT_OPTIONS;
if ( !function_exists( 'ldap_connect' ) ) return null;
$conn_info = array( $host,$this->port);
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
$this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] );
if (!$this->_connectionID) {
$e = 'Could not connect to ' . $conn_info[0];
$this->_errorMsg = $e;
if ($this->debug) ADOConnection::outp($e);
return false;
}
if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) {
$this->_inject_bind_options( $LDAP_CONNECT_OPTIONS );
}
if ($username) {
$bind = ldap_bind( $this->_connectionID, $username, $password );
} else {
$username = 'anonymous';
$bind = ldap_bind( $this->_connectionID );
}
if (!$bind) {
$e = 'Could not bind to ' . $conn_info[0] . " as ".$username;
$this->_errorMsg = $e;
if ($this->debug) ADOConnection::outp($e);
return false;
}
$this->_errorMsg = '';
$this->database = $ldapbase;
return $this->_connectionID;
}
/*
Valid Domain Values for LDAP Options:
LDAP_OPT_DEREF (integer)
LDAP_OPT_SIZELIMIT (integer)
LDAP_OPT_TIMELIMIT (integer)
LDAP_OPT_PROTOCOL_VERSION (integer)
LDAP_OPT_ERROR_NUMBER (integer)
LDAP_OPT_REFERRALS (boolean)
LDAP_OPT_RESTART (boolean)
LDAP_OPT_HOST_NAME (string)
LDAP_OPT_ERROR_STRING (string)
LDAP_OPT_MATCHED_DN (string)
LDAP_OPT_SERVER_CONTROLS (array)
LDAP_OPT_CLIENT_CONTROLS (array)
Make sure to set this BEFORE calling Connect()
Example:
$LDAP_CONNECT_OPTIONS = Array(
Array (
"OPTION_NAME"=>LDAP_OPT_DEREF,
"OPTION_VALUE"=>2
),
Array (
"OPTION_NAME"=>LDAP_OPT_SIZELIMIT,
"OPTION_VALUE"=>100
),
Array (
"OPTION_NAME"=>LDAP_OPT_TIMELIMIT,
"OPTION_VALUE"=>30
),
Array (
"OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION,
"OPTION_VALUE"=>3
),
Array (
"OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER,
"OPTION_VALUE"=>13
),
Array (
"OPTION_NAME"=>LDAP_OPT_REFERRALS,
"OPTION_VALUE"=>FALSE
),
Array (
"OPTION_NAME"=>LDAP_OPT_RESTART,
"OPTION_VALUE"=>FALSE
)
);
*/
function _inject_bind_options( $options ) {
foreach( $options as $option ) {
ldap_set_option( $this->_connectionID, $option["OPTION_NAME"], $option["OPTION_VALUE"] )
or die( "Unable to set server option: " . $option["OPTION_NAME"] );
}
}
/* returns _queryID or false */
function _query($sql,$inputarr)
{
$rs = ldap_search( $this->_connectionID, $this->database, $sql );
return $rs;
$rs = ldap_search( $this->_connectionID, $this->database, $sql );
$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql;
return $rs;
}
/* closes the LDAP connection */
@ -72,9 +161,14 @@ class ADODB_ldap extends ADOConnection {
$this->_connectionID = false;
}
function SelectDB($db) {
$this->database = $db;
return true;
} // SelectDB
function ServerInfo()
{
if( is_array( $this->version ) ) return $this->version;
if( !empty( $this->version ) ) return $this->version;
$version = array();
/*
Determines how aliases are handled during search.
@ -160,8 +254,8 @@ class ADODB_ldap extends ADOConnection {
}
/* The host name (or list of hosts) for the primary LDAP server. */
ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] );
ldap_get_option( $this->_connectionID, OPT_ERROR_NUMBER, $version['OPT_ERROR_NUMBER'] );
ldap_get_option( $this->_connectionID, OPT_ERROR_STRING, $version['OPT_ERROR_STRING'] );
ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_NUMBER, $version['LDAP_OPT_ERROR_NUMBER'] );
ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_STRING, $version['LDAP_OPT_ERROR_STRING'] );
ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] );
return $this->version = $version;
@ -193,9 +287,9 @@ class ADORecordSet_ldap extends ADORecordSet{
case ADODB_FETCH_ASSOC:
$this->fetchMode = LDAP_ASSOC;
break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = LDAP_BOTH;
break;
}
@ -292,11 +386,12 @@ class ADORecordSet_ldap extends ADORecordSet{
break;
case LDAP_NUM:
$this->fields = $this->GetRowNums();
$this->fields = array_merge($this->GetRowNums(),$this->GetRowAssoc());
break;
case LDAP_BOTH:
default:
$this->fields = $this->GetRowNums();
break;
}
return ( is_array( $this->fields ) );

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -103,7 +103,6 @@ class ADODB_mssql extends ADOConnection {
var $uniqueOrderBy = true;
var $_bindInputArray = true;
function ADODB_mssql()
{
$this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);
@ -306,10 +305,51 @@ class ADODB_mssql extends ADOConnection {
See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
*/
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='top 1 null as ignore')
{
if (!$this->transCnt) $this->BeginTrans();
return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where");
return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
}
function &MetaIndexes($table,$primary=false)
{
$table = $this->qstr($table);
$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
ORDER BY O.name, I.Name, K.keyno";
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($sql);
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
}
$indexes = array();
while ($row = $rs->FetchRow()) {
if (!$primary && $row[5]) continue;
$indexes[$row[0]]['unique'] = $row[6];
$indexes[$row[0]]['columns'][] = $row[1];
}
return $indexes;
}
function MetaForeignKeys($table, $owner=false, $upper=false)
@ -395,7 +435,8 @@ order by constraint_name, referenced_table_name, keyno";
$ADODB_FETCH_MODE = $savem;
if ($a && sizeof($a)>0) return $a;
return false;
$false = false;
return $false;
}
@ -413,46 +454,6 @@ order by constraint_name, referenced_table_name, keyno";
}
return $ret;
}
function &MetaIndexes($table,$primary=false)
{
$table = $this->Quote($table);
$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
ORDER BY O.name, I.Name, K.keyno";
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($sql);
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
}
$indexes = array();
while ($row = $rs->FetchRow()) {
if (!$primary && $row[5]) continue;
$indexes[$row[0]]['unique'] = $row[6];
$indexes[$row[0]]['columns'][] = $row[1];
}
return $indexes;
}
function SelectDB($dbName)
{
@ -534,6 +535,30 @@ order by constraint_name, referenced_table_name, keyno";
return array($sql,$stmt);
}
// returns concatenated string
// MSSQL requires integers to be cast as strings
// automatically cast every datatype to VARCHAR(255)
// @author David Rogers (introspectshun)
function Concat()
{
$s = "";
$arr = func_get_args();
// Split single record on commas, if possible
if (sizeof($arr) == 1) {
foreach ($arr as $arg) {
$args = explode(',', $arg);
}
$arr = $args;
}
array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";'));
$s = implode('+',$arr);
if (sizeof($arr) > 0) return "$s";
return '';
}
/*
Usage:
$stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
@ -756,15 +781,17 @@ class ADORecordset_mssql extends ADORecordSet {
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function FetchField($fieldOffset = -1)
function &FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
return @mssql_fetch_field($this->_queryID, $fieldOffset);
$f = @mssql_fetch_field($this->_queryID, $fieldOffset);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
return @mssql_fetch_field($this->_queryID);
$f = @mssql_fetch_field($this->_queryID);
}
return null;
$false = false;
if (empty($f)) return $false;
return $f;
}
function _seek($row)

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -79,6 +79,7 @@ class ADODB_mysql extends ADOConnection {
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
@ -95,7 +96,7 @@ class ADODB_mysql extends ADOConnection {
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
return $false;
}
$indexes = array ();
@ -148,7 +149,8 @@ class ADODB_mysql extends ADOConnection {
function _insertid()
{
return mysql_insert_id($this->_connectionID);
return ADOConnection::GetOne('SELECT LAST_INSERT_ID()');
//return mysql_insert_id($this->_connectionID);
}
function GetOne($sql,$inputarr=false)
@ -302,7 +304,13 @@ class ADODB_mysql extends ADOConnection {
$s .= '%p';
break;
case 'w':
$s .= '%w';
break;
case 'l':
$s .= '%W';
break;
}
}
$s.="')";
@ -333,6 +341,8 @@ class ADODB_mysql extends ADOConnection {
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!empty($this->port)) $argHostname .= ":".$this->port;
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect,$this->clientFlags);
@ -350,6 +360,8 @@ class ADODB_mysql extends ADOConnection {
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!empty($this->port)) $argHostname .= ":".$this->port;
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
else
@ -368,86 +380,86 @@ class ADODB_mysql extends ADOConnection {
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
$this->_findschema($table,$schema);
if ($schema) {
$dbName = $this->database;
$this->SelectDB($schema);
}
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
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;
}
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === 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);
// split type into type(length):
$fld->scale = null;
if (preg_match('/^enum\((.+)\)$/',$type,$enum_vals)) { // convert enum to varchar
$fld->type = 'varchar';
$fld->max_length = 1;
$enum_vals = explode(',',$enum_vals[1]);
foreach($enum_vals as $val)
{
if ($fld->max_length < strlen($val)-2) $fld->max_length = strlen($val)-2;
}
} elseif (strpos($type,',') && 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;
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != '' && $d != 'NULL') {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->max_length = -1;
$fld->type = $type;
$fld->has_default = false;
}
/*
// split type into type(length):
if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
} else {
$fld->max_length = -1;
$fld->type = $type;
}*/
$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($fld->type,'blob') !== 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;
}
if ($save == ADODB_FETCH_NUM) {
$retarr[] = $fld;
} else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
// returns true or false
function SelectDB($dbName)
{
$this->databaseName = $dbName;
$this->database = $dbName;
if ($this->_connectionID) {
return @mysql_select_db($dbName,$this->_connectionID);
}
@ -519,6 +531,42 @@ class ADODB_mysql extends ADOConnection {
return 4294967295;
}
// "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $asociative = FALSE )
{
if ( !empty($owner) ) {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
$create_sql = $a_create_table[1];
$matches = array();
$foreign_keys = array();
if ( preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches) ) {
$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 ( $asociative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
}
}
}
}
return $foreign_keys;
}
}
/*--------------------------------------------------------------------------------------
@ -541,11 +589,12 @@ class ADORecordSet_mysql extends ADORecordSet{
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = MYSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
@ -608,7 +657,7 @@ class ADORecordSet_mysql extends ADORecordSet{
{
//return adodb_movenext($this);
//if (defined('ADODB_EXTENSION')) return adodb_movenext($this);
if (@$this->fields =& mysql_fetch_array($this->_queryID,$this->fetchMode)) {
if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
@ -676,7 +725,7 @@ class ADORecordSet_mysql extends ADORecordSet{
case 'MEDIUMINT':
case 'SMALLINT':
if (is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->auto_increment) return 'R';
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
@ -696,17 +745,18 @@ class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = MYSQL_BOTH; break;
}
$this->ADORecordSet($queryID);
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
function MoveNext()
{
return adodb_movenext($this);
return @adodb_movenext($this);
}
}

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -19,6 +19,11 @@ Based on adodb 3.40
if (! defined("_ADODB_MYSQLI_LAYER")) {
define("_ADODB_MYSQLI_LAYER", 1 );
if (!defined('MYSQLI_READ_DEFAULT_GROUP')) define('MYSQLI_READ_DEFAULT_GROUP',1);
// disable adodb extension - currently incompatible.
global $ADODB_EXTENSION; $ADODB_EXTENSION = false;
class ADODB_mysqli extends ADOConnection {
var $databaseType = 'mysqli';
var $dataProvider = 'native';
@ -33,7 +38,7 @@ class ADODB_mysqli extends ADOConnection {
var $isoDates = true; // accepts dates in ISO format
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasTransactions = false;
var $hasTransactions = true;
var $forceNewConnect = false;
var $poorAffectedRows = true;
var $clientFlags = 0;
@ -42,11 +47,12 @@ class ADODB_mysqli extends ADOConnection {
var $socket = false;
var $_bindInputArray = false;
var $nameQuote = '`'; /// string to use to quote identifiers and names
var $optionFlags = array(array(MYSQLI_READ_DEFAULT_GROUP,0));
function ADODB_mysqli()
{
if(!extension_loaded("mysqli"))
trigger_error("You must have the MySQLi extension.", E_USER_ERROR);
// if(!extension_loaded("mysqli"))
;//trigger_error("You must have the mysqli extension installed.", E_USER_ERROR);
}
@ -59,6 +65,9 @@ class ADODB_mysqli extends ADOConnection {
$argPassword = NULL,
$argDatabasename = NULL, $persist=false)
{
if(!extension_loaded("mysqli")) {
return null;
}
$this->_connectionID = @mysqli_init();
if (is_null($this->_connectionID)) {
@ -67,29 +76,34 @@ class ADODB_mysqli extends ADOConnection {
ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg());
return false;
}
// Set connection options
// Not implemented now
// mysqli_options($this->_connection,,);
if (mysqli_real_connect($this->_connectionID,
/*
I suggest a simple fix which would enable adodb and mysqli driver to
read connection options from the standard mysql configuration file
/etc/my.cnf - "Bastien Duclaux" <bduclaux#yahoo.com>
*/
foreach($this->optionFlags as $arr) {
mysqli_options($this->_connectionID,$arr[0],$arr[1]);
}
if (!empty($this->port)) $argHostname .= ":".$this->port;
$ok = mysqli_real_connect($this->_connectionID,
$argHostname,
$argUsername,
$argPassword,
$argDatabasename,
$this->port,
$this->socket,
$this->clientFlags))
{
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
else {
$this->clientFlags);
if ($ok) {
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
} else {
if ($this->debug)
ADOConnection::outp("Could't connect : " . $this->ErrorMsg());
return false;
}
}
}
}
// returns true or false
// How to force a persistent connection
@ -104,7 +118,7 @@ class ADODB_mysqli extends ADOConnection {
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->forceNewConnect = true;
$this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function IfNull( $field, $ifNull )
@ -158,7 +172,7 @@ class ADODB_mysqli extends ADOConnection {
// ensure that the variable is not quoted twice, once by qstr and once
// by the magic_quotes_gpc.
//
//Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());
//Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
function qstr($s, $magic_quotes = false)
{
if (!$magic_quotes) {
@ -176,7 +190,6 @@ class ADODB_mysqli extends ADOConnection {
function _insertid()
{
// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
$result = @mysqli_insert_id($this->_connectionID);
if ($result == -1){
if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg());
@ -187,7 +200,6 @@ class ADODB_mysqli extends ADOConnection {
// Only works for INSERT, UPDATE and DELETE query's
function _affectedrows()
{
// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
$result = @mysqli_affected_rows($this->_connectionID);
if ($result == -1) {
if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg());
@ -235,62 +247,72 @@ class ADODB_mysqli extends ADOConnection {
}
function &MetaDatabases()
{
$query = "SHOW DATABASES";
$ret =& $this->Execute($query);
return $ret;
}
{
$query = "SHOW DATABASES";
$ret =& $this->Execute($query);
if ($ret && is_object($ret)){
$arr = array();
while (!$ret->EOF){
$db = $ret->Fields('Database');
if ($db != 'mysql') $arr[] = $db;
$ret->MoveNext();
}
return $arr;
}
return $ret;
}
function &MetaIndexes ($table, $primary = 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);
}
// get index details
$rs = $this->Execute(sprintf('SHOW INDEXES 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 ($row = $rs->FetchRow()) {
if ($primary == FALSE AND $row[2] == 'PRIMARY') {
continue;
}
if (!isset($indexes[$row[2]])) {
$indexes[$row[2]] = array(
'unique' => ($row[1] == 0),
'columns' => array()
);
}
$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index )
{
ksort ($indexes[$index]['columns']);
}
return $indexes;
// 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 INDEXES 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 ($row = $rs->FetchRow()) {
if ($primary == FALSE AND $row[2] == 'PRIMARY') {
continue;
}
if (!isset($indexes[$row[2]])) {
$indexes[$row[2]] = array(
'unique' => ($row[1] == 0),
'columns' => array()
);
}
$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index )
{
ksort ($indexes[$index]['columns']);
}
return $indexes;
}
@ -348,6 +370,14 @@ class ADODB_mysqli extends ADOConnection {
case 'A':
$s .= '%p';
break;
case 'w':
$s .= '%w';
break;
case 'l':
$s .= '%W';
break;
default:
@ -385,112 +415,125 @@ class ADODB_mysqli extends ADOConnection {
return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
}
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 =& ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
// "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $asociative = FALSE )
{
if ( !empty($owner) ) {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
$create_sql = $a_create_table[1];
$matches = array();
$foreign_keys = array();
if ( preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches) ) {
$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 ( $asociative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
}
}
}
}
return $foreign_keys;
}
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$rs = false;
switch($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM:
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs = $this->Execute(sprintf($this->metaColumnsSQL,
$table));
$false = false;
if (!$this->metaColumnsSQL)
return $false;
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 (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) break;
if (!is_object($rs))
return $false;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
// split type into type(length):
if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
{
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
}
else
{
$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($fld->type,'blob') !== false);
if (!$fld->binary)
{
$d = $rs->fields[4];
$d = $rs->fields['Default'];
if ($d != "" && $d != "NULL")
{
$fld->has_default = true;
$fld->default_value = $d;
}
else
{
$fld->has_default = false;
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];
$fld->max_length = max(array_map("strlen",explode(",",$query_array[2]))) - 2; // PHP >= 4.0.6
$fld->max_length = ($fld->max_length == 0 ? 1 : $fld->max_length);
} else {
$fld->type = $type;
$fld->max_length = -1;
}
}
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
break;
case ADODB_FETCH_ASSOC:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$rs = $this->Execute(sprintf($this->metaColumnsSQL,
$table));
$ADODB_FETCH_MODE = $save;
if ($rs === false) break;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields['Field'];
$fld->type = $rs->fields['Type'];
// split type into type(length):
if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
{
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
}
else
{
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields['Null'] != 'YES');
$fld->primary_key = ($rs->fields['Key'] == 'PRI');
$fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false);
$fld->binary = (strpos($fld->type,'blob') !== false);
if (!$fld->binary)
{
$d = $rs->fields['Default'];
if ($d != "" && $d != "NULL")
{
$fld->has_default = true;
$fld->default_value = $d;
}
else
{
$fld->has_default = false;
$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;
}
}
}
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
if ($save == ADODB_FETCH_NUM) {
$retarr[] = $fld;
} else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
break;
default:
}
if ($rs === false) return false;
$rs->Close();
return $retarr;
}
return false;
$rs->Close();
return $retarr;
}
// returns true or false
@ -517,6 +560,7 @@ class ADODB_mysqli extends ADOConnection {
$secs = 0)
{
$offsetStr = ($offset >= 0) ? "$offset," : '';
if ($nrows < 0) $nrows = '18446744073709551615';
if ($secs)
$rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
@ -572,7 +616,7 @@ class ADODB_mysqli extends ADOConnection {
function ErrorMsg()
{
if (empty($this->_connectionID))
$this->_errorMsg = @mysqli_error();
$this->_errorMsg = @mysqli_connect_error();
else
$this->_errorMsg = @mysqli_error($this->_connectionID);
return $this->_errorMsg;
@ -582,7 +626,7 @@ class ADODB_mysqli extends ADOConnection {
function ErrorNo()
{
if (empty($this->_connectionID))
return @mysqli_errno();
return @mysqli_connect_errno();
else
return @mysqli_errno($this->_connectionID);
}
@ -644,7 +688,7 @@ class ADORecordSet_mysqli extends ADORecordSet{
$this->fetchMode = MYSQLI_BOTH;
break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
@ -710,7 +754,7 @@ class ADORecordSet_mysqli extends ADORecordSet{
{
if ($this->EOF) return false;
$this->_currentRow++;
$this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);
$this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode);
if (is_array($this->fields)) return true;
$this->EOF = true;
@ -729,70 +773,132 @@ class ADORecordSet_mysqli extends ADORecordSet{
$this->_queryID = false;
}
/*
0 = MYSQLI_TYPE_DECIMAL
1 = MYSQLI_TYPE_CHAR
1 = MYSQLI_TYPE_TINY
2 = MYSQLI_TYPE_SHORT
3 = MYSQLI_TYPE_LONG
4 = MYSQLI_TYPE_FLOAT
5 = MYSQLI_TYPE_DOUBLE
6 = MYSQLI_TYPE_NULL
7 = MYSQLI_TYPE_TIMESTAMP
8 = MYSQLI_TYPE_LONGLONG
9 = MYSQLI_TYPE_INT24
10 = MYSQLI_TYPE_DATE
11 = MYSQLI_TYPE_TIME
12 = MYSQLI_TYPE_DATETIME
13 = MYSQLI_TYPE_YEAR
14 = MYSQLI_TYPE_NEWDATE
247 = MYSQLI_TYPE_ENUM
248 = MYSQLI_TYPE_SET
249 = MYSQLI_TYPE_TINY_BLOB
250 = MYSQLI_TYPE_MEDIUM_BLOB
251 = MYSQLI_TYPE_LONG_BLOB
252 = MYSQLI_TYPE_BLOB
253 = MYSQLI_TYPE_VAR_STRING
254 = MYSQLI_TYPE_STRING
255 = MYSQLI_TYPE_GEOMETRY
*/
function MetaType($t, $len = -1, $fieldobj = false)
{
if (is_object($t))
{
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
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';
$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 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
// Added floating-point types
// Maybe not necessery.
case 'FLOAT':
case 'DOUBLE':
// case 'DOUBLE PRECISION':
case 'DECIMAL':
case 'DEC':
case 'FIXED':
default:
return 'N';
}
}
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
}
} // rs class
}

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -59,6 +59,12 @@ class ADODB_mysqlt extends ADODB_mysql {
return true;
}
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");
}
}
class ADORecordSet_mysqlt extends ADORecordSet_mysql{
@ -70,21 +76,24 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode)
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default: $this->fetchMode = MYSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
function MoveNext()
{
if (@$this->fields =& mysql_fetch_array($this->_queryID,$this->fetchMode)) {
if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
$this->_currentRow += 1;
return true;
}
@ -98,7 +107,7 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{
class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt {
function ADORecordSet_ext_mysqli($queryID,$mode=false)
function ADORecordSet_ext_mysqlt($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
@ -108,11 +117,13 @@ class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt {
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = MYSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved.
First cut at the Netezza Driver by Josh Eldridge joshuae74#hotmail.com
Based on the previous postgres drivers.
@ -149,10 +149,12 @@ class ADORecordSet_netezza extends ADORecordSet_postgres64
{
case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default: $this->fetchMode = PGSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}

View File

@ -1,7 +1,7 @@
<?php
/*
version V4.50 6 July 2004 (c) 2000-2004 John Lim. All rights reserved.
version V4.65 22 July 2005 (c) 2000-2005 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
@ -99,6 +99,7 @@ class ADODB_oci8 extends ADOConnection {
{
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
@ -107,7 +108,9 @@ class ADODB_oci8 extends ADOConnection {
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return false;
if (!$rs) {
return $false;
}
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
@ -128,7 +131,10 @@ class ADODB_oci8 extends ADOConnection {
$rs->MoveNext();
}
$rs->Close();
return $retarr;
if (empty($retarr))
return $false;
else
return $retarr;
}
function Time()
@ -203,14 +209,25 @@ NATSOFT.DOMAIN =
//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
if ($mode==1) {
$this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename);
$this->_connectionID = ($this->charSet) ?
OCIPLogon($argUsername,$argPassword, $argDatabasename)
:
OCIPLogon($argUsername,$argPassword, $argDatabasename, $this->charSet)
;
if ($this->_connectionID && $this->autoRollback) OCIrollback($this->_connectionID);
} else if ($mode==2) {
$this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename);
$this->_connectionID = ($this->charSet) ?
OCINLogon($argUsername,$argPassword, $argDatabasename)
:
OCINLogon($argUsername,$argPassword, $argDatabasename, $this->charSet);
} else {
$this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename);
$this->_connectionID = ($this->charSet) ?
OCILogon($argUsername,$argPassword, $argDatabasename)
:
OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet);
}
if ($this->_connectionID === false) return false;
if (!$this->_connectionID) return false;
if ($this->_initdate) {
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
}
@ -270,10 +287,10 @@ NATSOFT.DOMAIN =
return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
}
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='1 as ignore')
{
if ($this->autoCommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
return $this->GetOne("select $flds from $tables where $where for update");
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
@ -291,6 +308,73 @@ NATSOFT.DOMAIN =
return $ret;
}
// Mark Newnham
function &MetaIndexes ($table, $primary = FALSE, $owner=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);
}
// get index details
$table = strtoupper($table);
// get Primary index
$primary_key = '';
$false = false;
$rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table));
if ($row = $rs->FetchRow())
$primary_key = $row[1]; //constraint_name
if ($primary==TRUE && $primary_key=='') {
if (isset($savem))
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $false; //There is no primary key
}
$rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table));
if (!is_object($rs)) {
if (isset($savem))
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $false;
}
$indexes = array ();
// parse index data into array
while ($row = $rs->FetchRow()) {
if ($primary && $row[0] != $primary_key) continue;
if (!isset($indexes[$row[0]])) {
$indexes[$row[0]] = array(
'unique' => ($row[1] == 'UNIQUE'),
'columns' => array()
);
}
$indexes[$row[0]]['columns'][$row[2] - 1] = $row[3];
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index ) {
ksort ($indexes[$index]['columns']);
}
if (isset($savem)) {
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
}
return $indexes;
}
function BeginTrans()
{
if ($this->transOff) return true;
@ -412,6 +496,14 @@ NATSOFT.DOMAIN =
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
default:
// handle escape characters...
if ($ch == '\\') {
@ -457,9 +549,9 @@ NATSOFT.DOMAIN =
if ($offset > 0) $nrows += $offset;
//$inputarr['adodb_rownum'] = $nrows;
if ($this->databaseType == 'oci8po') {
$sql = "select * from ($sql) where rownum <= ?";
$sql = "select * from (".$sql.") where rownum <= ?";
} else {
$sql = "select * from ($sql) where rownum <= :adodb_offset";
$sql = "select * from (".$sql.") where rownum <= :adodb_offset";
}
$inputarr['adodb_offset'] = $nrows;
$nrows = -1;
@ -473,10 +565,13 @@ NATSOFT.DOMAIN =
// Algorithm by Tomas V V Cox, from PEAR DB oci8.php
// Let Oracle return the name of the columns
$q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL";
if (!$stmt = OCIParse($this->_connectionID, $q_fields)) {
return false;
}
$q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
$false = false;
if (! $stmt_arr = $this->Prepare($q_fields)) {
return $false;
}
$stmt = $stmt_arr[1];
if (is_array($inputarr)) {
foreach($inputarr as $k => $v) {
@ -499,7 +594,7 @@ NATSOFT.DOMAIN =
if (!OCIExecute($stmt, OCI_DEFAULT)) {
OCIFreeStatement($stmt);
return false;
return $false;
}
$ncols = OCINumCols($stmt);
@ -614,6 +709,46 @@ NATSOFT.DOMAIN =
return $rez;
}
/**
* Execute SQL
*
* @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
* @param [inputarr] holds the input data to bind to. Null elements will be set to null.
* @return RecordSet or false
*/
function &Execute($sql,$inputarr=false)
{
if ($this->fnExecute) {
$fn = $this->fnExecute;
$ret =& $fn($this,$sql,$inputarr);
if (isset($ret)) return $ret;
}
if ($inputarr) {
#if (!is_array($inputarr)) $inputarr = array($inputarr);
$element0 = reset($inputarr);
# is_object check because oci8 descriptors can be passed in
if (is_array($element0) && !is_object(reset($element0))) {
if (is_string($sql))
$stmt = $this->Prepare($sql);
else
$stmt = $sql;
foreach($inputarr as $arr) {
$ret =& $this->_Execute($stmt,$arr);
if (!$ret) return $ret;
}
} else {
$ret =& $this->_Execute($sql,$inputarr);
}
} else {
$ret =& $this->_Execute($sql,false);
}
return $ret;
}
/*
Example of usage:
@ -633,14 +768,12 @@ NATSOFT.DOMAIN =
$sttype = @OCIStatementType($stmt);
if ($sttype == 'BEGIN' || $sttype == 'DECLARE') {
return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
}
}
return array($sql,$stmt,0,$BINDNUM);
}
/*
Call an oracle stored procedure and return a cursor variable.
Convert the cursor variable into a recordset.
Call an oracle stored procedure and returns a cursor variable as a recordset.
Concept by Robert Tuttle robert@ud.com
Example:
@ -655,17 +788,24 @@ NATSOFT.DOMAIN =
*/
function &ExecuteCursor($sql,$cursorName='rs',$params=false)
{
$stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
if (is_array($sql)) $stmt = $sql;
else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
if (is_array($stmt) && sizeof($stmt) >= 5) {
$hasref = true;
$this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
if ($params) {
foreach($params as $k => $v) {
$this->Parameter($stmt,$params[$k], $k);
}
}
}
return $this->Execute($stmt);
} else
$hasref = false;
$rs =& $this->Execute($stmt);
if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]);
else if ($hasref) $rs->_refcursor = $stmt[4];
return $rs;
}
/*
@ -716,25 +856,26 @@ NATSOFT.DOMAIN =
ADOConnection::outp("<b>Bind</b>: name = $name");
}
//we have to create a new Descriptor here
$numlob = count($this -> _refLOBs);
$this -> _refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));
$this -> _refLOBs[$numlob]['TYPE'] = $isOutput;
$numlob = count($this->_refLOBs);
$this->_refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));
$this->_refLOBs[$numlob]['TYPE'] = $isOutput;
$tmp = &$this -> _refLOBs[$numlob]['LOB'];
$tmp = &$this->_refLOBs[$numlob]['LOB'];
$rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type);
if ($this->debug) {
ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var binded");
ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded");
}
// if type is input then write data to lob now
if ($isOutput == false) {
$var = $this -> BlobEncode($var);
$tmp -> WriteTemporary($var);
$var = $this->BlobEncode($var);
$tmp->WriteTemporary($var);
$this->_refLOBs[$numlob]['VAR'] = &$var;
if ($this->debug) {
ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
}
} else {
$this -> _refLOBs[$numlob]['VAR'] = &$var;
$this->_refLOBs[$numlob]['VAR'] = &$var;
}
$rez = $tmp;
} else {
@ -791,12 +932,11 @@ NATSOFT.DOMAIN =
3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
$db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
$db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
$db->execute($stmt);
*/
function _query($sql,$inputarr)
{
if (is_array($sql)) { // is prepared sql
$stmt = $sql[1];
@ -812,7 +952,7 @@ NATSOFT.DOMAIN =
$bindarr = array();
foreach($inputarr as $k => $v) {
$bindarr[$k] = $v;
OCIBindByName($stmt,":$k",$bindarr[$k],4000);
OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
}
$this->_bind[$bindpos] = &$bindarr;
}
@ -861,9 +1001,14 @@ NATSOFT.DOMAIN =
}
//$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
$this -> _refLOBs[$key]['VAR'] = $tmp;
}
$this -> _refLOBs[$key]['LOB'] -> free();
unset($this -> _refLOBs[$key]);
} else {
$this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
$this -> _refLOBs[$key]['LOB']->free();
unset($this -> _refLOBs[$key]);
if ($this->debug) {
ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
}
}
}
}
@ -902,10 +1047,10 @@ NATSOFT.DOMAIN =
if (!$this->_connectionID) return;
if (!$this->autoCommit) OCIRollback($this->_connectionID);
if (count($this -> _refLOBs) > 0) {
foreach ($this -> _refLOBs as $key => $value) {
$this -> _refLOBs[$key] -> free();
unset($this -> _refLOBs[$key]);
if (count($this->_refLOBs) > 0) {
foreach ($this ->_refLOBs as $key => $value) {
$this->_refLOBs[$key]['LOB']->free();
unset($this->_refLOBs[$key]);
}
}
OCILogoff($this->_connectionID);
@ -1040,6 +1185,7 @@ class ADORecordset_oci8 extends ADORecordSet {
var $databaseType = 'oci8';
var $bind=false;
var $_fieldobjs;
//var $_arr = false;
function ADORecordset_oci8($queryID,$mode=false)
@ -1050,13 +1196,15 @@ class ADORecordset_oci8 extends ADORecordSet {
}
switch ($mode)
{
default:
case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_NUM:
default:
$this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
}
$this->adodbFetchMode = $mode;
$this->_queryID = $queryID;
}
@ -1160,6 +1308,39 @@ class ADORecordset_oci8 extends ADORecordSet {
return false;
}
/*
# does not work as first record is retrieved in _initrs(), so is not included in GetArray()
function &GetArray($nRows = -1)
{
global $ADODB_OCI8_GETARRAY;
if (true || !empty($ADODB_OCI8_GETARRAY)) {
# does not support $ADODB_ANSI_PADDING_OFF
//OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by OCIfetchstatement
switch($this->adodbFetchMode) {
case ADODB_FETCH_NUM:
$ncols = @OCIfetchstatement($this->_queryID, $results, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM);
$results = array_merge(array($this->fields),$results);
return $results;
case ADODB_FETCH_ASSOC:
if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break;
$ncols = @OCIfetchstatement($this->_queryID, $assoc, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW);
$results =& array_merge(array($this->fields),$assoc);
return $results;
default:
break;
}
}
$results =& ADORecordSet::GetArray($nRows);
return $results;
} */
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
@ -1215,7 +1396,11 @@ class ADORecordset_oci8 extends ADORecordSet {
function _close()
{
if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
OCIFreeStatement($this->_queryID);
if (!empty($this->_refcursor)) {
OCIFreeCursor($this->_refcursor);
$this->_refcursor = false;
}
@OCIFreeStatement($this->_queryID);
$this->_queryID = false;
}
@ -1274,13 +1459,13 @@ class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 {
}
switch ($mode)
{
default:
case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
case ADODB_FETCH_NUM:
default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
}
$this->adodbFetchMode = $mode;
$this->_queryID = $queryID;
}

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim. All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim. 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.
@ -151,11 +151,19 @@ class ADORecordset_oci8po extends ADORecordset_oci8 {
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) return $this->GetArray($nrows);
if ($offset <= 0) {
$arr = $this->GetArray($nrows);
return $arr;
}
for ($i=1; $i < $offset; $i++)
if (!@OCIFetch($this->_queryID)) return array();
if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
if (!@OCIFetch($this->_queryID)) {
$arr = array();
return $arr;
}
if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
$arr = array();
return $arr;
}
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
$results = array();
$cnt = 0;

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
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.
@ -45,6 +45,49 @@ class ADODB_odbc extends ADOConnection {
$this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
}
// returns true or false
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
if (!function_exists('odbc_connect')) return null;
if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {
ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
}
if (isset($php_errormsg)) $php_errormsg = '';
if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
return $this->_connectionID != false;
}
// returns true or false
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
if (!function_exists('odbc_connect')) return null;
if (isset($php_errormsg)) $php_errormsg = '';
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if ($this->debug && $argDatabasename) {
ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
}
// print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
return $this->_connectionID != false;
}
function ServerInfo()
{
@ -156,48 +199,6 @@ class ADODB_odbc extends ADOConnection {
}
// returns true or false
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
if (!function_exists('odbc_connect')) return null;
if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {
ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
}
if (isset($php_errormsg)) $php_errormsg = '';
if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
//if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
return $this->_connectionID != false;
}
// returns true or false
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
if (!function_exists('odbc_connect')) return null;
if (isset($php_errormsg)) $php_errormsg = '';
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if ($this->debug && $argDatabasename) {
ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
}
// print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
return $this->_connectionID != false;
}
function BeginTrans()
{
@ -274,8 +275,10 @@ class ADODB_odbc extends ADOConnection {
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
if (!$rs) {
$false = false;
return $false;
}
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr =& $rs->GetArray();
@ -300,6 +303,7 @@ class ADODB_odbc extends ADOConnection {
}
/*
See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp
/ SQL data type codes /
#define SQL_UNKNOWN_TYPE 0
#define SQL_CHAR 1
@ -315,6 +319,7 @@ class ADODB_odbc extends ADOConnection {
#endif
#define SQL_VARCHAR 12
/ One-parameter shortcuts for date/time data types /
#if (ODBCVER >= 0x0300)
#define SQL_TYPE_DATE 91
@ -340,13 +345,16 @@ class ADODB_odbc extends ADOConnection {
case -4: //image
return 'B';
case 9:
case 91:
case 11:
return 'D';
case 10:
case 11:
case 92:
case 93:
case 9: return 'T';
return 'T';
case 4:
case 5:
case -6:
@ -366,6 +374,7 @@ class ADODB_odbc extends ADOConnection {
{
global $ADODB_FETCH_MODE;
$false = false;
if ($this->uCaseTables) $table = strtoupper($table);
$schema = '';
$this->_findschema($table,$schema);
@ -411,15 +420,15 @@ class ADODB_odbc extends ADOConnection {
if (empty($qid)) $qid = odbc_columns($this->_connectionID);
break;
}
if (empty($qid)) return false;
if (empty($qid)) return $false;
$rs = new ADORecordSet_odbc($qid);
$rs =& new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
if (!$rs) return $false;
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$rs->_fetch();
$retarr = array();
/*
@ -438,8 +447,8 @@ class ADODB_odbc extends ADOConnection {
11 REMARKS
*/
while (!$rs->EOF) {
//adodb_pr($rs->fields);
if (strtoupper($rs->fields[2]) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
// adodb_pr($rs->fields);
if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[3];
$fld->type = $this->ODBCTypes($rs->fields[4]);
@ -464,6 +473,7 @@ class ADODB_odbc extends ADOConnection {
}
$rs->Close(); //-- crashes 4.03pl1 -- why?
if (empty($retarr)) $retarr = false;
return $retarr;
}
@ -681,11 +691,13 @@ class ADORecordSet_odbc extends ADORecordSet {
{
if ($this->_numOfRows != 0 && !$this->EOF) {
$this->_currentRow++;
$row = 0;
if ($this->_has_stupid_odbc_fetch_api_change)
$rez = @odbc_fetch_into($this->_queryID,$this->fields);
else
else {
$row = 0;
$rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
}
if ($rez) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
@ -700,12 +712,13 @@ class ADORecordSet_odbc extends ADORecordSet {
function _fetch()
{
$row = 0;
if ($this->_has_stupid_odbc_fetch_api_change)
$rez = @odbc_fetch_into($this->_queryID,$this->fields,$row);
else
$rez = @odbc_fetch_into($this->_queryID,$this->fields);
else {
$row = 0;
$rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
}
if ($rez) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
@ -722,5 +735,4 @@ class ADORecordSet_odbc extends ADORecordSet {
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -43,7 +43,7 @@ class ADODB_odbc_mssql extends ADODB_odbc {
function ADODB_odbc_mssql()
{
$this->ADODB_odbc();
$this->curmode = SQL_CUR_USE_ODBC;
//$this->curmode = SQL_CUR_USE_ODBC;
}
// crashes php...
@ -132,7 +132,8 @@ order by constraint_name, referenced_table_name, keyno";
function &MetaColumns($table)
{
return ADOConnection::MetaColumns($table);
$arr = ADOConnection::MetaColumns($table);
return $arr;
}
function _query($sql,$inputarr)
@ -163,7 +164,8 @@ order by constraint_name, referenced_table_name, keyno";
$ADODB_FETCH_MODE = $savem;
if ($a && sizeof($a)>0) return $a;
return false;
$false = false;
return $false;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -38,44 +38,41 @@ class ADODB_odbc_oracle extends ADODB_odbc {
function &MetaTables()
{
if ($this->metaTablesSQL) {
$rs = $this->Execute($this->metaTablesSQL);
if ($rs === false) return false;
$arr = $rs->GetArray();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
$arr2[] = $arr[$i][0];
}
$rs->Close();
return $arr2;
$false = false;
$rs = $this->Execute($this->metaTablesSQL);
if ($rs === false) return $false;
$arr = $rs->GetArray();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
$arr2[] = $arr[$i][0];
}
return false;
$rs->Close();
return $arr2;
}
function &MetaColumns($table)
{
if (!empty($this->metaColumnsSQL)) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
if ($rs === false) {
$false = false;
return $false;
}
return false;
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
// returns true or false

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -28,10 +28,10 @@ class ADODB_odbtp extends ADOConnection{
var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)";
var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'";
var $_autocommit = true;
var $_bindInputArray = false;
var $_useUnicodeSQL = false;
var $_canPrepareSP = false;
var $_dontPoolDBC = true;
function ADODB_odbtp()
{
@ -106,7 +106,7 @@ class ADODB_odbtp extends ADOConnection{
function GenID($seq='adodbseq',$start=1)
{
$seqtab='adodb_seq';
if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
if( $this->odbc_driver == ODB_DRIVER_FOXPRO) {
$path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );
//if using vfp dbc file
if( !strcasecmp(strrchr($path, '.'), '.dbc') )
@ -150,16 +150,31 @@ class ADODB_odbtp extends ADOConnection{
function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
{
$this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
if ($this->_connectionID === false)
{
if ($this->_connectionID === false) {
$this->_errorMsg = $this->ErrorMsg() ;
return false;
}
if ($this->_dontPoolDBC) {
if (function_exists('odbtp_dont_pool_dbc'))
@odbtp_dont_pool_dbc($this->_connectionID);
}
else {
$this->_dontPoolDBC = true;
}
$this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID);
$dbms = strtolower(@odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID));
$this->odbc_name = $dbms;
// Account for inconsistent DBMS names
if( $this->odbc_driver == ODB_DRIVER_ORACLE )
$dbms = 'oracle';
else if( $this->odbc_driver == ODB_DRIVER_SYBASE )
$dbms = 'sybase';
// Set driver specific attributes
switch( $this->odbc_driver ) {
case ODB_DRIVER_MSSQL:
// Set DBMS specific attributes
switch( $dbms ) {
case 'microsoft sql server':
$this->databaseType = 'odbtp_mssql';
$this->fmtDate = "'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
$this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
@ -176,8 +191,10 @@ class ADODB_odbtp extends ADOConnection{
$this->length = 'len';
$this->identitySQL = 'select @@IDENTITY';
$this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'";
$this->_canPrepareSP = true;
break;
case ODB_DRIVER_JET:
case 'access':
$this->databaseType = 'odbtp_access';
$this->fmtDate = "#Y-m-d#";
$this->fmtTimeStamp = "#Y-m-d h:i:sA#";
$this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
@ -185,24 +202,22 @@ class ADODB_odbtp extends ADOConnection{
$this->hasTop = 'top';
$this->hasTransactions = false;
$this->_canPrepareSP = true; // For MS Access only.
// Can't rebind ODB_CHAR to ODB_WCHAR if row cache enabled.
if ($this->_useUnicodeSQL)
odbtp_use_row_cache($this->_connectionID, FALSE, 0);
break;
case ODB_DRIVER_FOXPRO:
case 'visual foxpro':
$this->databaseType = 'odbtp_vfp';
$this->fmtDate = "{^Y-m-d}";
$this->fmtTimeStamp = "{^Y-m-d, h:i:sA}";
$this->sysDate = 'date()';
$this->sysTimeStamp = 'datetime()';
$this->ansiOuter = true;
$this->hasTop = 'top';
$this->hasTransactions = false;
$this->hasTransactions = false;
$this->replaceQuote = "'+chr(39)+'";
$this->true = '.T.';
$this->false = '.F.';
break;
case ODB_DRIVER_ORACLE:
case 'oracle':
$this->databaseType = 'odbtp_oci8';
$this->fmtDate = "'Y-m-d 00:00:00'";
$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
$this->sysDate = 'TRUNC(SYSDATE)';
@ -211,7 +226,8 @@ class ADODB_odbtp extends ADOConnection{
$this->_bindInputArray = true;
$this->concat_operator = '||';
break;
case ODB_DRIVER_SYBASE:
case 'sybase':
$this->databaseType = 'odbtp_sybase';
$this->fmtDate = "'Y-m-d'";
$this->fmtTimeStamp = "'Y-m-d H:i:s'";
$this->sysDate = 'GetDate()';
@ -223,22 +239,26 @@ class ADODB_odbtp extends ADOConnection{
$this->identitySQL = 'select @@IDENTITY';
break;
default:
$this->databaseType = 'odbtp';
if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) )
$this->hasTransactions = true;
$this->hasTransactions = true;
else
$this->hasTransactions = false;
}
@odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID );
if ($this->_useUnicodeSQL )
@odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID);
return true;
}
function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
{
$this->_dontPoolDBC = false;
return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase);
}
function SelectDB($dbName)
{
if (!@odbtp_select_db($dbName, $this->_connectionID)) {
@ -254,7 +274,11 @@ class ADODB_odbtp extends ADOConnection{
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
$arr =& $this->GetArray("||SQLTables||||$ttype");
if (isset($savefm)) $this->SetFetchMode($savefm);
$ADODB_FETCH_MODE = $savem;
$arr2 = array();
@ -276,11 +300,17 @@ class ADODB_odbtp extends ADOConnection{
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
$rs = $this->Execute( "||SQLColumns||$schema|$table" );
if (isset($savefm)) $this->SetFetchMode($savefm);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
if (!$rs || $rs->EOF) {
$false = false;
return $false;
}
while (!$rs->EOF) {
//print_r($rs->fields);
if (strtoupper($rs->fields[2]) == $table) {
@ -299,7 +329,7 @@ class ADODB_odbtp extends ADOConnection{
break;
$rs->MoveNext();
}
$rs->Close();
$rs->Close();
return $retarr;
}
@ -335,8 +365,11 @@ class ADODB_odbtp extends ADOConnection{
//print_r($constr);
$arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3];
}
if (!$arr) return false;
if (!$arr) {
$false = false;
return $false;
}
$arr2 = array();
foreach($arr as $k => $v) {
@ -353,10 +386,14 @@ class ADODB_odbtp extends ADOConnection{
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
$this->transCnt += 1;
$this->_autocommit = false;
$rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,ODB_TXN_READUNCOMMITTED,$this->_connectionID);
$this->autoCommit = false;
if (defined('ODB_TXN_DEFAULT'))
$txn = ODB_TXN_DEFAULT;
else
$txn = ODB_TXN_READUNCOMMITTED;
$rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,$txn,$this->_connectionID);
if(!$rs) return false;
else return true;
return true;
}
function CommitTrans($ok=true)
@ -364,8 +401,8 @@ class ADODB_odbtp extends ADOConnection{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->_autocommit = true;
if( ($ret = odbtp_commit($this->_connectionID)) )
$this->autoCommit = true;
if( ($ret = @odbtp_commit($this->_connectionID)) )
$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
return $ret;
}
@ -374,8 +411,8 @@ class ADODB_odbtp extends ADOConnection{
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->_autocommit = true;
if( ($ret = odbtp_rollback($this->_connectionID)) )
$this->autoCommit = true;
if( ($ret = @odbtp_rollback($this->_connectionID)) )
$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
return $ret;
}
@ -386,13 +423,14 @@ class ADODB_odbtp extends ADOConnection{
if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
}
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$ret =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $ret;
}
function Prepare($sql)
{
if (! $this->_bindInputArray) return $sql; // no binding
$stmt = odbtp_prepare($sql,$this->_connectionID);
$stmt = @odbtp_prepare($sql,$this->_connectionID);
if (!$stmt) {
// print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
return $sql;
@ -404,7 +442,7 @@ class ADODB_odbtp extends ADOConnection{
{
if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures
$stmt = odbtp_prepare_proc($sql,$this->_connectionID);
$stmt = @odbtp_prepare_proc($sql,$this->_connectionID);
if (!$stmt) return false;
return array($sql,$stmt);
}
@ -441,7 +479,7 @@ class ADODB_odbtp extends ADOConnection{
else {
$name = '@'.$name;
}
return odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen);
return @odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen);
}
/*
@ -457,13 +495,13 @@ class ADODB_odbtp extends ADOConnection{
function UpdateBlob($table,$column,$val,$where,$blobtype='image')
{
$sql = "UPDATE $table SET $column = ? WHERE $where";
if( !($stmt = odbtp_prepare($sql, $this->_connectionID)) )
if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) )
return false;
if( !odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )
if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )
return false;
if( !odbtp_set( $stmt, 1, $val ) )
if( !@odbtp_set( $stmt, 1, $val ) )
return false;
return odbtp_execute( $stmt ) != false;
return @odbtp_execute( $stmt ) != false;
}
function IfNull( $field, $ifNull )
@ -483,23 +521,23 @@ class ADODB_odbtp extends ADOConnection{
if (is_array($sql)) {
$stmtid = $sql[1];
} else {
$stmtid = odbtp_prepare($sql,$this->_connectionID);
$stmtid = @odbtp_prepare($sql,$this->_connectionID);
if ($stmtid == false) {
$this->_errorMsg = $php_errormsg;
return false;
}
}
$num_params = odbtp_num_params( $stmtid );
$num_params = @odbtp_num_params( $stmtid );
for( $param = 1; $param <= $num_params; $param++ ) {
@odbtp_input( $stmtid, $param );
@odbtp_set( $stmtid, $param, $inputarr[$param-1] );
}
if (! odbtp_execute($stmtid) ) {
if (!@odbtp_execute($stmtid) ) {
return false;
}
} else if (is_array($sql)) {
$stmtid = $sql[1];
if (!odbtp_execute($stmtid)) {
if (!@odbtp_execute($stmtid)) {
return false;
}
} else {
@ -540,6 +578,19 @@ class ADORecordSet_odbtp extends ADORecordSet {
$this->_numOfFields = @odbtp_num_fields($this->_queryID);
if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))
$this->_numOfRows = -1;
if (!$this->connection->_useUnicodeSQL) return;
if ($this->connection->odbc_driver == ODB_DRIVER_JET) {
if (!@odbtp_get_attr(ODB_ATTR_MAPCHARTOWCHAR,
$this->connection->_connectionID))
{
for ($f = 0; $f < $this->_numOfFields; $f++) {
if (@odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR)
@odbtp_bind_field($this->_queryID, $f, ODB_WCHAR);
}
}
}
}
function &FetchField($fieldOffset = 0)
@ -570,7 +621,7 @@ class ADORecordSet_odbtp extends ADORecordSet {
$this->bind[strtoupper($name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _fetch_odbtp($type=0)
@ -597,18 +648,18 @@ class ADORecordSet_odbtp extends ADORecordSet {
{
if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false;
$this->EOF = false;
$this->_currentRow = 0;
return true;
$this->_currentRow = 0;
return true;
}
function MoveLast()
{
function MoveLast()
{
if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false;
$this->EOF = false;
$this->_currentRow = $this->_numOfRows - 1;
return true;
}
return true;
}
function NextRecordSet()
{
if (!@odbtp_next_result($this->_queryID)) return false;
@ -625,4 +676,53 @@ class ADORecordSet_odbtp extends ADORecordSet {
}
}
?>
class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_mssql';
function ADORecordSet_odbtp_mssql($id,$mode=false)
{
return $this->ADORecordSet_odbtp($id,$mode);
}
}
class ADORecordSet_odbtp_access extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_access';
function ADORecordSet_odbtp_access($id,$mode=false)
{
return $this->ADORecordSet_odbtp($id,$mode);
}
}
class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_vfp';
function ADORecordSet_odbtp_vfp($id,$mode=false)
{
return $this->ADORecordSet_odbtp($id,$mode);
}
}
class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_oci8';
function ADORecordSet_odbtp_oci8($id,$mode=false)
{
return $this->ADORecordSet_odbtp($id,$mode);
}
}
class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_sybase';
function ADORecordSet_odbtp_sybase($id,$mode=false)
{
return $this->ADORecordSet_odbtp($id,$mode);
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -28,7 +28,7 @@ if (!defined('_ADODB_ODBTP_LAYER')) {
}
class ADODB_odbtp_unicode extends ADODB_odbtp {
var $databaseType = "odbtp_unicode";
var $databaseType = 'odbtp';
var $_useUnicodeSQL = true;
function ADODB_odbtp_unicode()
@ -36,27 +36,4 @@ class ADODB_odbtp_unicode extends ADODB_odbtp {
$this->ADODB_odbtp();
}
}
class ADORecordSet_odbtp_unicode extends ADORecordSet_odbtp {
var $databaseType = 'odbtp_unicode';
function ADORecordSet_odbtp_unicode($queryID,$mode=false)
{
$this->ADORecordSet_odbtp($queryID, $mode);
}
function _initrs()
{
$this->_numOfFields = @odbtp_num_fields($this->_queryID);
if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))
$this->_numOfRows = -1;
if ($this->connection->odbc_driver == ODB_DRIVER_JET) {
for ($f = 0; $f < $this->_numOfFields; $f++) {
if (odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR)
odbtp_bind_field($this->_queryID, $f, ODB_WCHAR);
}
}
}
}
?>
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -230,7 +230,7 @@ class ADORecordset_oracle extends ADORecordSet {
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function FetchField($fieldOffset = -1)
function &FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fld->name = ora_columnname($this->_queryID, $fieldOffset);

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
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.
@ -9,13 +9,91 @@ Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Requires ODBC. Works on Windows and Unix.
Problems:
Where is float/decimal type in pdo_param_type
LOB handling for CLOB/BLOB differs significantly
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
/*
enum pdo_param_type {
PDO_PARAM_NULL, 0
/* int as in long (the php native int type).
* If you mark a column as an int, PDO expects get_col to return
* a pointer to a long
PDO_PARAM_INT, 1
/* get_col ptr should point to start of the string buffer
PDO_PARAM_STR, 2
/* get_col: when len is 0 ptr should point to a php_stream *,
* otherwise it should behave like a string. Indicate a NULL field
* value by setting the ptr to NULL
PDO_PARAM_LOB, 3
/* get_col: will expect the ptr to point to a new PDOStatement object handle,
* but this isn't wired up yet
PDO_PARAM_STMT, 4 /* hierarchical result set
/* get_col ptr should point to a zend_bool
PDO_PARAM_BOOL, 5
/* magic flag to denote a parameter as being input/output
PDO_PARAM_INPUT_OUTPUT = 0x80000000
};
*/
function adodb_pdo_type($t)
{
switch($t) {
case 2: return 'VARCHAR';
case 3: return 'BLOB';
default: return 'NUMERIC';
}
}
/*--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------*/
////////////////////////////////////////////////
class ADODB_pdo_base extends ADODB_pdo {
function _init($parentDriver)
{
$parentDriver->_bindInputArray = false;
#$parentDriver->_connectionID->setAttribute(PDO_MYSQL_ATTR_USE_BUFFERED_QUERY,true);
}
function ServerInfo()
{
return ADOConnection::ServerInfo();
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $ret;
}
function MetaTables()
{
return false;
}
function MetaColumns()
{
return false;
}
}
class ADODB_pdo extends ADOConnection {
var $databaseType = "pdo";
@ -30,17 +108,51 @@ class ADODB_pdo extends ADOConnection {
var $_haserrorfunctions = true;
var $_lastAffectedRows = 0;
var $_errormsg = false;
var $_errorno = false;
var $dsnType = '';
var $stmt = false;
function ADODB_pdo()
function ADODB_pdo()
{
}
function _UpdatePDO()
{
$d = &$this->_driver;
$this->fmtDate = $d->fmtDate;
$this->fmtTimeStamp = $d->fmtTimeStamp;
$this->replaceQuote = $d->replaceQuote;
$this->sysDate = $d->sysDate;
$this->sysTimeStamp = $d->sysTimeStamp;
$this->random = $d->random;
$this->concat_operator = $d->concat_operator;
$d->_init($this);
}
function Time()
{
return false;
}
// returns true or false
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false)
{
$this->_connectionID = new PDO($argDSN, $argUsername, $argPassword);
$at = strpos($argDSN,':');
$this->dsnType = substr($argDSN,0,$at);
try {
$this->_connectionID = new PDO($argDSN, $argUsername, $argPassword);
} catch (Exception $e) {
$this->_connectionID = false;
$this->_errorno = -1;
//var_dump($e);
$this->_errormsg = 'Connection attempt failed: '.$e->getMessage();
return false;
}
if ($this->_connectionID) {
switch(ADODB_ASSOC_CASE){
case 0: $m = PDO_CASE_LOWER; break;
@ -52,10 +164,25 @@ class ADODB_pdo extends ADOConnection {
//$this->_connectionID->setAttribute(PDO_ATTR_ERRMODE,PDO_ERRMODE_SILENT );
$this->_connectionID->setAttribute(PDO_ATTR_CASE,$m);
$class = 'ADODB_pdo_'.$this->dsnType;
//$this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true);
switch($this->dsnType) {
case 'oci':
case 'mysql':
case 'pgsql':
include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
break;
}
if (class_exists($class))
$this->_driver = new $class();
else
$this->_driver = new ADODB_pdo_base();
$this->_driver->_connectionID = $this->_connectionID;
$this->_UpdatePDO();
return true;
}
$this->_driver = new ADODB_pdo_base();
return false;
}
@ -65,15 +192,32 @@ class ADODB_pdo extends ADOConnection {
return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true);
}
function ErrorMsg()
/*------------------------------------------------------------------------------*/
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$save = $this->_driver->fetchMode;
$this->_driver->fetchMode = $this->fetchMode;
$ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$this->_driver->fetchMode = $save;
return $ret;
}
function ServerInfo()
{
if ($this->_stmt) $arr = $this->_stmt->errorInfo();
else $arr = $this->_connectionID->errorInfo();
if ($arr) {
if ($arr[0]) return $arr[2];
else return '';
} else return '-1';
return $this->_driver->ServerInfo();
}
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
return $this->_driver->MetaTables($ttype,$showSchema,$mask);
}
function MetaColumns($table,$normalize=true)
{
return $this->_driver->MetaColumns($table,$normalize);
}
function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
@ -83,11 +227,36 @@ class ADODB_pdo extends ADOConnection {
else $obj->bindParam($name, $var);
}
function ErrorMsg()
{
if ($this->_errormsg !== false) return $this->_errormsg;
if (!empty($this->_stmt)) $arr = $this->_stmt->errorInfo();
else if (!empty($this->_connectionID)) $arr = $this->_connectionID->errorInfo();
else return 'No Connection Established';
if ($arr) {
if (sizeof($arr)<2) return '';
if ((integer)$arr[1]) return $arr[2];
else return '';
} else return '-1';
}
function ErrorNo()
{
if ($this->_stmt) return $this->_stmt->errorCode();
else return $this->_connectionID->errorInfo();
if ($this->_errorno !== false) return $this->_errorno;
if (!empty($this->_stmt)) $err = $this->_stmt->errorCode();
else if (!empty($this->_connectionID)) {
$arr = $this->_connectionID->errorInfo();
if (isset($arr[0])) $err = $arr[0];
else $err = -1;
} else
return 0;
if ($err == '00000') return 0; // allows empty check
return $err;
}
function BeginTrans()
@ -102,6 +271,7 @@ class ADODB_pdo extends ADOConnection {
function CommitTrans($ok=true)
{
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
@ -114,6 +284,7 @@ class ADODB_pdo extends ADOConnection {
function RollbackTrans()
{
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->_autocommit = true;
@ -145,14 +316,36 @@ class ADODB_pdo extends ADOConnection {
if (is_array($sql)) {
$stmt = $sql[1];
} else {
$stmt = $this->_connectionID->prepare($sql);
$stmt = $this->_connectionID->prepare($sql);
}
if ($stmt) {
if ($inputarr) $stmt->execute($inputarr);
else $stmt->execute();
if ($inputarr) $ok = $stmt->execute($inputarr);
else $ok = $stmt->execute();
}
$this->_errormsg = false;
$this->_errorno = false;
if ($ok) {
$this->_stmt = $stmt;
return $stmt;
}
$this->_stmt = $stmt;
return $stmt;
if ($stmt) {
$arr = $stmt->errorinfo();
if ((integer)$arr[1]) {
$this->_errormsg = $arr[2];
$this->_errorno = $arr[1];
}
} else {
$this->_errormsg = false;
$this->_errorno = false;
}
return false;
}
// returns true or false
@ -210,13 +403,18 @@ class ADOPDOStatement {
{
if ($this->_stmt) $arr = $this->_stmt->errorInfo();
else $arr = $this->_connectionID->errorInfo();
print_r($arr);
if ($arr) {
if ($arr[0]) return $arr[2];
if (is_array($arr)) {
if ((integer) $arr[0] && isset($arr[2])) return $arr[2];
else return '';
} else return '-1';
}
function NumCols()
{
return ($this->_stmt) ? $this->_stmt->columnCount() : 0;
}
function ErrorNo()
{
if ($this->_stmt) return $this->_stmt->errorCode();
@ -240,11 +438,13 @@ class ADORecordSet_pdo extends ADORecordSet {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->adodbFetchMode = $mode;
switch($mode) {
default:
case ADODB_FETCH_BOTH: $mode = PDO_FETCH_BOTH; break;
case ADODB_FETCH_NUM: $mode = PDO_FETCH_NUM; break;
case ADODB_FETCH_ASSOC: $mode = PDO_FETCH_ASSOC; break;
case ADODB_FETCH_BOTH:
default: $mode = PDO_FETCH_BOTH; break;
}
$this->fetchMode = $mode;
@ -252,21 +452,6 @@ class ADORecordSet_pdo extends ADORecordSet {
$this->ADORecordSet($id);
}
// returns the field object
function &FetchField($fieldOffset = -1)
{
$off=$fieldOffset+1; // offsets begin at 1
$o= new ADOFieldObject();
$o->name = @odbc_field_name($this->_queryID,$off);
$o->type = @odbc_field_type($this->_queryID,$off);
$o->max_length = @odbc_field_len($this->_queryID,$off);
if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
return $o;
}
function Init()
{
@ -282,21 +467,46 @@ class ADORecordSet_pdo extends ADORecordSet {
if ($this->EOF = ($this->_fetch() === false)) {
$this->_numOfRows = 0; // _numOfRows could be -1
}
$this->_numOfFields = sizeof($this->fields);
} else {
$this->EOF = true;
}
}
function _initrs()
{
global $ADODB_COUNTRECS;
$this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1;
if (!$this->_numOfRows) $this->_numOfRows = -1;
$this->_numOfFields =0;
}
$this->_numOfFields = $this->_queryID->columnCount();
}
// returns the field object
function &FetchField($fieldOffset = -1)
{
$off=$fieldOffset+1; // offsets begin at 1
$o= new ADOFieldObject();
$arr = @$this->_queryID->getColumnMeta($fieldOffset);
if (!$arr) {
$o->name = 'bad getColumnMeta()';
$o->max_length = -1;
$o->type = 'VARCHAR';
$o->precision = 0;
# $false = false;
return $o;
}
//adodb_pr($arr);
$o->name = $arr['name'];
if (isset($arr['native_type'])) $o->type = $arr['native_type'];
else $o->type = adodb_pdo_type($arr['pdo_type']);
$o->max_length = $arr['len'];
$o->precision = $arr['precision'];
if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
return $o;
}
function _seek($row)
{
@ -305,6 +515,8 @@ class ADORecordSet_pdo extends ADORecordSet {
function _fetch()
{
if (!$this->_queryID) return false;
$this->fields = $this->_queryID->fetch($this->fetchMode);
return !empty($this->fields);
}
@ -313,6 +525,20 @@ class ADORecordSet_pdo extends ADORecordSet {
{
$this->_queryID = false;
}
function Fields($colname)
{
if ($this->adodbFetchMode != ADODB_FETCH_NUM) return @$this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
}

View File

@ -0,0 +1,145 @@
<?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 8.
*/
class ADODB_pdo_mysql extends ADODB_pdo {
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
var $_bindInputArray = false;
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
function _init($parentDriver)
{
$parentDriver->hasTransactions = false;
$parentDriver->_bindInputArray = false;
$parentDriver->_connectionID->setAttribute(PDO_MYSQL_ATTR_USE_BUFFERED_QUERY,true);
}
function ServerInfo()
{
$arr['description'] = ADOConnection::GetOne("select version()");
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
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 =& ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
function &MetaColumns($table)
{
$this->_findschema($table,$schema);
if ($schema) {
$dbName = $this->database;
$this->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;
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
{
$offsetStr =($offset>=0) ? "$offset," : '';
// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
if ($nrows < 0) $nrows = '18446744073709551615';
if ($secs)
$rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
else
$rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
return $rs;
}
}
?>

View File

@ -0,0 +1,92 @@
<?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 8.
*/
class ADODB_pdo_oci extends ADODB_pdo_base {
var $concat_operator='||';
var $sysDate = "TRUNC(SYSDATE)";
var $sysTimeStamp = 'SYSDATE';
var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS'
var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";
var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno";
var $_initdate = true;
function _init($parentDriver)
{
$parentDriver->_bindInputArray = false;
if ($this->_initdate) {
$parentDriver->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
}
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtoupper($mask));
$this->metaTablesSQL .= " AND table_name like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
function &MetaColumns($table)
{
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) {
return $false;
}
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->scale = $rs->fields[3];
if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
$fld->type ='INT';
$fld->max_length = $rs->fields[4];
}
$fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
$fld->binary = (strpos($fld->type,'BLOB') !== false);
$fld->default_value = $rs->fields[6];
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
else $retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
if (empty($retarr))
return $false;
else
return $retarr;
}
}
?>

View File

@ -0,0 +1,228 @@
<?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 8.
*/
class ADODB_pdo_pgsql extends ADODB_pdo {
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\_%'";
//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
var $isoDates = true; // accepts dates in ISO format
var $sysDate = "CURRENT_DATE";
var $sysTimeStamp = "CURRENT_TIMESTAMP";
var $blobEncodeType = 'C';
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 $hasAffectedRows = true;
var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
// below suggested by Freek Dijkstra
var $true = 't'; // string that represents TRUE for a database
var $false = 'f'; // string that represents FALSE for a database
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $hasMoveFirst = true;
var $hasGenID = true;
var $_genIDSQL = "SELECT NEXTVAL('%s')";
var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
var $_dropSeqSQL = "DROP SEQUENCE %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";
var $random = 'random()'; /// random function
var $concat_operator='||';
function _init($parentDriver)
{
$parentDriver->hasTransactions = false;
}
function ServerInfo()
{
$arr['description'] = ADOConnection::GetOne("select version()");
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : '';
if ($secs2cache)
$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
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 =& ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
function &MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
$schema = 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) {
$false = 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];
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
if ($rs->fields[4] == $this->true) {
$fld->not_null = true;
}
// Freek
if (is_array($keys)) {
foreach($keys as $key) {
if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true)
$fld->primary_key = true;
if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true)
$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)) {
$false = false;
return $false;
} else return $retarr;
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -73,12 +73,13 @@ class ADODB_postgres64 extends ADOConnection{
var $blobEncodeType = 'C';
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 = 'r' AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
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 = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
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";
@ -90,8 +91,8 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
var $hasAffectedRows = true;
var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
// below suggested by Freek Dijkstra
var $true = 't'; // string that represents TRUE for a database
var $false = 'f'; // string that represents FALSE for a database
var $true = 'TRUE'; // string that represents TRUE for a database
var $false = 'FALSE'; // string that represents FALSE for a database
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $hasMoveFirst = true;
@ -101,10 +102,11 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
var $_dropSeqSQL = "DROP SEQUENCE %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";
var $random = 'random()'; /// random function
var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4
var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
// http://bugs.php.net/bug.php?id=25404
var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
// The last (fmtTimeStamp is not entirely correct:
// PostgreSQL also has support for time zones,
@ -128,12 +130,12 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
$this->version = $arr;
return $arr;
}
/*
function IfNull( $field, $ifNull )
{
return " NULLIF($field, $ifNull) "; // if PGSQL
return " coalesce($field, $ifNull) ";
}
*/
// get the last id - never tested
function pg_insert_id($tablename,$fieldname)
{
@ -175,10 +177,10 @@ a different OID if a database must be reloaded. */
return @pg_Exec($this->_connectionID, "begin");
}
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='1 as ignore')
{
if (!$this->transCnt) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
return $this->GetOne("select $flds from $tables where $where for update");
}
// returns true/false.
@ -200,12 +202,26 @@ a different OID if a database must be reloaded. */
}
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));
$this->metaTablesSQL = "
select tablename,'T' from pg_tables where tablename like $mask union
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 =& ADOConnection::MetaTables($ttype,$showSchema);
@ -289,6 +305,14 @@ select viewname,'V' from pg_views where viewname like $mask";
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
default:
// handle escape characters...
if ($ch == '\\') {
@ -333,6 +357,15 @@ select viewname,'V' from pg_views where viewname like $mask";
return $rez;
}
/*
Hueristic - not guaranteed to work.
*/
function GuessOID($oid)
{
if (strlen($oid)>16) return false;
return is_numeric($oid);
}
/*
* If an OID is detected, then we use pg_lo_* to open the oid file and read the
* real blob from the db using the oid supplied as a parameter. If you are storing
@ -341,20 +374,24 @@ select viewname,'V' from pg_views where viewname like $mask";
* contributed by Mattia Rossi mattia@technologist.com
*
* see http://www.postgresql.org/idocs/index.php?largeobjects.html
*
* Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
* added maxsize parameter, which defaults to $db->maxblobsize if not defined.
*/
function BlobDecode( $blob)
{
if (strlen($blob) > 24) return $blob;
function BlobDecode($blob,$maxsize=false,$hastrans=true)
{
if (!$this->GuessOID($blob)) return $blob;
@pg_exec($this->_connectionID,"begin");
if ($hastrans) @pg_exec($this->_connectionID,"begin");
$fd = @pg_lo_open($this->_connectionID,$blob,"r");
if ($fd === false) {
@pg_exec($this->_connectionID,"commit");
if ($hastrans) @pg_exec($this->_connectionID,"commit");
return $blob;
}
$realblob = @pg_loreadall($fd);
if (!$maxsize) $maxsize = $this->maxblobsize;
$realblob = @pg_loread($fd,$maxsize);
@pg_loclose($fd);
@pg_exec($this->_connectionID,"commit");
if ($hastrans) @pg_exec($this->_connectionID,"commit");
return $realblob;
}
@ -377,8 +414,13 @@ select viewname,'V' from pg_views where viewname like $mask";
// note that there is a pg_escape_bytea function only for php 4.2.0 or later
}
// assumes bytea for blob, and varchar for clob
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
{
if ($blobtype == 'CLOB') {
return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
}
// do not use bind params which uses qstr(), as blobencode() already quotes data
return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
}
@ -397,6 +439,7 @@ select viewname,'V' from pg_views where viewname like $mask";
global $ADODB_FETCH_MODE;
$schema = false;
$false = false;
$this->_findschema($table,$schema);
if ($normalize) $table = strtolower($table);
@ -410,8 +453,9 @@ select viewname,'V' from pg_views where viewname like $mask";
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
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
@ -443,8 +487,10 @@ select viewname,'V' from pg_views where viewname like $mask";
$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,-1);
$s = substr($s, 1);
$s = substr($s, 0, strlen($s) - 1);
}
$rsdefa[$num] = $s;
$rsdef->MoveNext();
}
@ -455,7 +501,7 @@ select viewname,'V' from pg_views where viewname like $mask";
}
$retarr = array();
while (!$rs->EOF) {
while (!$rs->EOF) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
@ -474,16 +520,16 @@ select viewname,'V' from pg_views where viewname like $mask";
}
//Freek
if ($rs->fields[4] == $this->true) {
if ($rs->fields[4] == 't') {
$fld->not_null = true;
}
// Freek
if (is_array($keys)) {
foreach($keys as $key) {
if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true)
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'] == $this->true)
if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
$fld->unique = true; // What name is more compatible?
}
}
@ -494,7 +540,10 @@ select viewname,'V' from pg_views where viewname like $mask";
$rs->MoveNext();
}
$rs->Close();
return $retarr;
if (empty($retarr))
return $false;
else
return $retarr;
}
@ -539,7 +588,8 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')';
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
$false = false;
return $false;
}
$col_names = $this->MetaColumnNames($table,true);
@ -580,6 +630,7 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')';
if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
else $str = 'host=localhost';
if (isset($host[1])) $str .= " port=$host[1]";
else if (!empty($this->port)) $str .= " port=".$this->port;
}
if ($user) $str .= " user=".$user;
if ($pwd) $str .= " password=".$pwd;
@ -714,7 +765,7 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')';
if (!empty($this->_connectionID)) {
$this->_errorMsg = @pg_last_error($this->_connectionID);
} else $this->_errorMsg = DB_ERROR_CONNECT_FAILED;
} else $this->_errorMsg = @pg_last_error();
} else {
if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();
else $this->_errorMsg = @pg_errormessage($this->_connectionID);
@ -782,10 +833,12 @@ class ADORecordSet_postgres64 extends ADORecordSet{
{
case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;
case ADODB_FETCH_BOTH:
default: $this->fetchMode = PGSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
@ -804,6 +857,8 @@ class ADORecordSet_postgres64 extends ADORecordSet{
$this->_numOfFields = @pg_numfields($qid);
// cache types for blob decode check
// apparently pg_fieldtype actually performs an sql query on the database to get the type.
if (empty($this->connection->noBlobs))
for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
if (pg_fieldtype($qid,$i) == 'bytea') {
$this->_blobArr[$i] = pg_fieldname($qid,$i);
@ -888,7 +943,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
return (is_array($this->fields));
}
@ -914,6 +969,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{
case 'NAME':
case 'BPCHAR':
case '_VARCHAR':
case 'INET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
@ -945,8 +1001,8 @@ class ADORecordSet_postgres64 extends ADORecordSet{
case 'INT8':
case 'INT4':
case 'INT2':
if (!is_object($fieldobj) || !$fieldobj->primary_key || !$fieldobj->unique ||
!$fieldobj->has_default || substr($fieldobj->default_value,0,8) != 'nextval(') return 'I';
if (isset($fieldobj) &&
empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
case 'OID':
case 'SERIAL':
@ -958,4 +1014,4 @@ class ADORecordSet_postgres64 extends ADORecordSet{
}
}
?>
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -90,41 +90,6 @@ function MetaForeignKeys($table, $owner=false, $upper=false)
}
function xMetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = '
SELECT t.tgargs as args
FROM pg_trigger t,
pg_class c,
pg_class c2,
pg_proc f
WHERE t.tgenabled
AND t.tgrelid=c.oid
AND t.tgconstrrelid=c2.oid
AND t.tgfoid=f.oid
AND f.proname ~ \'^RI_FKey_check_ins\'
AND t.tgargs like \'$1\\\000'.strtolower($table).'%\'
ORDER BY t.tgrelid';
$rs = $this->Execute($sql);
if ($rs && !$rs->EOF) {
$arr =& $rs->GetArray();
$a = array();
foreach($arr as $v) {
$data = explode(chr(0), $v['args']);
if ($upper) {
$a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5]));
} else {
$a[] = array($data[2] => $data[4].'='.$data[5]);
}
}
return $a;
}
else return false;
}
// this is a set of functions for managing client encoding - very important if the encodings
// of your database and your output target (i.e. HTML) don't match

View File

@ -0,0 +1,12 @@
<?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.
NOTE: The "postgres8" driver is remapped to "postgres7".
*/
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -30,7 +30,7 @@ class ADODB_SAPDB extends ADODB_odbc {
var $fmtTimeStamp = "'Y-m-d H:i:s'"; /// used by DBTimeStamp as the default timestamp fmt.
var $hasInsertId = true;
var $_bindInputArray = true;
function ADODB_SAPDB()
{
//if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
@ -181,4 +181,4 @@ class ADORecordSet_sapdb extends ADORecordSet_odbc {
}
} //define
?>
?>

View File

@ -1,6 +1,6 @@
<?php
/*
version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights
version 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,

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -109,7 +109,10 @@ class ADODB_sqlite extends ADOConnection {
global $ADODB_FETCH_MODE;
$rs = $this->Execute("select * from $tab limit 1");
if (!$rs) return false;
if (!$rs) {
$false = false;
return $false;
}
$arr = array();
for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) {
$fld =& $rs->FetchField($i);
@ -131,6 +134,7 @@ class ADODB_sqlite extends ADOConnection {
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!function_exists('sqlite_open')) return null;
if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename;
$this->_connectionID = sqlite_open($argHostname);
if ($this->_connectionID === false) return false;
@ -142,6 +146,7 @@ class ADODB_sqlite extends ADOConnection {
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!function_exists('sqlite_open')) return null;
if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename;
$this->_connectionID = sqlite_popen($argHostname);
if ($this->_connectionID === false) return false;
@ -187,7 +192,7 @@ class ADODB_sqlite extends ADOConnection {
$MAXLOOPS = 100;
//$this->debug=1;
while (--$MAXLOOPS>=0) {
$num = $this->GetOne("select id from $seq");
@($num = $this->GetOne("select id from $seq"));
if ($num === false) {
$this->Execute(sprintf($this->_genSeqSQL ,$seq));
$start -= 1;
@ -231,6 +236,51 @@ class ADODB_sqlite extends ADOConnection {
return @sqlite_close($this->_connectionID);
}
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;
}
}
@ -255,6 +305,7 @@ class ADORecordset_sqlite extends ADORecordSet {
case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;
default: $this->fetchMode = SQLITE_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->_queryID = $queryID;

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim. All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim. 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.
@ -20,7 +20,7 @@ if (!defined('ADODB_DIR')) die();
class ADODB_sybase extends ADOConnection {
var $databaseType = "sybase";
//var $dataProvider = 'sybase';
var $dataProvider = 'sybase';
var $replaceQuote = "''"; // string to use to replace quotes
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
@ -86,15 +86,16 @@ class ADODB_sybase extends ADOConnection {
}
// http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
function RowLock($tables,$where)
function RowLock($tables,$where,$flds='top 1 null as ignore')
{
if (!$this->_hastrans) $this->BeginTrans();
$tables = str_replace(',',' HOLDLOCK,',$tables);
return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");
return $this->GetOne("select $flds from $tables HOLDLOCK where $where");
}
function SelectDB($dbName) {
function SelectDB($dbName)
{
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @sybase_select_db($dbName);
@ -105,10 +106,14 @@ class ADODB_sybase extends ADOConnection {
/* Returns: the last error message from previous database operation
Note: This function is NOT available for Microsoft SQL Server. */
function ErrorMsg()
function ErrorMsg()
{
if ($this->_logsql) return $this->_errorMsg;
$this->_errorMsg = sybase_get_last_message();
if (function_exists('sybase_get_last_message'))
$this->_errorMsg = sybase_get_last_message();
else
$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : 'SYBASE error messages not supported on this platform';
return $this->_errorMsg;
}
@ -151,12 +156,12 @@ class ADODB_sybase extends ADOConnection {
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $rs;
}
$cnt = ($nrows > 0) ? $nrows : 0;
$cnt = ($nrows >= 0) ? $nrows : 999999999;
if ($offset > 0 && $cnt) $cnt += $offset;
$this->Execute("set rowcount $cnt");
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0);
$this->Execute("set rowcount 0");
$this->Execute("set rowcount 0");
return $rs;
}
@ -283,7 +288,7 @@ class ADORecordset_sybase extends ADORecordSet {
}
if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
else $this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
$this->ADORecordSet($id,$mode);
}
/* Returns: an object containing field information.

View File

@ -0,0 +1,115 @@
<?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.
Contributed by Interakt Online. Thx Cristian MARIN cristic#interaktonline.com
*/
class ADODB_sybase_ase extends ADODB_sybase {
var $databaseType = "sybase_ase";
var $metaTablesSQL="SELECT sysobjects.name FROM sysobjects, sysusers WHERE sysobjects.type='U' AND sysobjects.uid = sysusers.uid";
var $metaColumnsSQL = "SELECT syscolumns.name AS field_name, systypes.name AS type, systypes.length AS width FROM sysobjects, syscolumns, systypes WHERE sysobjects.name='%s' AND syscolumns.id = sysobjects.id AND systypes.type=syscolumns.type";
var $metaDatabasesSQL ="SELECT a.name FROM master.dbo.sysdatabases a, master.dbo.syslogins b WHERE a.suid = b.suid and a.name like '%' and a.name != 'tempdb' and a.status3 != 256 order by 1";
function ADODB_sybase_ase()
{
}
// split the Views, Tables and procedures.
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$false = false;
if ($this->metaTablesSQL) {
// complicated state saving by the need for backward compat
if ($ttype == 'VIEWS'){
$sql = str_replace('U', 'V', $this->metaTablesSQL);
}elseif (false === $ttype){
$sql = str_replace('U',"U' OR type='V", $this->metaTablesSQL);
}else{ // TABLES OR ANY OTHER
$sql = $this->metaTablesSQL;
}
$rs = $this->Execute($sql);
if ($rs === false || !method_exists($rs, 'GetArray')){
return $false;
}
$arr =& $rs->GetArray();
$arr2 = array();
foreach($arr as $key=>$value){
$arr2[] = trim($value['name']);
}
return $arr2;
}
return $false;
}
function MetaDatabases()
{
$arr = array();
if ($this->metaDatabasesSQL!='') {
$rs = $this->Execute($this->metaDatabasesSQL);
if ($rs && !$rs->EOF){
while (!$rs->EOF){
$arr[] = $rs->Fields('name');
$rs->MoveNext();
}
return $arr;
}
}
return false;
}
// fix a bug which prevent the metaColumns query to be executed for Sybase ASE
function &MetaColumns($table,$upper=false)
{
$false = false;
if (!empty($this->metaColumnsSQL)) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($rs === false) return $false;
$retarr = array();
while (!$rs->EOF) {
$fld =& new ADOFieldObject();
$fld->name = $rs->Fields('field_name');
$fld->type = $rs->Fields('type');
$fld->max_length = $rs->Fields('width');
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return $false;
}
function getProcedureList($schema)
{
return false;
}
function ErrorMsg()
{
if (!function_exists('sybase_connect')){
return 'Your PHP doesn\'t contain the Sybase connection module!';
}
return parent::ErrorMsg();
}
}
class adorecordset_sybase_ase extends ADORecordset_sybase {
var $databaseType = "sybase_ase";
function ADORecordset_sybase_ase($id,$mode=false)
{
$this->ADORecordSet_sybase($id,$mode);
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -32,7 +32,7 @@ class ADODB_vfp extends ADODB_odbc {
var $sysDate = 'date()';
var $ansiOuter = true;
var $hasTransactions = false;
var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
var $curmode = false ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
function ADODB_vfp()
{
@ -58,7 +58,8 @@ class ADODB_vfp extends ADODB_odbc {
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
$this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false;
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $ret;
}

View File

@ -0,0 +1,34 @@
<?php
// by "El-Shamaa, Khaled" <k.el-shamaa#cgiar.org>
$ADODB_LANG_ARRAY = array (
'LANG' => 'ar',
DB_ERROR => 'خطأ غير محدد',
DB_ERROR_ALREADY_EXISTS => 'موجود مسبقا',
DB_ERROR_CANNOT_CREATE => 'لا يمكن إنشاء',
DB_ERROR_CANNOT_DELETE => 'لا يمكن حذف',
DB_ERROR_CANNOT_DROP => 'لا يمكن حذف',
DB_ERROR_CONSTRAINT => 'عملية إدخال ممنوعة',
DB_ERROR_DIVZERO => 'عملية التقسيم على صفر',
DB_ERROR_INVALID => 'غير صحيح',
DB_ERROR_INVALID_DATE => 'صيغة وقت أو تاريخ غير صحيحة',
DB_ERROR_INVALID_NUMBER => 'صيغة رقم غير صحيحة',
DB_ERROR_MISMATCH => 'غير متطابق',
DB_ERROR_NODBSELECTED => 'لم يتم إختيار قاعدة البيانات بعد',
DB_ERROR_NOSUCHFIELD => 'ليس هنالك حقل بهذا الاسم',
DB_ERROR_NOSUCHTABLE => 'ليس هنالك جدول بهذا الاسم',
DB_ERROR_NOT_CAPABLE => 'قاعدة البيانات المرتبط بها غير قادرة',
DB_ERROR_NOT_FOUND => 'لم يتم إيجاده',
DB_ERROR_NOT_LOCKED => 'غير مقفول',
DB_ERROR_SYNTAX => 'خطأ في الصيغة',
DB_ERROR_UNSUPPORTED => 'غير مدعوم',
DB_ERROR_VALUE_COUNT_ON_ROW => 'عدد القيم في السجل',
DB_ERROR_INVALID_DSN => 'DNS غير صحيح',
DB_ERROR_CONNECT_FAILED => 'فشل عملية الإتصال',
0 => 'ليس هنالك أخطاء', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'البيانات المزودة غير كافية',
DB_ERROR_EXTENSION_NOT_FOUND=> 'لم يتم إيجاد الإضافة المتعلقة',
DB_ERROR_NOSUCHDB => 'ليس هنالك قاعدة بيانات بهذا الاسم',
DB_ERROR_ACCESS_VIOLATION => 'سماحيات غير كافية'
);
?>

View File

@ -0,0 +1,33 @@
<?php
// Arne Eckmann bananstat#users.sourceforge.net
$ADODB_LANG_ARRAY = array (
'LANG' => 'da',
DB_ERROR => 'ukendt fejl',
DB_ERROR_ALREADY_EXISTS => 'eksisterer allerede',
DB_ERROR_CANNOT_CREATE => 'kan ikke oprette',
DB_ERROR_CANNOT_DELETE => 'kan ikke slette',
DB_ERROR_CANNOT_DROP => 'kan ikke droppe',
DB_ERROR_CONSTRAINT => 'begr&aelig;nsning kr&aelig;nket',
DB_ERROR_DIVZERO => 'division med nul',
DB_ERROR_INVALID => 'ugyldig',
DB_ERROR_INVALID_DATE => 'ugyldig dato eller klokkeslet',
DB_ERROR_INVALID_NUMBER => 'ugyldigt tal',
DB_ERROR_MISMATCH => 'mismatch',
DB_ERROR_NODBSELECTED => 'ingen database valgt',
DB_ERROR_NOSUCHFIELD => 'felt findes ikke',
DB_ERROR_NOSUCHTABLE => 'tabel findes ikke',
DB_ERROR_NOT_CAPABLE => 'DB backend opgav',
DB_ERROR_NOT_FOUND => 'ikke fundet',
DB_ERROR_NOT_LOCKED => 'ikke l&aring;st',
DB_ERROR_SYNTAX => 'syntaksfejl',
DB_ERROR_UNSUPPORTED => 'ikke underst&oslash;ttet',
DB_ERROR_VALUE_COUNT_ON_ROW => 'resulterende antal felter svarer ikke til foresp&oslash;rgslens antal felter',
DB_ERROR_INVALID_DSN => 'ugyldig DSN',
DB_ERROR_CONNECT_FAILED => 'tilslutning mislykkedes',
0 => 'ingen fejl', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'utilstr&aelig;kkelige data angivet',
DB_ERROR_EXTENSION_NOT_FOUND=> 'udvidelse ikke fundet',
DB_ERROR_NOSUCHDB => 'database ikke fundet',
DB_ERROR_ACCESS_VIOLATION => 'utilstr&aelig;kkelige rettigheder'
);
?>

View File

@ -22,8 +22,7 @@ $ADODB_LANG_ARRAY = array (
DB_ERROR_SYNTAX => 'error de sintaxis',
DB_ERROR_UNSUPPORTED => 'no soportado',
DB_ERROR_VALUE_COUNT_ON_ROW => 'la cantidad de columnas no corresponden a la cantidad de valores',
DB_ERROR_INVALID_DSN
=> 'DSN invalido',
DB_ERROR_INVALID_DSN => 'DSN invalido',
DB_ERROR_CONNECT_FAILED => 'fallo la conexion',
0 => 'sin error', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'insuficientes datos',

View File

@ -0,0 +1,35 @@
<?php
// Vivu Esperanto cxiam!
// Traduko fare de Antono Vasiljev (anders[#]brainactive.org)
$ADODB_LANG_ARRAY = array (
'LANG' => 'eo',
DB_ERROR => 'nekonata eraro',
DB_ERROR_ALREADY_EXISTS => 'jam ekzistas',
DB_ERROR_CANNOT_CREATE => 'maleblas krei',
DB_ERROR_CANNOT_DELETE => 'maleblas elimini',
DB_ERROR_CANNOT_DROP => 'maleblas elimini (drop)',
DB_ERROR_CONSTRAINT => 'rompo de kondicxoj de provo',
DB_ERROR_DIVZERO => 'divido per 0 (nul)',
DB_ERROR_INVALID => 'malregule',
DB_ERROR_INVALID_DATE => 'malregula dato kaj tempo',
DB_ERROR_INVALID_NUMBER => 'malregula nombro',
DB_ERROR_MISMATCH => 'eraro',
DB_ERROR_NODBSELECTED => 'datumbazo ne elektita',
DB_ERROR_NOSUCHFIELD => 'ne ekzistas kampo',
DB_ERROR_NOSUCHTABLE => 'ne ekzistas tabelo',
DB_ERROR_NOT_CAPABLE => 'DBMS ne povas',
DB_ERROR_NOT_FOUND => 'ne trovita',
DB_ERROR_NOT_LOCKED => 'ne blokita',
DB_ERROR_SYNTAX => 'sintaksa eraro',
DB_ERROR_UNSUPPORTED => 'ne apogata',
DB_ERROR_VALUE_COUNT_ON_ROW => 'nombrilo de valoroj en linio',
DB_ERROR_INVALID_DSN => 'malregula DSN-o',
DB_ERROR_CONNECT_FAILED => 'konekto malsukcesa',
0 => 'cxio bone', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'ne suficxe da datumo',
DB_ERROR_EXTENSION_NOT_FOUND=> 'etendo ne trovita',
DB_ERROR_NOSUCHDB => 'datumbazo ne ekzistas',
DB_ERROR_ACCESS_VIOLATION => 'ne suficxe da rajto por atingo'
);
?>

View File

@ -0,0 +1,34 @@
<?php
# Hungarian language, encoding by ISO 8859-2 charset (Iso Latin-2)
# Halászvári Gábor <g.halaszvari#portmax.hu>
$ADODB_LANG_ARRAY = array (
'LANG' => 'hu',
DB_ERROR => 'ismeretlen hiba',
DB_ERROR_ALREADY_EXISTS => 'már létezik',
DB_ERROR_CANNOT_CREATE => 'nem sikerült létrehozni',
DB_ERROR_CANNOT_DELETE => 'nem sikerült törölni',
DB_ERROR_CANNOT_DROP => 'nem sikerült eldobni',
DB_ERROR_CONSTRAINT => 'szabályok megszegése',
DB_ERROR_DIVZERO => 'osztás nullával',
DB_ERROR_INVALID => 'érvénytelen',
DB_ERROR_INVALID_DATE => 'érvénytelen dátum vagy idõ',
DB_ERROR_INVALID_NUMBER => 'érvénytelen szám',
DB_ERROR_MISMATCH => 'nem megfelelõ',
DB_ERROR_NODBSELECTED => 'nincs kiválasztott adatbázis',
DB_ERROR_NOSUCHFIELD => 'nincs ilyen mezõ',
DB_ERROR_NOSUCHTABLE => 'nincs ilyen tábla',
DB_ERROR_NOT_CAPABLE => 'DB backend nem támogatja',
DB_ERROR_NOT_FOUND => 'nem található',
DB_ERROR_NOT_LOCKED => 'nincs lezárva',
DB_ERROR_SYNTAX => 'szintaktikai hiba',
DB_ERROR_UNSUPPORTED => 'nem támogatott',
DB_ERROR_VALUE_COUNT_ON_ROW => 'soron végzett érték számlálás',
DB_ERROR_INVALID_DSN => 'hibás DSN',
DB_ERROR_CONNECT_FAILED => 'sikertelen csatlakozás',
0 => 'nincs hiba', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'túl kevés az adat',
DB_ERROR_EXTENSION_NOT_FOUND=> 'bõvítmény nem található',
DB_ERROR_NOSUCHDB => 'nincs ilyen adatbázis',
DB_ERROR_ACCESS_VIOLATION => 'nincs jogosultság'
);
?>

View File

@ -0,0 +1,35 @@
<?php
// Ukrainian language file contributed by Alex Rootoff rootoff{AT}pisem.net.
$ADODB_LANG_ARRAY = array (
'LANG' => 'uk1251',
DB_ERROR => 'невідома помилка',
DB_ERROR_ALREADY_EXISTS => 'вже існує',
DB_ERROR_CANNOT_CREATE => 'неможливо створити',
DB_ERROR_CANNOT_DELETE => 'неможливо видалити',
DB_ERROR_CANNOT_DROP => 'неможливо знищити (drop)',
DB_ERROR_CONSTRAINT => 'порушення умов перевірки',
DB_ERROR_DIVZERO => 'ділення на 0',
DB_ERROR_INVALID => 'неправильно',
DB_ERROR_INVALID_DATE => 'неправильна дата чи час',
DB_ERROR_INVALID_NUMBER => 'неправильне число',
DB_ERROR_MISMATCH => 'помилка',
DB_ERROR_NODBSELECTED => 'не вибрано БД',
DB_ERROR_NOSUCHFIELD => 'не існує поле',
DB_ERROR_NOSUCHTABLE => 'не існує таблиця',
DB_ERROR_NOT_CAPABLE => 'СУБД не в стані',
DB_ERROR_NOT_FOUND => 'не знайдено',
DB_ERROR_NOT_LOCKED => 'не заблоковано',
DB_ERROR_SYNTAX => 'синтаксична помилка',
DB_ERROR_UNSUPPORTED => 'не підтримується',
DB_ERROR_VALUE_COUNT_ON_ROW => 'рахівник значень в стрічці',
DB_ERROR_INVALID_DSN => 'неправильна DSN',
DB_ERROR_CONNECT_FAILED => 'з\'єднання неуспішне',
0 => 'все гаразд', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'надано недостатньо даних',
DB_ERROR_EXTENSION_NOT_FOUND=> 'розширення не знайдено',
DB_ERROR_NOSUCHDB => 'не існує БД',
DB_ERROR_ACCESS_VIOLATION => 'недостатньо прав доступа'
);
?>

View File

@ -82,7 +82,6 @@ class Auth_Container_ADOdb extends Auth_Container
} else {
// Extract db_type from dsn string.
$this->options['dsn'] = $dsn;
$this->_parseDsn( $dsn );
}
}
@ -100,22 +99,12 @@ class Auth_Container_ADOdb extends Auth_Container
{
if (is_string($dsn) || is_array($dsn)) {
if(!$this->db) {
$this->db = &ADONewConnection($this->options['db_type']);
$this->db = &ADONewConnection($dsn);
if( $err = ADODB_Pear_error() ) {
return PEAR::raiseError($err);
}
}
$dbconnected = $this->db->Connect(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name'] );
if( !$dbconnected ) {
PEAR::raiseError('Unable to connect to database' );
}
} else {
return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
41,
@ -410,23 +399,11 @@ class Auth_Container_ADOdb extends Auth_Container
}
// }}}
function _parseDsn( $dsn )
{
if( is_string( $dsn )) {
preg_match( '/^(\w*):\/\/(\w*)(:(\w*))?@(\w*)\/(\w*)$/', $dsn, $match );
$this->options['db_type'] = $match[1];
$this->options['db_user'] = $match[2];
$this->options['db_pass'] = $match[3];
$this->options['db_host'] = $match[5];
$this->options['db_name'] = $match[6];
}
}
}
function showDbg( $string ) {
print "<P>$string</P>";
print "
-- $string</P>";
}
function dump( $var, $str, $vardump = false ) {
print "<H4>$str</H4><pre>";

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -132,7 +132,11 @@ class perf_mysql extends adodb_perf{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
@ -157,7 +161,11 @@ class perf_mysql extends adodb_perf{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
@ -185,7 +193,17 @@ class perf_mysql extends adodb_perf{
{
// first find out type of table
//$this->conn->debug=1;
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show table status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return '';
$type = strtoupper($rs->fields[1]);
$rs->Close();
@ -209,7 +227,7 @@ class perf_mysql extends adodb_perf{
$total += $this->_DBParameter(array("show status","Qcache_not_cached"));
$total += $hits;
if ($total) return ($hits*100)/$total;
if ($total) return round(($hits*100)/$total,2);
return 0;
}
@ -227,9 +245,17 @@ class perf_mysql extends adodb_perf{
*/
function GetInnoDBHitRatio()
{
global $HTTP_SESSION_VARS;
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show innodb status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs || $rs->EOF) return 0;
$stat = $rs->fields[0];
$rs->Close();
@ -237,10 +263,10 @@ class perf_mysql extends adodb_perf{
$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];
$HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;
return $val;
$_SESSION['INNODB_HIT_PCT'] = $val;
return round($val,2);
} else {
if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];
if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
return 0;
}
return 0;
@ -252,8 +278,38 @@ class perf_mysql extends adodb_perf{
$reqs = $this->_DBParameter(array("show status","Key_reads"));
if ($reqs == 0) return 0;
return ($hits/($reqs+$hits))*100;
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;
$conn = $this->conn;
if ( !$conn) 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)
ADOConnection::outp( sprintf( "<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, __FUNCTION__, $mode));
return false;
}
}
$sql = sprintf( $sql, $table);
return $conn->Execute( $sql) !== false;
}
// end hack
}
?>

View File

@ -1,6 +1,6 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -263,6 +263,7 @@ CREATE TABLE PLAN_TABLE (
$this->conn->BeginTrans();
$id = "ADODB ".microtime();
$rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
$m = $this->conn->ErrorMsg();
if ($m) {
@ -271,7 +272,7 @@ CREATE TABLE PLAN_TABLE (
$s .= "<p>$m</p>";
return $s;
}
$rs = $this->conn->Execute("
$rs =& $this->conn->Execute("
select
'<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>' as Operation,
object_name,COST,CARDINALITY,bytes
@ -345,7 +346,7 @@ select a.size_for_estimate as cache_mb_estimate,
$check = $rs->fields[0].'::'.$rs->fields[1];
} else
$sql .= $rs->fields[2];
if (substr($sql,strlen($sql)-1) == "\0") $sql = substr($sql,0,strlen($sql)-1);
$rs->MoveNext();
}
$rs->Close();
@ -402,28 +403,33 @@ where
order by
1 desc, s.address, p.piece";
global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) {
$partial = empty($HTTP_GET_VARS['part']);
echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
global $ADODB_CACHE_MODE;
if (isset($_GET['expsixora']) && isset($_GET['sql'])) {
$partial = empty($_GET['part']);
echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
}
if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL();
if (isset($_GET['sql'])) return $this->_SuspiciousSQL($numsql);
$s = '';
$s .= $this->_SuspiciousSQL($numsql);
$s .= '<p>';
$save = $ADODB_CACHE_MODE;
$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$savelog = $this->conn->LogSQL(false);
$rs =& $this->conn->SelectLimit($sql);
$this->conn->LogSQL($savelog);
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_CACHE_MODE = $save;
if ($rs) {
$s = "\n<h3>Ixora Suspicious SQL</h3>";
$s .= "\n<h3>Ixora Suspicious SQL</h3>";
$s .= $this->tohtml($rs,'expsixora');
} else
$s = '';
}
if ($s) $s .= '<p>';
$s .= $this->_SuspiciousSQL();
return $s;
}
@ -467,31 +473,35 @@ where
order by
1 desc, s.address, p.piece
";
global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) {
$partial = empty($HTTP_GET_VARS['part']);
echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
global $ADODB_CACHE_MODE;
if (isset($_GET['expeixora']) && isset($_GET['sql'])) {
$partial = empty($_GET['part']);
echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
}
if (isset($HTTP_GET_VARS['sql'])) {
$var =& $this->_ExpensiveSQL();
if (isset($_GET['sql'])) {
$var = $this->_ExpensiveSQL($numsql);
return $var;
}
$s = '';
$s .= $this->_ExpensiveSQL($numsql);
$s .= '<p>';
$save = $ADODB_CACHE_MODE;
$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$savelog = $this->conn->LogSQL(false);
$rs =& $this->conn->Execute($sql);
$this->conn->LogSQL($savelog);
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_CACHE_MODE = $save;
if ($rs) {
$s = "\n<h3>Ixora Expensive SQL</h3>";
$s .= "\n<h3>Ixora Expensive SQL</h3>";
$s .= $this->tohtml($rs,'expeixora');
} else
$s = '';
if ($s) $s .= '<p>';
$s .= $this->_ExpensiveSQL();
}
return $s;
}

View File

@ -1,7 +1,7 @@
<?php
/*
V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
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.
@ -42,14 +42,14 @@ class perf_postgres extends adodb_perf{
"select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",
'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),
'data cache hit ratio' => array('RATIO',
"select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'",
"select case when blks_hit=0 then 0 else round( ((1-blks_read::float/blks_hit)*100)::numeric, 2) end from pg_stat_database where datname='\$DATABASE'",
'=WarnCacheRatio'),
'IO',
'data reads' => array('IO',
'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',
),
'data writes' => array('IO',
'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables',
'select round((sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16)::numeric,2) from pg_stat_user_tables',
'Count of inserts/updates/deletes * coef'),
'Data Cache',
@ -66,8 +66,9 @@ class perf_postgres extends adodb_perf{
"select setting::integer*8192 from pg_settings where name='effective_cache_size'",
'(effective cache size)' ),
'Memory Usage',
'sort buffer size' => array('CACHE',
"select setting::integer*1024 from pg_settings where name='sort_mem'",
# Postgres 7.5 changelog: Rename server parameters SortMem and VacuumMem to work_mem and maintenance_work_mem;
'sort/work buffer size' => array('CACHE',
"select setting::integer*1024 from pg_settings where name='sort_mem' or name = 'work_mem' order by name",
'Size of sort buffer (per query)' ),
'Connections',
'current connections' => array('SESS',

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -37,6 +37,8 @@
if ($aggfield) $hidecnt = true;
else $hidecnt = false;
$iif = strpos($db->databaseType,'access') !== false;
// note - vfp still doesn' work even with IIF enabled || $db->databaseType == 'vfp';
//$hidecnt = false;
@ -47,20 +49,39 @@
$sel = "$rowfields, ";
if (is_array($colfield)) {
foreach ($colfield as $k => $v) {
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
if ($aggfield)
$sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
$k = trim($k);
if (!$hidecnt) {
$sel .= $iif ?
"\n\t$aggfn(IIF($v,1,0)) AS \"$k\", "
:
"\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
}
if ($aggfield) {
$sel .= $iif ?
"\n\t$aggfn(IIF($v,$aggfield,0)) AS \"$sumlabel$k\", "
:
"\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
}
}
} else {
foreach ($colarr as $v) {
if (!is_numeric($v)) $vq = $db->qstr($v);
else $vq = $v;
$v = trim($v);
if (strlen($v) == 0 ) $v = 'null';
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
if (!$hidecnt) {
$sel .= $iif ?
"\n\t$aggfn(IIF($colfield=$vq,1,0)) AS \"$v\", "
:
"\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
}
if ($aggfield) {
if ($hidecnt) $label = $v;
else $label = "{$v}_$aggfield";
$sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
$sel .= $iif ?
"\n\t$aggfn(IIF($colfield=$vq,$aggfield,0)) AS \"$label\", "
:
"\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
}
}
}
@ -123,7 +144,7 @@ GROUP BY CompanyName,QuantityPerUnit
#
# Query the main "product" table
# Set the rows to CompanyName and QuantityPerUnit
# and the columns to the UnitsInStock for different ranges
# and the columns to the UnitsInStock for diiferent ranges
# and define the joins to link to lookup tables
# "categories" and "suppliers"
#

View File

@ -1,6 +1,6 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -42,7 +42,14 @@ function &RSFilter($rs,$fn)
}
$rows = $rs->RecordCount();
for ($i=0; $i < $rows; $i++) {
$fn($rs->_array[$i],$rs);
if (is_array ($fn)) {
$obj = $fn[0];
$method = $fn[1];
$obj->$method ($rs->_array[$i],$rs);
} else {
$fn($rs->_array[$i],$rs);
}
}
if (!$rs->EOF) {
$rs->_currentRow = 0;

View File

@ -1,7 +1,7 @@
<?php
/**
* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
* @version 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.
@ -65,9 +65,9 @@ function undomq(&$m)
///////////////////////////////////////// DEFINITIONS
$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"];
$remote = $_SERVER["REMOTE_ADDR"];
if (empty($HTTP_GET_VARS['sql'])) err('No SQL');
if (empty($_GET['sql'])) err('No SQL');
if (!empty($ACCEPTIP))
if ($remote != '127.0.0.1' && $remote != $ACCEPTIP)
@ -77,14 +77,14 @@ if (!empty($ACCEPTIP))
$conn = &ADONewConnection($driver);
if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
$sql = undomq($HTTP_GET_VARS['sql']);
$sql = undomq($_GET['sql']);
if (isset($HTTP_GET_VARS['fetch']))
$ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];
if (isset($_GET['fetch']))
$ADODB_FETCH_MODE = $_GET['fetch'];
if (isset($HTTP_GET_VARS['nrows'])) {
$nrows = $HTTP_GET_VARS['nrows'];
$offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;
if (isset($_GET['nrows'])) {
$nrows = $_GET['nrows'];
$offset = isset($_GET['offset']) ? $_GET['offset'] : -1;
$rs = $conn->SelectLimit($sql,$nrows,$offset);
} else
$rs = $conn->Execute($sql);

View File

@ -1,7 +1,7 @@
<?php
/*
V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Contributed by Ross Smith (adodb@netebb.com).
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,

View File

@ -2,7 +2,7 @@
/*
V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Contributed by Ross Smith (adodb@netebb.com).
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,

View File

@ -2,7 +2,7 @@
/*
V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Contributed by Ross Smith (adodb@netebb.com).
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,

View File

@ -2,7 +2,7 @@
/*
V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Contributed by Ross Smith (adodb@netebb.com).
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,

View File

@ -1,7 +1,7 @@
<?php
/*
V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
Contributed by Ross Smith (adodb@netebb.com).
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,

Some files were not shown because too many files have changed in this diff Show More