2
0
mirror of https://github.com/ACSPRI/queXS synced 2024-04-02 12:12:16 +00:00

Merged from McMasterReports branch

This commit is contained in:
azammitdcarf
2010-01-14 07:45:37 +00:00
parent 18dbb16138
commit d1b139d315
1884 changed files with 555891 additions and 364768 deletions

View File

@@ -1,7 +1,7 @@
<?php
/*
@version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
@version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Latest version is available at http://adodb.sourceforge.net
Released under both BSD license and Lesser GPL library license.
@@ -10,19 +10,22 @@
Active Record implementation. Superset of Zend Framework's.
Version 0.07
Version 0.92
See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
for info on Ruby on Rails Active Record implementation
*/
global $_ADODB_ACTIVE_DBS;
global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
global $ACTIVE_RECORD_SAFETY; // set to false to disable safety checks
global $ADODB_ACTIVE_DEFVALS; // use default values of table definition when creating new active record.
// array of ADODB_Active_DB's, indexed by ADODB_Active_Record->_dbat
$_ADODB_ACTIVE_DBS = array();
$ACTIVE_RECORD_SAFETY = true;
$ADODB_ACTIVE_DEFVALS = false;
class ADODB_Active_DB {
var $db; // ADOConnection
@@ -34,10 +37,15 @@ class ADODB_Active_Table {
var $flds; // assoc array of adofieldobjs, indexed by fieldname
var $keys; // assoc array of primary keys, indexed by fieldname
var $_created; // only used when stored as a cached file
var $_belongsTo = array();
var $_hasMany = array();
}
// $db = database connection
// $index = name of index - can be associative, for an example see
// http://phplens.com/lens/lensforum/msgs.php?id=17790
// returns index into $_ADODB_ACTIVE_DBS
function ADODB_SetDatabaseAdapter(&$db)
function ADODB_SetDatabaseAdapter(&$db, $index=false)
{
global $_ADODB_ACTIVE_DBS;
@@ -51,16 +59,21 @@ function ADODB_SetDatabaseAdapter(&$db)
}
$obj = new ADODB_Active_DB();
$obj->db =& $db;
$obj->db = $db;
$obj->tables = array();
$_ADODB_ACTIVE_DBS[] = $obj;
if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
$_ADODB_ACTIVE_DBS[$index] = $obj;
return sizeof($_ADODB_ACTIVE_DBS)-1;
}
class ADODB_Active_Record {
static $_changeNames = true; // dynamically pluralize table names
static $_foreignSuffix = '_id'; //
var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
var $_table; // tablename, if set in class definition then use it as table name
var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
@@ -68,17 +81,27 @@ class ADODB_Active_Record {
var $_saved = false; // indicates whether data is already inserted.
var $_lasterr = false; // last error message
var $_original = false; // the original values loaded or inserted, refreshed on update
// should be static
function SetDatabaseAdapter(&$db)
var $foreignName; // CFR: class name when in a relationship
static function UseDefaultValues($bool=null)
{
return ADODB_SetDatabaseAdapter($db);
global $ADODB_ACTIVE_DEFVALS;
if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
return $ADODB_ACTIVE_DEFVALS;
}
// should be static
static function SetDatabaseAdapter(&$db, $index=false)
{
return ADODB_SetDatabaseAdapter($db, $index);
}
// php4 constructor
function ADODB_Active_Record($table = false, $pkeyarr=false, $db=false)
public function __set($name, $value)
{
ADODB_Active_Record::__construct($table,$pkeyarr,$db);
$name = str_replace(' ', '_', $name);
$this->$name = $value;
}
// php5 constructor
@@ -95,16 +118,18 @@ class ADODB_Active_Record {
if (!empty($this->_table)) $table = $this->_table;
else $table = $this->_pluralize(get_class($this));
}
$this->foreignName = strtolower(get_class($this)); // CFR: default foreign name
if ($db) {
$this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
} else
$this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
} else if (!isset($this->_dbat)) {
if (sizeof($_ADODB_ACTIVE_DBS) == 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
end($_ADODB_ACTIVE_DBS);
$this->_dbat = key($_ADODB_ACTIVE_DBS);
}
$this->_table = $table;
$this->_tableat = $table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
$this->UpdateActiveTable($pkeyarr);
}
@@ -116,6 +141,8 @@ class ADODB_Active_Record {
function _pluralize($table)
{
if (!ADODB_Active_Record::$_changeNames) return $table;
$ut = strtoupper($table);
$len = strlen($table);
$lastc = $ut[$len-1];
@@ -135,26 +162,196 @@ class ADODB_Active_Record {
}
}
// CFR Lamest singular inflector ever - @todo Make it real!
// Note: There is an assumption here...and it is that the argument's length >= 4
function _singularize($tables)
{
if (!ADODB_Active_Record::$_changeNames) return $table;
$ut = strtoupper($tables);
$len = strlen($tables);
if($ut[$len-1] != 'S')
return $tables; // I know...forget oxen
if($ut[$len-2] != 'E')
return substr($tables, 0, $len-1);
switch($ut[$len-3])
{
case 'S':
case 'X':
return substr($tables, 0, $len-2);
case 'I':
return substr($tables, 0, $len-3) . 'y';
case 'H';
if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
return substr($tables, 0, $len-2);
default:
return substr($tables, 0, $len-1); // ?
}
}
function hasMany($foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new $foreignClass($foreignRef);
$ar->foreignName = $foreignRef;
$ar->UpdateActiveTable();
$ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
$table =& $this->TableInfo();
$table->_hasMany[$foreignRef] = $ar;
# $this->$foreignRef = $this->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
}
// use when you don't want ADOdb to auto-pluralize tablename
static function TableHasMany($table, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new ADODB_Active_Record($table);
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
// use when you don't want ADOdb to auto-pluralize tablename
static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
$ar = new ADODB_Active_Record($table,$tablePKey);
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
// use when you want ADOdb to auto-pluralize tablename for you. Note that the class must already be defined.
// e.g. class Person will generate relationship for table Persons
static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new $parentclass();
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
function belongsTo($foreignRef,$foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
global $inflector;
$ar = new $parentClass($this->_pluralize($foreignRef));
$ar->foreignName = $foreignRef;
$ar->parentKey = $parentKey;
$ar->UpdateActiveTable();
$ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
$table =& $this->TableInfo();
$table->_belongsTo[$foreignRef] = $ar;
# $this->$foreignRef = $this->_belongsTo[$foreignRef];
}
static function ClassBelongsTo($class, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
$ar = new $class();
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
static function TableBelongsTo($table, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
$ar = new ADOdb_Active_Record($table);
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
$ar = new ADOdb_Active_Record($table, $tablePKey);
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
/**
* __get Access properties - used for lazy loading
*
* @param mixed $name
* @access protected
* @return mixed
*/
function __get($name)
{
return $this->LoadRelations($name, '', -1, -1);
}
/**
* @param string $name
* @param string $whereOrderBy : eg. ' AND field1 = value ORDER BY field2'
* @param offset
* @param limit
* @return mixed
*/
function LoadRelations($name, $whereOrderBy='', $offset=-1,$limit=-1)
{
$extras = array();
$table = $this->TableInfo();
if ($limit >= 0) $extras['limit'] = $limit;
if ($offset >= 0) $extras['offset'] = $offset;
if (strlen($whereOrderBy))
if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
$whereOrderBy = 'AND '.$whereOrderBy;
if(!empty($table->_belongsTo[$name]))
{
$obj = $table->_belongsTo[$name];
$columnName = $obj->foreignKey;
if(empty($this->$columnName))
$this->$name = null;
else
{
if ($obj->parentKey) $key = $obj->parentKey;
else $key = reset($table->keys);
$arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
if ($arrayOfOne) {
$this->$name = $arrayOfOne[0];
return $arrayOfOne[0];
}
}
}
if(!empty($table->_hasMany[$name]))
{
$obj = $table->_hasMany[$name];
$key = reset($table->keys);
$id = @$this->$key;
if (!is_numeric($id)) {
$db = $this->DB();
$id = $db->qstr($id);
}
$objs = $obj->Find($obj->foreignKey.'='.$id. ' '.$whereOrderBy,false,false,$extras);
if (!$objs) $objs = array();
$this->$name = $objs;
return $objs;
}
return array();
}
//////////////////////////////////
// update metadata
function UpdateActiveTable($pkeys=false,$forceUpdate=false)
{
global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
$activedb =& $_ADODB_ACTIVE_DBS[$this->_dbat];
global $ADODB_ACTIVE_DEFVALS,$ADODB_FETCH_MODE;
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$table = $this->_table;
$tables = $activedb->tables;
$tableat = $this->_tableat;
if (!$forceUpdate && !empty($tables[$tableat])) {
$tobj =& $tables[$tableat];
foreach($tobj->flds as $name => $fld)
$tobj = $tables[$tableat];
foreach($tobj->flds as $name => $fld) {
if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
$this->$name = $fld->default_value;
else
$this->$name = null;
}
return;
}
$db =& $activedb->db;
$db = $activedb->db;
$fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
$fp = fopen($fname,'r');
@@ -175,8 +372,15 @@ class ADODB_Active_Record {
$activetab = new ADODB_Active_Table();
$activetab->name = $table;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
$cols = $db->MetaColumns($table);
if (isset($savem)) $db->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$cols) {
$this->Error("Invalid table name: $table",'UpdateActiveTable');
return false;
@@ -203,7 +407,10 @@ class ADODB_Active_Record {
case 0:
foreach($cols as $name => $fldobj) {
$name = strtolower($name);
$this->$name = null;
if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
$this->$name = $fldobj->default_value;
else
$this->$name = null;
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
@@ -214,7 +421,11 @@ class ADODB_Active_Record {
case 1:
foreach($cols as $name => $fldobj) {
$name = strtoupper($name);
$this->$name = null;
if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
$this->$name = $fldobj->default_value;
else
$this->$name = null;
$attr[$name] = $fldobj;
}
@@ -225,7 +436,11 @@ class ADODB_Active_Record {
default:
foreach($cols as $name => $fldobj) {
$name = ($fldobj->name);
$this->$name = null;
if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
$this->$name = $fldobj->default_value;
else
$this->$name = null;
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
@@ -243,6 +458,12 @@ class ADODB_Active_Record {
if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
adodb_write_file($fname,$s);
}
if (isset($activedb->tables[$table])) {
$oldtab = $activedb->tables[$table];
if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
}
$activedb->tables[$table] = $activetab;
}
@@ -262,7 +483,7 @@ class ADODB_Active_Record {
if ($this->_dbat < 0) $db = false;
else {
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$db =& $activedb->db;
$db = $activedb->db;
}
if (function_exists('adodb_throw')) {
@@ -296,7 +517,7 @@ class ADODB_Active_Record {
// retrieve ADOConnection from _ADODB_Active_DBs
function &DB()
function DB()
{
global $_ADODB_ACTIVE_DBS;
@@ -306,7 +527,7 @@ class ADODB_Active_Record {
return $false;
}
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$db =& $activedb->db;
$db = $activedb->db;
return $db;
}
@@ -314,18 +535,29 @@ class ADODB_Active_Record {
function &TableInfo()
{
global $_ADODB_ACTIVE_DBS;
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$table =& $activedb->tables[$this->_tableat];
$table = $activedb->tables[$this->_tableat];
return $table;
}
// I have an ON INSERT trigger on a table that sets other columns in the table.
// So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
function Reload()
{
$db =& $this->DB(); if (!$db) return false;
$table =& $this->TableInfo();
$where = $this->GenWhere($db, $table);
return($this->Load($where));
}
// set a numeric array (using natural table field ordering) as object properties
function Set(&$row)
{
global $ACTIVE_RECORD_SAFETY;
$db =& $this->DB();
$db = $this->DB();
if (!$row) {
$this->_saved = false;
@@ -334,18 +566,36 @@ class ADODB_Active_Record {
$this->_saved = true;
$table =& $this->TableInfo();
$table = $this->TableInfo();
if ($ACTIVE_RECORD_SAFETY && sizeof($table->flds) != sizeof($row)) {
# <AP>
$bad_size = TRUE;
if (sizeof($row) == 2 * sizeof($table->flds)) {
// Only keep string keys
$keys = array_filter(array_keys($row), 'is_string');
if (sizeof($keys) == sizeof($table->flds))
$bad_size = FALSE;
}
if ($bad_size) {
$this->Error("Table structure of $this->_table has changed","Load");
return false;
}
$cnt = 0;
foreach($table->flds as $name=>$fld) {
$this->$name = $row[$cnt];
$cnt += 1;
# </AP>
}
$this->_original = $row;
else
$keys = array_keys($row);
# <AP>
reset($keys);
$this->_original = array();
foreach($table->flds as $name=>$fld) {
$value = $row[current($keys)];
$this->$name = $value;
$this->_original[] = $value;
next($keys);
}
# </AP>
return true;
}
@@ -371,12 +621,15 @@ class ADODB_Active_Record {
case 'D':
case 'T':
if (empty($val)) return 'null';
case 'B':
case 'N':
case 'C':
case 'X':
if (is_null($val)) return 'null';
if (strncmp($val,"'",1) != 0 && substr($val,strlen($val)-1,1) != "'") {
if (strlen($val)>1 &&
(strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
return $db->qstr($val);
break;
}
@@ -404,18 +657,48 @@ class ADODB_Active_Record {
//------------------------------------------------------------ Public functions below
function Load($where,$bindarr=false)
function Load($where=null,$bindarr=false)
{
$db =& $this->DB(); if (!$db) return false;
global $ADODB_FETCH_MODE;
$db = $this->DB(); if (!$db) return false;
$this->_where = $where;
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$row = $db->GetRow("select * from ".$this->_table.' WHERE '.$where,$bindarr);
$db->SetFetchMode($save);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
$qry = "select * from ".$this->_table;
if($where) {
$qry .= ' WHERE '.$where;
}
$row = $db->GetRow($qry,$bindarr);
if (isset($savem)) $db->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $this->Set($row);
}
# useful for multiple record inserts
# see http://phplens.com/lens/lensforum/msgs.php?id=17795
function Reset()
{
$this->_where=null;
$this->_saved = false;
$this->_lasterr = false;
$this->_original = false;
$vars=get_object_vars($this);
foreach($vars as $k=>$v){
if(substr($k,0,1)!=='_'){
$this->{$k}=null;
}
}
$this->foreignName=strtolower(get_class($this));
return true;
}
// false on error
function Save()
{
@@ -428,9 +711,9 @@ class ADODB_Active_Record {
// false on error
function Insert()
{
$db =& $this->DB(); if (!$db) return false;
$db = $this->DB(); if (!$db) return false;
$cnt = 0;
$table =& $this->TableInfo();
$table = $this->TableInfo();
$valarr = array();
$names = array();
@@ -438,7 +721,7 @@ class ADODB_Active_Record {
foreach($table->flds as $name=>$fld) {
$val = $this->$name;
if(!is_null($val) || !array_key_exists($name, $table->keys)) {
if(!is_array($val) || !is_null($val) || !array_key_exists($name, $table->keys)) {
$valarr[] = $val;
$names[] = $name;
$valstr[] = $db->Param($cnt);
@@ -478,8 +761,8 @@ class ADODB_Active_Record {
function Delete()
{
$db =& $this->DB(); if (!$db) return false;
$table =& $this->TableInfo();
$db = $this->DB(); if (!$db) return false;
$table = $this->TableInfo();
$where = $this->GenWhere($db,$table);
$sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
@@ -489,10 +772,10 @@ class ADODB_Active_Record {
}
// returns an array of active record objects
function &Find($whereOrderBy,$bindarr=false,$pkeysArr=false)
function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
{
$db =& $this->DB(); if (!$db || empty($this->_table)) return false;
$arr =& $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr);
$db = $this->DB(); if (!$db || empty($this->_table)) return false;
$arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
return $arr;
}
@@ -501,8 +784,8 @@ class ADODB_Active_Record {
{
global $ADODB_ASSOC_CASE;
$db =& $this->DB(); if (!$db) return false;
$table =& $this->TableInfo();
$db = $this->DB(); if (!$db) return false;
$table = $this->TableInfo();
$pkey = $table->keys;
@@ -521,6 +804,9 @@ class ADODB_Active_Record {
if (is_null($val) && !empty($fld->auto_increment)) {
continue;
}
if (is_array($val)) continue;
$t = $db->MetaType($fld->type);
$arr[$name] = $this->doquote($db,$val,$t);
$valarr[] = $val;
@@ -532,7 +818,7 @@ class ADODB_Active_Record {
if ($ADODB_ASSOC_CASE == 0)
foreach($pkey as $k => $v)
$pkey[$k] = strtolower($v);
elseif ($ADODB_ASSOC_CASE == 0)
elseif ($ADODB_ASSOC_CASE == 1)
foreach($pkey as $k => $v)
$pkey[$k] = strtoupper($v);
@@ -553,7 +839,7 @@ class ADODB_Active_Record {
}
}
$this->_original =& $valarr;
$this->_original = $valarr;
}
return $ok;
}
@@ -561,8 +847,8 @@ class ADODB_Active_Record {
// returns 0 on error, 1 on update, -1 if no change in data (no update)
function Update()
{
$db =& $this->DB(); if (!$db) return false;
$table =& $this->TableInfo();
$db = $this->DB(); if (!$db) return false;
$table = $this->TableInfo();
$where = $this->GenWhere($db, $table);
@@ -580,9 +866,8 @@ class ADODB_Active_Record {
$val = $this->$name;
$neworig[] = $val;
if (isset($table->keys[$name])) {
if (isset($table->keys[$name]) || is_array($val))
continue;
}
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
@@ -607,7 +892,7 @@ class ADODB_Active_Record {
$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
$ok = $db->Execute($sql,$valarr);
if ($ok) {
$this->_original =& $neworig;
$this->_original = $neworig;
return 1;
}
return 0;
@@ -615,11 +900,72 @@ class ADODB_Active_Record {
function GetAttributeNames()
{
$table =& $this->TableInfo();
$table = $this->TableInfo();
if (!$table) return false;
return array_keys($table->flds);
}
};
function adodb_GetActiveRecordsClass(&$db, $class, $table,$whereOrderBy,$bindarr, $primkeyArr,
$extra)
{
global $_ADODB_ACTIVE_DBS;
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$qry = "select * from ".$table;
if (!empty($whereOrderBy))
$qry .= ' WHERE '.$whereOrderBy;
if(isset($extra['limit']))
{
$rows = false;
if(isset($extra['offset'])) {
$rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
} else {
$rs = $db->SelectLimit($qry, $extra['limit']);
}
if ($rs) {
while (!$rs->EOF) {
$rows[] = $rs->fields;
$rs->MoveNext();
}
}
} else
$rows = $db->GetAll($qry,$bindarr);
$db->SetFetchMode($save);
$false = false;
if ($rows === false) {
return $false;
}
if (!class_exists($class)) {
$db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
return $false;
}
$arr = array();
// arrRef will be the structure that knows about our objects.
// It is an associative array.
// We will, however, return arr, preserving regular 0.. order so that
// obj[0] can be used by app developpers.
$arrRef = array();
$bTos = array(); // Will store belongTo's indices if any
foreach($rows as $row) {
$obj = new $class($table,$primkeyArr,$db);
if ($obj->ErrorNo()){
$db->_errorMsg = $obj->ErrorMsg();
return $false;
}
$obj->Set($row);
$arr[] = $obj;
} // foreach($rows as $row)
return $arr;
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,7 @@ $ADODB_INCLUDED_CSV = 1;
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -54,7 +54,7 @@ $ADODB_INCLUDED_CSV = 1;
$line = "====1,$tt,$sql\n";
if ($rs->databaseType == 'array') {
$rows =& $rs->_array;
$rows = $rs->_array;
} else {
$rows = array();
while (!$rs->EOF) {
@@ -64,7 +64,7 @@ $ADODB_INCLUDED_CSV = 1;
}
for($i=0; $i < $max; $i++) {
$o =& $rs->FetchField($i);
$o = $rs->FetchField($i);
$flds[] = $o;
}
@@ -90,7 +90,7 @@ $ADODB_INCLUDED_CSV = 1;
* error occurred in sql INSERT/UPDATE/DELETE,
* empty recordset is returned
*/
function &csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
function csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
{
$false = false;
$err = false;
@@ -261,6 +261,7 @@ $ADODB_INCLUDED_CSV = 1;
/**
* Save a file $filename and its $contents (normally for caching) with file locking
* Returns true if ok, false if fopen/fwrite error, 0 if rename error (eg. file is locked)
*/
function adodb_write_file($filename, $contents,$debug=false)
{
@@ -280,27 +281,31 @@ $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;
$ok = ftruncate($fd,0);
if (!fwrite($fd,$contents)) $ok = false;
if (!($fd = @fopen($tmpname,'w'))) return false;
if (fwrite($fd,$contents)) $ok = true;
else $ok = false;
fclose($fd);
chmod($tmpname,0644);
// the tricky moment
@unlink($filename);
if (!@rename($tmpname,$filename)) {
unlink($tmpname);
$ok = false;
}
if (!$ok) {
if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
if ($ok) {
@chmod($tmpname,0644);
// the tricky moment
@unlink($filename);
if (!@rename($tmpname,$filename)) {
unlink($tmpname);
$ok = 0;
}
if (!$ok) {
if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
}
}
return $ok;
}
if (!($fd = @fopen($filename, 'a'))) return false;
if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
$ok = fwrite( $fd, $contents );
if (fwrite( $fd, $contents )) $ok = true;
else $ok = false;
fclose($fd);
chmod($filename,0644);
@chmod($filename,0644);
}else {
fclose($fd);
if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -215,7 +215,6 @@ class ADODB_DataDict {
return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
static $typeMap = array(
@@ -231,6 +230,7 @@ class ADODB_DataDict {
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
'VAR_STRING' => 'C', # mysql
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
@@ -258,6 +258,7 @@ class ADODB_DataDict {
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'SMALLDATETIME' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
@@ -369,7 +370,7 @@ class ADODB_DataDict {
function ExecuteSQLArray($sql, $continueOnError = true)
{
$rez = 2;
$conn = &$this->connection;
$conn = $this->connection;
$saved = $conn->debug;
foreach($sql as $line) {
@@ -813,7 +814,7 @@ class ADODB_DataDict {
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
@@ -918,7 +919,7 @@ class ADODB_DataDict {
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)
function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false)
{
global $ADODB_FETCH_MODE;
@@ -951,13 +952,15 @@ class ADODB_DataDict {
$obj = $cols[$k];
if (isset($obj->not_null) && $obj->not_null)
$v = str_replace('NOT NULL','',$v);
if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT']))
$v = str_replace('AUTOINCREMENT','',$v);
$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']) {
if (($mt != $v['TYPE']) || $ml != $v['SIZE'] || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
$holdflds[$k] = $v;
}
} else {
@@ -981,8 +984,11 @@ class ADODB_DataDict {
$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)) {
echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
// $flds[1] holds the type, $flds[2] holds the size -postnuke addition
if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)
&& (isset($flds[0][2]) && is_numeric($flds[0][2]))) {
if ($this->debug) ADOConnection::outp(sprintf("<h3>%s cannot be changed to %s currently</h3>", $flds[0][0], $flds[0][1]));
#echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
continue;
}
$sql[] = $alter . $this->alterCol . ' ' . $v;
@@ -991,6 +997,11 @@ class ADODB_DataDict {
}
}
if ($dropOldFlds) {
foreach ( $cols as $id => $v )
if ( !isset($lines[$id]) )
$sql[] = $alter . $this->dropCol . ' ' . $v->name;
}
return $sql;
}
} // class

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -92,14 +92,14 @@ function adodb_error_pg($errormsg)
{
if (is_numeric($errormsg)) return (integer) $errormsg;
static $error_regexps = array(
'/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS,
'/divide by zero$/' => DB_ERROR_DIVZERO,
'/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
'/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
'/parser: parse error at or near \"/' => DB_ERROR_SYNTAX,
'/referential integrity violation/' => DB_ERROR_CONSTRAINT,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/'
'/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/i' => DB_ERROR_NOSUCHTABLE,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/i' => DB_ERROR_ALREADY_EXISTS,
'/divide by zero$/i' => DB_ERROR_DIVZERO,
'/pg_atoi: error in .*: can\'t parse /i' => DB_ERROR_INVALID_NUMBER,
'/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/i' => DB_ERROR_NOSUCHFIELD,
'/parser: parse error at or near \"/i' => DB_ERROR_SYNTAX,
'/referential integrity violation/i' => DB_ERROR_CONSTRAINT,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/i'
=> DB_ERROR_ALREADY_EXISTS
);
reset($error_regexps);

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -78,7 +78,7 @@ global $ADODB_Last_PEAR_Error;
* Returns last PEAR_Error object. This error might be for an error that
* occured several sql statements ago.
*/
function &ADODB_PEAR_Error()
function ADODB_PEAR_Error()
{
global $ADODB_Last_PEAR_Error;

View File

@@ -1,7 +1,7 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -18,68 +18,13 @@
Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2
Moved to adodb.inc.php to improve performance.
*/
class ADODB_Iterator implements Iterator {
private $rs;
function __construct($rs)
{
$this->rs = $rs;
}
function rewind()
{
$this->rs->MoveFirst();
}
function valid()
{
return !$this->rs->EOF;
}
function key()
{
return $this->rs->_currentRow;
}
function current()
{
return $this->rs->fields;
}
function next()
{
$this->rs->MoveNext();
}
function __call($func, $params)
{
return call_user_func_array(array($this->rs, $func), $params);
}
function hasMore()
{
return !$this->rs->EOF;
}
}
class ADODB_BASE_RS implements IteratorAggregate {
function getIterator() {
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');
return _adodb_export($this,',',',',false,true);
}
}
?>

View File

@@ -1,5 +1,8 @@
<?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
@@ -7,7 +10,7 @@ global $ADODB_INCLUDED_LIB;
$ADODB_INCLUDED_LIB = 1;
/*
@version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim\@natsoft.com.my). All rights reserved.
@version V5.06 16 Oct 2008 (c) 2000-2009 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.
@@ -16,6 +19,36 @@ $ADODB_INCLUDED_LIB = 1;
Less commonly used functions are placed here to reduce size of adodb.inc.php.
*/
function adodb_strip_order_by($sql)
{
$rez = preg_match('/(\sORDER\s+BY\s[^)]*)/is',$sql,$arr);
if ($arr)
if (strpos($arr[0],'(') !== false) {
$at = strpos($sql,$arr[0]);
$cntin = 0;
for ($i=$at, $max=strlen($sql); $i < $max; $i++) {
$ch = $sql[$i];
if ($ch == '(') {
$cntin += 1;
} elseif($ch == ')') {
$cntin -= 1;
if ($cntin < 0) {
break;
}
}
}
$sql = substr($sql,0,$at).substr($sql,$i);
} else
$sql = str_replace($arr[0], '', $sql);
return $sql;
}
if (false) {
$sql = 'select * from (select a from b order by a(b),b(c) desc)';
$sql = '(select * from abc order by 1)';
die(adodb_strip_order_by($sql));
}
function adodb_probetypes(&$array,&$types,$probe=8)
{
// probe and guess the type
@@ -25,7 +58,7 @@ function adodb_probetypes(&$array,&$types,$probe=8)
for ($j=0;$j < $max; $j++) {
$row =& $array[$j];
$row = $array[$j];
if (!$row) break;
$i = -1;
foreach($row as $v) {
@@ -111,7 +144,10 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
$keyCol = array($keyCol);
}
foreach($fieldArray as $k => $v) {
if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,$zthis->null2null)!=0) {
if ($v === null) {
$v = 'NULL';
$fieldArray[$k] = $v;
} else if ($autoQuote && /*!is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ strcasecmp($v,$zthis->null2null)!=0) {
$v = $zthis->qstr($v);
$fieldArray[$k] = $v;
}
@@ -123,7 +159,7 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
} else
$uSet .= ",$k=$v";
}
$where = false;
foreach ($keyCol as $v) {
if (isset($fieldArray[$v])) {
@@ -369,42 +405,35 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
preg_match('/\s+GROUP\s+BY\s+/is',$sql) ||
preg_match('/\s+UNION\s+/is',$sql)) {
$rewritesql = adodb_strip_order_by($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);
// 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) {
$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql);
} else if (strncmp($zthis->databaseType,'postgres',8) == 0 || strncmp($zthis->databaseType,'mysql',5) == 0) {
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
} else {
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
}
} 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!
// also see http://phplens.com/lens/lensforum/msgs.php?id=12752
if (preg_match('/\sORDER\s+BY\s*\(/i',$rewritesql))
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
else
$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql);
$rewritesql = adodb_strip_order_by($rewritesql);
}
if (isset($rewritesql) && $rewritesql != $sql) {
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[1];
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
if ($secs2cache) {
// we only use half the time of secs2cache because the count can quickly
@@ -422,11 +451,11 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
// 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);
else $rewritesql = $rewritesql = adodb_strip_order_by($sql);
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
$rstest = &$zthis->Execute($rewritesql,$inputarr);
$rstest = $zthis->Execute($rewritesql,$inputarr);
if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
if ($rstest) {
@@ -460,7 +489,7 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
data will get out of synch. use CachePageExecute() only with tables that
rarely change.
*/
function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
$inputarr=false, $secs2cache=0)
{
$atfirstpage = false;
@@ -496,9 +525,9 @@ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0)
$rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
$rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else
$rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
$rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
@@ -514,7 +543,7 @@ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
}
// Iván Oliva version
function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
{
$atfirstpage = false;
@@ -530,16 +559,16 @@ function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputar
// the last page number.
$pagecounter = $page + 1;
$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
if ($rstest) {
while ($rstest && $rstest->EOF && $pagecounter>0) {
$atlastpage = true;
$pagecounter--;
$pagecounteroffset = $nrows * ($pagecounter - 1);
$rstest->Close();
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
}
if ($rstest) $rstest->Close();
}
@@ -551,8 +580,8 @@ function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputar
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
if ($secs2cache > 0) $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
@@ -747,10 +776,10 @@ static $cacheCols;
//php can't do a $rsclass::MetaType()
$rsclass = $zthis->rsPrefix.$zthis->databaseType;
$recordSet = new $rsclass(-1,$zthis->fetchMode);
$recordSet->connection = &$zthis;
$recordSet->connection = $zthis;
if (is_string($cacheRS) && $cacheRS == $rs) {
$columns =& $cacheCols;
$columns = $cacheCols;
} else {
$columns = $zthis->MetaColumns( $tableName );
$cacheRS = $tableName;
@@ -758,7 +787,7 @@ static $cacheCols;
}
} else if (is_subclass_of($rs, 'adorecordset')) {
if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
$columns =& $cacheCols;
$columns = $cacheCols;
} else {
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
$columns[] = $rs->FetchField($i);
@@ -766,7 +795,7 @@ static $cacheCols;
$cacheCols = $columns;
$rs->insertSig = $cacheSig++;
}
$recordSet =& $rs;
$recordSet = $rs;
} else {
printf(ADODB_BAD_RS,'GetInsertSQL');
@@ -968,18 +997,19 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
$val = $zthis->DBDate($arrFields[$fname]);
break;
case "T":
case "T":
$val = $zthis->DBTimeStamp($arrFields[$fname]);
break;
break;
case "N":
$val = (float) $arrFields[$fname];
$val = $arrFields[$fname];
if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
break;
case "I":
case "R":
$val = (int) $arrFields[$fname];
$val = $arrFields[$fname];
if (!is_numeric($val)) $val = (integer) $val;
break;
default:
@@ -1003,7 +1033,8 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
if ($inputarr) {
foreach($inputarr as $kk=>$vv) {
if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
$ss .= "($kk=>'$vv') ";
if (is_null($vv)) $ss .= "($kk=>null) ";
else $ss .= "($kk=>'$vv') ";
}
$ss = "[ $ss ]";
}
@@ -1022,11 +1053,13 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
$ss = '<code>'.htmlspecialchars($ss).'</code>';
}
if ($zthis->debug === -1)
ADOConnection::outp( "<br />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br />\n",false);
else
ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false);
ADOConnection::outp( "<br>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br>\n",false);
else if ($zthis->debug !== -99)
ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
} else {
ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false);
$ss = "\n ".$ss;
if ($zthis->debug !== -99)
ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt." $ss\n-----<hr>\n",false);
}
$qID = $zthis->_query($sql,$inputarr);
@@ -1037,10 +1070,21 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
*/
if ($zthis->databaseType == 'mssql') {
// ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
if($emsg = $zthis->ErrorMsg()) {
if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg);
if ($err = $zthis->ErrorNo()) {
if ($zthis->debug === -99)
ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
ADOConnection::outp($err.': '.$emsg);
}
}
} else if (!$qID) {
if ($zthis->debug === -99)
if ($inBrowser) ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
else ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt."$ss\n-----<hr>\n",false);
ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
}
@@ -1049,11 +1093,13 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
}
# pretty print the debug_backtrace function
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
{
if (!function_exists('debug_backtrace')) return '';
$html = (isset($_SERVER['HTTP_USER_AGENT']));
if ($ishtml === null) $html = (isset($_SERVER['HTTP_USER_AGENT']));
else $html = $ishtml;
$fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
$MAXSTRLEN = 128;
@@ -1084,7 +1130,7 @@ function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
else {
$v = (string) @$v;
$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
$str = htmlspecialchars(str_replace(array("\r","\n"),' ',substr($v,0,$MAXSTRLEN)));
if (strlen($v) > $MAXSTRLEN) $str .= '...';
$args[] = $str;
}

View File

@@ -1,118 +1,190 @@
<?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
global $ADODB_INCLUDED_MEMCACHE;
$ADODB_INCLUDED_MEMCACHE = 1;
/*
V4.90 8 June 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
*/
function &getmemcache($key,&$err, $timeout=0, $host, $port)
{
$false = false;
$err = false;
if (!function_exists('memcache_pconnect')) {
$err = 'Memcache module PECL extension not found!';
return $false;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
$err = 'Can\'t connect to memcache server on: '.$host.':'.$port;
return $false;
}
$rs = $memcache->get($key);
if (!$rs) {
$err = 'Item with such key doesn\'t exists on the memcached server.';
return $false;
}
$tdiff = intval($rs->timeCreated+$timeout - time());
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 15) == 0) {
$err = "Timeout 2";
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
$err = "Timeout 1";
return $false;
}
break;
default:
$err = "Timeout 0";
return $false;
}
}
return $rs;
}
function putmemcache($key, $rs, $host, $port, $compress, $debug=false)
{
$false = false;
$true = true;
if (!function_exists('memcache_pconnect')) {
if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
return $false;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
return $false;
}
$rs->timeCreated = time();
if (!$memcache->set($key, $rs, $compress, 0)) {
if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
return $false;
}
return $true;
}
function flushmemcache($key=false, $host, $port, $debug=false)
{
if (!function_exists('memcache_pconnect')) {
if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
return;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
return;
}
if ($key) {
if (!$memcache->delete($key)) {
if ($debug) ADOConnection::outp("CacheFlush: $key entery doesn't exist on memcached server!<br>\n");
} else {
if ($debug) ADOConnection::outp("CacheFlush: $key entery flushed from memcached server!<br>\n");
}
} else {
if (!$memcache->flush()) {
if ($debug) ADOConnection::outp("CacheFlush: Failure flushing all enteries from memcached server!<br>\n");
} else {
if ($debug) ADOConnection::outp("CacheFlush: All enteries flushed from memcached server!<br>\n");
}
}
return;
}
?>
<?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
global $ADODB_INCLUDED_MEMCACHE;
$ADODB_INCLUDED_MEMCACHE = 1;
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
/*
V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Usage:
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = array($ip1, $ip2, $ip3);
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
Note the memcache class is shared by all connections, is created during the first call to Connect/PConnect.
Class instance is stored in $ADODB_CACHE
*/
class ADODB_Cache_MemCache {
var $createdir = false; // create caching directory structure?
//-----------------------------
// memcache specific variables
var $hosts; // array of hosts
var $port = 11211;
var $compress = false; // memcache compression with zlib
var $_connected = false;
var $_memcache = false;
function ADODB_Cache_MemCache(&$obj)
{
$this->hosts = $obj->memCacheHost;
$this->port = $obj->memCachePort;
$this->compress = $obj->memCacheCompress;
}
// implement as lazy connection. The connection only occurs on CacheExecute call
function connect(&$err)
{
if (!function_exists('memcache_pconnect')) {
$err = 'Memcache module PECL extension not found!';
return false;
}
$memcache = new MemCache;
if (!is_array($this->hosts)) $this->hosts = array($hosts);
$failcnt = 0;
foreach($this->hosts as $host) {
if (!@$memcache->addServer($host,$this->port,true)) {
$failcnt += 1;
}
}
if ($failcnt == sizeof($this->hosts)) {
$err = 'Can\'t connect to any memcache server';
return false;
}
$this->_connected = true;
$this->_memcache = $memcache;
return true;
}
// returns true or false. true if successful save
function writecache($filename, $contents, $debug, $secs2cache)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
if (!$this->_memcache->set($filename, $contents, $this->compress, $secs2cache)) {
if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
return false;
}
return true;
}
// returns a recordset
function readcache($filename, &$err, $secs2cache, $rsClass)
{
$false = false;
if (!$this->_connected) $this->connect($err);
if (!$this->_memcache) return $false;
$rs = $this->_memcache->get($filename);
if (!$rs) {
$err = 'Item with such key doesn\'t exists on the memcached server.';
return $false;
}
// hack, should actually use _csv2rs
$rs = explode("\n", $rs);
unset($rs[0]);
$rs = join("\n", $rs);
$rs = unserialize($rs);
if (! is_object($rs)) {
$err = 'Unable to unserialize $rs';
return $false;
}
if ($rs->timeCreated == 0) return $rs; // apparently have been reports that timeCreated was set to 0 somewhere
$tdiff = intval($rs->timeCreated+$secs2cache - time());
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 15) == 0) {
$err = "Timeout 2";
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
$err = "Timeout 1";
return $false;
}
break;
default:
$err = "Timeout 0";
return $false;
}
}
return $rs;
}
function flushall($debug=false)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
$del = $this->_memcache->flush();
if ($debug)
if (!$del) ADOConnection::outp("flushall: failed!<br>\n");
else ADOConnection::outp("flushall: succeeded!<br>\n");
return $del;
}
function flushcache($filename, $debug=false)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
$del = $this->_memcache->delete($filename);
if ($debug)
if (!$del) ADOConnection::outp("flushcache: $key entry doesn't exist on memcached server!<br>\n");
else ADOConnection::outp("flushcache: $key entry flushed from memcached server!<br>\n");
return $del;
}
// not used for memcache
function createdir($dir, $hash)
{
return true;
}
}
?>

View File

@@ -1,7 +1,7 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -60,7 +60,7 @@ class ADODB_Pager {
global $PHP_SELF;
$curr_page = $id.'_curr_page';
if (empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
if (!empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
$this->sql = $sql;
$this->id = $id;
@@ -247,12 +247,12 @@ class ADODB_Pager {
$savec = $ADODB_COUNTRECS;
if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
if ($this->cache)
$rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
$rs = $this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
else
$rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
$rs = $this->db->PageExecute($this->sql,$rows,$this->curr_page);
$ADODB_COUNTRECS = $savec;
$this->rs = &$rs;
$this->rs = $rs;
if (!$rs) {
print "<h3>Query failed: $this->sql</h3>";
return;

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,11 +109,11 @@ class DB
* error
*/
function &factory($type)
function factory($type)
{
include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");
$obj = &NewADOConnection($type);
if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
$obj = NewADOConnection($type);
if (!is_object($obj)) $obj = new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
return $obj;
}
@@ -136,7 +136,7 @@ class DB
* @see DB::parseDSN
* @see DB::isError
*/
function &connect($dsn, $options = false)
function connect($dsn, $options = false)
{
if (is_array($dsn)) {
$dsninfo = $dsn;
@@ -157,9 +157,9 @@ class DB
@include_once("adodb-$type.inc.php");
}
@$obj =& NewADOConnection($type);
@$obj = NewADOConnection($type);
if (!is_object($obj)) {
$obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
$obj = new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
return $obj;
}
if (is_array($options)) {
@@ -211,7 +211,7 @@ class DB
function isError($value)
{
if (!is_object($value)) return false;
$class = get_class($value);
$class = strtolower(get_class($value));
return $class == 'pear_error' || is_subclass_of($value, 'pear_error') ||
$class == 'db_error' || is_subclass_of($value, 'db_error');
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,10 @@ include_once(ADODB_DIR.'/tohtml.inc.php');
define( 'ADODB_OPT_HIGH', 2);
define( 'ADODB_OPT_LOW', 1);
global $ADODB_PERF_MIN;
$ADODB_PERF_MIN = 0.05; // log only if >= minimum number of secs to run
// returns in K the memory of current process, or 0 if not known
function adodb_getmem()
{
@@ -62,37 +66,31 @@ function adodb_microtime()
}
/* sql code timing */
function& adodb_log_sql(&$connx,$sql,$inputarr)
function adodb_log_sql(&$connx,$sql,$inputarr)
{
$perf_table = adodb_perf::table();
$connx->fnExecute = false;
$t0 = microtime();
$rs =& $connx->Execute($sql,$inputarr);
$t1 = microtime();
$a0 = microtime(true);
$rs = $connx->Execute($sql,$inputarr);
$a1 = microtime(true);
if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
global $ADODB_LOG_CONN;
if (!empty($ADODB_LOG_CONN)) {
$conn = &$ADODB_LOG_CONN;
$conn = $ADODB_LOG_CONN;
if ($conn->databaseType != $connx->databaseType)
$prefix = '/*dbx='.$connx->databaseType .'*/ ';
else
$prefix = '';
} else {
$conn =& $connx;
$conn = $connx;
$prefix = '';
}
$conn->_logsql = false; // disable logsql error simulation
$dbT = $conn->databaseType;
$a0 = split(' ',$t0);
$a0 = (float)$a0[1]+(float)$a0[0];
$a1 = split(' ',$t1);
$a1 = (float)$a1[1]+(float)$a1[0];
$time = $a1 - $a0;
if (!$rs) {
@@ -113,9 +111,9 @@ function& adodb_log_sql(&$connx,$sql,$inputarr)
}
if (isset($_SERVER['HTTP_HOST'])) {
$tracer .= '<br>'.$_SERVER['HTTP_HOST'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= htmlspecialchars($_SERVER['PHP_SELF']);
} else
if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.htmlspecialchars($_SERVER['PHP_SELF']);
//$tracer .= (string) adodb_backtrace(false);
$tracer = (string) substr($tracer,0,500);
@@ -165,7 +163,13 @@ function& adodb_log_sql(&$connx,$sql,$inputarr)
if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
}
$ok = $conn->Execute($isql,$arr);
global $ADODB_PERF_MIN;
if ($errN != 0 || $time >= $ADODB_PERF_MIN) {
$ok = $conn->Execute($isql,$arr);
} else
$ok = true;
$conn->debug = $saved;
if ($ok) {
@@ -173,7 +177,7 @@ function& adodb_log_sql(&$connx,$sql,$inputarr)
} else {
$err2 = $conn->ErrorMsg();
$conn->_logsql = true; // enable logsql error simulation
$perf =& NewPerfMonitor($conn);
$perf = NewPerfMonitor($conn);
if ($perf) {
if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
} else {
@@ -227,7 +231,7 @@ class adodb_perf {
var $maxLength = 2000;
// Sets the tablename to be used
function table($newtable = false)
static function table($newtable = false)
{
static $_table;
@@ -254,7 +258,7 @@ 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
// http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/414b0e1b-499c-411e-8a02-6a12e339c0f1/
if (strncmp(PHP_OS,'WIN',3)==0) {
if (PHP_VERSION == '5.0.0') return false;
if (PHP_VERSION == '5.0.1') return false;
@@ -262,14 +266,33 @@ processes 69293
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;
static $FAIL = false;
if ($FAIL) return false;
$objName = "winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\CIMV2";
$myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'";
try {
@$objWMIService = new COM($objName);
if (!$objWMIService) {
$FAIL = true;
return false;
}
$info[0] = -1;
$info[1] = 0;
$info[2] = 0;
$info[3] = 0;
foreach($objWMIService->ExecQuery($myQuery) as $objItem) {
$info[0] = $objItem->PercentProcessorTime();
}
} catch(Exception $e) {
$FAIL = true;
echo $e->getMessage();
return false;
}
$info[0] = $c->PercentProcessorTime;
$info[1] = 0;
$info[2] = 0;
$info[3] = $c->TimeStamp_Sys100NS;
//print_r($info);
return $info;
}
@@ -332,27 +355,26 @@ Committed_AS: 348732 kB
{
$info = $this->_CPULoad();
if (!$info) return false;
if (empty($this->_lastLoad)) {
sleep(1);
$this->_lastLoad = $info;
$info = $this->_CPULoad();
}
$last = $this->_lastLoad;
$this->_lastLoad = $info;
$d_user = $info[0] - $last[0];
$d_nice = $info[1] - $last[1];
$d_system = $info[2] - $last[2];
$d_idle = $info[3] - $last[3];
//printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
if (strncmp(PHP_OS,'WIN',3)==0) {
if ($d_idle < 1) $d_idle = 1;
return 100*(1-$d_user/$d_idle);
return (integer) $info[0];
}else {
if (empty($this->_lastLoad)) {
sleep(1);
$this->_lastLoad = $info;
$info = $this->_CPULoad();
}
$last = $this->_lastLoad;
$this->_lastLoad = $info;
$d_user = $info[0] - $last[0];
$d_nice = $info[1] - $last[1];
$d_system = $info[2] - $last[2];
$d_idle = $info[3] - $last[3];
//printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
$total=$d_user+$d_nice+$d_system+$d_idle;
if ($total<1) $total=1;
return 100*($d_user+$d_nice+$d_system)/$total;
@@ -408,7 +430,7 @@ Committed_AS: 348732 kB
$saveE = $this->conn->fnExecute;
$this->conn->fnExecute = false;
$perf_table = adodb_perf::table();
$rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
$rs = $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
$this->conn->fnExecute = $saveE;
if ($rs) {
$s .= rs2html($rs,false,false,false,false);
@@ -442,7 +464,7 @@ Committed_AS: 348732 kB
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
//$this->conn->debug=1;
$rs =& $this->conn->SelectLimit(
$rs = $this->conn->SelectLimit(
"select avg(timer) as avg_timer,$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')
@@ -521,7 +543,7 @@ Committed_AS: 348732 kB
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs =& $this->conn->SelectLimit(
$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')
@@ -570,7 +592,7 @@ Committed_AS: 348732 kB
/*
Raw function returning array of poll paramters
*/
function &PollParameters()
function PollParameters()
{
$arr[0] = (float)$this->DBParameter('data cache hit ratio');
$arr[1] = (float)$this->DBParameter('data reads');
@@ -640,6 +662,11 @@ Committed_AS: 348732 kB
else return '';
}
function clearsql()
{
$perf_table = adodb_perf::table();
$this->conn->Execute("delete from $perf_table where created<".$this->conn->sysTimeStamp);
}
/***********************************************************************************************/
// HIGH LEVEL UI FUNCTIONS
/***********************************************************************************************/
@@ -647,6 +674,7 @@ Committed_AS: 348732 kB
function UI($pollsecs=5)
{
global $ADODB_LOG_CONN;
$perf_table = adodb_perf::table();
$conn = $this->conn;
@@ -659,7 +687,7 @@ Committed_AS: 348732 kB
$savelog = $this->conn->LogSQL(false);
$info = $conn->ServerInfo();
if (isset($_GET['clearsql'])) {
$this->conn->Execute("delete from $perf_table");
$this->clearsql();
}
$this->conn->LogSQL($savelog);
@@ -688,6 +716,8 @@ Committed_AS: 348732 kB
else $form = "<td>&nbsp;</td>";
$allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
global $ADODB_PERF_MIN;
$app .= " (Min sql timing \$ADODB_PERF_MIN=$ADODB_PERF_MIN secs)";
if (empty($_GET['hidem']))
echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
@@ -702,13 +732,16 @@ Committed_AS: 348732 kB
switch ($do) {
default:
case 'stats':
if (empty($ADODB_LOG_CONN))
echo "<p>&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
echo $this->HealthCheck();
//$this->conn->debug=1;
echo $this->CheckMemory();
echo $this->CheckMemory();
break;
case 'poll':
$self = htmlspecialchars($_SERVER['PHP_SELF']);
echo "<iframe width=720 height=80%
src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
src=\"{$self}?do=poll2&hidem=1\"></iframe>";
break;
case 'poll2':
echo "<pre>";
@@ -743,13 +776,13 @@ Committed_AS: 348732 kB
//$this->conn->debug=1;
if ($secs <= 1) $secs = 1;
echo "Accumulating statistics, every $secs seconds...\n";flush();
$arro =& $this->PollParameters();
$arro = $this->PollParameters();
$cnt = 0;
set_time_limit(0);
sleep($secs);
while (1) {
$arr =& $this->PollParameters();
$arr = $this->PollParameters();
$hits = sprintf('%2.2f',$arr[0]);
$reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
@@ -885,7 +918,7 @@ Committed_AS: 348732 kB
{
$PHP_SELF = $_SERVER['PHP_SELF'];
$PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']);
$sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];

View File

@@ -1,7 +1,7 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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

@@ -241,6 +241,24 @@ b. Implement daylight savings, which looks awfully complicated, see
CHANGELOG
- 11 Feb 2008 0.33
* Bug in 0.32 fix for hour handling. Fixed.
- 1 Feb 2008 0.32
* Now adodb_mktime(0,0,0,12+$m,20,2040) works properly.
- 10 Jan 2008 0.31
* Now adodb_mktime(0,0,0,24,1,2037) works correctly.
- 15 July 2007 0.30
Added PHP 5.2.0 compatability fixes.
* gmtime behaviour for 1970 has changed. We use the actual date if it is between 1970 to 2038 to get the
* timezone, otherwise we use the current year as the baseline to retrieve the timezone.
* Also the timezone's in php 5.2.* support historical data better, eg. if timezone today was +8, but
in 1970 it was +7:30, then php 5.2 return +7:30, while this library will use +8.
*
- 19 March 2006 0.24
Changed strftime() locale detection, because some locales prepend the day of week to the date when %c is used.
@@ -368,7 +386,9 @@ First implementation.
/*
Version Number
*/
define('ADODB_DATE_VERSION',0.24);
define('ADODB_DATE_VERSION',0.33);
$ADODB_DATETIME_CLASS = (PHP_VERSION >= 5.2);
/*
This code was originally for windows. But apparently this problem happens
@@ -387,10 +407,13 @@ if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
function adodb_date_test_date($y1,$m,$d=13)
{
$t = adodb_mktime(0,0,0,$m,$d,$y1);
$h = round(rand()% 24);
$t = adodb_mktime($h,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>";
if ($h == 0) $h = '00';
else if ($h < 10) $h = '0'.$h;
if ("$y1-$m-$d $h:00:00" != $rez) {
print "<b>$y1 error, expected=$y1-$m-$d $h:00:00, adodb=$rez</b><br>";
return false;
}
return true;
@@ -403,16 +426,19 @@ function adodb_date_test_strftime($fmt)
if ($s1 == $s2) return true;
echo "error for $fmt, strftime=$s1, $adodb=$s2<br>";
echo "error for $fmt, strftime=$s1, adodb=$s2<br>";
return false;
}
/**
Test Suite
*/
*/
function adodb_date_test()
{
for ($m=-24; $m<=24; $m++)
echo "$m :",adodb_date('d-m-Y',adodb_mktime(0,0,0,1+$m,20,2040)),"<br>";
error_reporting(E_ALL);
print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."</h4>";
@set_time_limit(0);
@@ -421,6 +447,15 @@ function adodb_date_test()
// 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);
$t = time();
$fmt = 'Y-m-d H:i:s';
echo '<pre>';
echo 'adodb: ',adodb_date($fmt,$t),'<br>';
echo 'php : ',date($fmt,$t),'<br>';
echo '</pre>';
adodb_date_test_strftime('%Y %m %x %X');
adodb_date_test_strftime("%A %d %B %Y");
adodb_date_test_strftime("%H %M S");
@@ -480,6 +515,7 @@ function adodb_date_test()
// Test string formating
print "<p>Testing date formating</p>";
$fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C2822 r s t U w y Y z Z 2003';
$s1 = date($fmt,0);
$s2 = adodb_date($fmt,0);
@@ -657,15 +693,45 @@ function adodb_year_digit_check($y)
return $y;
}
/**
get local time zone offset from GMT
*/
function adodb_get_gmt_diff()
function adodb_get_gmt_diff_ts($ts)
{
static $TZ;
if (isset($TZ)) return $TZ;
if (0 <= $ts && $ts <= 0x7FFFFFFF) { // check if number in 32-bit signed range) {
$arr = getdate($ts);
$y = $arr['year'];
$m = $arr['mon'];
$d = $arr['mday'];
return adodb_get_gmt_diff($y,$m,$d);
} else {
return adodb_get_gmt_diff(false,false,false);
}
}
/**
get local time zone offset from GMT. Does not handle historical timezones before 1970.
*/
function adodb_get_gmt_diff($y,$m,$d)
{
static $TZ,$tzo;
global $ADODB_DATETIME_CLASS;
if (!defined('ADODB_TEST_DATES')) $y = false;
else if ($y < 1970 || $y >= 2038) $y = false;
if ($ADODB_DATETIME_CLASS && $y !== false) {
$dt = new DateTime();
$dt->setISODate($y,$m,$d);
if (empty($tzo)) {
$tzo = new DateTimeZone(date_default_timezone_get());
# $tzt = timezone_transitions_get( $tzo );
}
return -$tzo->getOffset($dt);
} else {
if (isset($TZ)) return $TZ;
$y = date('Y');
$TZ = mktime(0,0,0,12,2,$y,0) - gmmktime(0,0,0,12,2,$y,0);
}
$TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0);
return $TZ;
}
@@ -712,8 +778,8 @@ function adodb_validdate($y,$m,$d)
{
global $_month_table_normal,$_month_table_leaf;
if (_adodb_is_leap_year($y)) $marr =& $_month_table_leaf;
else $marr =& $_month_table_normal;
if (_adodb_is_leap_year($y)) $marr = $_month_table_leaf;
else $marr = $_month_table_normal;
if ($m > 12 || $m < 1) return false;
@@ -736,8 +802,7 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
static $YRS;
global $_month_table_normal,$_month_table_leaf;
$d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff());
$d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff_ts($origd));
$_day_power = 86400;
$_hour_power = 3600;
$_min_power = 60;
@@ -927,6 +992,22 @@ global $_month_table_normal,$_month_table_leaf;
0 => $origd
);
}
/*
if ($isphp5)
$dates .= sprintf('%s%04d',($gmt<=0)?'+':'-',abs($gmt)/36);
else
$dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36);
break;*/
function adodb_tz_offset($gmt,$isphp5)
{
$zhrs = abs($gmt)/3600;
$hrs = floor($zhrs);
if ($isphp5)
return sprintf('%s%02d%02d',($gmt<=0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
else
return sprintf('%s%02d%02d',($gmt<0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
}
function adodb_gmdate($fmt,$d=false)
{
@@ -958,6 +1039,7 @@ function adodb_date2($fmt, $d=false, $is_gmt=false)
function adodb_date($fmt,$d=false,$is_gmt=false)
{
static $daylight;
global $ADODB_DATETIME_CLASS;
if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt);
if (!defined('ADODB_TEST_DATES')) {
@@ -992,7 +1074,14 @@ static $daylight;
*/
for ($i=0; $i < $max; $i++) {
switch($fmt[$i]) {
case 'T': $dates .= date('T');break;
case 'T':
if ($ADODB_DATETIME_CLASS) {
$dt = new DateTime();
$dt->SetDate($year,$month,$day);
$dates .= $dt->Format('T');
} else
$dates .= date('T');
break;
// YEAR
case 'L': $dates .= $arr['leap'] ? '1' : '0'; break;
case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
@@ -1008,13 +1097,11 @@ static $daylight;
if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs;
$gmt = adodb_get_gmt_diff();
if ($isphp5)
$dates .= sprintf(' %s%04d',($gmt<=0)?'+':'-',abs($gmt)/36);
else
$dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36);
$gmt = adodb_get_gmt_diff($year,$month,$day);
$dates .= ' '.adodb_tz_offset($gmt,$isphp5);
break;
case 'Y': $dates .= $year; break;
case 'y': $dates .= substr($year,strlen($year)-2,2); break;
// MONTH
@@ -1041,14 +1128,11 @@ static $daylight;
// HOUR
case 'Z':
$dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break;
$dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff($year,$month,$day); break;
case 'O':
$gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff();
$gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff($year,$month,$day);
if ($isphp5)
$dates .= sprintf('%s%04d',($gmt<=0)?'+':'-',abs($gmt)/36);
else
$dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36);
$dates .= adodb_tz_offset($gmt,$isphp5);
break;
case 'H':
@@ -1130,16 +1214,21 @@ function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=fa
// 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
$usephpfns = (1971 < $year && $year < 2038
|| !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038)
) {
);
if ($usephpfns && ($year + $mon/12+$day/365.25+$hr/(24*365.25) >= 2038)) $usephpfns = false;
if ($usephpfns) {
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();
$gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff($year,$mon,$day);
/*
# disabled because some people place large values in $sec.
@@ -1156,7 +1245,7 @@ function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=fa
$year = adodb_year_digit_check($year);
if ($mon > 12) {
$y = floor($mon / 12);
$y = floor(($mon-1)/ 12);
$year += $y;
$mon -= $y*12;
} else if ($mon < 1) {

View File

@@ -119,7 +119,7 @@ class dbObject {
* NOP
*/
function dbObject( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
}
/**
@@ -249,7 +249,7 @@ class dbTable extends dbObject {
* @param array $attributes Array of table attributes.
*/
function dbTable( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
$this->name = $this->prefix($attributes['NAME']);
}
@@ -362,9 +362,9 @@ class dbTable extends dbObject {
* @param array $attributes Index attributes
* @return object dbIndex object
*/
function &addIndex( $attributes ) {
function addIndex( $attributes ) {
$name = strtoupper( $attributes['NAME'] );
$this->indexes[$name] =& new dbIndex( $this, $attributes );
$this->indexes[$name] = new dbIndex( $this, $attributes );
return $this->indexes[$name];
}
@@ -374,9 +374,9 @@ class dbTable extends dbObject {
* @param array $attributes Data attributes
* @return object dbData object
*/
function &addData( $attributes ) {
function addData( $attributes ) {
if( !isset( $this->data ) ) {
$this->data =& new dbData( $this, $attributes );
$this->data = new dbData( $this, $attributes );
}
return $this->data;
}
@@ -463,10 +463,12 @@ class dbTable extends dbObject {
* @return array Options
*/
function addTableOpt( $opt ) {
$this->opts[] = $opt;
if(isset($this->currentPlatform)) {
$this->opts[$this->parent->db->databaseType] = $opt;
}
return $this->opts;
}
/**
* Generates the SQL that will create the table in the database
@@ -641,7 +643,7 @@ class dbIndex extends dbObject {
* @internal
*/
function dbIndex( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
$this->name = $this->prefix ($attributes['NAME']);
}
@@ -785,7 +787,7 @@ class dbData extends dbObject {
* @internal
*/
function dbData( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
}
/**
@@ -984,7 +986,7 @@ class dbQuerySet extends dbObject {
* @param array $attributes Attributes
*/
function dbQuerySet( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
// Overrides the manual prefix key
if( isset( $attributes['KEY'] ) ) {
@@ -1304,7 +1306,7 @@ class adoSchema {
$this->mgq = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
$this->db =& $db;
$this->db = $db;
$this->debug = $this->db->debug;
$this->dict = NewDataDictionary( $this->db );
$this->sqlArray = array();
@@ -1627,7 +1629,7 @@ class adoSchema {
*
* @access private
*/
function &create_parser() {
function create_parser() {
// Create the parser
$xmlParser = xml_parser_create();
xml_set_object( $xmlParser, $this );

View File

@@ -137,7 +137,7 @@ class dbObject {
* NOP
*/
function dbObject( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
}
/**
@@ -274,7 +274,7 @@ class dbTable extends dbObject {
* @param array $attributes Array of table attributes.
*/
function dbTable( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
$this->name = $this->prefix($attributes['NAME']);
}
@@ -399,9 +399,9 @@ class dbTable extends dbObject {
* @param array $attributes Index attributes
* @return object dbIndex object
*/
function &addIndex( $attributes ) {
function addIndex( $attributes ) {
$name = strtoupper( $attributes['NAME'] );
$this->indexes[$name] =& new dbIndex( $this, $attributes );
$this->indexes[$name] = new dbIndex( $this, $attributes );
return $this->indexes[$name];
}
@@ -411,9 +411,9 @@ class dbTable extends dbObject {
* @param array $attributes Data attributes
* @return object dbData object
*/
function &addData( $attributes ) {
function addData( $attributes ) {
if( !isset( $this->data ) ) {
$this->data =& new dbData( $this, $attributes );
$this->data = new dbData( $this, $attributes );
}
return $this->data;
}
@@ -504,11 +504,12 @@ class dbTable extends dbObject {
* @return array Options
*/
function addTableOpt( $opt ) {
if( $this->currentPlatform ) {
$this->opts[] = $opt;
if(isset($this->currentPlatform)) {
$this->opts[$this->parent->db->databaseType] = $opt;
}
return $this->opts;
}
/**
* Generates the SQL that will create the table in the database
@@ -683,7 +684,7 @@ class dbIndex extends dbObject {
* @internal
*/
function dbIndex( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
$this->name = $this->prefix ($attributes['NAME']);
}
@@ -828,7 +829,7 @@ class dbData extends dbObject {
* @internal
*/
function dbData( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
}
/**
@@ -1084,7 +1085,7 @@ class dbQuerySet extends dbObject {
* @param array $attributes Attributes
*/
function dbQuerySet( &$parent, $attributes = NULL ) {
$this->parent =& $parent;
$this->parent = $parent;
// Overrides the manual prefix key
if( isset( $attributes['KEY'] ) ) {
@@ -1409,7 +1410,7 @@ class adoSchema {
$this->mgq = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
$this->db =& $db;
$this->db = $db;
$this->debug = $this->db->debug;
$this->dict = NewDataDictionary( $this->db );
$this->sqlArray = array();
@@ -1497,7 +1498,7 @@ class adoSchema {
$mode = XMLS_MODE_INSERT;
break;
default:
$mode = XMLS_EXISITNG_DATA;
$mode = XMLS_EXISTING_DATA;
break;
}
$this->existingData = $mode;
@@ -1785,7 +1786,7 @@ class adoSchema {
*
* @access private
*/
function &create_parser() {
function create_parser() {
// Create the parser
$xmlParser = xml_parser_create();
xml_set_object( $xmlParser, $this );

File diff suppressed because it is too large Load Diff

View File

@@ -1,183 +1,183 @@
<?php
/**
* Helper functions to convert between ADODB recordset objects and XMLRPC values.
* Uses John Lim's AdoDB and Edd Dumbill's phpxmlrpc libs
*
* @author Daniele Baroncelli
* @author Gaetano Giunta
* @copyright (c) 2003-2004 Giunta/Baroncelli. All rights reserved.
*
* @todo some more error checking here and there
* @todo document the xmlrpc-struct used to encode recordset info
* @todo verify if using xmlrpc_encode($rs->GetArray()) would work with:
* - ADODB_FETCH_BOTH
* - null values
*/
/**
* Include the main libraries
*/
require_once('xmlrpc.inc');
if (!defined('ADODB_DIR')) require_once('adodb.inc.php');
/**
* Builds an xmlrpc struct value out of an AdoDB recordset
*/
function rs2xmlrpcval(&$adodbrs) {
$header =& rs2xmlrpcval_header($adodbrs);
$body =& rs2xmlrpcval_body($adodbrs);
// put it all together and build final xmlrpc struct
$xmlrpcrs =& new xmlrpcval ( array(
"header" => $header,
"body" => $body,
), "struct");
return $xmlrpcrs;
}
/**
* Builds an xmlrpc struct value describing an AdoDB recordset
*/
function rs2xmlrpcval_header($adodbrs)
{
$numfields = $adodbrs->FieldCount();
$numrecords = $adodbrs->RecordCount();
// build structure holding recordset information
$fieldstruct = array();
for ($i = 0; $i < $numfields; $i++) {
$fld = $adodbrs->FetchField($i);
$fieldarray = array();
if (isset($fld->name))
$fieldarray["name"] =& new xmlrpcval ($fld->name);
if (isset($fld->type))
$fieldarray["type"] =& new xmlrpcval ($fld->type);
if (isset($fld->max_length))
$fieldarray["max_length"] =& new xmlrpcval ($fld->max_length, "int");
if (isset($fld->not_null))
$fieldarray["not_null"] =& new xmlrpcval ($fld->not_null, "boolean");
if (isset($fld->has_default))
$fieldarray["has_default"] =& new xmlrpcval ($fld->has_default, "boolean");
if (isset($fld->default_value))
$fieldarray["default_value"] =& new xmlrpcval ($fld->default_value);
$fieldstruct[$i] =& new xmlrpcval ($fieldarray, "struct");
}
$fieldcount =& new xmlrpcval ($numfields, "int");
$recordcount =& new xmlrpcval ($numrecords, "int");
$sql =& new xmlrpcval ($adodbrs->sql);
$fieldinfo =& new xmlrpcval ($fieldstruct, "array");
$header =& new xmlrpcval ( array(
"fieldcount" => $fieldcount,
"recordcount" => $recordcount,
"sql" => $sql,
"fieldinfo" => $fieldinfo
), "struct");
return $header;
}
/**
* Builds an xmlrpc struct value out of an AdoDB recordset
* (data values only, no data definition)
*/
function rs2xmlrpcval_body($adodbrs)
{
$numfields = $adodbrs->FieldCount();
// build structure containing recordset data
$adodbrs->MoveFirst();
$rows = array();
while (!$adodbrs->EOF) {
$columns = array();
// This should work on all cases of fetch mode: assoc, num, both or default
if ($adodbrs->fetchMode == 'ADODB_FETCH_BOTH' || count($adodbrs->fields) == 2 * $adodbrs->FieldCount())
for ($i = 0; $i < $numfields; $i++)
if ($adodbrs->fields[$i] === null)
$columns[$i] =& new xmlrpcval ('');
else
$columns[$i] =& xmlrpc_encode ($adodbrs->fields[$i]);
else
foreach ($adodbrs->fields as $val)
if ($val === null)
$columns[] =& new xmlrpcval ('');
else
$columns[] =& xmlrpc_encode ($val);
$rows[] =& new xmlrpcval ($columns, "array");
$adodbrs->MoveNext();
}
$body =& new xmlrpcval ($rows, "array");
return $body;
}
/**
* Returns an xmlrpc struct value as string out of an AdoDB recordset
*/
function rs2xmlrpcstring (&$adodbrs) {
$xmlrpc = rs2xmlrpcval ($adodbrs);
if ($xmlrpc)
return $xmlrpc->serialize();
else
return null;
}
/**
* Given a well-formed xmlrpc struct object returns an AdoDB object
*
* @todo add some error checking on the input value
*/
function xmlrpcval2rs (&$xmlrpcval) {
$fields_array = array();
$data_array = array();
// rebuild column information
$header =& $xmlrpcval->structmem('header');
$numfields = $header->structmem('fieldcount');
$numfields = $numfields->scalarval();
$numrecords = $header->structmem('recordcount');
$numrecords = $numrecords->scalarval();
$sqlstring = $header->structmem('sql');
$sqlstring = $sqlstring->scalarval();
$fieldinfo =& $header->structmem('fieldinfo');
for ($i = 0; $i < $numfields; $i++) {
$temp =& $fieldinfo->arraymem($i);
$fld =& new ADOFieldObject();
while (list($key,$value) = $temp->structeach()) {
if ($key == "name") $fld->name = $value->scalarval();
if ($key == "type") $fld->type = $value->scalarval();
if ($key == "max_length") $fld->max_length = $value->scalarval();
if ($key == "not_null") $fld->not_null = $value->scalarval();
if ($key == "has_default") $fld->has_default = $value->scalarval();
if ($key == "default_value") $fld->default_value = $value->scalarval();
} // while
$fields_array[] = $fld;
} // for
// fetch recordset information into php array
$body =& $xmlrpcval->structmem('body');
for ($i = 0; $i < $numrecords; $i++) {
$data_array[$i]= array();
$xmlrpcrs_row =& $body->arraymem($i);
for ($j = 0; $j < $numfields; $j++) {
$temp =& $xmlrpcrs_row->arraymem($j);
$data_array[$i][$j] = $temp->scalarval();
} // for j
} // for i
// finally build in-memory recordset object and return it
$rs =& new ADORecordSet_array();
$rs->InitArrayFields($data_array,$fields_array);
return $rs;
}
<?php
/**
* Helper functions to convert between ADODB recordset objects and XMLRPC values.
* Uses John Lim's AdoDB and Edd Dumbill's phpxmlrpc libs
*
* @author Daniele Baroncelli
* @author Gaetano Giunta
* @copyright (c) 2003-2004 Giunta/Baroncelli. All rights reserved.
*
* @todo some more error checking here and there
* @todo document the xmlrpc-struct used to encode recordset info
* @todo verify if using xmlrpc_encode($rs->GetArray()) would work with:
* - ADODB_FETCH_BOTH
* - null values
*/
/**
* Include the main libraries
*/
require_once('xmlrpc.inc');
if (!defined('ADODB_DIR')) require_once('adodb.inc.php');
/**
* Builds an xmlrpc struct value out of an AdoDB recordset
*/
function rs2xmlrpcval(&$adodbrs) {
$header = rs2xmlrpcval_header($adodbrs);
$body = rs2xmlrpcval_body($adodbrs);
// put it all together and build final xmlrpc struct
$xmlrpcrs = new xmlrpcval ( array(
"header" => $header,
"body" => $body,
), "struct");
return $xmlrpcrs;
}
/**
* Builds an xmlrpc struct value describing an AdoDB recordset
*/
function rs2xmlrpcval_header($adodbrs)
{
$numfields = $adodbrs->FieldCount();
$numrecords = $adodbrs->RecordCount();
// build structure holding recordset information
$fieldstruct = array();
for ($i = 0; $i < $numfields; $i++) {
$fld = $adodbrs->FetchField($i);
$fieldarray = array();
if (isset($fld->name))
$fieldarray["name"] = new xmlrpcval ($fld->name);
if (isset($fld->type))
$fieldarray["type"] = new xmlrpcval ($fld->type);
if (isset($fld->max_length))
$fieldarray["max_length"] = new xmlrpcval ($fld->max_length, "int");
if (isset($fld->not_null))
$fieldarray["not_null"] = new xmlrpcval ($fld->not_null, "boolean");
if (isset($fld->has_default))
$fieldarray["has_default"] = new xmlrpcval ($fld->has_default, "boolean");
if (isset($fld->default_value))
$fieldarray["default_value"] = new xmlrpcval ($fld->default_value);
$fieldstruct[$i] = new xmlrpcval ($fieldarray, "struct");
}
$fieldcount = new xmlrpcval ($numfields, "int");
$recordcount = new xmlrpcval ($numrecords, "int");
$sql = new xmlrpcval ($adodbrs->sql);
$fieldinfo = new xmlrpcval ($fieldstruct, "array");
$header = new xmlrpcval ( array(
"fieldcount" => $fieldcount,
"recordcount" => $recordcount,
"sql" => $sql,
"fieldinfo" => $fieldinfo
), "struct");
return $header;
}
/**
* Builds an xmlrpc struct value out of an AdoDB recordset
* (data values only, no data definition)
*/
function rs2xmlrpcval_body($adodbrs)
{
$numfields = $adodbrs->FieldCount();
// build structure containing recordset data
$adodbrs->MoveFirst();
$rows = array();
while (!$adodbrs->EOF) {
$columns = array();
// This should work on all cases of fetch mode: assoc, num, both or default
if ($adodbrs->fetchMode == 'ADODB_FETCH_BOTH' || count($adodbrs->fields) == 2 * $adodbrs->FieldCount())
for ($i = 0; $i < $numfields; $i++)
if ($adodbrs->fields[$i] === null)
$columns[$i] = new xmlrpcval ('');
else
$columns[$i] = xmlrpc_encode ($adodbrs->fields[$i]);
else
foreach ($adodbrs->fields as $val)
if ($val === null)
$columns[] = new xmlrpcval ('');
else
$columns[] = xmlrpc_encode ($val);
$rows[] = new xmlrpcval ($columns, "array");
$adodbrs->MoveNext();
}
$body = new xmlrpcval ($rows, "array");
return $body;
}
/**
* Returns an xmlrpc struct value as string out of an AdoDB recordset
*/
function rs2xmlrpcstring (&$adodbrs) {
$xmlrpc = rs2xmlrpcval ($adodbrs);
if ($xmlrpc)
return $xmlrpc->serialize();
else
return null;
}
/**
* Given a well-formed xmlrpc struct object returns an AdoDB object
*
* @todo add some error checking on the input value
*/
function xmlrpcval2rs (&$xmlrpcval) {
$fields_array = array();
$data_array = array();
// rebuild column information
$header = $xmlrpcval->structmem('header');
$numfields = $header->structmem('fieldcount');
$numfields = $numfields->scalarval();
$numrecords = $header->structmem('recordcount');
$numrecords = $numrecords->scalarval();
$sqlstring = $header->structmem('sql');
$sqlstring = $sqlstring->scalarval();
$fieldinfo = $header->structmem('fieldinfo');
for ($i = 0; $i < $numfields; $i++) {
$temp = $fieldinfo->arraymem($i);
$fld = new ADOFieldObject();
while (list($key,$value) = $temp->structeach()) {
if ($key == "name") $fld->name = $value->scalarval();
if ($key == "type") $fld->type = $value->scalarval();
if ($key == "max_length") $fld->max_length = $value->scalarval();
if ($key == "not_null") $fld->not_null = $value->scalarval();
if ($key == "has_default") $fld->has_default = $value->scalarval();
if ($key == "default_value") $fld->default_value = $value->scalarval();
} // while
$fields_array[] = $fld;
} // for
// fetch recordset information into php array
$body = $xmlrpcval->structmem('body');
for ($i = 0; $i < $numrecords; $i++) {
$data_array[$i]= array();
$xmlrpcrs_row = $body->arraymem($i);
for ($j = 0; $j < $numfields; $j++) {
$temp = $xmlrpcrs_row->arraymem($j);
$data_array[$i][$j] = $temp->scalarval();
} // for j
} // for i
// finally build in-memory recordset object and return it
$rs = new ADORecordSet_array();
$rs->InitArrayFields($data_array,$fields_array);
return $rs;
}
?>

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -49,7 +49,7 @@ class ADODB2_access extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'COUNTER';

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -47,7 +47,7 @@ class ADODB2_db2 extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with
@@ -83,7 +83,7 @@ class ADODB2_db2 extends ADODB_DataDict {
$validTypes = array("CHAR","VARC");
$invalidTypes = array("BIGI","BLOB","CLOB","DATE", "DECI","DOUB", "INTE", "REAL","SMAL", "TIME");
// check table exists
$cols = &$this->MetaColumns($tablename);
$cols = $this->MetaColumns($tablename);
if ( empty($cols)) {
return $this->CreateTableSQL($tablename, $flds, $tableoptions);
}

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -93,7 +93,7 @@ class ADODB2_firebird extends ADODB_DataDict {
}
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -62,7 +62,7 @@ class ADODB2_informix extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'SERIAL';

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,7 @@ class ADODB2_mssql extends ADODB_DataDict {
case 'TINYINT': return 'I1';
case 'SMALLINT': return 'I2';
case 'BIGINT': return 'I8';
case 'SMALLDATETIME': return 'T';
case 'REAL':
case 'FLOAT': return 'F';
default: return parent::MetaType($t,$len,$fieldobj);
@@ -151,7 +151,7 @@ class ADODB2_mssql extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";

View File

@@ -0,0 +1,282 @@
<?php
/**
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
*/
/*
In ADOdb, named quotes for MS SQL Server use ". From the MSSQL Docs:
Note Delimiters are for identifiers only. Delimiters cannot be used for keywords,
whether or not they are marked as reserved in SQL Server.
Quoted identifiers are delimited by double quotation marks ("):
SELECT * FROM "Blanks in Table Name"
Bracketed identifiers are delimited by brackets ([ ]):
SELECT * FROM [Blanks In Table Name]
Quoted identifiers are valid only when the QUOTED_IDENTIFIER option is set to ON. By default,
the Microsoft OLE DB Provider for SQL Server and SQL Server ODBC driver set QUOTED_IDENTIFIER ON
when they connect.
In Transact-SQL, the option can be set at various levels using SET QUOTED_IDENTIFIER,
the quoted identifier option of sp_dboption, or the user options option of sp_configure.
When SET ANSI_DEFAULTS is ON, SET QUOTED_IDENTIFIER is enabled.
Syntax
SET QUOTED_IDENTIFIER { ON | OFF }
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_mssqlnative extends ADODB_DataDict {
var $databaseType = 'mssqlnative';
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)
{
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 'R':
case 'INT':
case 'INTEGER': return 'I';
case 'BIT':
case 'TINYINT': return 'I1';
case 'SMALLINT': return 'I2';
case 'BIGINT': return 'I8';
case 'REAL':
case 'FLOAT': return 'F';
default: return parent::MetaType($t,$len,$fieldobj);
}
}
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
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';
case 'B': return 'IMAGE';
case 'D': return 'DATETIME';
case 'T': return 'DATETIME';
case 'L': return 'BIT';
case 'R':
case 'I': return 'INT';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INT';
case 'I8': return 'BIGINT';
case 'F': return 'REAL';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname $this->addCol";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
/*
function AlterColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
*/
function DropColumnSQL($tabname, $flds)
{
$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 ".$this->NameQuote($v);
}
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
// return string must begin with space
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
if ($fnotnull) $suffix .= ' NOT NULL';
else if ($suffix == '') $suffix .= ' NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }
| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)
[ ON { filegroup | DEFAULT } ]
[ TEXTIMAGE_ON { filegroup | DEFAULT } ]
< column_definition > ::= { column_name data_type }
[ COLLATE < collation_name > ]
[ [ DEFAULT constant_expression ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL]
[ < column_constraint > ] [ ...n ]
< column_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[ WITH FILLFACTOR = fillfactor ]
[ON {filegroup | DEFAULT} ] ]
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
]
| CHECK [ NOT FOR REPLICATION ]
( logical_expression )
}
< table_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
{ ( column [ ASC | DESC ] [ ,...n ] ) }
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ]
( search_conditions )
}
*/
/*
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
[ WITH < index_option > [ ,...n] ]
[ ON filegroup ]
< index_option > :: =
{ PAD_INDEX |
FILLFACTOR = fillfactor |
IGNORE_DUP_KEY |
DROP_EXISTING |
STATISTICS_NORECOMPUTE |
SORT_IN_TEMPDB
}
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
$clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
if ( is_array($flds) )
$flds = implode(', ',$flds);
$s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
function _GetSize($ftype, $ty, $fsize, $fprec)
{
switch ($ftype) {
case 'INT':
case 'SMALLINT':
case 'TINYINT':
case 'BIGINT':
return $ftype;
}
if ($ty == 'T') return $ftype;
return parent::_GetSize($ftype, $ty, $fsize, $fprec);
}
}
?>

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -107,7 +107,7 @@ class ADODB2_mysql extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -82,15 +82,16 @@ class ADODB2_oci8 extends ADODB_DataDict {
case 'D':
case 'T': return 'DATE';
case 'L': return 'DECIMAL(1)';
case 'I1': return 'DECIMAL(3)';
case 'I2': return 'DECIMAL(5)';
case 'L': return 'NUMBER(1)';
case 'I1': return 'NUMBER(3)';
case 'I2': return 'NUMBER(5)';
case 'I':
case 'I4': return 'DECIMAL(10)';
case 'I4': return 'NUMBER(10)';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'DECIMAL';
case 'N': return 'DECIMAL';
case 'I8': return 'NUMBER(20)';
case 'F': return 'NUMBER';
case 'N': return 'NUMBER';
case 'R': return 'NUMBER(20)';
default:
return $meta;
}
@@ -156,7 +157,7 @@ class ADODB2_oci8 extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.97 22 Jan 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -150,7 +150,7 @@ class ADODB2_postgres extends ADODB_DataDict {
}
return $sql;
}
function DropIndexSQL ($idxname, $tabname = NULL)
{
@@ -168,7 +168,8 @@ class ADODB2_postgres extends ADODB_DataDict {
* @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
* @return array with SQL strings
*/
/*function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
/*
function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
{
if (!$tableflds) {
if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
@@ -225,11 +226,11 @@ class ADODB2_postgres extends ADODB_DataDict {
}
// does not have alter column
if (!$tableflds) {
if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
return array();
}
return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
if (!$tableflds) {
if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
return array();
}
return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
}
/**
@@ -325,7 +326,7 @@ class ADODB2_postgres extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'SERIAL';

View File

@@ -1,121 +1,121 @@
<?php
/**
V4.50 6 July 2004 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified from datadict-generic.inc.php for sapdb by RalfBecker-AT-outdoor-training.de
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_sapdb extends ADODB_DataDict {
var $databaseType = 'sapdb';
var $seqField = false;
var $renameColumn = 'RENAME COLUMN %s.%s TO %s';
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'LONG';
case 'C2': return 'VARCHAR UNICODE';
case 'X2': return 'LONG UNICODE';
case 'B': return 'LONG';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'FIXED(3)';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'FIXED(20)';
case 'F': return 'FLOAT(38)';
case 'N': return 'FIXED';
default:
return $meta;
}
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
static $maxdb_type2adodb = array(
'VARCHAR' => 'C',
'CHARACTER' => 'C',
'LONG' => 'X', // no way to differ between 'X' and 'B' :-(
'DATE' => 'D',
'TIMESTAMP' => 'T',
'BOOLEAN' => 'L',
'INTEGER' => 'I4',
'SMALLINT' => 'I2',
'FLOAT' => 'F',
'FIXED' => 'N',
);
$type = isset($maxdb_type2adodb[$t]) ? $maxdb_type2adodb[$t] : 'C';
// convert integer-types simulated with fixed back to integer
if ($t == 'FIXED' && !$fieldobj->scale && ($len == 20 || $len == 3)) {
$type = $len == 20 ? 'I8' : 'I1';
}
if ($fieldobj->auto_increment) $type = 'R';
return $type;
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fautoinc) $suffix .= ' DEFAULT SERIAL';
elseif (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(', ',$lines) . ')' );
}
function AlterColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' );
}
function DropColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
if (!is_array($flds)) $flds = explode(',',$flds);
foreach($flds as $k => $v) {
$flds[$k] = $this->NameQuote($v);
}
return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(', ',$flds) . ')' );
}
}
<?php
/**
V4.50 6 July 2004 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Modified from datadict-generic.inc.php for sapdb by RalfBecker-AT-outdoor-training.de
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_sapdb extends ADODB_DataDict {
var $databaseType = 'sapdb';
var $seqField = false;
var $renameColumn = 'RENAME COLUMN %s.%s TO %s';
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'LONG';
case 'C2': return 'VARCHAR UNICODE';
case 'X2': return 'LONG UNICODE';
case 'B': return 'LONG';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'BOOLEAN';
case 'I': return 'INTEGER';
case 'I1': return 'FIXED(3)';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'FIXED(20)';
case 'F': return 'FLOAT(38)';
case 'N': return 'FIXED';
default:
return $meta;
}
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
static $maxdb_type2adodb = array(
'VARCHAR' => 'C',
'CHARACTER' => 'C',
'LONG' => 'X', // no way to differ between 'X' and 'B' :-(
'DATE' => 'D',
'TIMESTAMP' => 'T',
'BOOLEAN' => 'L',
'INTEGER' => 'I4',
'SMALLINT' => 'I2',
'FLOAT' => 'F',
'FIXED' => 'N',
);
$type = isset($maxdb_type2adodb[$t]) ? $maxdb_type2adodb[$t] : 'C';
// convert integer-types simulated with fixed back to integer
if ($t == 'FIXED' && !$fieldobj->scale && ($len == 20 || $len == 3)) {
$type = $len == 20 ? 'I8' : 'I1';
}
if ($fieldobj->auto_increment) $type = 'R';
return $type;
}
// return string must begin with space
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fautoinc) $suffix .= ' DEFAULT SERIAL';
elseif (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(', ',$lines) . ')' );
}
function AlterColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' );
}
function DropColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
if (!is_array($flds)) $flds = explode(',',$flds);
foreach($flds as $k => $v) {
$flds[$k] = $this->NameQuote($v);
}
return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(', ',$flds) . ')' );
}
}
?>

View File

@@ -1,7 +1,7 @@
<?php
/**
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -113,7 +113,7 @@ class ADODB2_sybase extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -20,8 +20,8 @@
</head>
<body style="background-color: rgb(255, 255, 255);">
<h2>ADOdb Data Dictionary Library for PHP</h2>
<p>V4.94 23 Jan 2007 (c) 2000-2007 John Lim (<a
href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>).<br>
<p>V5.06 16 Oct 2008 (c) 2000-2009 John Lim (<a
href="mailto:jlim#natsoft.com">jlim#natsoft.com</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
@@ -71,7 +71,7 @@ $dict-><b>ExecuteSQLArray</b>($sqlarray);
<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');
$db = NewADOConnection('odbtp');
$datadict = NewDataDictionary($db, 'mssql'); # force mssql
</pre>
<h3>Class Functions</h3>
@@ -103,7 +103,7 @@ represented as a string to avoid any rounding errors.</p>
<pre> AUTO For autoincrement number. Emulated with triggers if not available.<br> Sets NOTNULL also.<br> AUTOINCREMENT Same as auto.<br> KEY Primary key field. Sets NOTNULL also. Compound keys are supported.<br> PRIMARY Same as KEY.<br> DEF Synonym for DEFAULT for lazy typists.<br> DEFAULT The default value. Character strings are auto-quoted unless<br> the string begins and ends with spaces, eg ' SYSDATE '.<br> NOTNULL If field is not null.<br> DEFDATE Set default value to call function to get today's date.<br> DEFTIMESTAMP Set default to call function to get today's datetime.<br> NOQUOTE Prevents autoquoting of default string values.<br> CONSTRAINTS Additional constraints defined at the end of the field<br> definition.<br></pre>
<p>The Data Dictonary accepts two formats, the older array
specification:</p>
<pre> $flds = array(<br> array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' =&gt; 0, 'NOTNULL'),<br> array('id', 'I' , 'AUTO'),<br> array('`MY DATE`', 'D' , 'DEFDATE'),<br> array('NAME', 'C' , '32', 'CONSTRAINTS' =&gt; 'FOREIGN KEY REFERENCES reftable')<br> );<br></pre>
<pre> $flds = array(<br> array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' =gt; 0, 'NOTNULL'),<br> array('id', 'I' , 'AUTO'),<br> array('`MY DATE`', 'D' , 'DEFDATE'),<br> array('NAME', 'C' , '32', 'CONSTRAINTS' =gt; 'FOREIGN KEY REFERENCES reftable')<br> );<br></pre>
<p>Or the simpler declarative format:</p>
<pre> $flds = "<font color="#660000"><strong><br> COLNAME DECIMAL(8.4) DEFAULT 0 NOTNULL,<br> id I AUTO,<br> `MY DATE` D DEFDATE,<br> NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable'</strong></font><br> ";<br></pre>
<p>Note that if you have special characters in the field name (e.g. My
@@ -129,14 +129,14 @@ of the database type as the array key. In the following example, <em>create
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>
<pre> $taboptarray = array('mysql' =gt; 'TYPE=ISAM', 'oci8' =gt; 'tablespace users', 'REPLACE');</pre>
<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>
<pre> $taboptarray = array('constraints' =gt; ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');</pre>
<h4>function DropTableSQL($tabname)</h4>
<p>Returns the SQL to drop the specified table.</p>
<h4>function ChangeTableSQL($tabname, $flds)</h4>
<h4>function ChangeTableSQL($tabname, $flds, $tableOptions=false, $dropOldFlds=false)</h4>
<p>Checks to see if table exists, if table does not exist, behaves like
CreateTableSQL. If table exists, generates appropriate ALTER TABLE
MODIFY COLUMN commands if field already exists, or ALTER TABLE ADD
@@ -144,6 +144,7 @@ $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>
<p>Old fields not defined in $flds are not dropped by default. To drop old fields, set $dropOldFlds to true.
<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>
@@ -164,10 +165,10 @@ information can be embedded in the array. Other options include:</p>
<p>Drop 1 or more columns.</p>
<h4>function SetSchema($schema)</h4>
<p>Set the schema.</p>
<h4>function &amp;MetaTables()</h4>
<h4>function &amp;MetaColumns($tab, $upper=true, $schema=false)</h4>
<h4>function &amp;MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
<h4>function &amp;MetaIndexes($table, $primary = false, $owner = false)</h4>
<h4>function MetaTables()</h4>
<h4>function MetaColumns($tab, $upper=true, $schema=false)</h4>
<h4>function MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
<h4>function MetaIndexes($table, $primary = false, $owner = false)</h4>
<p>These functions are wrappers for the corresponding functions in the
connection object. However, the table names will be autoquoted by the
TableName function (see below) before being passed to the connection

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@ font-size: 8pt;
</head>
<body>
<h3>The ADOdb Performance Monitoring Library</h3>
<p>V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my)</p>
<p>V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com)</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>
@@ -229,7 +229,7 @@ need to echo or print the output of this function,</p>
<p>Returns database health check parameters formatted for a command
line interface. You will need to echo or print the output of this
function. Sample output for mysql:</p>
<pre>-- Ratios -- <br> MyISAM cache hit ratio =&gt; 56.5635738832 <br> InnoDB cache hit ratio =&gt; 0 <br> sql cache hit ratio =&gt; 0 <br> -- IO -- <br> data reads =&gt; 2622 <br> data writes =&gt; 2415.5 <br> -- Data Cache -- <br> MyISAM data cache size =&gt; 512K <br> BDB data cache size =&gt; 8388600<br> InnoDB data cache size =&gt; 8M<br> -- Memory Pools -- <br> read buffer size =&gt; 131072 <br> sort buffer size =&gt; 65528 <br> table cache =&gt; 4 <br> -- Connections -- <br> current connections =&gt; 3<br> max connections =&gt; 100</pre>
<pre>-- Ratios -- <br> MyISAM cache hit ratio =gt; 56.5635738832 <br> InnoDB cache hit ratio =gt; 0 <br> sql cache hit ratio =gt; 0 <br> -- IO -- <br> data reads =gt; 2622 <br> data writes =gt; 2415.5 <br> -- Data Cache -- <br> MyISAM data cache size =gt; 512K <br> BDB data cache size =gt; 8388600<br> InnoDB data cache size =gt; 8M<br> -- Memory Pools -- <br> read buffer size =gt; 131072 <br> sort buffer size =gt; 65528 <br> table cache =gt; 4 <br> -- Connections -- <br> current connections =gt; 3<br> max connections =gt; 100</pre>
<p><font face="Courier New, Courier, mono">function <b>Poll</b>($pollSecs=5)
</font> </p>
<p> Run in infinite loop, displaying the following information every
@@ -298,6 +298,9 @@ $this-&gt;DBParameter("data cache size").</p>
<p>Returns the CPU load of the database client (NOT THE SERVER) as a
percentage. Only works for Linux and Windows. For Windows, WMI must be
available.</p>
<h3>$ADODB_PERF_MIN</h3>
<p>New in adodb 4.97/5.03 is this global variable, which controls whether sql timings which are too small are not saved. Currently it defaults
to 0.05 (seconds). This means that all sql's which are faster than 0.05 seconds to execute are not saved.
<h3>Format of $settings Property</h3>
<p> To create new database parameters, you need to understand
$settings. The $settings data structure is an associative array. Each
@@ -334,7 +337,7 @@ will invoke $this-&gt;GetIndexDescription($val). This is useful for
generating tuning suggestions. For an example, see WarnCacheRatio().</li>
</ol>
<p>Example from MySQL, table_cache database parameter:</p>
<pre>'table cache' =&gt; array('CACHE', # category code<br> array("show variables", 'table_cache'), # array (type 1b)<br> 'Number of tables to keep open'), # description</pre>
<pre>'table cache' =gt; array('CACHE', # category code<br> array("show variables", 'table_cache'), # array (type 1b)<br> 'Number of tables to keep open'), # description</pre>
<h3>Example Health Check Output</h3>
<p><a href="#db2">db2</a> <a href="#informix">informix</a> <a
href="#mysql">mysql</a> <a href="#mssql">mssql</a> <a href="#oci8">oci8</a>

View File

@@ -21,7 +21,7 @@ font-size: 8pt;
<body style="background-color: rgb(255, 255, 255);">
<h1>ADODB Session 2 Management Manual</h1>
<p>
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my)
V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com)
</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

View File

@@ -1,822 +0,0 @@
<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.
<p>ADOdb sessions using oracle clobs contributed by achim.gosse#ddd.de. See adodb-session-clob.php.
<p>Added /s modifier to preg_match everywhere, which ensures that regex does not
stop at /n. Thx Pao-Hsi Huang.
<p>Fixed error in metacolumns() for mssql.
<p>Added time format support for SQLDate.
<p>Image => B added to metatype.
<p>MetaType now checks empty($this->blobSize) instead of empty($this).
<p>Datadict has beta support for informix, sybase (mapped to mssql), db2 and generic
(which is a fudge).
<p>BlobEncode for postgresql uses pg_escape_bytea, if available. Needed for compat
with 7.3.
<p>Added $ADODB_LANG, to support multiple languages in MetaErrorMsg().
<p>Datadict can now parse table definition as declarative text.
<p>For DataDict, oci8 autoincrement trigger missing semi-colon. Fixed.
<p>For DataDict, when REPLACE flag enabled, drop sequence in datadict for autoincrement
field in postgres and oci8.s
<p>Postgresql defaults to template1 database if no database defined in connect/pconnect.
<p>We now clear _resultid in postgresql if query fails.
<p><b>3.40 19 May 2003</b></p>
<p>Added insert_id for odbc_mssql.
<p>Modified postgresql UpdateBlobFile() because it did not work in safe mode.
<p>Now connection object is passed to raiseErrorFn as last parameter. Needed by
StartTrans().
<p>Added StartTrans() and CompleteTrans(). It is recommended that you do not modify
transOff, but use the above functions.
<p>oci8po now obeys ADODB_ASSOC_CASE settings.
<p>Added virtualized error codes, using PEAR DB equivalents. Requires you to manually
include adodb-error.inc.php yourself, with MetaError() and MetaErrorMsg($errno).
<p>GetRowAssoc for mysql and pgsql were flawed. Fix by Ross Smith.
<p>Added to datadict types I1, I2, I4 and I8. Changed datadict type 'T' to map
to timestamp instead of datetime for postgresql.
<p>Error handling in ExecuteSQLArray(), adodb-datadict.inc.php did not work.
<p>We now auto-quote postgresql connection parameters when building connection
string.
<p>Added session expiry notification.
<p>We now test with odbc mysql - made some changes to odbc recordset constructor.
<p>MetaColumns now special cases access and other databases for odbc.
<p><b>3.31 17 March 2003</b></p>
<p>Added row checking for _fetch in postgres.
<p>Added Interval type to MetaType for postgres.
<p>Remapped postgres driver to call postgres7 driver internally.
<p>Adorecordset_array::getarray() did not return array when nRows >= 0.
<p>Postgresql: at times, no error message returned by pg_result_error() but error
message returned in pg_last_error(). Recoded again.
<p>Interbase blob's now use chunking for updateblob.
<p>Move() did not set EOF correctly. Reported by Jorma T.
<p>We properly support mysql timestamp fields when we are creating mysql tables
using the data-dict interface.
<p>Table regex includes backticks character now.
<p><b>3.30 3 March 2003</b></p>
<p>Added $ADODB_EXTENSION and $ADODB_COMPAT_FETCH constant.
<p>Made blank1stItem configurable using syntax "value:text" in GetMenu/GetMenu2.
Thx to Gabriel Birke.
<p>Previously ADOdb differed from the Microsoft standard because it did not define
what to set $this->fields when EOF was reached. Now at EOF, ADOdb sets $this->fields
to false for all databases, which is consist with Microsoft's implementation.
Postgresql and mysql have always worked this way (in 3.11 and earlier). If you
are experiencing compatibility problems (and you are not using postgresql nor
mysql) on upgrading to 3.30, try setting the global variables $ADODB_COUNTRECS
= true (which is the default) and $ADODB_FETCH_COMPAT = true (this is a new
global variable).
<p>We now check both pg_result_error and pg_last_error as sometimes pg_result_error
does not display anything. Iman Mayes
<p> We no longer check for magic quotes gpc in Quote().
<p> Misc fixes for table creation in adodb-datadict.inc.php. Thx to iamsure.
<p> Time calculations use adodb_time library for all negative timestamps due to
problems in Red Hat 7.3 or later. Formerly, only did this for Windows.
<p> In mssqlpo, we now check if $sql in _query is a string before we change ||
to +. This is to support prepared stmts.
<p> Move() and MoveLast() internals changed to support to support EOF and $this->fields
change.
<p> Added ADODB_FETCH_BOTH support to mssql. Thx to Angel Fradejas afradejas#mediafusion.es
<p> We now check if link resource exists before we run mysql_escape_string in
qstr().
<p> Before we flock in csv code, we check that it is not a http url.
<p><b>3.20 17 Feb 2003</b></p>
<p>Added new Data Dictionary classes for creating tables and indexes. Warning
- this is very much alpha quality code. The API can still change. See adodb/tests/test-datadict.php
for more info.
<p>We now ignore $ADODB_COUNTRECS for mysql, because PHP truncates incomplete
recordsets when mysql_unbuffered_query() is called a second time.
<p>Now postgresql works correctly when $ADODB_COUNTRECS = false.
<p>Changed _adodb_getcount to properly support SELECT DISTINCT.
<p>Discovered that $ADODB_COUNTRECS=true has some problems with prepared queries
- suspect PHP bug.
<p>Now GetOne and GetRow run in $ADODB_COUNTRECS=false mode for better performance.
<p>Added support for mysql_real_escape_string() and pg_escape_string() in qstr().
<p>Added an intermediate variable for mysql _fetch() and MoveNext() to store fields,
to prevent overwriting field array with boolean when mysql_fetch_array() returns
false.
<p>Made arrays for getinsertsql and getupdatesql case-insensitive. Suggested by
Tim Uckun" tim#diligence.com
<p><b>3.11 11 Feb 2003</b></p>
<p>Added check for ADODB_NEVER_PERSIST constant in PConnect(). If defined, then
PConnect() will actually call non-persistent Connect().
<p>Modified interbase to properly work with Prepare().
<p>Added $this->ibase_timefmt to allow you to change the date and time format.
<p>Added support for $input_array parameter in CacheFlush().
<p>Added experimental support for dbx, which was then removed when i found that
it was slower than using native calls.
<p>Added MetaPrimaryKeys for mssql and ibase/firebird.
<p>Added new $trim parameter to GetCol and CacheGetCol
<p>Uses updated adodb-time.inc.php 0.06.
<p><b>3.10 27 Jan 2003</b>
<p>Added adodb_date(), adodb_getdate(), adodb_mktime() and adodb-time.inc.php.
<p>For interbase, added code to handle unlimited number of bind parameters. From
Daniel Hasan daniel#hasan.cl.
<p>Added BlobDecode and UpdateBlob for informix. Thx to Fernando Ortiz.
<p>Added constant ADODB_WINDOWS. If defined, means that running on Windows.
<p>Added constant ADODB_PHPVER which stores php version as a hex num. Removed
$ADODB_PHPVER variable.
<p>Felho Bacsi reported a minor white-space regular expression problem in GetInsertSQL.
<p>Modified ADO to use variant to store _affectedRows
<p>Changed ibase to use base class Replace(). Modified base class Replace() to
support ibase.
<p>Changed odbc to auto-detect when 0 records returned is wrong due to bad odbc
drivers.
<p>Changed mssql to use datetimeconvert ini setting only when 4.30 or later (does
not work in 4.23).
<p>ExecuteCursor($stmt, $cursorname, $params) now accepts a new $params array
of additional bind parameters -- William Lovaton walovaton#yahoo.com.mx.
<p>Added support for sybase_unbuffered_query if ADODB_COUNTRECS == false. Thx
to chuck may.
<p>Fixed FetchNextObj() bug. Thx to Jorma Tuomainen.
<p>We now use SCOPE_IDENTITY() instead of @@IDENTITY for mssql - thx to marchesini#eside.it
<p>Changed postgresql movenext logic to prevent illegal row number from being
passed to pg_fetch_array().
<p>Postgresql initrs bug found by "Bogdan RIPA" bripa#interakt.ro $f1 accidentally
named $f
<p><b>3.00 6 Jan 2003</b>
<p>Fixed adodb-pear.inc.php syntax error.
<p>Improved _adodb_getcount() to use SELECT COUNT(*) FROM ($sql) for languages
that accept it.
<p>Fixed _adodb_getcount() caching error.
<p>Added sql to retrive table and column info for odbc_mssql.
<p><strong>2.91 3 Jan 2003</strong>
<p>Revised PHP version checking to use $ADODB_PHPVER with legal values 0x4000,
0x4050, 0x4200, 0x4300.
<p>Added support for bytea fields and oid blobs in postgres by allowing BlobDecode()
to detect and convert non-oid fields. Also added BlobEncode to postgres when
you want to encode oid blobs.
<p>Added blobEncodeType property for connections to inform phpLens what encoding
method to use for blobs.
<p>Added BlobDecode() and BlobEncode() to base ADOConnection class.
<p>Added umask() to _gencachename() when creating directories.
<p>Added charPage for ado drivers, so you can set the code page.
<pre>
$conn->charPage = CP_UTF8;
$conn->Connect($dsn);
</pre>
<p>Modified _seek in mysql to check for num rows=0.
<p>Added to metatypes new informix types for IDS 9.30. Thx Fernando Ortiz.
<p>_maxrecordcount returned in CachePageExecute $rsreturn
<p>Fixed sybase cacheselectlimit( ) problems
<p>MetaColumns() max_length should use precision for types X and C for ms access.
Fixed.
<p>Speedup of odbc non-SELECT sql statements.
<p>Added support in MetaColumns for Wide Char types for ODBC. We halve max_length
if unicode/wide char.
<p>Added 'B' to types handled by GetUpdateSQL/GetInsertSQL.
<p>Fixed warning message in oci8 driver with $persist variable when using PConnect.
<p><b>2.90 11 Dec 2002</b>
<p>Mssql and mssqlpo and oci8po now support ADODB_ASSOC_CASE.
<p>Now MetaType() can accept a field object as the first parameter.
<p>New $arr = $db-&gt;ServerInfo( ) function. Returns $arr['description'] which
is the string description, and $arr['version'].
<p>PostgreSQL and MSSQL speedups for insert/updates.
<p> Implemented new SetFetchMode() that removes the need to use $ADODB_FETCH_MODE.
Each connection has independant fetchMode.
<p>ADODB_ASSOC_CASE now defaults to 2, use native defaults. This is because we
would break backward compat for too many applications otherwise.
<p>Patched encrypted sessions to use replace()
<p>The qstr function supports quoting of nulls when escape character is \
<p>Rewrote bits and pieces of session code to check for time synch and improve
reliability.
<p>Added property ADOConnection::hasTransactions = true/false;
<p>Added CreateSequence and DropSequence functions
<p>Found misplaced MoveNext() in adodb-postgres.inc.php. Fixed.
<p>Sybase SelectLimit not reliable because 'set rowcount' not cached - fixed.
<p>Moved ADOConnection to adodb-connection.inc.php and ADORecordSet to adodb-recordset.inc.php.
This allows us to use doxygen to generate documentation. Doxygen doesn't like
the classes in the main adodb.inc.php file for some mysterious reason.
<p><b>2.50, 14 Nov 2002</b>
<p>Added transOff and transCnt properties for disabling (transOff = true) and
tracking transaction status (transCnt>0).
<p>Added inputarray handling into _adodb_pageexecute_all_rows - "Ross Smith" RossSmith#bnw.com.
<p>Fixed postgresql inconsistencies in date handling.
<p>Added support for mssql_fetch_assoc.
<p>Fixed $ADODB_FETCH_MODE bug in odbc MetaTables() and MetaPrimaryKeys().
<p>Accidentally declared UnixDate() twice, making adodb incompatible with php
4.3.0. Fixed.
<p>Fixed pager problems with some databases that returned -1 for _currentRow on
MoveLast() by switching to MoveNext() in adodb-lib.inc.php.
<p>Also fixed uninited $discard in adodb-lib.inc.php.
<p><b>2.43, 25 Oct 2002</b></p>
Added ADODB_ASSOC_CASE constant to better support ibase and odbc field names.
<p>Added support for NConnect() for oracle OCINLogin.
<p>Fixed NumCols() bug.
<p>Changed session handler to use Replace() on write.
<p>Fixed oci8 SelectLimit aggregate function bug again.
<p>Rewrote pivoting code.
<p><b>2.42, 4 Oct 2002</b></p>
<p>Fixed ibase_fetch() problem with nulls. Also interbase now does automatic blob
decoding, and is backward compatible. Suggested by Heinz Hombergs heinz#hhombergs.de.
<p>Fixed postgresql MoveNext() problems when called repeatedly after EOF. Also
suggested by Heinz Hombergs.
<p>PageExecute() does not rewrite queries if SELECT DISTINCT is used. Requested
by hans#velum.net
<p>Added additional fixes to oci8 SelectLimit handling with aggregate functions
- thx to Christian Bugge for reporting the problem.
<p><b>2.41, 2 Oct 2002</b></p>
<p>Fixed ADODB_COUNTRECS bug in odbc. Thx to Joshua Zoshi jzoshi#hotmail.com.
<p>Increased buffers for adodb-csvlib.inc.php for extremely long sql from 8192
to 32000.
<p>Revised pivottable.inc.php code. Added better support for aggregate fields.
<p>Fixed mysql text/blob types problem in MetaTypes base class - thx to horacio
degiorgi.
<p>Added SQLDate($fmt,$date) function, which allows an sql date format string
to be generated - useful for group by's.
<p>Fixed bug in oci8 SelectLimit when offset>100.
<p><b>2.40 4 Sept 2002</b></p>
<p>Added new NLS_DATE_FORMAT property to oci8. Suggested by Laurent NAVARRO ln#altidev.com
<p>Now use bind parameters in oci8 selectlimit for better performance.
<p>Fixed interbase replaceQuote for dialect != 1. Thx to "BEGUIN Pierre-Henri
- INFOCOB" phb#infocob.com.
<p>Added white-space check to QA.
<p>Changed unixtimestamp to support fractional seconds (we always round down/floor
the seconds). Thanks to beezly#beezly.org.uk.
<p>Now you can set the trigger_error type your own user-defined type in adodb-errorhandler.inc.php.
Suggested by Claudio Bustos clbustos#entelchile.net.
<p>Added recordset filters with rsfilter.inc.php.
<p>$conn->_rs2rs does not create a new recordset when it detects it is of type
array. Some trickery there as there seems to be a bug in Zend Engine
<p>Added render_pagelinks to adodb-pager.inc.php. Code by "Pablo Costa" pablo#cbsp.com.br.
<p>MetaType() speedup in adodb.inc.php by using hashing instead of switch. Best
performance if constant arrays are supported, as they are in PHP5.
<p>adodb-session.php now updates only the expiry date if the crc32 check indicates
that the data has not been modified.
<p><b>2.31 20 Aug 2002</b></p>
<p>Made changes to pivottable.inc.php due to daniel lucuzaeu's suggestions (we sum the pivottable column if desired).
<p>Fixed ErrorNo() in postgres so it does not depend on _errorMsg property.
<p>Robert Tuttle added support for oracle cursors. See ExecuteCursor().
<p>Fixed Replace() so it works with mysql when updating record where data has not changed. Reported by
Cal Evans (cal#calevans.com).
<p><b>2.30 1 Aug 2002</b></p>
<p>Added pivottable.inc.php. Thanks to daniel.lucazeau#ajornet.com for the original
concept.
<p>Added ADOConnection::outp($msg,$newline) to output error and debugging messages. Now
you can override this using the ADODB_OUTP constant and use your own output handler.
<p>Changed == to === for 'null' comparison. Reported by ericquil#yahoo.com
<p>Fixed mssql SelectLimit( ) bug when distinct used.
<p><b>2.30 1 Aug 2002</b></p>
<p>New GetCol() and CacheGetCol() from ross#bnw.com that returns the first field as a 1 dim array.
<p>We have an empty recordset, but RecordCount() could return -1. Fixed. Reported by "Jonathan Polansky" jonathan#polansky.com.
<p>We now check for session variable changes using strlen($sessval).crc32($sessval).
Formerly we only used crc32().
<p>Informix SelectLimit() problem with $ADODB_COUNTRECS fixed.
<p>Fixed informix SELECT FIRST x DISTINCT, and not SELECT DISTINCT FIRST x - reported by F Riosa
<p>Now default adodb error handlers ignores error if @ used.
<p>If you set $conn->autoRollback=true, we auto-rollback persistent connections for odbc, mysql, oci8, mssql.
Default for autoRollback is false. No need to do so for postgres.
As interbase requires a transaction id (what a flawed api), we don't do it for interbase.
<p>Changed PageExecute() to use non-greedy preg_match when searching for "FROM" keyword.
<p><b>2.20 9 July 2002</b></p>
<p>Added CacheGetOne($secs2cache,$sql), CacheGetRow($secs2cache,$sql), CacheGetAll($secs2cache,$sql).
<p>Added $conn->OffsetDate($dayFraction,$date=false) to generate sql that calcs
date offsets. Useful for scheduling appointments.
<p>Added connection properties: leftOuter, rightOuter that hold left and right
outer join operators.
<p>Added connection property: ansiOuter to indicate whether ansi outer joins supported.
<p>New driver <i>mssqlpo</i>, the portable mssql driver, which converts string
concat operator from || to +.
<p>Fixed ms access bug - SelectLimit() did not support ties - fixed.
<p>Karsten Kraus (Karsten.Kraus#web.de), contributed error-handling code to ADONewConnection.
Unfortunately due to backward compat problems, had to rollback most of the changes.
<p>Added new parameter to GetAssoc() to allow returning an array of key-value pairs,
ignoring any additional columns in the recordset. Off by default.
<p>Corrected mssql $conn->sysDate to return only date using convert().
<p>CacheExecute() improved debugging output.
<p>Changed rs2html() so newlines are converted to BR tags. Also optimized rs2html() based
on feedback by "Jerry Workman" jerry#mtncad.com.
<p>Added support for Replace() with Interbase, using DELETE and INSERT.
<p>Some minor optimizations (mostly removing & references when passing arrays).
<p>Changed GenID() to allows id's larger than the size of an integer.
<p>Added force_session property to oci8 for better updateblob() support.
<p>Fixed PageExecute() which did not work properly with sql containing GROUP BY.
<p><b>2.12 12 June 2002</b></p>
<p>Added toexport.inc.php to export recordsets in CSV and tab-delimited format.
<p>CachePageExecute() does not work - fixed - thx John Huong.
<p>Interbase aliases not set properly in FetchField() - fixed. Thx Stefan Goethals.
<p>Added cache property to adodb pager class. The number of secs to cache recordsets.
<p>SQL rewriting bug in pageexecute() due to skipping of newlines due to missing /s modifier. Fixed.
<p>Max size of cached recordset due to a bug was 256000 bytes. Fixed.
<p>Speedup of 1st invocation of CacheExecute() by tuning code.
<p>We compare $rewritesql with $sql in pageexecute code in case of rewrite failure.
<p><b>2.11 7 June 2002</b></p>
<p>Fixed PageExecute() rewrite sql problem - COUNT(*) and ORDER BY don't go together with
mssql, access and postgres. Thx to Alexander Zhukov alex#unipack.ru
<p>DB2 support for CHARACTER type added - thx John Huong huongch#bigfoot.com
<p>For ado, $argProvider not properly checked. Fixed - kalimero#ngi.it
<p>Added $conn->Replace() function for update with automatic insert if the record does not exist.
Supported by all databases except interbase.
<p><b>2.10 4 June 2002</b></p>
<p>Added uniqueSort property to indicate mssql ORDER BY cols must be unique.
<p>Optimized session handler by crc32 the data. We only write if session data has changed.
<p>adodb_sess_read in adodb-session.php now returns ''correctly - thanks to Jorma Tuomainen, webmaster#wizactive.com
<p>Mssql driver did not throw EXECUTE errors correctly because ErrorMsg() and ErrorNo() called in wrong order.
Pointed out by Alexios Fakos. Fixed.
<p>Changed ado to use client cursors. This fixes BeginTran() problems with ado.
<p>Added handling of timestamp type in ado.
<p>Added to ado_mssql support for insert_id() and affected_rows().
<p>Added support for mssql.datetimeconvert=0, available since php 4.2.0.
<p>Made UnixDate() less strict, so that the time is ignored if present.
<p>Changed quote() so that it checks for magic_quotes_gpc.
<p>Changed maxblobsize for odbc to default to 64000.
<p><b>2.00 13 May 2002</b></p>
<p>Added drivers <i>informix72</i> for pre-7.3 versions, and <i>oci805</i> for
oracle 8.0.5, and postgres64 for postgresql 6.4 and earlier. The postgres and postgres7 drivers
are now identical.
<p>Interbase now partially supports ADODB_FETCH_BOTH, by defaulting to ASSOC mode.
<p>Proper support for blobs in mssql. Also revised blob support code
is base class. Now UpdateBlobFile() calls UpdateBlob() for consistency.
<p>Added support for changed odbc_fetch_into api in php 4.2.0
with $conn-&gt;_has_stupid_odbc_fetch_api_change.
<p>Fixed spelling of tablock locking hint in GenID( ) for mssql.
<p>Added RowLock( ) to several databases, including oci8, informix, sybase, etc.
Fixed where error in mssql RowLock().
<p>Added sysDate and sysTimeStamp properties to most database drivers. These are the sql
functions/constants for that database that return the current date and current timestamp, and
are useful for portable inserts and updates.
<p>Support for RecordCount() caused date handling in sybase and mssql to break.
Fixed, thanks to Toni Tunkkari, by creating derived classes for ADORecordSet_array for
both databases. Generalized using arrayClass property. Also to support RecordCount(),
changed metatype handling for ado drivers. Now the type returned in FetchField
is no longer a number, but the 1-char data type returned by MetaType.
At the same time, fixed a lot of date handling. Now mssql support dmy and mdy date formats.
Also speedups in sybase and mssql with preg_match and ^ in date/timestamp handling.
Added support in sybase and mssql for 24 hour clock in timestamps (no AM/PM).
<p>Extensive revisions to informix driver - thanks to Samuel CARRIERE samuel_carriere#hotmail.com
<p>Added $ok parameter to CommitTrans($ok) for easy rollbacks.
<p>Fixed odbc MetaColumns and MetaTables to save and restore $ADODB_FETCH_MODE.
<p>Some odbc drivers did not call the base connection class constructor. Fixed.
<p>Fixed regex for GetUpdateSQL() and GetInsertSQL() to support more legal character combinations.
<p><b>1.99 21 April 2002</b></p>
<p>Added emulated RecordCount() to all database drivers if $ADODB_COUNTRECS = true
(which it is by default). Inspired by Cristiano Duarte (cunha17#uol.com.br).
<p>Unified stored procedure support for mssql and oci8. Parameter() and PrepareSP()
functions implemented.
<p>Added support for SELECT FIRST in informix, modified hasTop property to support
this.
<p>Changed csv driver to handle updates/deletes/inserts properly (when Execute() returns true).
Bind params also work now, and raiseErrorFn with csv driver. Added csv driver to QA process.
<p>Better error checking in oci8 UpdateBlob() and UpdateBlobFile().
<p>Added TIME type to MySQL - patch by Manfred h9125297#zechine.wu-wien.ac.at
<p>Prepare/Execute implemented for Interbase/Firebird
<p>Changed some regular expressions to be anchored by /^ $/ for speed.
<p>Added UnixTimeStamp() and UnixDate() to ADOConnection(). Now these functions
are in both ADOConnection and ADORecordSet classes.
<p>Empty recordsets were not cached - fixed.
<p>Thanks to Gaetano Giunta (g.giunta#libero.it) for the oci8 code review. We
didn't agree on everything, but i hoped we agreed to disagree!
<p><b>1.90 6 April 2002</b></p>
<p>Now all database drivers support fetch modes ADODB_FETCH_NUM and ADODB_FETCH_ASSOC, though
still not fully tested. Eg. Frontbase, Sybase, Informix.
<p>NextRecordSet() support for mssql. Contributed by "Sven Axelsson" sven.axelsson#bokochwebb.se
<p>Added blob support for SQL Anywhere. Contributed by Wade Johnson wade#wadejohnson.de
<p>Fixed some security loopholes in server.php. Server.php also supports fetch mode.
<p>Generalized GenID() to support odbc and mssql drivers. Mssql no longer generates GUID's.
<p>Experimental RowLock($table,$where) for mssql.
<p>Properly implemented Prepare() in oci8 and ODBC.
<p>Added Bind() support to oci8 to support Prepare().
<p>Improved error handler. Catches CacheExecute() and GenID() errors now.
<p>Now if you are running php from the command line, debugging messages do not output html formating.
Not 100% complete, but getting there.
<p><b>1.81 22 March 2002</b></p>
<p>Restored default $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT for backward compatibility.
<p>SelectLimit for oci8 improved - Our FIRST_ROWS optimization now does not overwrite existing hint.
<p>New Sybase SQL Anywhere driver. Contributed by Wade Johnson wade#wadejohnson.de
<p><b>1.80 15 March 2002</b></p>
<p>Redesigned directory structure of ADOdb files. Added new driver directory where
all database drivers reside.
<p>Changed caching algorithm to create subdirectories. Now we scale better.
<p>Informix driver now supports insert_id(). Contribution by "Andrea Pinnisi" pinnisi#sysnet.it
<p>Added experimental ISO date and FetchField support for informix.
<p>Fixed a quoting bug in Execute() with bind parameters, causing problems with blobs.
<p>Mssql driver speedup by 10-15%.
<p>Now in CacheExecute($secs2cache,$sql,...), $secs2cache is optional. If missing, it will
take the value defined in $connection->cacheSecs (default is 3600 seconds). Note that
CacheSelectLimit(), the secs2cache is still compulsory - sigh.
<p>Sybase SQL Anywhere driver (using ODBC) contributed by Wade Johnson wade#wadejohnson.de
<p><b>1.72 8 March 2002</b></p>
<p>Added @ when returning Fields() to prevent spurious error - "Michael William Miller" mille562#pilot.msu.edu
<p>MetaDatabases() for postgres contributed by Phil pamelant#nerim.net
<p>Mitchell T. Young (mitch#youngfamily.org) contributed informix driver.
<p>Fixed rs2html() problem. I cannot reproduce, so probably a problem with pre PHP 4.1.0 versions,
when supporting new ADODB_FETCH_MODEs.
<p>Mattia Rossi (mattia#technologist.com) contributed BlobDecode() and UpdateBlobFile() for postgresql
using the postgres specific pg_lo_import()/pg_lo_open() - i don't use them but hopefully others will
find this useful. See <a href="http://phplens.com/lens/lensforum/msgs.php?id=1262">this posting</a>
for an example of usage.
<p>Added UpdateBlobFile() for uploading files to a database.
<p>Made UpdateBlob() compatible with oci8po driver.
<p>Added noNullStrings support to oci8 driver. Oracle changes all ' ' strings to nulls,
so you need to set strings to ' ' to prevent the nullifying of strings. $conn->noNullStrings = true;
will do this for you automatically. This is useful when you define a char column as NOT NULL.
<p>Fixed UnixTimeStamp() bug - wasn't setting minutes and seconds properly. Patch from Agusti Fita i Borrell agusti#anglatecnic.com.
<p>Toni Tunkkari added patch for sybase dates. Problem with spaces in day part of date fixed.
<p><b>1.71 18 Jan 2002</b></p>
<p>Sequence start id support. Now $conn->Gen_ID('seqname', 50) to start sequence from 50.
<p>CSV driver fix for selectlimit, from Andreas - akaiser#vocote.de.
<P>Gam3r spotted that a global variable was undefined in the session handler.
<p>Mssql date regex had error. Fixed - reported by Minh Hoang vb_user#yahoo.com.
<p>DBTimeStamp() and DBDate() now accept iso dates and unix timestamps. This means
that the PostgreSQL handling of dates in GetInsertSQL() and GetUpdateSQL() can
be removed. Also if these functions are passed '' or null or false, we return a SQL null.
<p>GetInsertSQL() and GetUpdateSQL() now accept a new parameter, $magicq to
indicate whether quotes should be inserted based on magic quote settings - suggested by
dj#4ict.com.
<p>Reformated docs slightly based on suggestions by Chris Small.
<p><b>1.65 28 Dec 2001</b></p>
<p>Fixed borland_ibase class naming bug.
<p>Now instead of using $rs->fields[0] internally, we use reset($rs->fields) so
that we are compatible with ADODB_FETCH_ASSOC mode. Reported by Nico S.
<p>Changed recordset constructor and _initrs() for oci8 so that it returns the field definitions even
if no rows in the recordset. Reported by Rick Hickerson (rhickers#mv.mv.com).
<p>Improved support for postgresql in GetInsertSQL and GetUpdateSQL by
"mike" mike#partner2partner.com and "Ryan Bailey" rebel#windriders.com
<p><b>1.64 20 Dec 2001</b></p>
<p>Danny Milosavljevic &lt;danny.milo#gmx.net> added some patches for MySQL error handling
and displaying default values.
<p>Fixed some ADODB_FETCH_BOTH inconsistencies in odbc and interbase.
<p>Added more tests to test suite to cover ADODB_FETCH_* and ADODB_ERROR_HANDLER.
<p>Added firebird (ibase) driver
<p>Added borland_ibase driver for interbase 6.5
<p><b>1.63 13 Dec 2001</b></p>
Absolute to the adodb-lib.inc.php file not set properly. Fixed.<p>
<p><b>1.62 11 Dec 2001</b></p>
<p>Major speedup of ADOdb for low-end web sites by reducing the php code loading and compiling
cycle. We conditionally compile not so common functions.
Moved csv code to adodb-csvlib.inc.php to reduce adodb.inc.php parsing. This file
is loaded only when the csv/proxy driver is used, or CacheExecute() is run.
Also moved PageExecute(), GetSelectSQL() and GetUpdateSQL() core code to adodb-lib.inc.php.
This reduced the 70K main adodb.inc.php file to 55K, and since at least 20K of the file
is comments, we have reduced 50K of code in adodb.inc.php to 35K. There
should be 35% reduction in memory and thus 35% speedup in compiling the php code for the
main adodb.inc.php file.
<p>Highly tuned SelectLimit() for oci8 for massive speed improvements on large files.
Selecting 20 rows starting from the 20,000th row of a table is now 7 times faster.
Thx to Tomas V V Cox.
<p>Allow . and # in table definitions in GetInsertSQL and GetUpdateSQL.
See ADODB_TABLE_REGEX constant. Thx to Ari Kuorikoski.
<p>Added ADODB_PREFETCH_ROWS constant, defaulting to 10. This determines the number
of records to prefetch in a SELECT statement. Only used by oci8.</p>
<p>Added high portability Oracle class called oci8po. This uses ? for bind variables, and
lower cases column names.</p>
<p>Now all database drivers support $ADODB_FETCH_MODE, including interbase, ado, and odbc:
ADODB_FETCH_NUM and ADODB_FETCH_ASSOC. ADODB_FETCH_BOTH is not fully implemented for all
database drivers.
<p><b>1.61 Nov 2001</b></p>
<p>Added PO_RecordCount() and PO_Insert_ID(). PO stands for portable. Pablo Roca
[pabloroca#mvps.org]</p>
<p>GenID now returns 0 if not available. Safer is that you should check $conn->hasGenID
for availability.</p>
<p>M'soft ADO we now correctly close recordset in _close() peterd#telephonetics.co.uk</p>
<p>MSSQL now supports GenID(). It generates a 16-byte GUID from mssql newid()
function.</p>
<p>Changed ereg_replace to preg_replace in SelectLimit. This is a fix for mssql.
Ereg doesn't support t or n! Reported by marino Carlos xaplo#postnuke-espanol.org</p>
<p>Added $recordset->connection. This is the ADOConnection object for the recordset.
Works with cached and normal recordsets. Surprisingly, this had no affect on performance!</p>
<p><b>1.54 15 Nov 2001</b></p>
Fixed some more bugs in PageExecute(). I am getting sick of bug in this and will have to
reconsider my QA here. The main issue is that I don't use PageExecute() and
to check whether it is working requires a visual inspection of the html generated currently.
It is possible to write a test script but it would be quite complicated :(
<p> More speedups of SelectLimit() for DB2, Oci8, access, vfp, mssql.
<p>
<p><b>1.53 7 Nov 2001</b></p>
Added support for ADODB_FETCH_ASSOC for ado and odbc drivers.<p>
Tuned GetRowAssoc(false) in postgresql and mysql.<p>
Stephen Van Dyke contributed ADOdb icon, accepted with some minor mods.<p>
Enabled Affected_Rows() for postgresql<p>
Speedup for Concat() using implode() - Benjamin Curtis ben_curtis#yahoo.com<p>
Fixed some more bugs in PageExecute() to prevent infinite loops<p>
<p><b>1.52 5 Nov 2001</b></p>
Spelling error in CacheExecute() caused it to fail. $ql should be $sql in line 625!<p>
Added fixes for parsing [ and ] in GetUpdateSQL().
<p><b>1.51 5 Nov 2001</b></p>
<p>Oci8 SelectLimit() speedup by using OCIFetch().
<p>Oci8 was mistakenly reporting errors when $db->debug = true.
<p>If a connection failed with ODBC, it was not correctly reported - fixed.
<p>_connectionID was inited to -1, changed to false.
<p>Added $rs->FetchRow(), to simplify API, ala PEAR DB
<p>Added PEAR DB compat mode, which is still faster than PEAR! See adodb-pear.inc.php.
<p>Removed postgres pconnect debugging statement.
<p><b>1.50 31 Oct 2001</b></p>
<p>ADOdbConnection renamed to ADOConnection, and ADOdbFieldObject to ADOFieldObject.
<p>PageExecute() now checks for empty $rs correctly, and the errors in the docs on this subject have been fixed.
<p>odbc_error() does not return 6 digit error correctly at times. Implemented workaround.
<p>Added ADORecordSet_empty class. This will speedup INSERTS/DELETES/UPDATES because the return
object created is much smaller.
<p>Added Prepare() to odbc, and oci8 (but doesn't work properly for oci8 still).
<p>Made pgsql a synonym for postgre7, and changed SELECT LIMIT to use OFFSET for compat with
postgres 7.2.
<p>Revised adodb-cryptsession.php thanks to Ari.
<p>Set resources to false on _close, to force freeing of resources.
<p>Added adodb-errorhandler.inc.php, adodb-errorpear.inc.php and raiseErrorFn on Freek's urging.
<p>GetRowAssoc($toUpper=true): $toUpper added as default.
<p>Errors when connecting to a database were not captured formerly. Now we do it correctly.
<p><b>1.40 19 September 2001</b></p>
<p>PageExecute() to implement page scrolling added. Code and idea by Iv&aacute;n Oliva.</p>
<p>Some minor postgresql fixes.</p>
<p>Added sequence support using GenID() for postgresql, oci8, mysql, interbase.</p>
<p>Added UpdateBlob support for interbase (untested).</p>
<p>Added encrypted sessions (see adodb-cryptsession.php). By Ari Kuorikoski &lt;kuoriari#finebyte.com></p>
<p><b>1.31 21 August 2001</b></p>
<p>Many bug fixes thanks to "GaM3R (Cameron)" &lt;gamr#outworld.cx>. Some session changes due to Gam3r.
<p>Fixed qstr() to quote also.
<p>rs2html() now pretty printed.
<p>Jonathan Younger jyounger#unilab.com contributed the great idea GetUpdateSQL() and GetInsertSQL() which
generates SQL to update and insert into a table from a recordset. Modify the recordset fields
array, then can this function to generate the SQL (the SQL is not executed).
<p>"Nicola Fankhauser" &lt;nicola.fankhauser#couniq.com> found some bugs in date handling for mssql.</p>
<p>Added minimal Oracle support for LOBs. Still under development.</p>
Added $ADODB_FETCH_MODE so you can control whether recordsets return arrays which are
numeric, associative or both. This is a global variable you set. Currently only MySQL, Oci8, Postgres
drivers support this.
<p>PostgreSQL properly closes recordsets now. Reported by several people.
<p>
Added UpdateBlob() for Oracle. A hack to make it easier to save blobs.
<p>
Oracle timestamps did not display properly. Fixed.
<p><b>1.20 6 June 2001</b></p>
<p>Now Oracle can connect using tnsnames.ora or server and service name</p>
<p>Extensive Oci8 speed optimizations.
Oci8 code revised to support variable binding, and /*+ FIRST_ROWS */ hint.</p>
<p>Worked around some 4.0.6 bugs in odbc_fetch_into().</p>
<p>Paolo S. Asioli paolo.asioli#libero.it suggested GetRowAssoc().</p>
<p>Escape quotes for oracle wrongly set to '. Now '' is used.</p>
<p>Variable binding now works in ODBC also.</p>
<p>Jumped to version 1.20 because I don't like 13 :-)</p>
<p><b>1.12 6 June 2001</b></p>
<p>Changed $ADODB_DIR to ADODB_DIR constant to plug a security loophole.</p>
<p>Changed _close() to close persistent connections also. Prevents connection leaks.</p>
<p>Major revision of oracle and oci8 drivers.
Added OCI_RETURN_NULLS and OCI_RETURN_LOBS to OCIFetchInto(). BLOB, CLOB and VARCHAR2 recognition
in MetaType() improved. MetaColumns() returns columns in correct sort order.</p>
<p>Interbase timestamp input format was wrong. Fixed.</p>
<p><b>1.11 20 May 2001</b></p>
<p>Improved file locking for Windows.</p>
<p>Probabilistic flushing of cache to avoid avalanche updates when cache timeouts.</p>
<p>Cached recordset timestamp not saved in some scenarios. Fixed.</p>
<p><b>1.10 19 May 2001</b></p>
<p>Added caching. CacheExecute() and CacheSelectLimit().
<p>Added csv driver. See <a href="http://php.weblogs.com/adodb_csv">http://php.weblogs.com/ADODB_csv</a>.
<p>Fixed SelectLimit(), SELECT TOP not working under certain circumstances.
<p>Added better Frontbase support of MetaTypes() by Frank M. Kromann.
<p><b>1.01 24 April 2001</b></p>
<p>Fixed SelectLimit bug. not quoted properly.
<p>SelectLimit: SELECT TOP -1 * FROM TABLE not support by Microsoft. Fixed.</p>
<p>GetMenu improved by glen.davies#cce.ac.nz to support multiple hilited items<p>
<p>FetchNextObject() did not work with only 1 record returned. Fixed bug reported by $tim#orotech.net</p>
<p>Fixed mysql field max_length problem. Fix suggested by Jim Nicholson (jnich#att.com)</p>
<p><b>1.00 16 April 2001</b></p>
<p>Given some brilliant suggestions on how to simplify ADOdb by akul. You no longer need to
setup $ADODB_DIR yourself, and ADOLoadCode() is automatically called by ADONewConnection(),
simplifying the startup code.</p>
<p>FetchNextObject() added. Suggested by Jakub Marecek. This makes FetchObject() obsolete, as
this is more flexible and powerful.</p>
<p>Misc fixes to SelectLimit() to support Access (top must follow distinct) and Fields()
in the array recordset. From Reinhard Balling.</p>
<p><b>0.96 27 Mar 2001</b></p>
<p>ADOConnection Close() did not return a value correctly. Thanks to akul#otamedia.com.</p>
<p>When the horrible magic_quotes is enabled, back-slash () is changed to double-backslash (\).
This doesn't make sense for Microsoft/Sybase databases. We fix this in qstr().</p>
<p>Fixed Sybase date problem in UnixDate() thanks to Toni Tunkkari. Also fixed MSSQL problem
in UnixDate() - thanks to milhouse31#hotmail.com.</p>
<p>MoveNext() moved to leaf classes for speed in MySQL/PostgreSQL. 10-15% speedup.</p>
<p>Added null handling in bindInputArray in Execute() -- Ron Baldwin suggestion.</p>
<p>Fixed some option tags. Thanks to john#jrmstudios.com.</p>
<p><b>0.95 13 Mar 2001</b></p>
<p>Added postgres7 database driver which supports LIMIT and other version 7 stuff in the future.</p>
<p>Added SelectLimit to ADOConnection to simulate PostgreSQL's "select * from table limit 10 offset 3".
Added helper function GetArrayLimit() to ADORecordSet.</p>
<p>Fixed mysql metacolumns bug. Thanks to Freek Dijkstra (phpeverywhere#macfreek.com).</p>
<p>Also many PostgreSQL changes by Freek. He almost rewrote the whole PostgreSQL driver!</p>
<p>Added fix to input parameters in Execute for non-strings by Ron Baldwin.</p>
<p>Added new metatype, X for TeXt. Formerly, metatype B for Blob also included
text fields. Now 'B' is for binary/image data. 'X' for textual data.</p>
<p>Fixed $this->GetArray() in GetRows().</p>
<p>Oracle and OCI8: 1st parameter is always blank -- now warns if it is filled.</p>
<p>Now <i>hasLimit</i> and <i>hasTop</i> added to indicate whether
SELECT * FROM TABLE LIMIT 10 or SELECT TOP 10 * FROM TABLE are supported.</p>
<p><b>0.94 04 Feb 2001</b></p>
<p>Added ADORecordSet::GetRows() for compatibility with Microsoft ADO. Synonym for GetArray().</p>
<p>Added new metatype 'R' to represent autoincrement numbers.</p>
<p>Added ADORecordSet.FetchObject() to return a row as an object.</p>
<p>Finally got a Linux box to test PostgreSql. Many fixes.</p>
<p>Fixed copyright misspellings in 0.93.</p>
<p>Fixed mssql MetaColumns type bug.</p>
<p>Worked around odbc bug in PHP4 for sessions.</p>
<p>Fixed many documentation bugs (affected_rows, metadatabases, qstr).</p>
<p>Fixed MySQL timestamp format (removed comma).</p>
<p>Interbase driver did not call ibase_pconnect(). Fixed.</p>
<p><b>0.93 18 Jan 2002</b></p>
<p>Fixed GetMenu bug.</p>
<p>Simplified Interbase commit and rollback.</p>
<p>Default behaviour on closing a connection is now to rollback all active transactions.</p>
<p>Added field object handling for array recordset for future XML compatibility.</p>
<p>Added arr2html() to convert array to html table.</p>
<p><b>0.92 2 Jan 2002</b></p>
<p>Interbase Commit and Rollback should be working again.</p>
<p>Changed initialisation of ADORecordSet. This is internal and should not affect users. We
are doing this to support cached recordsets in the future.</p>
<p>Implemented ADORecordSet_array class. This allows you to simulate a database recordset
with an array.</p>
<p>Added UnixDate() and UnixTimeStamp() to ADORecordSet.</p>
<p><b>0.91 21 Dec 2000</b></p>
<p>Fixed ODBC so ErrorMsg() is working.</p>
<p>Worked around ADO unrecognised null (0x1) value problem in COM.</p>
<p>Added Sybase support for FetchField() type</p>
<p>Removed debugging code and unneeded html from various files</p>
<p>Changed to javadoc style comments to adodb.inc.php.</p>
<p>Added maxsql as synonym for mysqlt</p>
<p>Now ODBC downloads first 8K of blob by default
<p><b>0.90 15 Nov 2000</b></p>
<p>Lots of testing of Microsoft ADO. Should be more stable now.</p>
<p>Added $ADODB_COUNTREC. Set to false for high speed selects.</p>
<p>Added Sybase support. Contributed by Toni Tunkkari (toni.tunkkari#finebyte.com). Bug in Sybase
API: GetFields is unable to determine date types.</p>
<p>Changed behaviour of RecordSet.GetMenu() to support size parameter (listbox) properly.</p>
<p>Added emptyDate and emptyTimeStamp to RecordSet class that defines how to represent
empty dates.</p>
<p>Added MetaColumns($table) that returns an array of ADOFieldObject's listing
the columns of a table.</p>
<p>Added transaction support for PostgresSQL -- thanks to "Eric G. Werk" egw#netguide.dk.</p>
<p>Added adodb-session.php for session support.</p>
<p><b>0.80 30 Nov 2000</b></p>
<p>Added support for charSet for interbase. Implemented MetaTables for most databases.
PostgreSQL more extensively tested.</p>
<p><b>0.71 22 Nov 2000</b></p>
<p>Switched from using require_once to include/include_once for backward compatability with PHP 4.02 and earlier.</p>
<p><b>0.70 15 Nov 2000</b></p>
<p>Calls by reference have been removed (call_time_pass_reference=Off) to ensure compatibility with future versions of PHP,
except in Oracle 7 driver due to a bug in php_oracle.dll.</p>
<p>PostgreSQL database driver contributed by Alberto Cerezal (acerezalp#dbnet.es).
</p>
<p>Oci8 driver for Oracle 8 contributed by George Fourlanos (fou#infomap.gr).</p>
<p>Added <i>mysqlt</i> database driver to support MySQL 3.23 which has transaction
support. </p>
<p>Oracle default date format (DD-MON-YY) did not match ADOdb default date format (which is YYYY-MM-DD). Use ALTER SESSION to force the default date.</p>
<p>Error message checking is now included in test suite.</p>
<p>MoveNext() did not check EOF properly -- fixed.</p>
<p><b>0.60 Nov 8 2000</b></p>
<p>Fixed some constructor bugs in ODBC and ADO. Added ErrorNo function to ADOConnection
class. </p>
<p><b>0.51 Oct 18 2000</b></p>
<p>Fixed some interbase bugs.</p>
<p><b>0.50 Oct 16 2000</b></p>
<p>Interbase commit/rollback changed to be compatible with PHP 4.03. </p>
<p>CommitTrans( ) will now return true if transactions not supported. </p>
<p>Conversely RollbackTrans( ) will return false if transactions not supported.
</p>
<p><b>0.46 Oct 12</b></p>
Many Oracle compatibility issues fixed.
<p><b>0.40 Sept 26</b></p>
<p>Many bug fixes</p>
<p>Now Code for BeginTrans, CommitTrans and RollbackTrans is working. So is the Affected_Rows
and Insert_ID. Added above functions to test.php.</p>
<p>ADO type handling was busted in 0.30. Fixed.</p>
<p>Generalised Move( ) so it works will all databases, including ODBC.</p>
<p><b>0.30 Sept 18</b></p>
<p>Renamed ADOLoadDB to ADOLoadCode. This is clearer.</p>
<p>Added BeginTrans, CommitTrans and RollbackTrans functions.</p>
<p>Added Affected_Rows() and Insert_ID(), _affectedrows() and _insertID(), ListTables(),
ListDatabases(), ListColumns().</p>
<p>Need to add New_ID() and hasInsertID and hasAffectedRows, autoCommit </p>
<p><b>0.20 Sept 12</b></p>
<p>Added support for Microsoft's ADO.</p>
<p>Added new field to ADORecordSet -- canSeek</p>
<p>Added new parameter to _fetch($ignore_fields = false). Setting to true will
not update fields array for faster performance.</p>
<p>Added new field to ADORecordSet/ADOConnection -- dataProvider to indicate whether
a class is derived from odbc or ado.</p>
<p>Changed class ODBCFieldObject to ADOFieldObject -- not documented currently.</p>
<p>Added benchmark.php and testdatabases.inc.php to the test suite.</p>
<p>Added to ADORecordSet FastForward( ) for future high speed scrolling. Not documented.</p>
<p>Realised that ADO's Move( ) uses relative positioning. ADOdb uses absolute.
</p>
<p><b>0.10 Sept 9 2000</b></p>
<p>First release</p>
</body></html>

View File

@@ -1,367 +1,367 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
</head>
<body bgcolor=white>
<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
<div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
<p>Updated 6 Oct 2006. Added OffsetDate example.
<p>Updated 18 Sep 2003. Added Portable Native SQL section.
<p>
If you are writing an application that is used in multiple environments and
operating systems, you need to plan to support multiple databases. This article
is based on my experiences with multiple database systems, stretching from 4th
Dimension in my Mac days, to the databases I currently use, which are: Oracle,
FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies
to using SQL with Perl, Python and other programming languages, I will focus on PHP and how
the <a href="http://adodb.sourceforge.net/">ADOdb</a> database abstraction library
offers some solutions.<p></p>
<p>Most database vendors practice product lock-in. The best or fastest way to
do things is often implemented using proprietary extensions to SQL. This makes
it extremely hard to write portable SQL code that performs well under all conditions.
When the first ANSI committee got together in 1984 to standardize SQL, the database
vendors had such different implementations that they could only agree on the
core functionality of SQL. Many important application specific requirements
were not standardized, and after so many years since the ANSI effort began,
it looks as if much useful database functionality will never be standardized.
Even though ANSI-92 SQL has codified much more, we still have to implement portability
at the application level.</p>
<h3><b>Selects</b></h3>
<p>The SELECT statement has been standardized to a great degree. Nearly every
database supports the following:</p>
<p>SELECT [cols] FROM [tables]<br>
&nbsp;&nbsp;[WHERE conditions]<br>
&nbsp; [GROUP BY cols]<br>
&nbsp; [HAVING conditions] <br>
&nbsp; [ORDER BY cols]</p>
<p>But so many useful techniques can only be implemented by using proprietary
extensions. For example, when writing SQL to retrieve the first 10 rows for
paging, you could write...</p>
<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><b>Database</b></td>
<td><b>SQL Syntax</b></td>
</tr>
<tr>
<td>DB2</td>
<td>select * from table fetch first 10 rows only</td>
</tr>
<tr>
<td>Informix</td>
<td>select first 10 * from table</td>
</tr>
<tr>
<td>Microsoft SQL Server and Access</td>
<td>select top 10 * from table</td>
</tr>
<tr>
<td>MySQL and PostgreSQL</td>
<td>select * from table limit 10</td>
</tr>
<tr>
<td>Oracle 8i</td>
<td>select * from (select * from table) where rownum &lt;= 10</td>
</tr>
</table>
<p>This feature of getting a subset of data is so useful that in the PHP class
library ADOdb, we have a SelectLimit( ) function that allows you to hide the
implementation details within a function that will rewrite your SQL for you:</p>
<pre>$connection-&gt;SelectLimit('select * from table', 10);
</pre>
<p><b>Selects: Fetch Modes</b></p>
<p>PHP allows you to retrieve database records as arrays. You can choose to have
the arrays indexed by field name or number. However different low-level PHP
database drivers are inconsistent in their indexing efforts. ADOdb allows you
to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE
to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC
(using field names as an associative index).</p>
<p>The default behaviour of ADOdb varies depending on the database you are using.
For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or
ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
<p><b>Selects: Counting Records</b></p>
<p>Another problem with SELECTs is that some databases do not return the number
of rows retrieved from a select statement. This is because the highest performance
databases will return records to you even before the last record has been found.
</p>
<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate
it by buffering the rows and returning the count after all rows have been returned.
This can be disabled for performance reasons when retrieving large recordsets
by setting the global variable $ADODB_COUNTRECS = false. This variable is checked
every time a query is executed, so you can selectively choose which recordsets
to count.</p>
<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount(
) function. This will return the number of rows, or if it is not found, it will
return an estimate using SELECT COUNT(*):</p>
<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
<p><b>Selects: Locking</b> </p>
<p>SELECT statements are commonly used to implement row-level locking of tables.
Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB
do not require row-level locking because they use versioning to display data
consistent with a specific point in time.</p>
<p>Currently, I recommend encapsulating the row-level locking in a separate function,
such as RowLock($table, $where):</p>
<pre>$connection-&gt;BeginTrans( );
$connection-&gt;RowLock($table, $where); </pre>
<pre><font color=green># some operation</font></pre>
<pre>if ($ok) $connection-&gt;CommitTrans( );
else $connection-&gt;RollbackTrans( );
</pre>
<p><b>Selects: Outer Joins</b></p>
<p>Not all databases support outer joins. Furthermore the syntax for outer joins
differs dramatically between database vendors. One portable (and possibly slower)
method of implementing outer joins is using UNION.</p>
<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could
look like:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola <br> FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
<p>This can be emulated using:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br> WHERE t1.col = t2.col
UNION ALL
SELECT col1, col2, null FROM t1 <br> WHERE t1.col not in (select distinct col from t2)
</pre>
<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal
join variations. This is still incomplete and sometimes depends on the database
version you are using, but is useful as a general guideline:</p>
<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the
operator used for left outer joins (eg. '*='), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the
operator used for right outer joins (eg '=*'), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean
that if true means that ANSI-92 style outer joins are supported, or false if
not known.</p>
<h3><b>Inserts</b> </h3>
<p>When you create records, you need to generate unique id's for each record.
There are two common techniques: (1) auto-incrementing columns and (2) sequences.
</p>
<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access
and SQL Server. However most other databases do not support this feature. So
for portability, you have little choice but to use sequences. Sequences are
special functions that return a unique incrementing number every time you call
it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function.
It has takes a parameter, the sequence name. Different tables can have different
sequences. </p>
<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br> values ($id, $firstname, $lastname)&quot;);</pre>
<p>For databases that do not support sequences natively, ADOdb emulates sequences
by creating a table for every sequence.</p>
<h3><b>Binding</b></h3>
<p>Binding variables in an SQL statement is another tricky feature. Binding is
useful because it allows pre-compilation of SQL. When inserting multiple records
into a database in a loop, binding can offer a 50% (or greater) speedup. However
many databases such as Access and MySQL do not support binding natively and
there is some overhead in emulating binding. Furthermore, different databases
(specificly Oracle!) implement binding differently. My recommendation is to
use binding if your database queries are too slow, but make sure you are using
a database that supports it like Oracle. </p>
<p>ADOdb supports portable Prepare/Execute with:</p>
<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
<p>Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates
the correct placeholder (available since ADOdb 3.92):
<pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;
<font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'
# or 'insert into table (col1,col2) values (:a,:b)</font>'
$stmt = $DB-&gt;Prepare($sql);
$stmt = $DB-&gt;Execute($stmt,array('one','two'));
</font></pre>
<a name="native"></a>
<h2>Portable Native SQL</h2>
<p>ADOdb provides the following functions for portably generating SQL functions
as strings to be merged into your SQL statements (some are only available since
ADOdb 3.92): </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>&nbsp; </p>
<h2>DDL and Tuning</h2>
There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams.
<p>
However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with:
<ol>
<li> Auto-increment primary key 'ID', </li>
<li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>
<li>The date and time of record creation 'CREATED', </li>
<li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>
</ol>
<p>
Also create a compound index consisting of 'NAME' and 'AGE':
<pre>
$datadict = <strong>NewDataDictionary</strong>($connection);
$flds = "
<font color="#660000"> ID I AUTOINCREMENT PRIMARY,
NAME C(32) DEFAULT '' NOTNULL,
CREATED T DEFTIMESTAMP,
AGE N(16) DEFAULT 0</font>
";
$sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);
$sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');
</pre>
<h3>Data Types</h3>
<p>Stick to a few data types that are available in most databases. Char, varchar
and numeric/number are supported by most databases. Most other data types (including
integer, boolean and float) cannot be relied on being available. I recommend
using char(1) or number(1) to hold booleans. </p>
<p>Different databases have different ways of representing dates and timestamps/datetime.
ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides
DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable
to that database. Both functions accept Unix integer timestamps and date strings
in ISO format.</p>
<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
<p>We also provide functions to convert database dates to Unix timestamps:</p>
<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =&gt; unix timestamp</font></pre>
<p>For date calculations, we have OffsetDate which allows you to calculate dates such as <i>yesterday</i> and <i>next week</i> in a RDBMS independant fashion. For example, if we want to set a field to 6 hour from now, use:
<pre>
$sql = 'update table set dtimefld='.$db-&gt;OffsetDate($db-&gtsysTimeStamp, 6/24).' where ...';
</pre>
<p>The maximum length of a char/varchar field is also database specific. You can
only assume that field lengths of up to 250 characters are supported. This is
normally impractical for web based forum or content management systems. You
will need to be familiar with how databases handle large objects (LOBs). ADOdb
implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to
update fields holding Binary Large Objects (eg. pictures) and Character Large
Objects (eg. HTML articles):</p>
<pre><font color=green># for oracle </font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
<font color=green># non-oracle databases</font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
</pre>
<p>Null handling is another area where differences can occur. This is a mine-field,
because 3-value logic is tricky.
<p>In general, I avoid using nulls except for dates and default all my numeric
and character fields to 0 or the empty string. This maintains consistency with
PHP, where empty strings and zero are treated as equivalent, and avoids SQL
ambiguities when you use the ANY and EXISTS operators. However if your database
has significant amounts of missing or unknown data, using nulls might be a good
idea.
<p>
ADOdb also supports a portable <a href=http://phplens.com/adodb/reference.functions.concat.html#ifnull>IfNull</a> function, so you can define what to display
if the field contains a null.
<h3><b>Stored Procedures</b></h3>
<p>Stored procedures are another problem area. Some databases allow recordsets
to be returned in a stored procedure (Microsoft SQL Server and Sybase), and
others only allow output parameters to be returned. Stored procedures sometimes
need to be wrapped in special syntax. For example, Oracle requires such code
to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators
and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors.
</p>
<p>An example of how to call a stored procedure with 2 parameters and 1 return
value follows:</p>
<pre> switch ($db->databaseType) {
case '<font color="#993300">mssql</font>':
$sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
case '<font color="#993300">oci8</font>':
$sql =
<font color="#993300"> </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
</font> break;</font>
default:
die('<font color="#993300">Unsupported feature</font>');
}
<font color="#000000"><font color="green"> # @RETVAL = SP_RUNSOMETHING @myid,@group</font>
$stmt = $db-&gt;PrepareSP($sql); <br> $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>');
$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
<font color="green"># true indicates output parameter<br> </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true);
$db-&gt;Execute($stmt); </font></pre>
<p>As you can see, the ADOdb API is the same for both databases. But the stored
procedure SQL syntax is quite different between databases and is not portable,
so be forewarned! However sometimes you have little choice as some systems only
allow data to be accessed via stored procedures. This is when the ultimate portability
solution might be the only solution: <i>treating portable SQL as a localization
exercise...</i></p>
<h3><b>SQL as a Localization Exercise</b></h3>
<p> In general to provide real portability, you will have to treat SQL coding
as a localization exercise. In PHP, it has become common to define separate
language files for English, Russian, Korean, etc. Similarly, I would suggest
you have separate Sybase, Intebase, MySQL, etc files, and conditionally include
the SQL based on the database. For example, each MySQL SQL statement would be
stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
$sqlSearchKeyword = &quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
<p>In our main PHP file:</p>
<pre><font color=green># define which database to load...</font>
<b>$database = '<font color="#993300">mysql</font>';
include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
$db = &amp;NewADOConnection($database);
$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
<font color=green># search for a keyword $word</font>
$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
<p>Note that we quote the $word variable using the qstr( ) function. This is because
each database quotes strings using different conventions.</p>
<p>
<h3>Final Thoughts</h3>
<p>The best way to ensure that you have portable SQL is to have your data tables designed using
sound principles. Learn the theory of normalization and entity-relationship diagrams and model
your data carefully. Understand how joins and indexes work and how they are used to tune performance.
<p> Visit the following page for more references on database theory and vendors:
<a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>.
Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
<p>
<font size=1>(c) 2002-2003 John Lim.</font>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
</head>
<body bgcolor=white>
<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
<div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
<p>Updated 6 Oct 2006. Added OffsetDate example.
<p>Updated 18 Sep 2003. Added Portable Native SQL section.
<p>
If you are writing an application that is used in multiple environments and
operating systems, you need to plan to support multiple databases. This article
is based on my experiences with multiple database systems, stretching from 4th
Dimension in my Mac days, to the databases I currently use, which are: Oracle,
FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies
to using SQL with Perl, Python and other programming languages, I will focus on PHP and how
the <a href="http://adodb.sourceforge.net/">ADOdb</a> database abstraction library
offers some solutions.<p></p>
<p>Most database vendors practice product lock-in. The best or fastest way to
do things is often implemented using proprietary extensions to SQL. This makes
it extremely hard to write portable SQL code that performs well under all conditions.
When the first ANSI committee got together in 1984 to standardize SQL, the database
vendors had such different implementations that they could only agree on the
core functionality of SQL. Many important application specific requirements
were not standardized, and after so many years since the ANSI effort began,
it looks as if much useful database functionality will never be standardized.
Even though ANSI-92 SQL has codified much more, we still have to implement portability
at the application level.</p>
<h3><b>Selects</b></h3>
<p>The SELECT statement has been standardized to a great degree. Nearly every
database supports the following:</p>
<p>SELECT [cols] FROM [tables]<br>
&nbsp;&nbsp;[WHERE conditions]<br>
&nbsp; [GROUP BY cols]<br>
&nbsp; [HAVING conditions] <br>
&nbsp; [ORDER BY cols]</p>
<p>But so many useful techniques can only be implemented by using proprietary
extensions. For example, when writing SQL to retrieve the first 10 rows for
paging, you could write...</p>
<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><b>Database</b></td>
<td><b>SQL Syntax</b></td>
</tr>
<tr>
<td>DB2</td>
<td>select * from table fetch first 10 rows only</td>
</tr>
<tr>
<td>Informix</td>
<td>select first 10 * from table</td>
</tr>
<tr>
<td>Microsoft SQL Server and Access</td>
<td>select top 10 * from table</td>
</tr>
<tr>
<td>MySQL and PostgreSQL</td>
<td>select * from table limit 10</td>
</tr>
<tr>
<td>Oracle 8i</td>
<td>select * from (select * from table) where rownum &lt;= 10</td>
</tr>
</table>
<p>This feature of getting a subset of data is so useful that in the PHP class
library ADOdb, we have a SelectLimit( ) function that allows you to hide the
implementation details within a function that will rewrite your SQL for you:</p>
<pre>$connection-&gt;SelectLimit('select * from table', 10);
</pre>
<p><b>Selects: Fetch Modes</b></p>
<p>PHP allows you to retrieve database records as arrays. You can choose to have
the arrays indexed by field name or number. However different low-level PHP
database drivers are inconsistent in their indexing efforts. ADOdb allows you
to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE
to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC
(using field names as an associative index).</p>
<p>The default behaviour of ADOdb varies depending on the database you are using.
For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or
ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
<p><b>Selects: Counting Records</b></p>
<p>Another problem with SELECTs is that some databases do not return the number
of rows retrieved from a select statement. This is because the highest performance
databases will return records to you even before the last record has been found.
</p>
<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate
it by buffering the rows and returning the count after all rows have been returned.
This can be disabled for performance reasons when retrieving large recordsets
by setting the global variable $ADODB_COUNTRECS = false. This variable is checked
every time a query is executed, so you can selectively choose which recordsets
to count.</p>
<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount(
) function. This will return the number of rows, or if it is not found, it will
return an estimate using SELECT COUNT(*):</p>
<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
<p><b>Selects: Locking</b> </p>
<p>SELECT statements are commonly used to implement row-level locking of tables.
Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB
do not require row-level locking because they use versioning to display data
consistent with a specific point in time.</p>
<p>Currently, I recommend encapsulating the row-level locking in a separate function,
such as RowLock($table, $where):</p>
<pre>$connection-&gt;BeginTrans( );
$connection-&gt;RowLock($table, $where); </pre>
<pre><font color=green># some operation</font></pre>
<pre>if ($ok) $connection-&gt;CommitTrans( );
else $connection-&gt;RollbackTrans( );
</pre>
<p><b>Selects: Outer Joins</b></p>
<p>Not all databases support outer joins. Furthermore the syntax for outer joins
differs dramatically between database vendors. One portable (and possibly slower)
method of implementing outer joins is using UNION.</p>
<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could
look like:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola <br> FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
<p>This can be emulated using:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br> WHERE t1.col = t2.col
UNION ALL
SELECT col1, col2, null FROM t1 <br> WHERE t1.col not in (select distinct col from t2)
</pre>
<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal
join variations. This is still incomplete and sometimes depends on the database
version you are using, but is useful as a general guideline:</p>
<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the
operator used for left outer joins (eg. '*='), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the
operator used for right outer joins (eg '=*'), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean
that if true means that ANSI-92 style outer joins are supported, or false if
not known.</p>
<h3><b>Inserts</b> </h3>
<p>When you create records, you need to generate unique id's for each record.
There are two common techniques: (1) auto-incrementing columns and (2) sequences.
</p>
<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access
and SQL Server. However most other databases do not support this feature. So
for portability, you have little choice but to use sequences. Sequences are
special functions that return a unique incrementing number every time you call
it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function.
It has takes a parameter, the sequence name. Different tables can have different
sequences. </p>
<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br> values ($id, $firstname, $lastname)&quot;);</pre>
<p>For databases that do not support sequences natively, ADOdb emulates sequences
by creating a table for every sequence.</p>
<h3><b>Binding</b></h3>
<p>Binding variables in an SQL statement is another tricky feature. Binding is
useful because it allows pre-compilation of SQL. When inserting multiple records
into a database in a loop, binding can offer a 50% (or greater) speedup. However
many databases such as Access and MySQL do not support binding natively and
there is some overhead in emulating binding. Furthermore, different databases
(specificly Oracle!) implement binding differently. My recommendation is to
use binding if your database queries are too slow, but make sure you are using
a database that supports it like Oracle. </p>
<p>ADOdb supports portable Prepare/Execute with:</p>
<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
<p>Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates
the correct placeholder (available since ADOdb 3.92):
<pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;
<font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'
# or 'insert into table (col1,col2) values (:a,:b)</font>'
$stmt = $DB-&gt;Prepare($sql);
$stmt = $DB-&gt;Execute($stmt,array('one','two'));
</font></pre>
<a name="native"></a>
<h2>Portable Native SQL</h2>
<p>ADOdb provides the following functions for portably generating SQL functions
as strings to be merged into your SQL statements (some are only available since
ADOdb 3.92): </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>&nbsp; </p>
<h2>DDL and Tuning</h2>
There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams.
<p>
However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with:
<ol>
<li> Auto-increment primary key 'ID', </li>
<li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>
<li>The date and time of record creation 'CREATED', </li>
<li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>
</ol>
<p>
Also create a compound index consisting of 'NAME' and 'AGE':
<pre>
$datadict = <strong>NewDataDictionary</strong>($connection);
$flds = "
<font color="#660000"> ID I AUTOINCREMENT PRIMARY,
NAME C(32) DEFAULT '' NOTNULL,
CREATED T DEFTIMESTAMP,
AGE N(16) DEFAULT 0</font>
";
$sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);
$sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');
</pre>
<h3>Data Types</h3>
<p>Stick to a few data types that are available in most databases. Char, varchar
and numeric/number are supported by most databases. Most other data types (including
integer, boolean and float) cannot be relied on being available. I recommend
using char(1) or number(1) to hold booleans. </p>
<p>Different databases have different ways of representing dates and timestamps/datetime.
ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides
DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable
to that database. Both functions accept Unix integer timestamps and date strings
in ISO format.</p>
<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
<p>We also provide functions to convert database dates to Unix timestamps:</p>
<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =gt; unix timestamp</font></pre>
<p>For date calculations, we have OffsetDate which allows you to calculate dates such as <i>yesterday</i> and <i>next week</i> in a RDBMS independant fashion. For example, if we want to set a field to 6 hour from now, use:
<pre>
$sql = 'update table set dtimefld='.$db-&gt;OffsetDate($db-&gtsysTimeStamp, 6/24).' where ...';
</pre>
<p>The maximum length of a char/varchar field is also database specific. You can
only assume that field lengths of up to 250 characters are supported. This is
normally impractical for web based forum or content management systems. You
will need to be familiar with how databases handle large objects (LOBs). ADOdb
implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to
update fields holding Binary Large Objects (eg. pictures) and Character Large
Objects (eg. HTML articles):</p>
<pre><font color=green># for oracle </font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
<font color=green># non-oracle databases</font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
</pre>
<p>Null handling is another area where differences can occur. This is a mine-field,
because 3-value logic is tricky.
<p>In general, I avoid using nulls except for dates and default all my numeric
and character fields to 0 or the empty string. This maintains consistency with
PHP, where empty strings and zero are treated as equivalent, and avoids SQL
ambiguities when you use the ANY and EXISTS operators. However if your database
has significant amounts of missing or unknown data, using nulls might be a good
idea.
<p>
ADOdb also supports a portable <a href=http://phplens.com/adodb/reference.functions.concat.html#ifnull>IfNull</a> function, so you can define what to display
if the field contains a null.
<h3><b>Stored Procedures</b></h3>
<p>Stored procedures are another problem area. Some databases allow recordsets
to be returned in a stored procedure (Microsoft SQL Server and Sybase), and
others only allow output parameters to be returned. Stored procedures sometimes
need to be wrapped in special syntax. For example, Oracle requires such code
to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators
and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors.
</p>
<p>An example of how to call a stored procedure with 2 parameters and 1 return
value follows:</p>
<pre> switch ($db->databaseType) {
case '<font color="#993300">mssql</font>':
$sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
case '<font color="#993300">oci8</font>':
$sql =
<font color="#993300"> </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
</font> break;</font>
default:
die('<font color="#993300">Unsupported feature</font>');
}
<font color="#000000"><font color="green"> # @RETVAL = SP_RUNSOMETHING @myid,@group</font>
$stmt = $db-&gt;PrepareSP($sql); <br> $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>');
$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
<font color="green"># true indicates output parameter<br> </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true);
$db-&gt;Execute($stmt); </font></pre>
<p>As you can see, the ADOdb API is the same for both databases. But the stored
procedure SQL syntax is quite different between databases and is not portable,
so be forewarned! However sometimes you have little choice as some systems only
allow data to be accessed via stored procedures. This is when the ultimate portability
solution might be the only solution: <i>treating portable SQL as a localization
exercise...</i></p>
<h3><b>SQL as a Localization Exercise</b></h3>
<p> In general to provide real portability, you will have to treat SQL coding
as a localization exercise. In PHP, it has become common to define separate
language files for English, Russian, Korean, etc. Similarly, I would suggest
you have separate Sybase, Intebase, MySQL, etc files, and conditionally include
the SQL based on the database. For example, each MySQL SQL statement would be
stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
$sqlSearchKeyword = quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
<p>In our main PHP file:</p>
<pre><font color=green># define which database to load...</font>
<b>$database = '<font color="#993300">mysql</font>';
include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
$db = NewADOConnection($database);
$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
<font color=green># search for a keyword $word</font>
$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
<p>Note that we quote the $word variable using the qstr( ) function. This is because
each database quotes strings using different conventions.</p>
<p>
<h3>Final Thoughts</h3>
<p>The best way to ensure that you have portable SQL is to have your data tables designed using
sound principles. Learn the theory of normalization and entity-relationship diagrams and model
your data carefully. Understand how joins and indexes work and how they are used to tune performance.
<p> Visit the following page for more references on database theory and vendors:
<a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>.
Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
<p>
<font size=1>(c) 2002-2003 John Lim.</font>
</body>
</html>

View File

@@ -156,7 +156,7 @@ based on the $ADODB_FETCH_MODE setting when the recordset was created by Execute
$recordset passed to it. An example with the relevant lines in bold:
<pre> include('adodb.inc.php');
<b>include('tohtml.inc.php');</b> /* includes the rs2html function */
$conn = &amp;ADONewConnection('mysql');
$conn = ADONewConnection('mysql');
$conn-&gt;PConnect('localhost','userid','password','database');
$rs = $conn-&gt;Execute('select * from table');
<b> rs2html($rs)</b>; /* recordset to html table */ </pre>

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -49,7 +49,7 @@ class ADODB_access extends ADODB_odbc {
return " IIF(IsNull($field), $ifNull, $field) "; // if Access
}
/*
function &MetaTables()
function MetaTables()
{
global $ADODB_FETCH_MODE;
@@ -62,7 +62,7 @@ class ADODB_access extends ADODB_odbc {
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr = &$rs->GetArray();
$arr = $rs->GetArray();
//print_pre($arr);
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -147,7 +147,7 @@ class ADODB_ado extends ADOConnection {
*/
function &MetaTables()
function MetaTables()
{
$arr= array();
$dbc = $this->_connectionID;
@@ -169,7 +169,7 @@ class ADODB_ado extends ADOConnection {
return $arr;
}
function &MetaColumns($table)
function MetaColumns($table)
{
$table = strtoupper($table);
$arr = array();
@@ -204,7 +204,7 @@ class ADODB_ado extends ADOConnection {
/* returns queryID or false */
function &_query($sql,$inputarr=false)
function _query($sql,$inputarr=false)
{
$dbc = $this->_connectionID;
@@ -221,11 +221,27 @@ class ADODB_ado extends ADOConnection {
$oCmd->CommandText = $sql;
$oCmd->CommandType = 1;
foreach($inputarr as $val) {
// Map by http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthcreateparam.asp
// Check issue http://bugs.php.net/bug.php?id=40664 !!!
while(list(, $val) = each($inputarr)) {
$type = gettype($val);
$len=strlen($val);
if ($type == 'boolean')
$this->adoParameterType = 11;
else if ($type == 'integer')
$this->adoParameterType = 3;
else if ($type == 'double')
$this->adoParameterType = 5;
elseif ($type == 'string')
$this->adoParameterType = 202;
else if (($val === null) || (!defined($val)))
$len=1;
else
$this->adoParameterType = 130;
// name, type, direction 1 = input, len,
$this->adoParameterType = 130;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
//print $p->Type.' '.$p->value;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);
$oCmd->Parameters->Append($p);
}
$p = false;
@@ -337,7 +353,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();
@@ -587,6 +603,16 @@ class ADORecordSet_ado extends ADORecordSet {
ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
$this->fields[] = (float) $f->value;
break;
case 11: //BIT;
$val = "";
if(is_bool($f->value)) {
if($f->value==true) $val = 1;
else $val = 0;
}
if(is_null($f->value)) $val = null;
$this->fields[] = $val;
break;
default:
$this->fields[] = $f->value;
break;
@@ -599,7 +625,7 @@ class ADORecordSet_ado extends ADORecordSet {
@$rs->MoveNext(); // @ needed for some versions of PHP!
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -70,7 +70,8 @@ class ADODB_ado extends ADOConnection {
} else {
$argDatabasename = '';
if ($argDBorProvider) $argProvider = $argDBorProvider;
else $argProvider = 'MSDASQL';
else if (stripos($argHostname,'PROVIDER') === false) /* full conn string is not in $argHostname */
$argProvider = 'MSDASQL';
}
@@ -101,6 +102,9 @@ class ADODB_ado extends ADOConnection {
if ($argProvider) $dbc->Provider = $argProvider;
if ($argProvider) $argHostname = "PROVIDER=$argProvider;DRIVER={SQL Server};SERVER=$argHostname";
if ($argDatabasename) $argHostname .= ";DATABASE=$argDatabasename";
if ($argUsername) $argHostname .= ";$u=$argUsername";
if ($argPassword)$argHostname .= ";$p=$argPassword";
@@ -114,6 +118,7 @@ class ADODB_ado extends ADOConnection {
$dbc->CursorLocation = $this->_cursor_location;
return $dbc->State > 0;
} catch (exception $e) {
if ($this->debug);echo "<pre>",$argHostname,"\n",$e,"</pre>\n";
}
return false;
@@ -167,7 +172,7 @@ class ADODB_ado extends ADOConnection {
*/
function &MetaTables()
function MetaTables()
{
$arr= array();
$dbc = $this->_connectionID;
@@ -189,7 +194,7 @@ class ADODB_ado extends ADOConnection {
return $arr;
}
function &MetaColumns($table)
function MetaColumns($table)
{
$table = strtoupper($table);
$arr= array();
@@ -221,7 +226,7 @@ class ADODB_ado extends ADOConnection {
}
/* returns queryID or false */
function &_query($sql,$inputarr=false)
function _query($sql,$inputarr=false)
{
try { // In PHP5, all COM errors are exceptions, so to maintain old behaviour...
@@ -241,13 +246,28 @@ class ADODB_ado extends ADOConnection {
$oCmd->CommandText = $sql;
$oCmd->CommandType = 1;
foreach($inputarr as $val) {
while(list(, $val) = each($inputarr)) {
$type = gettype($val);
$len=strlen($val);
if ($type == 'boolean')
$this->adoParameterType = 11;
else if ($type == 'integer')
$this->adoParameterType = 3;
else if ($type == 'double')
$this->adoParameterType = 5;
elseif ($type == 'string')
$this->adoParameterType = 202;
else if (($val === null) || (!defined($val)))
$len=1;
else
$this->adoParameterType = 130;
// name, type, direction 1 = input, len,
$this->adoParameterType = 130;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
//print $p->Type.' '.$p->value;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);
$oCmd->Parameters->Append($p);
}
$p = false;
$rs = $oCmd->Execute();
$e = $dbc->Errors;
@@ -367,11 +387,13 @@ 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();
$rs = $this->_queryID;
if (!$rs) return false;
$f = $rs->Fields($fieldOffset);
$o->name = $f->Name;
$t = $f->Type;
@@ -403,8 +425,12 @@ class ADORecordSet_ado extends ADORecordSet {
function _initrs()
{
$rs = $this->_queryID;
$this->_numOfRows = $rs->RecordCount;
try {
$this->_numOfRows = $rs->RecordCount;
} catch (Exception $e) {
$this->_numOfRows = -1;
}
$f = $rs->Fields;
$this->_numOfFields = $f->Count;
}
@@ -618,6 +644,16 @@ class ADORecordSet_ado extends ADORecordSet {
ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
$this->fields[] = (float) $f->value;
break;
case 11: //BIT;
$val = "";
if(is_bool($f->value)) {
if($f->value==true) $val = 1;
else $val = 0;
}
if(is_null($f->value)) $val = null;
$this->fields[] = $val;
break;
default:
$this->fields[] = $f->value;
break;
@@ -630,7 +666,7 @@ class ADORecordSet_ado extends ADORecordSet {
@$rs->MoveNext(); // @ needed for some versions of PHP!
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}
@@ -656,7 +692,10 @@ class ADORecordSet_ado extends ADORecordSet {
function _close() {
$this->_flds = false;
try {
@$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
} catch (Exception $e) {
}
$this->_queryID = false;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -46,7 +46,7 @@ class ADODB_ado_mssql extends ADODB_ado {
function _insertid()
{
return $this->GetOne('select @@identity');
return $this->GetOne('select SCOPE_IDENTITY()');
}
function _affectedrows()

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -55,7 +55,7 @@ class ADODB_borland_ibase extends ADODB_ibase {
// SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
// Firebird uses
// SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
if ($nrows > 0) {
if ($offset <= 0) $str = " ROWS $nrows ";

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -50,7 +50,7 @@ class ADODB_csv extends ADOConnection {
return $this->_affectedrows;
}
function &MetaDatabases()
function MetaDatabases()
{
return false;
}
@@ -72,14 +72,14 @@ class ADODB_csv extends ADOConnection {
return true;
}
function &MetaColumns($table)
function MetaColumns($table)
{
return false;
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1)
function SelectLimit($sql,$nrows=-1,$offset=-1)
{
global $ADODB_FETCH_MODE;
@@ -108,13 +108,13 @@ class ADODB_csv extends ADOConnection {
$rs->databaseType='csv';
$rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE;
$rs->connection = &$this;
$rs->connection = $this;
}
return $rs;
}
// returns queryID or false
function &_Execute($sql,$inputarr=false)
function _Execute($sql,$inputarr=false)
{
global $ADODB_FETCH_MODE;
@@ -166,7 +166,7 @@ class ADODB_csv extends ADOConnection {
$this->_affectedrows = $rs->affectedrows;
$this->_insertid = $rs->insertid;
$rs->databaseType='csv';
$rs->connection = &$this;
$rs->connection = $this;
}
return $rs;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2006 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.06 16 Oct 2008 (c) 2006 John Lim (jlim#natsoft.com). All rights reserved.
This is a version of the ADODB driver for DB2. It uses the 'ibm_db2' PECL extension
for PHP (http://pecl.php.net/package/ibm_db2), which in turn requires DB2 V8.2.2 or
@@ -33,7 +33,7 @@ class ADODB_db2 extends ADOConnection {
var $sysDate = 'CURRENT DATE';
var $sysTimeStamp = 'CURRENT TIMESTAMP';
var $fmtTimeStamp = "'Y-m-d-H:i:s'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $replaceQuote = "''"; // string to use to replace quotes
var $dataProvider = "db2";
var $hasAffectedRows = true;
@@ -44,7 +44,7 @@ class ADODB_db2 extends ADOConnection {
// breaking backward-compat
var $_bindInputArray = false;
var $_genIDSQL = "VALUES NEXTVAL FOR %s";
var $_genSeqSQL = "CREATE SEQUENCE %s START WITH 1 NO MAXVALUE NO CYCLE";
var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s NO MAXVALUE NO CYCLE";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $_autocommit = true;
var $_haserrorfunctions = true;
@@ -68,7 +68,7 @@ class ADODB_db2 extends ADOConnection {
global $php_errormsg;
if (!function_exists('db2_connect')) {
ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension.");
ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension which is not installed.");
return null;
}
// This needs to be set before the connect().
@@ -228,7 +228,7 @@ class ADODB_db2 extends ADOConnection {
function CreateSequence($seqname='adodbseq',$start=1)
{
if (empty($this->_genSeqSQL)) return false;
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$start));
if (!$ok) return false;
return true;
}
@@ -249,9 +249,9 @@ class ADODB_db2 extends ADOConnection {
{
// if you have to modify the parameter below, your database is overloaded,
// or you need to implement generation of id's yourself!
$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
return $num;
}
}
function ErrorMsg()
@@ -335,7 +335,7 @@ class ADODB_db2 extends ADOConnection {
if (!$rs) return false;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$rs->Close();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
@@ -390,7 +390,7 @@ class ADODB_db2 extends ADOConnection {
}
function &MetaTables($ttype=false,$schema=false)
function MetaTables($ttype=false,$schema=false)
{
global $ADODB_FETCH_MODE;
@@ -406,7 +406,7 @@ class ADODB_db2 extends ADOConnection {
return $false;
}
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$rs->Close();
$arr2 = array();
@@ -495,7 +495,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/db2/htm/db2
}
}
function &MetaColumns($table)
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;
@@ -511,7 +511,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/db2/htm/db2
$qid = db2_columns($this->_connectionID, "", $schema, $table, $colname);
if (empty($qid)) return $false;
$rs =& new ADORecordSet_db2($qid);
$rs = new ADORecordSet_db2($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return $false;
@@ -563,7 +563,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/db2/htm/db2
$qid = db2_primary_keys($this->_connectionID, "", $schema, $table);
if (empty($qid)) return $false;
$rs =& new ADORecordSet_db2($qid);
$rs = new ADORecordSet_db2($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return $retarr;
@@ -719,7 +719,7 @@ class ADORecordSet_db2 extends ADORecordSet {
// returns the field object
function &FetchField($offset = -1)
function FetchField($offset = -1)
{
$o= new ADOFieldObject();
$o->name = @db2_field_name($this->_queryID,$offset);
@@ -761,10 +761,10 @@ class ADORecordSet_db2 extends ADORecordSet {
}
// speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
function &GetArrayLimit($nrows,$offset=-1)
function GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) {
$rs =& $this->GetArray($nrows);
$rs = $this->GetArray($nrows);
return $rs;
}
$savem = $this->fetchMode;
@@ -773,7 +773,7 @@ class ADORecordSet_db2 extends ADORecordSet {
$this->fetchMode = $savem;
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
$results = array();
@@ -795,7 +795,7 @@ class ADORecordSet_db2 extends ADORecordSet {
$this->fields = @db2_fetch_array($this->_queryID);
if ($this->fields) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}
@@ -811,7 +811,7 @@ class ADORecordSet_db2 extends ADORecordSet {
$this->fields = db2_fetch_array($this->_queryID);
if ($this->fields) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
@version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
@version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,7 +37,7 @@ class ADODB_fbsql extends ADOConnection {
return fbsql_affected_rows($this->_connectionID);
}
function &MetaDatabases()
function MetaDatabases()
{
$qid = fbsql_list_dbs($this->_connectionID);
$arr = array();
@@ -80,7 +80,7 @@ class ADODB_fbsql extends ADOConnection {
return true;
}
function &MetaColumns($table)
function MetaColumns($table)
{
if ($this->metaColumnsSQL) {
@@ -127,7 +127,7 @@ class ADODB_fbsql extends ADOConnection {
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
return fbsql_query("$sql;",$this->_connectionID);
}
@@ -187,7 +187,7 @@ class ADORecordSet_fbsql extends ADORecordSet{
function &FetchField($fieldOffset = -1) {
function FetchField($fieldOffset = -1) {
if ($fieldOffset != -1) {
$o = @fbsql_fetch_field($this->_queryID, $fieldOffset);
//$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -44,7 +44,7 @@ class ADODB_firebird extends ADODB_ibase {
// Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!
// SELECT col1, col2 FROM table ROWS 5 -- get 5 rows
// SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)
{
$nrows = (integer) $nrows;
$offset = (integer) $offset;
@@ -54,9 +54,9 @@ class ADODB_firebird extends ADODB_ibase {
$sql = preg_replace('/^[ \t]*select/i',$str,$sql);
if ($secs)
$rs =& $this->CacheExecute($secs,$sql,$inputarr);
$rs = $this->CacheExecute($secs,$sql,$inputarr);
else
$rs =& $this->Execute($sql,$inputarr);
$rs = $this->Execute($sql,$inputarr);
return $rs;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -159,17 +159,17 @@ class ADODB_ibase extends ADOConnection {
// there are some compat problems with ADODB_COUNTRECS=false and $this->_logsql currently.
// it appears that ibase extension cannot support multiple concurrent queryid's
function &_Execute($sql,$inputarr=false)
function _Execute($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
if ($this->_logsql) {
$savecrecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = true; // force countrecs
$ret =& ADOConnection::_Execute($sql,$inputarr);
$ret = ADOConnection::_Execute($sql,$inputarr);
$ADODB_COUNTRECS = $savecrecs;
} else {
$ret =& ADOConnection::_Execute($sql,$inputarr);
$ret = ADOConnection::_Execute($sql,$inputarr);
}
return $ret;
}
@@ -187,7 +187,7 @@ class ADODB_ibase extends ADOConnection {
return $ret;
}
function &MetaIndexes ($table, $primary = FALSE, $owner=false)
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
@@ -326,7 +326,7 @@ class ADODB_ibase extends ADOConnection {
if (is_array($iarr)) {
if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
$fnarr =& array_merge( array($sql) , $iarr);
$fnarr = array_merge( array($sql) , $iarr);
$ret = call_user_func_array($fn,$fnarr);
} else {
switch(sizeof($iarr)) {
@@ -348,7 +348,7 @@ class ADODB_ibase extends ADOConnection {
if (is_array($iarr)) {
if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
if (sizeof($iarr) == 0) $iarr[0] = ''; // PHP5 compat hack
$fnarr =& array_merge( array($conn,$sql) , $iarr);
$fnarr = array_merge( array($conn,$sql) , $iarr);
$ret = call_user_func_array($fn,$fnarr);
} else {
switch(sizeof($iarr)) {
@@ -476,7 +476,7 @@ class ADODB_ibase extends ADOConnection {
}
//OPN STUFF end
// returns array of ADOFieldObjects for current table
function &MetaColumns($table)
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;
@@ -743,7 +743,7 @@ class ADORecordset_ibase 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;
$ibf = ibase_field_info($this->_queryID,$fieldOffset);
@@ -822,9 +822,9 @@ class ADORecordset_ibase extends ADORecordSet
$this->fields = $f;
if ($this->fetchMode == ADODB_FETCH_ASSOC) {
$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
} else if ($this->fetchMode == ADODB_FETCH_BOTH) {
$this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
$this->fields = array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
}
return true;
}

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 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.
@@ -147,7 +147,7 @@ class ADODB_informix72 extends ADOConnection {
}
function &MetaColumns($table)
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;
@@ -199,7 +199,7 @@ class ADODB_informix72 extends ADOConnection {
return $false;
}
function &xMetaColumns($table)
function xMetaColumns($table)
{
return ADOConnection::MetaColumns($table,false);
}
@@ -219,7 +219,7 @@ class ADODB_informix72 extends ADOConnection {
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$a = array();
foreach($arr as $v) {
$coldest=$this->metaColumnNames($v["tabname"]);
@@ -284,7 +284,7 @@ class ADODB_informix72 extends ADOConnection {
}
*/
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
@@ -362,7 +362,7 @@ class ADORecordset_informix72 extends ADORecordSet {
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
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 (empty($this->_fieldprops)) {
$fp = ifx_fieldproperties($this->_queryID);

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -40,6 +40,9 @@ class ADODB_ldap extends ADOConnection {
# Options configuration information
var $LDAP_CONNECT_OPTIONS;
# error on binding, eg. "Binding: invalid credentials"
var $_bind_errmsg = "Binding: %s";
function ADODB_ldap()
{
}
@@ -52,13 +55,17 @@ class ADODB_ldap extends ADOConnection {
if ( !function_exists( 'ldap_connect' ) ) return null;
$conn_info = array( $host,$this->port);
if (strpos('ldap://',$host) === 0 || strpos('ldaps://',$host) === 0) {
$this->_connectionID = @ldap_connect($host);
} else {
$conn_info = array( $host,$this->port);
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
$this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] );
$this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] );
}
if (!$this->_connectionID) {
$e = 'Could not connect to ' . $conn_info[0];
$this->_errorMsg = $e;
@@ -70,14 +77,14 @@ class ADODB_ldap extends ADOConnection {
}
if ($username) {
$bind = ldap_bind( $this->_connectionID, $username, $password );
$bind = @ldap_bind( $this->_connectionID, $username, $password );
} else {
$username = 'anonymous';
$bind = ldap_bind( $this->_connectionID );
$bind = @ldap_bind( $this->_connectionID );
}
if (!$bind) {
$e = 'Could not bind to ' . $conn_info[0] . " as ".$username;
$e = sprintf($this->_bind_errmsg,ldap_error($this->_connectionID));
$this->_errorMsg = $e;
if ($this->debug) ADOConnection::outp($e);
return false;
@@ -147,13 +154,23 @@ class ADODB_ldap extends ADOConnection {
}
/* returns _queryID or false */
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$rs = ldap_search( $this->_connectionID, $this->database, $sql );
$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql;
$rs = @ldap_search( $this->_connectionID, $this->database, $sql );
$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql.': '.ldap_error($this->_connectionID);
return $rs;
}
function ErrorMsg()
{
return $this->_errorMsg;
}
function ErrorNo()
{
return @ldap_errno($this->_connectionID);
}
/* closes the LDAP connection */
function _close()
{
@@ -311,7 +328,7 @@ class ADORecordSet_ldap extends ADORecordSet{
/*
Return whole recordset as a multi-dimensional associative array
*/
function &GetAssoc($force_array = false, $first2cols = false)
function GetAssoc($force_array = false, $first2cols = false)
{
$records = $this->_numOfRows;
$results = array();
@@ -331,7 +348,7 @@ class ADORecordSet_ldap extends ADORecordSet{
return $results;
}
function &GetRowAssoc()
function GetRowAssoc()
{
$results = array();
foreach ( $this->fields as $k=>$v ) {

File diff suppressed because it is too large Load Diff

View File

@@ -1,166 +1,171 @@
<?php
/// $Id $
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// ADOdb - Database Abstraction Library for PHP //
// http://adodb.sourceforge.net/ //
// //
// Copyright (C) 2000-2007 John Lim (jlim\@natsoft.com.my) //
// All rights reserved. //
// Released under both BSD license and LGPL library license. //
// Whenever there is any discrepancy between the two licenses, //
// the BSD license will take precedence //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.com //
// //
// Copyright (C) 2001-3001 Martin Dougiamas http://dougiamas.com //
// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* MSSQL Driver with auto-prepended "N" for correct unicode storage
* of SQL literal strings. Intended to be used with MSSQL drivers that
* are sending UCS-2 data to MSSQL (FreeTDS and ODBTP) in order to get
* true cross-db compatibility from the application point of view.
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
// one useful constant
if (!defined('SINGLEQUOTE')) define('SINGLEQUOTE', "'");
include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
class ADODB_mssql_n extends ADODB_mssql {
var $databaseType = "mssql_n";
function ADODB_mssqlpo()
{
ADODB_mssql::ADODB_mssql();
}
function _query($sql,$inputarr)
{
$sql = $this->_appendN($sql);
return ADODB_mssql::_query($sql,$inputarr);
}
/**
* This function will intercept all the literals used in the SQL, prepending the "N" char to them
* in order to allow mssql to store properly data sent in the correct UCS-2 encoding (by freeTDS
* and ODBTP) keeping SQL compatibility at ADOdb level (instead of hacking every project to add
* the "N" notation when working against MSSQL.
*
* Note that this hack only must be used if ALL the char-based columns in your DB are of type nchar,
* nvarchar and ntext
*/
function _appendN($sql) {
$result = $sql;
/// Check we have some single quote in the query. Exit ok.
if (strpos($sql, SINGLEQUOTE) === false) {
return $sql;
}
/// Check we haven't an odd number of single quotes (this can cause problems below
/// and should be considered one wrong SQL). Exit with debug info.
if ((substr_count($sql, SINGLEQUOTE) & 1)) {
if ($this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Wrong number of quotes (odd)");
}
return $sql;
}
/// Check we haven't any backslash + single quote combination. It should mean wrong
/// backslashes use (bad magic_quotes_sybase?). Exit with debug info.
$regexp = '/(\\\\' . SINGLEQUOTE . '[^' . SINGLEQUOTE . '])/';
if (preg_match($regexp, $sql)) {
if ($this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Found bad use of backslash + single quote");
}
return $sql;
}
/// Remove pairs of single-quotes
$pairs = array();
$regexp = '/(' . SINGLEQUOTE . SINGLEQUOTE . ')/';
preg_match_all($regexp, $result, $list_of_pairs);
if ($list_of_pairs) {
foreach (array_unique($list_of_pairs[0]) as $key=>$value) {
$pairs['<@#@#@PAIR-'.$key.'@#@#@>'] = $value;
}
if (!empty($pairs)) {
$result = str_replace($pairs, array_keys($pairs), $result);
}
}
/// Remove the rest of literals present in the query
$literals = array();
$regexp = '/(N?' . SINGLEQUOTE . '.*?' . SINGLEQUOTE . ')/is';
preg_match_all($regexp, $result, $list_of_literals);
if ($list_of_literals) {
foreach (array_unique($list_of_literals[0]) as $key=>$value) {
$literals['<#@#@#LITERAL-'.$key.'#@#@#>'] = $value;
}
if (!empty($literals)) {
$result = str_replace($literals, array_keys($literals), $result);
}
}
/// Analyse literals to prepend the N char to them if their contents aren't numeric
if (!empty($literals)) {
foreach ($literals as $key=>$value) {
if (!is_numeric(trim($value, SINGLEQUOTE))) {
/// Non numeric string, prepend our dear N
$literals[$key] = 'N' . trim($value, 'N'); //Trimming potentially existing previous "N"
}
}
}
/// Re-apply literals to the text
if (!empty($literals)) {
$result = str_replace(array_keys($literals), $literals, $result);
}
/// Re-apply pairs of single-quotes to the text
if (!empty($pairs)) {
$result = str_replace(array_keys($pairs), $pairs, $result);
}
/// Print transformation if debug = on
if ($result != $sql && $this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation:<br>{$sql}<br>to<br>{$result}");
}
return $result;
}
}
class ADORecordset_mssql_n extends ADORecordset_mssql {
var $databaseType = "mssql_n";
function ADORecordset_mssql_n($id,$mode=false)
{
$this->ADORecordset_mssql($id,$mode);
}
}
<?php
/// $Id $
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// ADOdb - Database Abstraction Library for PHP //
// http://adodb.sourceforge.net/ //
// //
// Copyright (C) 2000-2009 John Lim (jlim\@natsoft.com.my) //
// All rights reserved. //
// Released under both BSD license and LGPL library license. //
// Whenever there is any discrepancy between the two licenses, //
// the BSD license will take precedence //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.com //
// //
// Copyright (C) 2001-3001 Martin Dougiamas http://dougiamas.com //
// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* MSSQL Driver with auto-prepended "N" for correct unicode storage
* of SQL literal strings. Intended to be used with MSSQL drivers that
* are sending UCS-2 data to MSSQL (FreeTDS and ODBTP) in order to get
* true cross-db compatibility from the application point of view.
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
// one useful constant
if (!defined('SINGLEQUOTE')) define('SINGLEQUOTE', "'");
include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
class ADODB_mssql_n extends ADODB_mssql {
var $databaseType = "mssql_n";
function ADODB_mssqlpo()
{
ADODB_mssql::ADODB_mssql();
}
function _query($sql,$inputarr=false)
{
$sql = $this->_appendN($sql);
return ADODB_mssql::_query($sql,$inputarr);
}
/**
* This function will intercept all the literals used in the SQL, prepending the "N" char to them
* in order to allow mssql to store properly data sent in the correct UCS-2 encoding (by freeTDS
* and ODBTP) keeping SQL compatibility at ADOdb level (instead of hacking every project to add
* the "N" notation when working against MSSQL.
*
* Note that this hack only must be used if ALL the char-based columns in your DB are of type nchar,
* nvarchar and ntext
*/
function _appendN($sql) {
$result = $sql;
/// Check we have some single quote in the query. Exit ok.
if (strpos($sql, SINGLEQUOTE) === false) {
return $sql;
}
/// Check we haven't an odd number of single quotes (this can cause problems below
/// and should be considered one wrong SQL). Exit with debug info.
if ((substr_count($sql, SINGLEQUOTE) & 1)) {
if ($this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Wrong number of quotes (odd)");
}
return $sql;
}
/// Check we haven't any backslash + single quote combination. It should mean wrong
/// backslashes use (bad magic_quotes_sybase?). Exit with debug info.
$regexp = '/(\\\\' . SINGLEQUOTE . '[^' . SINGLEQUOTE . '])/';
if (preg_match($regexp, $sql)) {
if ($this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Found bad use of backslash + single quote");
}
return $sql;
}
/// Remove pairs of single-quotes
$pairs = array();
$regexp = '/(' . SINGLEQUOTE . SINGLEQUOTE . ')/';
preg_match_all($regexp, $result, $list_of_pairs);
if ($list_of_pairs) {
foreach (array_unique($list_of_pairs[0]) as $key=>$value) {
$pairs['<@#@#@PAIR-'.$key.'@#@#@>'] = $value;
}
if (!empty($pairs)) {
$result = str_replace($pairs, array_keys($pairs), $result);
}
}
/// Remove the rest of literals present in the query
$literals = array();
$regexp = '/(N?' . SINGLEQUOTE . '.*?' . SINGLEQUOTE . ')/is';
preg_match_all($regexp, $result, $list_of_literals);
if ($list_of_literals) {
foreach (array_unique($list_of_literals[0]) as $key=>$value) {
$literals['<#@#@#LITERAL-'.$key.'#@#@#>'] = $value;
}
if (!empty($literals)) {
$result = str_replace($literals, array_keys($literals), $result);
}
}
/// Analyse literals to prepend the N char to them if their contents aren't numeric
if (!empty($literals)) {
foreach ($literals as $key=>$value) {
if (!is_numeric(trim($value, SINGLEQUOTE))) {
/// Non numeric string, prepend our dear N
$literals[$key] = 'N' . trim($value, 'N'); //Trimming potentially existing previous "N"
}
}
}
/// Re-apply literals to the text
if (!empty($literals)) {
$result = str_replace(array_keys($literals), $literals, $result);
}
/// Any pairs followed by N' must be switched to N' followed by those pairs
/// (or strings beginning with single quotes will fail)
$result = preg_replace("/((<@#@#@PAIR-(\d+)@#@#@>)+)N'/", "N'$1", $result);
/// Re-apply pairs of single-quotes to the text
if (!empty($pairs)) {
$result = str_replace(array_keys($pairs), $pairs, $result);
}
/// Print transformation if debug = on
if ($result != $sql && $this->debug) {
ADOConnection::outp("{$this->databaseType} internal transformation:<br>{$sql}<br>to<br>{$result}");
}
return $result;
}
}
class ADORecordset_mssql_n extends ADORecordset_mssql {
var $databaseType = "mssql_n";
function ADORecordset_mssql_n($id,$mode=false)
{
$this->ADORecordset_mssql($id,$mode);
}
}
?>

View File

@@ -0,0 +1,922 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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
Native mssql driver. Requires mssql client. Works on Windows.
http://www.microsoft.com/sql/technologies/php/default.mspx
To configure for Unix, see
http://phpbuilder.com/columns/alberto20000919.php3
$stream = sqlsrv_get_field($stmt, $index, SQLSRV_SQLTYPE_STREAM(SQLSRV_ENC_BINARY));
stream_filter_append($stream, "convert.iconv.ucs-2/utf-8"); // Voila, UTF-8 can be read directly from $stream
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
if (!function_exists('sqlsrv_configure')) {
die("mssqlnative extension not installed");
}
if (!function_exists('sqlsrv_set_error_handling')) {
function sqlsrv_set_error_handling($constant) {
sqlsrv_configure("WarningsReturnAsErrors", $constant);
}
}
if (!function_exists('sqlsrv_log_set_severity')) {
function sqlsrv_log_set_severity($constant) {
sqlsrv_configure("LogSeverity", $constant);
}
}
if (!function_exists('sqlsrv_log_set_subsystems')) {
function sqlsrv_log_set_subsystems($constant) {
sqlsrv_configure("LogSubsystems", $constant);
}
}
//----------------------------------------------------------------
// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002
// and this causes tons of problems because localized versions of
// MSSQL will return the dates in dmy or mdy order; and also the
// month strings depends on what language has been configured. The
// following two variables allow you to control the localization
// settings - Ugh.
//
// MORE LOCALIZATION INFO
// ----------------------
// To configure datetime, look for and modify sqlcommn.loc,
// typically found in c:\mssql\install
// Also read :
// http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918
// Alternatively use:
// CONVERT(char(12),datecol,120)
//
// Also if your month is showing as month-1,
// e.g. Jan 13, 2002 is showing as 13/0/2002, then see
// http://phplens.com/lens/lensforum/msgs.php?id=7048&x=1
// it's a localisation problem.
//----------------------------------------------------------------
// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc
if (ADODB_PHPVER >= 0x4300) {
// docs say 4.2.0, but testing shows only since 4.3.0 does it work!
ini_set('mssql.datetimeconvert',0);
} else {
global $ADODB_mssql_mths; // array, months must be upper-case
$ADODB_mssql_date_order = 'mdy';
$ADODB_mssql_mths = array(
'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
}
//---------------------------------------------------------------------------
// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,
// just after you connect to the database. Supports mdy and dmy only.
// Not required for PHP 4.2.0 and above.
function AutoDetect_MSSQL_Date_Order($conn)
{
global $ADODB_mssql_date_order;
$adate = $conn->GetOne('select getdate()');
if ($adate) {
$anum = (int) $adate;
if ($anum > 0) {
if ($anum > 31) {
//ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");
} else
$ADODB_mssql_date_order = 'dmy';
} else
$ADODB_mssql_date_order = 'mdy';
}
}
class ADODB_mssqlnative extends ADOConnection {
var $databaseType = "mssqlnative";
var $dataProvider = "mssqlnative";
var $replaceQuote = "''"; // string to use to replace quotes
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $substr = "substring";
var $length = 'len';
var $hasAffectedRows = true;
var $poorAffectedRows = false;
var $metaDatabasesSQL = "select name from sys.sysdatabases where name <> 'master'";
var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))";
var $metaColumnsSQL = # xtype==61 is datetime
"select c.name,t.name,c.length,
(case when c.xusertype=61 then 0 else c.xprec end),
(case when c.xusertype=61 then 0 else c.xscale end)
from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
var $hasGenID = true;
var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
var $sysTimeStamp = 'GetDate()';
var $maxParameterLen = 4000;
var $arrayClass = 'ADORecordSet_array_mssqlnative';
var $uniqueSort = true;
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; // for mssql7 or later
var $identitySQL = 'select SCOPE_IDENTITY()'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $uniqueOrderBy = true;
var $_bindInputArray = true;
var $_dropSeqSQL = "drop table %s";
function ADODB_mssqlnative()
{
if ($this->debug) {
error_log("<pre>");
sqlsrv_set_error_handling( SQLSRV_ERRORS_LOG_ALL );
sqlsrv_log_set_severity( SQLSRV_LOG_SEVERITY_ALL );
sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
sqlsrv_configure('warnings_return_as_errors', 0);
} else {
sqlsrv_set_error_handling(0);
sqlsrv_log_set_severity(0);
sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
sqlsrv_configure('warnings_return_as_errors', 0);
}
}
function ServerInfo()
{
global $ADODB_FETCH_MODE;
if ($this->fetchMode === false) {
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
} else
$savem = $this->SetFetchMode(ADODB_FETCH_NUM);
$arrServerInfo = sqlsrv_server_info($this->_connectionID);
$arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase'];
$arr['version'] = $arrServerInfo['SQLServerVersion'];//ADOConnection::_findvers($arr['description']);
return $arr;
}
function IfNull( $field, $ifNull )
{
return " ISNULL($field, $ifNull) "; // if MS SQL Server
}
function _insertid()
{
// SCOPE_IDENTITY()
// Returns the last IDENTITY value inserted into an IDENTITY column in
// the same scope. A scope is a module -- a stored procedure, trigger,
// function, or batch. Thus, two statements are in the same scope if
// they are in the same stored procedure, function, or batch.
return $this->GetOne($this->identitySQL);
}
function _affectedrows()
{
return sqlsrv_rows_affected($this->_queryID);
}
function CreateSequence($seq='adodbseq',$start=1)
{
if($this->debug) error_log("<hr>CreateSequence($seq,$start)");
sqlsrv_begin_transaction($this->_connectionID);
$start -= 1;
$this->Execute("create table $seq (id int)");//was float(53)
$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
if (!$ok) {
if($this->debug) error_log("<hr>Error: ROLLBACK");
sqlsrv_rollback($this->_connectionID);
return false;
}
sqlsrv_commit($this->_connectionID);
return true;
}
function GenID($seq='adodbseq',$start=1)
{
if($this->debug) error_log("<hr>GenID($seq,$start)");
sqlsrv_begin_transaction($this->_connectionID);
$ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
if (!$ok) {
$this->Execute("create table $seq (id int)");
$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
if (!$ok) {
if($this->debug) error_log("<hr>Error: ROLLBACK");
sqlsrv_rollback($this->_connectionID);
return false;
}
sqlsrv_commit($this->_connectionID);
return $start;
}
$num = $this->GetOne("select id from $seq");
sqlsrv_commit($this->_connectionID);
if($this->debug) error_log(" Returning: $num");
return $num;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '+';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "datename(yyyy,$col)";
break;
case 'M':
$s .= "convert(char(3),$col,0)";
break;
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
$s .= "datename(quarter,$col)";
break;
case 'D':
case 'd':
$s .= "replace(str(day($col),2),' ','0')";
break;
case 'h':
$s .= "substring(convert(char(14),$col,0),13,2)";
break;
case 'H':
$s .= "replace(str(datepart(hh,$col),2),' ','0')";
break;
case 'i':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
break;
case 's':
$s .= "replace(str(datepart(ss,$col),2),' ','0')";
break;
case 'a':
case 'A':
$s .= "substring(convert(char(19),$col,0),18,2)";
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $this->qstr($ch);
break;
}
}
return $s;
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
if ($this->debug) error_log('<hr>begin transaction');
sqlsrv_begin_transaction($this->_connectionID);
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if ($this->debug) error_log('<hr>commit transaction');
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
sqlsrv_commit($this->_connectionID);
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->debug) error_log('<hr>rollback transaction');
if ($this->transCnt) $this->transCnt -= 1;
sqlsrv_rollback($this->_connectionID);
return true;
}
function SetTransactionMode( $transaction_mode )
{
$this->_transmode = $transaction_mode;
if (empty($transaction_mode)) {
$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
return;
}
if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
$this->Execute("SET TRANSACTION ".$transaction_mode);
}
/*
Usage:
$this->BeginTrans();
$this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables
# some operation on both tables table1 and table2
$this->CommitTrans();
See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
*/
function RowLock($tables,$where,$flds='top 1 null as ignore')
{
if (!$this->transCnt) $this->BeginTrans();
return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
}
function SelectDB($dbName)
{
$this->database = $dbName;
$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
if ($this->_connectionID) {
$rs = $this->Execute('USE '.$dbName);
if($rs) {
return true;
} else return false;
}
else return false;
}
function ErrorMsg()
{
$retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
if($retErrors != null) {
foreach($retErrors as $arrError) {
$this->_errorMsg .= "SQLState: ".$arrError[ 'SQLSTATE']."\n";
$this->_errorMsg .= "Error Code: ".$arrError[ 'code']."\n";
$this->_errorMsg .= "Message: ".$arrError[ 'message']."\n";
}
} else {
$this->_errorMsg = "No errors found";
}
return $this->_errorMsg;
}
function ErrorNo()
{
if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
$err = sqlsrv_errors(SQLSRV_ERR_ALL);
if($err[0]) return $err[0]['code'];
else return -1;
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!function_exists('sqlsrv_connect')) return null;
$connectionInfo = array("Database"=>$argDatabasename,'UID'=>$argUsername,'PWD'=>$argPassword);
if ($this->debug) error_log("<hr>connecting... hostname: $argHostname params: ".var_export($connectionInfo,true));
//if ($this->debug) error_log("<hr>_connectionID before: ".serialize($this->_connectionID));
if(!($this->_connectionID = sqlsrv_connect($argHostname,$connectionInfo))) {
if ($this->debug) error_log( "<hr><b>errors</b>: ".print_r( sqlsrv_errors(), true));
return false;
}
//if ($this->debug) error_log(" _connectionID after: ".serialize($this->_connectionID));
//if ($this->debug) error_log("<hr>defined functions: <pre>".var_export(get_defined_functions(),true)."</pre>");
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
//return null;//not implemented. NOTE: Persistent connections have no effect if PHP is used as a CGI program. (FastCGI!)
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function Prepare($sql)
{
$stmt = sqlsrv_prepare( $this->_connectionID, $sql);
if (!$stmt) return $sql;
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 '';
}
/*
Unfortunately, it appears that mssql cannot handle varbinary > 255 chars
So all your blobs must be of type "image".
Remember to set in php.ini the following...
; Valid range 0 - 2147483647. Default = 4096.
mssql.textlimit = 0 ; zero to pass through
; Valid range 0 - 2147483647. Default = 4096.
mssql.textsize = 0 ; zero to pass through
*/
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
{
if (strtoupper($blobtype) == 'CLOB') {
$sql = "UPDATE $table SET $column='" . $val . "' WHERE $where";
return $this->Execute($sql) != false;
}
$sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";
return $this->Execute($sql) != false;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr=false)
{
$this->_errorMsg = false;
if (is_array($inputarr)) {
$rez = sqlsrv_query($this->_connectionID,$sql,$inputarr);
} else if (is_array($sql)) {
$rez = sqlsrv_query($this->_connectionID,$sql[1],$inputarr);
} else {
$rez = sqlsrv_query($this->_connectionID,$sql);
}
if ($this->debug) error_log("<hr>running query: ".var_export($sql,true)."<hr>input array: ".var_export($inputarr,true)."<hr>result: ".var_export($rez,true));//"<hr>connection: ".serialize($this->_connectionID)
//fix for returning true on anything besides select statements
if (is_array($sql)) $sql = $sql[1];
$sql = ltrim($sql);
if(stripos($sql, 'SELECT') !== 0 && $rez !== false) {
if ($this->debug) error_log(" isn't a select query, returning boolean true");
return true;
}
//end fix
if(!$rez) $rez = false;
return $rez;
}
// returns true or false
function _close()
{
if ($this->transCnt) $this->RollbackTrans();
$rez = @sqlsrv_close($this->_connectionID);
$this->_connectionID = false;
return $rez;
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
return ADORecordSet_array_mssql::UnixDate($v);
}
static function UnixTimeStamp($v)
{
return ADORecordSet_array_mssql::UnixTimeStamp($v);
}
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)
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$table = $this->qstr(strtoupper($table));
$sql =
"select object_name(constid) as constraint_name,
col_name(fkeyid, fkey) as column_name,
object_name(rkeyid) as referenced_table_name,
col_name(rkeyid, rkey) as referenced_column_name
from sysforeignkeys
where upper(object_name(fkeyid)) = $table
order by constraint_name, referenced_table_name, keyno";
$constraints =& $this->GetArray($sql);
$ADODB_FETCH_MODE = $save;
$arr = false;
foreach($constraints as $constr) {
//print_r($constr);
$arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3];
}
if (!$arr) return false;
$arr2 = false;
foreach($arr as $k => $v) {
foreach($v as $a => $b) {
if ($upper) $a = strtoupper($a);
$arr2[$a] = $b;
}
}
return $arr2;
}
//From: Fernando Moreira <FMoreira@imediata.pt>
function MetaDatabases()
{
$this->SelectDB("master");
$rs =& $this->Execute($this->metaDatabasesSQL);
$rows = $rs->GetRows();
$ret = array();
for($i=0;$i<count($rows);$i++) {
$ret[] = $rows[$i][0];
}
$this->SelectDB($this->database);
if($ret)
return $ret;
else
return false;
}
// "Stein-Aksel Basma" <basma@accelero.no>
// tested with MSSQL 2000
function &MetaPrimaryKeys($table)
{
global $ADODB_FETCH_MODE;
$schema = '';
$this->_findschema($table,$schema);
if (!$schema) $schema = $this->database;
if ($schema) $schema = "and k.table_catalog like '$schema%'";
$sql = "select distinct k.column_name,ordinal_position from information_schema.key_column_usage k,
information_schema.table_constraints tc
where tc.constraint_name = k.constraint_name and tc.constraint_type =
'PRIMARY KEY' and k.table_name = '$table' $schema order by ordinal_position ";
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$a = $this->GetCol($sql);
$ADODB_FETCH_MODE = $savem;
if ($a && sizeof($a)>0) return $a;
$false = false;
return $false;
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(($mask));
$this->metaTablesSQL .= " AND name like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_mssqlnative extends ADORecordSet {
var $databaseType = "mssqlnative";
var $canSeek = false;
var $fieldOffset = 0;
// _mths works only in non-localised system
function ADORecordset_mssqlnative($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
}
function _initrs()
{
global $ADODB_COUNTRECS;
if ($this->connection->debug) error_log("(before) ADODB_COUNTRECS: {$ADODB_COUNTRECS} _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}");
/*$retRowsAff = sqlsrv_rows_affected($this->_queryID);//"If you need to determine the number of rows a query will return before retrieving the actual results, appending a SELECT COUNT ... query would let you get that information, and then a call to next_result would move you to the "real" results."
error_log("rowsaff: ".serialize($retRowsAff));
$this->_numOfRows = ($ADODB_COUNTRECS)? $retRowsAff:-1;*/
$this->_numOfRows = -1;//not supported
$fieldmeta = sqlsrv_field_metadata($this->_queryID);
$this->_numOfFields = ($fieldmeta)? count($fieldmeta):-1;
if ($this->connection->debug) error_log("(after) _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}");
}
//Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>
// get next resultset - requires PHP 4.0.5 or later
function NextRecordSet()
{
if (!sqlsrv_next_result($this->_queryID)) return false;
$this->_inited = false;
$this->bind = false;
$this->_currentRow = -1;
$this->Init();
return true;
}
/* Use associative array to get fields array */
function Fields($colname)
{
if ($this->fetchMode != 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)]];
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
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)
{
if ($this->connection->debug) error_log("<hr>fetchfield: $fieldOffset, fetch array: <pre>".print_r($this->fields,true)."</pre> backtrace: ".adodb_backtrace(false));
if ($fieldOffset != -1) $this->fieldOffset = $fieldOffset;
$arrKeys = array_keys($this->fields);
if(array_key_exists($this->fieldOffset,$arrKeys) && !array_key_exists($arrKeys[$this->fieldOffset],$this->fields)) {
$f = false;
} else {
$f = $this->fields[ $arrKeys[$this->fieldOffset] ];
if($fieldOffset == -1) $this->fieldOffset++;
}
if (empty($f)) {
$f = false;//PHP Notice: Only variable references should be returned by reference
}
return $f;
}
function _seek($row)
{
return false;//There is no support for cursors in the driver at this time. All data is returned via forward-only streams.
}
// speedup
function MoveNext()
{
if ($this->connection->debug) error_log("movenext()");
//if ($this->connection->debug) error_log("eof (beginning): ".$this->EOF);
if ($this->EOF) return false;
$this->_currentRow++;
if ($this->connection->debug) error_log("_currentRow: ".$this->_currentRow);
if ($this->_fetch()) return true;
$this->EOF = true;
//if ($this->connection->debug) error_log("eof (end): ".$this->EOF);
return false;
}
// INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4
// also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!
function _fetch($ignore_fields=false)
{
if ($this->connection->debug) error_log("_fetch()");
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
if ($this->fetchMode & ADODB_FETCH_NUM) {
if ($this->connection->debug) error_log("fetch mode: both");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_BOTH);
} else {
if ($this->connection->debug) error_log("fetch mode: assoc");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_ASSOC);
}
if (ADODB_ASSOC_CASE == 0) {
foreach($this->fields as $k=>$v) {
$this->fields[strtolower($k)] = $v;
}
} else if (ADODB_ASSOC_CASE == 1) {
foreach($this->fields as $k=>$v) {
$this->fields[strtoupper($k)] = $v;
}
}
} else {
if ($this->connection->debug) error_log("fetch mode: num");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_NUMERIC);
}
if(is_array($this->fields) && array_key_exists(1,$this->fields) && !array_key_exists(0,$this->fields)) {//fix fetch numeric keys since they're not 0 based
$arrFixed = array();
foreach($this->fields as $key=>$value) {
if(is_numeric($key)) {
$arrFixed[$key-1] = $value;
} else {
$arrFixed[$key] = $value;
}
}
//if($this->connection->debug) error_log("<hr>fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true));
$this->fields = $arrFixed;
}
if(is_array($this->fields)) {
foreach($this->fields as $key=>$value) {
if (is_object($value) && method_exists($value, 'format')) {//is DateTime object
$this->fields[$key] = $value->format("Y-m-d\TH:i:s\Z");
}
}
}
if($this->fields === null) $this->fields = false;
if ($this->connection->debug) error_log("<hr>after _fetch, fields: <pre>".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false));
return $this->fields;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
$rez = sqlsrv_free_stmt($this->_queryID);
$this->_queryID = false;
return $rez;
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
return ADORecordSet_array_mssqlnative::UnixDate($v);
}
static function UnixTimeStamp($v)
{
return ADORecordSet_array_mssqlnative::UnixTimeStamp($v);
}
}
class ADORecordSet_array_mssqlnative extends ADORecordSet_array {
function ADORecordSet_array_mssqlnative($id=-1,$mode=false)
{
$this->ADORecordSet_array($id,$mode);
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
global $ADODB_mssql_mths,$ADODB_mssql_date_order;
//Dec 30 2000 12:00AM
if ($ADODB_mssql_date_order == 'dmy') {
if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
return parent::UnixDate($v);
}
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[1];
$themth = substr(strtoupper($rr[2]),0,3);
} else {
if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
return parent::UnixDate($v);
}
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[2];
$themth = substr(strtoupper($rr[1]),0,3);
}
$themth = $ADODB_mssql_mths[$themth];
if ($themth <= 0) return false;
// h-m-s-MM-DD-YY
return mktime(0,0,0,$themth,$theday,$rr[3]);
}
static function UnixTimeStamp($v)
{
if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
global $ADODB_mssql_mths,$ADODB_mssql_date_order;
//Dec 30 2000 12:00AM
if ($ADODB_mssql_date_order == 'dmy') {
if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[1];
$themth = substr(strtoupper($rr[2]),0,3);
} else {
if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[2];
$themth = substr(strtoupper($rr[1]),0,3);
}
$themth = $ADODB_mssql_mths[$themth];
if ($themth <= 0) return false;
switch (strtoupper($rr[6])) {
case 'P':
if ($rr[4]<12) $rr[4] += 12;
break;
case 'A':
if ($rr[4]==12) $rr[4] = 0;
break;
default:
break;
}
// h-m-s-MM-DD-YY
return mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);
}
}
/*
Code Example 1:
select object_name(constid) as constraint_name,
object_name(fkeyid) as table_name,
col_name(fkeyid, fkey) as column_name,
object_name(rkeyid) as referenced_table_name,
col_name(rkeyid, rkey) as referenced_column_name
from sysforeignkeys
where object_name(fkeyid) = x
order by constraint_name, table_name, referenced_table_name, keyno
Code Example 2:
select constraint_name,
column_name,
ordinal_position
from information_schema.key_column_usage
where constraint_catalog = db_name()
and table_name = x
order by constraint_name, ordinal_position
http://www.databasejournal.com/scripts/article.php/1440551
*/
?>

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,7 +45,7 @@ class ADODB_mssqlpo extends ADODB_mssql {
return array($sql,$stmt);
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_mssql::_query($sql,$inputarr);

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -58,7 +58,7 @@ class ADODB_mysql extends ADOConnection {
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
@@ -69,14 +69,14 @@ class ADODB_mysql extends ADOConnection {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
function &MetaIndexes ($table, $primary = FALSE, $owner=false)
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
@@ -132,6 +132,7 @@ class ADODB_mysql extends ADOConnection {
// if magic quotes disabled, use mysql_real_escape_string()
function qstr($s,$magic_quotes=false)
{
if (is_null($s)) return 'NULL';
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x4300) {
@@ -158,7 +159,7 @@ class ADODB_mysql extends ADOConnection {
function GetOne($sql,$inputarr=false)
{
if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
$rs =& $this->SelectLimit($sql,1,-1,$inputarr);
$rs = $this->SelectLimit($sql,1,-1,$inputarr);
if ($rs) {
$rs->Close();
if ($rs->EOF) return false;
@@ -180,7 +181,7 @@ class ADODB_mysql extends ADOConnection {
return mysql_affected_rows($this->_connectionID);
}
// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
// Reference on Last_Insert_ID on the recommended way to simulate sequences
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
@@ -228,7 +229,7 @@ class ADODB_mysql extends ADOConnection {
return $this->genID;
}
function &MetaDatabases()
function MetaDatabases()
{
$qid = mysql_list_dbs($this->_connectionID);
$arr = array();
@@ -393,7 +394,7 @@ class ADODB_mysql extends ADOConnection {
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function &MetaColumns($table)
function MetaColumns($table)
{
$this->_findschema($table,$schema);
if ($schema) {
@@ -446,10 +447,10 @@ class ADODB_mysql extends ADOConnection {
$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);
$fld->binary = (strpos($type,'blob') !== false || strpos($type,'binary') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
$fld->zerofill = (strpos($type,'zerofill') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != '' && $d != 'NULL') {
@@ -484,21 +485,21 @@ class ADODB_mysql extends ADOConnection {
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
{
$offsetStr =($offset>=0) ? ((integer)$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".((integer)$nrows),$inputarr);
$rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
else
$rs =& $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
$rs = $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
return $rs;
}
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
//global $ADODB_COUNTRECS;
//if($ADODB_COUNTRECS)
@@ -558,8 +559,9 @@ class ADODB_mysql extends ADOConnection {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
if ($associative) {
$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} else $create_sql = $a_create_table[1];
$matches = array();
@@ -575,9 +577,12 @@ class ADODB_mysql extends ADOConnection {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$ref_table])) {
$foreign_keys[$ref_table] = array();
}
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
@@ -629,28 +634,28 @@ class ADORecordSet_mysql extends ADORecordSet{
$this->_numOfFields = @mysql_num_fields($this->_queryID);
}
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @mysql_fetch_field($this->_queryID, $fieldOffset);
$f = @mysql_field_flags($this->_queryID,$fieldOffset);
$o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com)
if ($o) $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
$o->binary = (strpos($f,'binary')!== false);
if ($o) $o->binary = (strpos($f,'binary')!== false);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @mysql_fetch_field($this->_queryID);
$o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
if ($o) $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
}
return $o;
}
function &GetRowAssoc($upper=true)
function GetRowAssoc($upper=true)
{
if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields;
else $row =& ADORecordSet::GetRowAssoc($upper);
else $row = ADORecordSet::GetRowAssoc($upper);
return $row;
}
@@ -732,6 +737,7 @@ class ADORecordSet_mysql extends ADORecordSet{
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
case 'BINARY':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -50,6 +50,7 @@ class ADODB_mysqli extends ADOConnection {
var $_bindInputArray = false;
var $nameQuote = '`'; /// string to use to quote identifiers and names
var $optionFlags = array(array(MYSQLI_READ_DEFAULT_GROUP,0));
var $arrayClass = 'ADORecordSet_array_mysqli';
function ADODB_mysqli()
{
@@ -113,6 +114,7 @@ class ADODB_mysqli extends ADOConnection {
} else {
if ($this->debug)
ADOConnection::outp("Could't connect : " . $this->ErrorMsg());
$this->_connectionID = null;
return false;
}
}
@@ -142,7 +144,7 @@ class ADODB_mysqli extends ADOConnection {
function GetOne($sql,$inputarr=false)
{
$ret = false;
$rs = &$this->Execute($sql,$inputarr);
$rs = $this->Execute($sql,$inputarr);
if ($rs) {
if (!$rs->EOF) $ret = reset($rs->fields);
$rs->Close();
@@ -196,7 +198,7 @@ class ADODB_mysqli extends ADOConnection {
{
if ($this->transCnt==0) $this->BeginTrans();
if ($where) $where = ' where '.$where;
$rs =& $this->Execute("select $flds from $tables $where for update");
$rs = $this->Execute("select $flds from $tables $where for update");
return !empty($rs);
}
@@ -212,6 +214,7 @@ class ADODB_mysqli extends ADOConnection {
//Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
function qstr($s, $magic_quotes = false)
{
if (is_null($s)) return 'NULL';
if (!$magic_quotes) {
if (PHP_VERSION >= 5)
return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
@@ -248,6 +251,7 @@ class ADODB_mysqli extends ADOConnection {
// Reference on Last_Insert_ID on the recommended way to simulate sequences
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
var $_genSeqCountSQL = "select count(*) from %s";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table %s";
@@ -287,10 +291,10 @@ class ADODB_mysqli extends ADOConnection {
return $this->genID;
}
function &MetaDatabases()
function MetaDatabases()
{
$query = "SHOW DATABASES";
$ret =& $this->Execute($query);
$ret = $this->Execute($query);
if ($ret && is_object($ret)){
$arr = array();
while (!$ret->EOF){
@@ -304,7 +308,7 @@ class ADODB_mysqli extends ADOConnection {
}
function &MetaIndexes ($table, $primary = FALSE)
function MetaIndexes ($table, $primary = FALSE)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
@@ -459,7 +463,7 @@ class ADODB_mysqli extends ADOConnection {
// return "from_unixtime(unix_timestamp($date)+$fraction)";
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
@@ -470,7 +474,7 @@ class ADODB_mysqli extends ADOConnection {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
@@ -487,8 +491,9 @@ class ADODB_mysqli extends ADOConnection {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
if ($associative) {
$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} else $create_sql = $a_create_table[1];
$matches = array();
@@ -504,8 +509,11 @@ class ADODB_mysqli extends ADOConnection {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$ref_table])) {
$foreign_keys[$ref_table] = array();
}
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
@@ -518,7 +526,7 @@ class ADODB_mysqli extends ADOConnection {
return $foreign_keys;
}
function &MetaColumns($table)
function MetaColumns($table)
{
$false = false;
if (!$this->metaColumnsSQL)
@@ -552,8 +560,10 @@ class ADODB_mysqli extends ADOConnection {
$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);
$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;
@@ -605,20 +615,19 @@ class ADODB_mysqli extends ADOConnection {
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,
function SelectLimit($sql,
$nrows = -1,
$offset = -1,
$inputarr = false,
$arg3 = false,
$secs = 0)
{
$offsetStr = ($offset >= 0) ? "$offset," : '';
if ($nrows < 0) $nrows = '18446744073709551615';
if ($secs)
$rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
$rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr );
else
$rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
$rs = $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr );
return $rs;
}
@@ -627,7 +636,6 @@ class ADODB_mysqli extends ADOConnection {
function Prepare($sql)
{
return $sql;
$stmt = $this->_connectionID->prepare($sql);
if (!$stmt) {
echo $this->ErrorMsg();
@@ -641,8 +649,18 @@ class ADODB_mysqli extends ADOConnection {
function _query($sql, $inputarr)
{
global $ADODB_COUNTRECS;
// Move to the next recordset, or return false if there is none. In a stored proc
// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
// returns false. I think this is because the last "recordset" is actually just the
// return value of the stored proc (ie the number of rows affected).
// Commented out for reasons of performance. You should retrieve every recordset yourself.
// if (!mysqli_next_result($this->connection->_connectionID)) return false;
if (is_array($sql)) {
// Prepare() not supported because mysqli_stmt_execute does not return a recordset, but
// returns as bound variables.
$stmt = $sql[1];
$a = '';
foreach($inputarr as $k => $v) {
@@ -653,16 +671,28 @@ class ADODB_mysqli extends ADOConnection {
$fnarr = array_merge( array($stmt,$a) , $inputarr);
$ret = call_user_func_array('mysqli_stmt_bind_param',$fnarr);
$ret = mysqli_stmt_execute($stmt);
return $ret;
}
/*
if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
return false;
}
return $mysql_res;
*/
if( $rs = mysqli_multi_query($this->_connectionID, $sql.';') )//Contributed by "Geisel Sierote" <geisel#4up.com.br>
{
$rs = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->_connectionID ) : @mysqli_use_result( $this->_connectionID );
return $rs ? $rs : true; // mysqli_more_results( $this->_connectionID )
} else {
if($this->debug)
ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
return false;
}
}
/* Returns: the last error message from previous database operation */
@@ -812,13 +842,14 @@ class ADORecordSet_mysqli extends ADORecordSet{
131072 = MYSQLI_BINCMP_FLAG
*/
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
$fieldnr = $fieldOffset;
if ($fieldOffset != -1) {
$fieldOffset = mysqli_field_seek($this->_queryID, $fieldnr);
$fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
}
$o = mysqli_fetch_field($this->_queryID);
$o = @mysqli_fetch_field($this->_queryID);
if (!$o) return false;
/* Properties of an ADOFieldObject as set by MetaColumns */
$o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
$o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
@@ -830,11 +861,11 @@ class ADORecordSet_mysqli extends ADORecordSet{
return $o;
}
function &GetRowAssoc($upper = true)
function GetRowAssoc($upper = true)
{
if ($this->fetchMode == MYSQLI_ASSOC && !$upper)
return $this->fields;
$row =& ADORecordSet::GetRowAssoc($upper);
$row = ADORecordSet::GetRowAssoc($upper);
return $row;
}
@@ -867,6 +898,33 @@ class ADORecordSet_mysqli extends ADORecordSet{
return true;
}
function NextRecordSet()
{
global $ADODB_COUNTRECS;
mysqli_free_result($this->_queryID);
$this->_queryID = -1;
// Move to the next recordset, or return false if there is none. In a stored proc
// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
// returns false. I think this is because the last "recordset" is actually just the
// return value of the stored proc (ie the number of rows affected).
if(!mysqli_next_result($this->connection->_connectionID)) {
return false;
}
// CD: There is no $this->_connectionID variable, at least in the ADO version I'm using
$this->_queryID = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->connection->_connectionID )
: @mysqli_use_result( $this->connection->_connectionID );
if(!$this->_queryID) {
return false;
}
$this->_inited = false;
$this->bind = false;
$this->_currentRow = -1;
$this->Init();
return true;
}
// 10% speedup to move MoveNext to child class
// This is the only implementation that works now (23-10-2003).
// Other functions return no or the wrong results.
@@ -942,7 +1000,7 @@ class ADORecordSet_mysqli extends ADORecordSet{
case 'SET':
case MYSQLI_TYPE_TINY_BLOB :
case MYSQLI_TYPE_CHAR :
#case MYSQLI_TYPE_CHAR :
case MYSQLI_TYPE_STRING :
case MYSQLI_TYPE_ENUM :
case MYSQLI_TYPE_SET :
@@ -1022,4 +1080,108 @@ class ADORecordSet_mysqli extends ADORecordSet{
}
class ADORecordSet_array_mysqli extends ADORecordSet_array {
function ADORecordSet_array_mysqli($id=-1,$mode=false)
{
$this->ADORecordSet_array($id,$mode);
}
function MetaType($t, $len = -1, $fieldobj = false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
case MYSQLI_TYPE_TINY_BLOB :
#case MYSQLI_TYPE_CHAR :
case MYSQLI_TYPE_STRING :
case MYSQLI_TYPE_ENUM :
case MYSQLI_TYPE_SET :
case 253 :
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
case MYSQLI_TYPE_BLOB :
case MYSQLI_TYPE_LONG_BLOB :
case MYSQLI_TYPE_MEDIUM_BLOB :
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE':
case MYSQLI_TYPE_DATE :
case MYSQLI_TYPE_YEAR :
return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case MYSQLI_TYPE_DATETIME :
case MYSQLI_TYPE_NEWDATE :
case MYSQLI_TYPE_TIME :
case MYSQLI_TYPE_TIMESTAMP :
return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
case MYSQLI_TYPE_INT24 :
case MYSQLI_TYPE_LONG :
case MYSQLI_TYPE_LONGLONG :
case MYSQLI_TYPE_SHORT :
case MYSQLI_TYPE_TINY :
if (!empty($fieldobj->primary_key)) return 'R';
return 'I';
// Added floating-point types
// Maybe not necessery.
case 'FLOAT':
case 'DOUBLE':
// case 'DOUBLE PRECISION':
case 'DECIMAL':
case 'DEC':
case 'FIXED':
default:
//if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
return 'N';
}
} // function
}
?>

View File

@@ -0,0 +1,138 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
MySQL code that supports transactions. For MySQL 3.23 or later.
Code from James Poon <jpoon88@yahoo.com>
Requires mysql client. Works on Windows and Unix.
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");
class ADODB_mysqlt extends ADODB_mysql {
var $databaseType = 'mysqlt';
var $ansiOuter = true; // for Version 3.23.17 or later
var $hasTransactions = true;
var $autoRollback = true; // apparently mysql does not autorollback properly
function ADODB_mysqlt()
{
global $ADODB_EXTENSION; if ($ADODB_EXTENSION) $this->rsPrefix .= 'ext_';
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('SET AUTOCOMMIT=0');
$this->Execute('BEGIN');
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RowLock($tables,$where='',$flds='1 as adodb_ignore')
{
if ($this->transCnt==0) $this->BeginTrans();
if ($where) $where = ' where '.$where;
$rs = $this->Execute("select $flds from $tables $where for update");
return !empty($rs);
}
}
class ADORecordSet_mysqlt extends ADORecordSet_mysql{
var $databaseType = "mysqlt";
function ADORecordSet_mysqlt($queryID,$mode=false)
{
if ($mode === false) {
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;
case ADODB_FETCH_DEFAULT:
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)) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
}
class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt {
function ADORecordSet_ext_mysqlt($queryID,$mode=false)
{
if ($mode === false) {
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;
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = MYSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
$this->ADORecordSet($queryID);
}
function MoveNext()
{
return adodb_movenext($this);
}
}
?>

View File

@@ -1,7 +1,7 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -62,25 +62,25 @@ class ADODB_mysqlt extends ADODB_mysql {
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$ok = $this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
return $ok ? true : false;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$ok = $this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
return $ok ? true : false;
}
function RowLock($tables,$where='',$flds='1 as adodb_ignore')
{
if ($this->transCnt==0) $this->BeginTrans();
if ($where) $where = ' where '.$where;
$rs =& $this->Execute("select $flds from $tables $where for update");
$rs = $this->Execute("select $flds from $tables $where for update");
return !empty($rs);
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
First cut at the Netezza Driver by Josh Eldridge joshuae74#hotmail.com
Based on the previous postgres drivers.
@@ -53,7 +53,7 @@ class ADODB_netezza extends ADODB_postgres64 {
}
function &MetaColumns($table,$upper=true)
function MetaColumns($table,$upper=true)
{
// Changed this function to support Netezza which has no concept of keys
@@ -67,7 +67,7 @@ class ADODB_netezza extends ADODB_postgres64 {
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;

View File

@@ -1,7 +1,7 @@
<?php
/*
version V4.94 23 Jan 2007 (c) 2000-2007 John Lim. All rights reserved.
version V5.06 16 Oct 2008 (c) 2000-2009 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
@@ -81,13 +81,13 @@ class ADODB_oci8 extends ADOConnection {
var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
var $session_sharing_force_blob = false; // alter session on updateblob if set to true
var $firstrows = true; // enable first rows optimization on SelectLimit()
var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.
var $selectOffsetAlg1 = 1000; // when to use 1st algorithm of selectlimit.
var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS'
var $dateformat = 'YYYY-MM-DD'; // for DBDate()
var $dateformat = 'YYYY-MM-DD'; // DBDate format
var $useDBDateFormatForTextInput=false;
var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
var $_refLOBs = array();
// var $ansiOuter = true; // if oracle9
function ADODB_oci8()
@@ -96,8 +96,8 @@ class ADODB_oci8 extends ADOConnection {
if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
}
/* Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
function &MetaColumns($table)
/* function MetaColumns($table) added by smondino@users.sourceforge.net*/
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;
@@ -141,7 +141,7 @@ class ADODB_oci8 extends ADOConnection {
function Time()
{
$rs =& $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
$rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
return false;
@@ -184,7 +184,7 @@ NATSOFT.DOMAIN =
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
{
if (!function_exists('OCIPLogon')) return null;
#adodb_backtrace();
$this->_errorMsg = false;
$this->_errorCode = false;
@@ -200,6 +200,11 @@ NATSOFT.DOMAIN =
$argHostport = empty($this->port)? "1521" : $this->port;
}
if (strncasecmp($argDatabasename,'SID=',4) == 0) {
$argDatabasename = substr($argDatabasename,4);
$this->connectSID = true;
}
if ($this->connectSID) {
$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
.")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
@@ -272,10 +277,10 @@ NATSOFT.DOMAIN =
}
// format and return date string in database date format
function DBDate($d)
function DBDate($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return 'TO_DATE('.$d.",'".$this->dateformat."')";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->dateformat."')";
}
@@ -297,9 +302,10 @@ NATSOFT.DOMAIN =
}
// format and return date string in database timestamp format
function DBTimeStamp($ts)
function DBTimeStamp($ts,$isfld=false)
{
if (empty($ts) && $ts !== 0) return 'null';
if ($isfld) return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')";
if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
return 'TO_DATE('.adodb_date("'Y-m-d H:i:s'",$ts).",'RRRR-MM-DD, HH24:MI:SS')";
}
@@ -310,14 +316,14 @@ NATSOFT.DOMAIN =
return $this->GetOne("select $flds from $tables where $where for update");
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtoupper($mask));
$this->metaTablesSQL .= " AND upper(table_name) like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
@@ -326,7 +332,7 @@ NATSOFT.DOMAIN =
}
// Mark Newnham
function &MetaIndexes ($table, $primary = FALSE, $owner=false)
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
@@ -399,8 +405,10 @@ NATSOFT.DOMAIN =
$this->autoCommit = false;
$this->_commit = OCI_DEFAULT;
if ($this->_transmode) $this->Execute("SET TRANSACTION ".$this->_transmode);
return true;
if ($this->_transmode) $ok = $this->Execute("SET TRANSACTION ".$this->_transmode);
else $ok = true;
return $ok ? true : false;
}
function CommitTrans($ok=true)
@@ -541,6 +549,12 @@ NATSOFT.DOMAIN =
return $s. "')";
}
function GetRandRow($sql, $arr = false)
{
$sql = "SELECT * FROM ($sql ORDER BY dbms_random.value) WHERE rownum = 1";
return $this->GetRow($sql,$arr);
}
/*
This algorithm makes use of
@@ -557,7 +571,7 @@ NATSOFT.DOMAIN =
This implementation does not appear to work with oracle 8.0.5 or earlier. Comment
out this function then, and the slower SelectLimit() in the base class will be used.
*/
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
// seems that oracle only supports 1 hint comment in 8i
if ($this->firstrows) {
@@ -567,7 +581,7 @@ NATSOFT.DOMAIN =
$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
}
if ($offset < $this->selectOffsetAlg1) {
if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) {
if ($nrows > 0) {
if ($offset > 0) $nrows += $offset;
//$inputarr['adodb_rownum'] = $nrows;
@@ -581,7 +595,7 @@ NATSOFT.DOMAIN =
}
// note that $nrows = 0 still has to work ==> no rows returned
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $rs;
} else {
@@ -589,14 +603,14 @@ NATSOFT.DOMAIN =
// Let Oracle return the name of the columns
$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)) {
if (is_array($inputarr)) {
foreach($inputarr as $k => $v) {
if (is_array($v)) {
if (sizeof($v) == 2) // suggested by g.giunta@libero.
@@ -610,6 +624,7 @@ NATSOFT.DOMAIN =
$bindarr[$k] = $v;
} else { // dynamic sql, so rebind every time
OCIBindByName($stmt,":$k",$inputarr[$k],$len);
}
}
}
@@ -628,16 +643,17 @@ NATSOFT.DOMAIN =
OCIFreeStatement($stmt);
$fields = implode(',', $cols);
$nrows += $offset;
if ($nrows <= 0) $nrows = 999999999999;
else $nrows += $offset;
$offset += 1; // in Oracle rownum starts at 1
if ($this->databaseType == 'oci8po') {
$sql = "SELECT $fields FROM".
$sql = "SELECT /*+ FIRST_ROWS */ $fields FROM".
"(SELECT rownum as adodb_rownum, $fields FROM".
" ($sql) WHERE rownum <= ?".
") WHERE adodb_rownum >= ?";
} else {
$sql = "SELECT $fields FROM".
$sql = "SELECT /*+ FIRST_ROWS */ $fields FROM".
"(SELECT rownum as adodb_rownum, $fields FROM".
" ($sql) WHERE rownum <= :adodb_nrows".
") WHERE adodb_rownum >= :adodb_offset";
@@ -645,8 +661,8 @@ NATSOFT.DOMAIN =
$inputarr['adodb_nrows'] = $nrows;
$inputarr['adodb_offset'] = $offset;
if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);
else $rs =& $this->Execute($sql,$inputarr);
if ($secs2cache>0) $rs = $this->CacheExecute($secs2cache, $sql,$inputarr);
else $rs = $this->Execute($sql,$inputarr);
return $rs;
}
@@ -704,7 +720,7 @@ NATSOFT.DOMAIN =
}
/**
* Usage: store file pointed to by $var in a blob
* Usage: store file pointed to by $val in a blob
*/
function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
{
@@ -739,11 +755,11 @@ NATSOFT.DOMAIN =
* @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)
function Execute($sql,$inputarr=false)
{
if ($this->fnExecute) {
$fn = $this->fnExecute;
$ret =& $fn($this,$sql,$inputarr);
$ret = $fn($this,$sql,$inputarr);
if (isset($ret)) return $ret;
}
if ($inputarr) {
@@ -751,6 +767,7 @@ NATSOFT.DOMAIN =
$element0 = reset($inputarr);
if (!$this->_bindInputArray) {
# is_object check because oci8 descriptors can be passed in
if (is_array($element0) && !is_object(reset($element0))) {
if (is_string($sql))
@@ -759,15 +776,48 @@ NATSOFT.DOMAIN =
$stmt = $sql;
foreach($inputarr as $arr) {
$ret =& $this->_Execute($stmt,$arr);
$ret = $this->_Execute($stmt,$arr);
if (!$ret) return $ret;
}
} else {
$ret =& $this->_Execute($sql,$inputarr);
$sqlarr = explode(':',$sql);
$sql = '';
$lastnomatch = -2;
#var_dump($sqlarr);echo "<hr>";var_dump($inputarr);echo"<hr>";
foreach($sqlarr as $k => $str) {
if ($k == 0) { $sql = $str; continue; }
// we need $lastnomatch because of the following datetime,
// eg. '10:10:01', which causes code to think that there is bind param :10 and :1
$ok = preg_match('/^([0-9]*)/', $str, $arr);
if (!$ok) $sql .= $str;
else {
$at = $arr[1];
if (isset($inputarr[$at]) || is_null($inputarr[$at])) {
if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) {
$sql .= ':'.$str;
$lastnomatch = $k;
} else if ($lastnomatch == $k-1) {
$sql .= ':'.$str;
} else {
if (is_null($inputarr[$at])) $sql .= 'null';
else $sql .= $this->qstr($inputarr[$at]);
$sql .= substr($str, strlen($at));
}
} else {
$sql .= ':'.$str;
}
}
}
$inputarr = false;
}
}
$ret = $this->_Execute($sql,$inputarr);
} else {
$ret =& $this->_Execute($sql,false);
$ret = $this->_Execute($sql,false);
}
return $ret;
@@ -818,7 +868,7 @@ NATSOFT.DOMAIN =
array('VAR1' => 'Mr Bean'));
*/
function &ExecuteCursor($sql,$cursorName='rs',$params=false)
function ExecuteCursor($sql,$cursorName='rs',$params=false)
{
if (is_array($sql)) $stmt = $sql;
else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
@@ -835,7 +885,7 @@ NATSOFT.DOMAIN =
} else
$hasref = false;
$rs =& $this->Execute($stmt);
$rs = $this->Execute($stmt);
if ($rs) {
if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]);
else if ($hasref) $rs->_refcursor = $stmt[4];
@@ -895,7 +945,7 @@ NATSOFT.DOMAIN =
$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 (".$name.") binded");
@@ -910,7 +960,7 @@ NATSOFT.DOMAIN =
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 {
@@ -970,7 +1020,7 @@ NATSOFT.DOMAIN =
$db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
$db->execute($stmt);
*/
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_array($sql)) { // is prepared sql
$stmt = $sql[1];
@@ -981,7 +1031,7 @@ NATSOFT.DOMAIN =
$bindpos = $sql[3];
if (isset($this->_bind[$bindpos])) {
// all tied up already
$bindarr = &$this->_bind[$bindpos];
$bindarr = $this->_bind[$bindpos];
} else {
// one statement to bind them all
$bindarr = array();
@@ -989,7 +1039,7 @@ NATSOFT.DOMAIN =
$bindarr[$k] = $v;
OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
}
$this->_bind[$bindpos] = &$bindarr;
$this->_bind[$bindpos] = $bindarr;
}
}
} else {
@@ -1009,7 +1059,13 @@ NATSOFT.DOMAIN =
else
OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
if ($this->debug==99) {
if (is_object($v[0]))
echo "name=:$k",' len='.$v[1],' type='.$v[2],'<br>';
else
echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
}
} else {
$len = -1;
if ($v === ' ') $len = 1;
@@ -1076,6 +1132,32 @@ NATSOFT.DOMAIN =
return false;
}
// From Oracle Whitepaper: PHP Scalability and High Availability
function IsConnectionError($err)
{
switch($err) {
case 378: /* buffer pool param incorrect */
case 602: /* core dump */
case 603: /* fatal error */
case 609: /* attach failed */
case 1012: /* not logged in */
case 1033: /* init or shutdown in progress */
case 1043: /* Oracle not available */
case 1089: /* immediate shutdown in progress */
case 1090: /* shutdown in progress */
case 1092: /* instance terminated */
case 3113: /* disconnect */
case 3114: /* not connected */
case 3122: /* closing window */
case 3135: /* lost contact */
case 12153: /* TNS: not connected */
case 27146: /* fatal or instance terminated */
case 28511: /* Lost RPC */
return true;
}
return false;
}
// returns true or false
function _close()
{
@@ -1118,7 +1200,7 @@ SELECT /*+ RULE */ distinct b.column_name
$rs = $this->Execute($sql);
if ($rs && !$rs->EOF) {
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$a = array();
foreach($arr as $v) {
$a[] = reset($v);
@@ -1149,7 +1231,7 @@ SELECT /*+ RULE */ distinct b.column_name
from {$tabp}constraints
where constraint_type = 'R' and table_name = $table $owner";
$constraints =& $this->GetArray($sql);
$constraints = $this->GetArray($sql);
$arr = false;
foreach($constraints as $constr) {
$cons = $this->qstr($constr[0]);
@@ -1290,24 +1372,31 @@ class ADORecordset_oci8 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;
$fieldOffset += 1;
$fld->name =OCIcolumnname($this->_queryID, $fieldOffset);
$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
if ($fld->type == 'NUMBER') {
switch($fld->type) {
case 'NUMBER':
$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
$sc = OCIColumnScale($this->_queryID, $fieldOffset);
if ($p != 0 && $sc == 0) $fld->type = 'INT';
//echo " $this->name ($p.$sc) ";
}
break;
case 'CLOB':
case 'NCLOB':
case 'BLOB':
$fld->max_length = -1;
break;
}
return $fld;
}
/* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
return $this->_fieldobjs[$fieldOffset];
}
@@ -1345,7 +1434,7 @@ class ADORecordset_oci8 extends ADORecordSet {
/*
# does not work as first record is retrieved in _initrs(), so is not included in GetArray()
function &GetArray($nRows = -1)
function GetArray($nRows = -1)
{
global $ADODB_OCI8_GETARRAY;
@@ -1364,7 +1453,7 @@ class ADORecordset_oci8 extends ADORecordSet {
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);
$results = array_merge(array($this->fields),$assoc);
return $results;
default:
@@ -1372,16 +1461,16 @@ class ADORecordset_oci8 extends ADORecordSet {
}
}
$results =& ADORecordSet::GetArray($nRows);
$results = ADORecordSet::GetArray($nRows);
return $results;
} */
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
function GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) {
$arr =& $this->GetArray($nrows);
$arr = $this->GetArray($nrows);
return $arr;
}
$arr = array();

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
<?php
/**
* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,7 +26,7 @@ class ADODB_oci805 extends ADODB_oci8 {
$this->ADODB_oci8();
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
// seems that oracle only supports 1 hint comment in 8i
if (strpos($sql,'/*+') !== false)

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 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.
@@ -50,7 +50,7 @@ class ADODB_oci8po extends ADODB_oci8 {
}
// emulate handling of parameters ? ?, replacing with :bind0 :bind1
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_array($inputarr)) {
$i = 0;
@@ -98,11 +98,12 @@ class ADORecordset_oci8po extends ADORecordset_oci8 {
}
// lowercase field names...
function &_FetchField($fieldOffset = -1)
function _FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fieldOffset += 1;
$fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
$fld->name = OCIcolumnname($this->_queryID, $fieldOffset);
if (ADODB_ASSOC_CASE == 0) $fld->name = strtolower($fld->name);
$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
if ($fld->type == 'NUMBER') {
@@ -149,7 +150,7 @@ class ADORecordset_oci8po extends ADORecordset_oci8 {
}
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
function GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) {
$arr = $this->GetArray($nrows);

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -252,7 +252,7 @@ class ADODB_odbc extends ADOConnection {
if (!$rs) return false;
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$rs->Close();
//print_r($arr);
$arr2 = array();
@@ -264,7 +264,7 @@ class ADODB_odbc extends ADOConnection {
function &MetaTables($ttype=false)
function MetaTables($ttype=false)
{
global $ADODB_FETCH_MODE;
@@ -281,7 +281,7 @@ class ADODB_odbc extends ADOConnection {
}
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
//print_r($arr);
$rs->Close();
@@ -370,7 +370,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/od
}
}
function &MetaColumns($table)
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;
@@ -422,7 +422,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/od
}
if (empty($qid)) return $false;
$rs =& new ADORecordSet_odbc($qid);
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return $false;
@@ -614,7 +614,7 @@ class ADORecordSet_odbc extends ADORecordSet {
// returns the field object
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
$off=$fieldOffset+1; // offsets begin at 1
@@ -661,10 +661,10 @@ class ADORecordSet_odbc extends ADORecordSet {
}
// speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
function &GetArrayLimit($nrows,$offset=-1)
function GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) {
$rs =& $this->GetArray($nrows);
$rs = $this->GetArray($nrows);
return $rs;
}
$savem = $this->fetchMode;
@@ -673,7 +673,7 @@ class ADORecordSet_odbc extends ADORecordSet {
$this->fetchMode = $savem;
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
$results = array();
@@ -700,7 +700,7 @@ class ADORecordSet_odbc extends ADORecordSet {
}
if ($rez) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}
@@ -721,7 +721,7 @@ class ADORecordSet_odbc extends ADORecordSet {
}
if ($rez) {
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
}
return true;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -140,7 +140,7 @@ class ADODB_ODBC_DB2 extends ADODB_odbc {
return $this->GetOne("select $flds from $tables where $where for update");
}
function &MetaTables($ttype=false,$showSchema=false, $qtable="%", $qschema="%")
function MetaTables($ttype=false,$showSchema=false, $qtable="%", $qschema="%")
{
global $ADODB_FETCH_MODE;
@@ -157,7 +157,7 @@ class ADODB_ODBC_DB2 extends ADODB_odbc {
}
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
//print_r($arr);
$rs->Close();
@@ -184,7 +184,7 @@ class ADODB_ODBC_DB2 extends ADODB_odbc {
return $arr2;
}
function &MetaIndexes ($table, $primary = FALSE, $owner=false)
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
@@ -278,20 +278,20 @@ class ADODB_ODBC_DB2 extends ADODB_odbc {
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)
{
$nrows = (integer) $nrows;
if ($offset <= 0) {
// could also use " OPTIMIZE FOR $nrows ROWS "
if ($nrows >= 0) $sql .= " FETCH FIRST $nrows ROWS ONLY ";
$rs =& $this->Execute($sql,$inputArr);
$rs = $this->Execute($sql,$inputArr);
} else {
if ($offset > 0 && $nrows < 0);
else {
$nrows += $offset;
$sql .= " FETCH FIRST $nrows ROWS ONLY ";
}
$rs =& ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);
$rs = ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);
}
return $rs;

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -35,7 +35,7 @@ class ADODB_odbc_mssql extends ADODB_odbc {
var $substr = 'substring';
var $length = 'len';
var $ansiOuter = true; // for mssql7 or later
var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $identitySQL = 'select @@identity'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $hasInsertID = true;
var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON,
# concatenating a null value with a string yields a NULL result
@@ -50,12 +50,11 @@ class ADODB_odbc_mssql extends ADODB_odbc {
function ServerInfo()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$save=$this->SetFetchMode(ADODB_FETCH_NUM);
$row = $this->GetRow("execute sp_server_info 2");
$ADODB_FETCH_MODE = $save;
$this->SetFetchMode($save);
if (!is_array($row)) return false;
@$arr['description'] = $row[2];
$arr['description'] = $row[2];
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
@@ -93,7 +92,7 @@ from sysforeignkeys
where upper(object_name(fkeyid)) = $table
order by constraint_name, referenced_table_name, keyno";
$constraints =& $this->GetArray($sql);
$constraints = $this->GetArray($sql);
$ADODB_FETCH_MODE = $save;
@@ -115,14 +114,14 @@ order by constraint_name, referenced_table_name, keyno";
return $arr2;
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {$this->debug=1;
$save = $this->metaTablesSQL;
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " AND name like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
@@ -130,14 +129,14 @@ order by constraint_name, referenced_table_name, keyno";
return $ret;
}
function &MetaColumns($table)
function MetaColumns($table)
{
$arr = ADOConnection::MetaColumns($table);
return $arr;
}
function &MetaIndexes($table,$primary=false)
function MetaIndexes($table,$primary=false)
{
$table = $this->qstr($table);
@@ -177,7 +176,7 @@ order by constraint_name, referenced_table_name, keyno";
return $indexes;
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_odbc::_query($sql,$inputarr);
@@ -196,7 +195,7 @@ order by constraint_name, referenced_table_name, keyno";
// "Stein-Aksel Basma" <basma@accelero.no>
// tested with MSSQL 2000
function &MetaPrimaryKeys($table)
function MetaPrimaryKeys($table)
{
global $ADODB_FETCH_MODE;
@@ -220,14 +219,14 @@ order by constraint_name, referenced_table_name, keyno";
return $false;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
if ($nrows > 0 && $offset <= 0) {
$sql = preg_replace(
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
$rs =& $this->Execute($sql,$inputarr);
$rs = $this->Execute($sql,$inputarr);
} else
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $rs;
}

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -36,7 +36,7 @@ class ADODB_odbc_oracle extends ADODB_odbc {
$this->ADODB_odbc();
}
function &MetaTables()
function MetaTables()
{
$false = false;
$rs = $this->Execute($this->metaTablesSQL);
@@ -50,7 +50,7 @@ class ADODB_odbc_oracle extends ADODB_odbc {
return $arr2;
}
function &MetaColumns($table)
function MetaColumns($table)
{
global $ADODB_FETCH_MODE;

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -45,16 +45,39 @@ class ADODB_odbtp extends ADOConnection{
function ErrorMsg()
{
if ($this->_errorMsg !== false) return $this->_errorMsg;
if (empty($this->_connectionID)) return @odbtp_last_error();
return @odbtp_last_error($this->_connectionID);
}
function ErrorNo()
{
if ($this->_errorCode !== false) return $this->_errorCode;
if (empty($this->_connectionID)) return @odbtp_last_error_state();
return @odbtp_last_error_state($this->_connectionID);
}
/*
function DBDate($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return "convert(date, $d, 120)";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
$d = adodb_date($this->fmtDate,$d);
return "convert(date, $d, 120)";
}
function DBTimeStamp($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return "convert(datetime, $d, 120)";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
$d = adodb_date($this->fmtDate,$d);
return "convert(datetime, $d, 120)";
}
*/
function _insertid()
{
// SCOPE_IDENTITY()
@@ -192,7 +215,7 @@ class ADODB_odbtp extends ADOConnection{
$this->_canSelectDb = true;
$this->substr = "substring";
$this->length = 'len';
$this->identitySQL = 'select @@IDENTITY';
$this->identitySQL = 'select SCOPE_IDENTITY()';
$this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'";
$this->_canPrepareSP = true;
break;
@@ -240,7 +263,7 @@ class ADODB_odbtp extends ADOConnection{
$this->rightOuter = '=*';
$this->hasInsertID = true;
$this->hasTransactions = true;
$this->identitySQL = 'select @@IDENTITY';
$this->identitySQL = 'select SCOPE_IDENTITY()';
break;
default:
$this->databaseType = 'odbtp';
@@ -273,7 +296,7 @@ class ADODB_odbtp extends ADOConnection{
return true;
}
function &MetaTables($ttype='',$showSchema=false,$mask=false)
function MetaTables($ttype='',$showSchema=false,$mask=false)
{
global $ADODB_FETCH_MODE;
@@ -281,7 +304,7 @@ class ADODB_odbtp extends ADOConnection{
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
$arr =& $this->GetArray("||SQLTables||||$ttype");
$arr = $this->GetArray("||SQLTables||||$ttype");
if (isset($savefm)) $this->SetFetchMode($savefm);
$ADODB_FETCH_MODE = $savem;
@@ -295,7 +318,7 @@ class ADODB_odbtp extends ADOConnection{
return $arr2;
}
function &MetaColumns($table,$upper=true)
function MetaColumns($table,$upper=true)
{
global $ADODB_FETCH_MODE;
@@ -341,13 +364,13 @@ class ADODB_odbtp extends ADOConnection{
return $retarr;
}
function &MetaPrimaryKeys($table, $owner='')
function MetaPrimaryKeys($table, $owner='')
{
global $ADODB_FETCH_MODE;
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$arr =& $this->GetArray("||SQLPrimaryKeys||$owner|$table");
$arr = $this->GetArray("||SQLPrimaryKeys||$owner|$table");
$ADODB_FETCH_MODE = $savem;
//print_r($arr);
@@ -358,13 +381,13 @@ class ADODB_odbtp extends ADOConnection{
return $arr2;
}
function &MetaForeignKeys($table, $owner='', $upper=false)
function MetaForeignKeys($table, $owner='', $upper=false)
{
global $ADODB_FETCH_MODE;
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$constraints =& $this->GetArray("||SQLForeignKeys|||||$owner|$table");
$constraints = $this->GetArray("||SQLForeignKeys|||||$owner|$table");
$ADODB_FETCH_MODE = $savem;
$arr = false;
@@ -424,19 +447,23 @@ class ADODB_odbtp extends ADOConnection{
return $ret;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
// TOP requires ORDER BY for Visual FoxPro
if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
}
$ret =& 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
$this->_errorMsg = false;
$this->_errorCode = false;
$stmt = @odbtp_prepare($sql,$this->_connectionID);
if (!$stmt) {
// print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
@@ -449,6 +476,9 @@ class ADODB_odbtp extends ADOConnection{
{
if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures
$this->_errorMsg = false;
$this->_errorCode = false;
$stmt = @odbtp_prepare_proc($sql,$this->_connectionID);
if (!$stmt) return false;
return array($sql,$stmt);
@@ -511,6 +541,56 @@ class ADODB_odbtp extends ADOConnection{
return @odbtp_execute( $stmt ) != false;
}
function MetaIndexes($table,$primary=false)
{
switch ( $this->odbc_driver) {
case ODB_DRIVER_MSSQL:
return $this->MetaIndexes_mssql($table, $primary);
default:
return array();
}
}
function MetaIndexes_mssql($table,$primary=false)
{
$table = strtolower($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 lower(O.Name) = $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 IfNull( $field, $ifNull )
{
switch( $this->odbc_driver ) {
@@ -526,6 +606,9 @@ class ADODB_odbtp extends ADOConnection{
{
global $php_errormsg;
$this->_errorMsg = false;
$this->_errorCode = false;
if ($inputarr) {
if (is_array($sql)) {
$stmtid = $sql[1];
@@ -537,10 +620,20 @@ class ADODB_odbtp extends ADOConnection{
}
}
$num_params = @odbtp_num_params( $stmtid );
/*
for( $param = 1; $param <= $num_params; $param++ ) {
@odbtp_input( $stmtid, $param );
@odbtp_set( $stmtid, $param, $inputarr[$param-1] );
}*/
$param = 1;
foreach($inputarr as $v) {
@odbtp_input( $stmtid, $param );
@odbtp_set( $stmtid, $param, $v );
$param += 1;
if ($param > $num_params) break;
}
if (!@odbtp_execute($stmtid) ) {
return false;
}
@@ -602,7 +695,7 @@ class ADORecordSet_odbtp extends ADORecordSet {
}
}
function &FetchField($fieldOffset = 0)
function FetchField($fieldOffset = 0)
{
$off=$fieldOffset; // offsets begin at 0
$o= new ADOFieldObject();

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -248,7 +248,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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -64,39 +64,7 @@ function adodb_pdo_type($t)
class ADODB_pdo_base extends ADODB_pdo {
var $sysDate = "'?'";
var $sysTimeStamp = "'?'";
function _init($parentDriver)
{
$parentDriver->_bindInputArray = true;
#$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 {
@@ -124,7 +92,7 @@ class ADODB_pdo extends ADOConnection {
function _UpdatePDO()
{
$d = &$this->_driver;
$d = $this->_driver;
$this->fmtDate = $d->fmtDate;
$this->fmtTimeStamp = $d->fmtTimeStamp;
$this->replaceQuote = $d->replaceQuote;
@@ -147,7 +115,7 @@ class ADODB_pdo extends ADOConnection {
if (!empty($this->_driver->_hasdual)) $sql = "select $this->sysTimeStamp from dual";
else $sql = "select $this->sysTimeStamp";
$rs =& $this->_Execute($sql);
$rs = $this->_Execute($sql);
if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
return false;
@@ -190,6 +158,7 @@ class ADODB_pdo extends ADOConnection {
case 'mysql':
case 'pgsql':
case 'mssql':
case 'sqlite':
include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
break;
}
@@ -206,6 +175,15 @@ class ADODB_pdo extends ADOConnection {
return false;
}
function Concat()
{
$args = func_get_args();
if(method_exists($this->_driver, 'Concat'))
return call_user_func_array(array($this->_driver, 'Concat'), $args);
return call_user_func_array(array($this,'parent::Concat'), $args);
}
// returns true or false
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
@@ -248,6 +226,10 @@ class ADODB_pdo extends ADOConnection {
else $obj->bindParam($name, $var);
}
function OffsetDate($dayFraction,$date=false)
{
return $this->_driver->OffsetDate($dayFraction,$date);
}
function ErrorMsg()
{
@@ -280,8 +262,19 @@ class ADODB_pdo extends ADOConnection {
return $err;
}
function SetTransactionMode($transaction_mode)
{
if(method_exists($this->_driver, 'SetTransactionMode'))
return $this->_driver->SetTransactionMode($transaction_mode);
return parent::SetTransactionMode($seqname);
}
function BeginTrans()
{
if(method_exists($this->_driver, 'BeginTrans'))
return $this->_driver->BeginTrans();
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
$this->transCnt += 1;
@@ -292,6 +285,9 @@ class ADODB_pdo extends ADOConnection {
function CommitTrans($ok=true)
{
if(method_exists($this->_driver, 'CommitTrans'))
return $this->_driver->CommitTrans($ok);
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
@@ -305,6 +301,9 @@ class ADODB_pdo extends ADOConnection {
function RollbackTrans()
{
if(method_exists($this->_driver, 'RollbackTrans'))
return $this->_driver->RollbackTrans();
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
@@ -331,6 +330,30 @@ class ADODB_pdo extends ADOConnection {
return $obj;
}
function CreateSequence($seqname='adodbseq',$startID=1)
{
if(method_exists($this->_driver, 'CreateSequence'))
return $this->_driver->CreateSequence($seqname, $startID);
return parent::CreateSequence($seqname, $startID);
}
function DropSequence($seqname='adodbseq')
{
if(method_exists($this->_driver, 'DropSequence'))
return $this->_driver->DropSequence($seqname);
return parent::DropSequence($seqname);
}
function GenID($seqname='adodbseq',$startID=1)
{
if(method_exists($this->_driver, 'GenID'))
return $this->_driver->GenID($seqname, $startID);
return parent::GenID($seqname, $startID);
}
/* returns queryID or false */
function _query($sql,$inputarr=false)
@@ -390,6 +413,40 @@ class ADODB_pdo extends ADOConnection {
}
}
class ADODB_pdo_base extends ADODB_pdo {
var $sysDate = "'?'";
var $sysTimeStamp = "'?'";
function _init($parentDriver)
{
$parentDriver->_bindInputArray = true;
#$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 ADOPDOStatement {
var $databaseType = "pdo";
@@ -506,7 +563,7 @@ class ADORecordSet_pdo extends ADORecordSet {
}
// returns the field object
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
$off=$fieldOffset+1; // offsets begin at 1

View File

@@ -2,7 +2,7 @@
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -47,12 +47,12 @@ class ADODB_pdo_mssql extends ADODB_pdo {
$this->Execute("SET TRANSACTION ".$transaction_mode);
}
function MetaTables()
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
return false;
}
function MetaColumns()
function MetaColumns($table,$normalize=true)
{
return false;
}

View File

@@ -2,7 +2,7 @@
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,13 +15,17 @@ class ADODB_pdo_mysql extends ADODB_pdo {
var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasGenID = true;
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_dropSeqSQL = "drop table %s";
var $fmtTimeStamp = "'Y-m-d, H:i:s'";
var $nameQuote = '`';
function _init($parentDriver)
{
$parentDriver->hasTransactions = false;
$parentDriver->_bindInputArray = false;
#$parentDriver->_bindInputArray = false;
$parentDriver->hasInsertID = true;
$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
}
@@ -37,6 +41,16 @@ class ADODB_pdo_mysql extends ADODB_pdo {
// return "from_unixtime(unix_timestamp($date)+$fraction)";
}
function Concat()
{
$s = "";
$arr = func_get_args();
// suggestion by andrew005#mnogo.ru
$s = implode(',',$arr);
if (strlen($s) > 0) return "CONCAT($s)"; return '';
}
function ServerInfo()
{
$arr['description'] = ADOConnection::GetOne("select version()");
@@ -44,7 +58,7 @@ class ADODB_pdo_mysql extends ADODB_pdo {
return $arr;
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
@@ -55,7 +69,7 @@ class ADODB_pdo_mysql extends ADODB_pdo {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
@@ -72,7 +86,7 @@ class ADODB_pdo_mysql extends ADODB_pdo {
$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
}
function &MetaColumns($table)
function MetaColumns($table,$normalize=true)
{
$this->_findschema($table,$schema);
if ($schema) {
@@ -152,16 +166,16 @@ class ADODB_pdo_mysql extends ADODB_pdo {
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
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);
$rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
else
$rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
$rs = $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
return $rs;
}
}

View File

@@ -2,7 +2,7 @@
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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,14 +32,14 @@ class ADODB_pdo_oci extends ADODB_pdo_base {
}
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
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);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
@@ -47,7 +47,7 @@ class ADODB_pdo_oci extends ADODB_pdo_base {
return $ret;
}
function &MetaColumns($table)
function MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;

View File

@@ -1,7 +1,7 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -11,11 +11,11 @@ V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights rese
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_%'
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 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";
@@ -69,26 +69,26 @@ WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
return $arr;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
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);
$rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
$rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
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_%'
$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') ";
select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
}
if ($mask) {
$save = $this->metaTablesSQL;
@@ -104,7 +104,7 @@ 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);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
@@ -112,7 +112,7 @@ select viewname,'V' from pg_views where viewname like $mask";
return $ret;
}
function &MetaColumns($table,$normalize=true)
function MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
@@ -125,8 +125,8 @@ select viewname,'V' from pg_views where viewname like $mask";
$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 ($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;
@@ -144,7 +144,7 @@ select viewname,'V' from pg_views where viewname like $mask";
$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
// fetch all result in once for performance.
$keys =& $rskey->GetArray();
$keys = $rskey->GetArray();
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;

View File

@@ -0,0 +1,190 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Thanks Diogo Toscano (diogo#scriptcase.net) for the code.
And also Sid Dunayer [sdunayer#interserv.com] for extensive fixes.
*/
class ADODB_pdo_sqlite extends ADODB_pdo {
var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table'";
var $sysDate = 'current_date';
var $sysTimeStamp = 'current_timestamp';
var $nameQuote = '`';
var $replaceQuote = "''";
var $hasGenID = true;
var $_genIDSQL = "UPDATE %s SET id=id+1 WHERE id=%s";
var $_genSeqSQL = "CREATE TABLE %s (id integer)";
var $_genSeqCountSQL = 'SELECT COUNT(*) FROM %s';
var $_genSeq2SQL = 'INSERT INTO %s VALUES(%s)';
var $_dropSeqSQL = 'DROP TABLE %s';
var $concat_operator = '||';
var $pdoDriver = false;
function _init($parentDriver)
{
$this->pdoDriver = $parentDriver;
$parentDriver->_bindInputArray = true;
$parentDriver->hasTransactions = true;
$parentDriver->hasInsertID = true;
}
function ServerInfo()
{
$parent = $this->pdoDriver;
@($ver = array_pop($parent->GetCol("SELECT sqlite_version()")));
@($end = array_pop($parent->GetCol("PRAGMA encoding")));
$arr['version'] = $ver;
$arr['description'] = 'SQLite ';
$arr['encoding'] = $enc;
return $arr;
}
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$parent = $this->pdoDriver;
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
if ($secs2cache)
$rs = $parent->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs = $parent->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
function GenID($seq='adodbseq',$start=1)
{
$parent = $this->pdoDriver;
// if you have to modify the parameter below, your database is overloaded,
// or you need to implement generation of id's yourself!
$MAXLOOPS = 100;
while (--$MAXLOOPS>=0) {
@($num = array_pop($parent->GetCol("SELECT id FROM {$seq}")));
if ($num === false || !is_numeric($num)) {
@$parent->Execute(sprintf($this->_genSeqSQL ,$seq));
$start -= 1;
$num = '0';
$cnt = $parent->GetOne(sprintf($this->_genSeqCountSQL,$seq));
if (!$cnt) {
$ok = $parent->Execute(sprintf($this->_genSeq2SQL,$seq,$start));
}
if (!$ok) return false;
}
$parent->Execute(sprintf($this->_genIDSQL,$seq,$num));
if ($parent->affected_rows() > 0) {
$num += 1;
$parent->genID = intval($num);
return intval($num);
}
}
if ($fn = $parent->raiseErrorFn) {
$fn($parent->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
}
return false;
}
function CreateSequence($seqname='adodbseq',$start=1)
{
$parent = $this->pdoDriver;
$ok = $parent->Execute(sprintf($this->_genSeqSQL,$seqname));
if (!$ok) return false;
$start -= 1;
return $parent->Execute("insert into $seqname values($start)");
}
function SetTransactionMode($transaction_mode)
{
$parent = $this->pdoDriver;
$parent->_transmode = strtoupper($transaction_mode);
}
function BeginTrans()
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
$parent->transCnt += 1;
$parent->_autocommit = false;
return $parent->Execute("BEGIN {$parent->_transmode}");
}
function CommitTrans($ok=true)
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
if (!$ok) return $parent->RollbackTrans();
if ($parent->transCnt) $parent->transCnt -= 1;
$parent->_autocommit = true;
$ret = $parent->Execute('COMMIT');
return $ret;
}
function RollbackTrans()
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
if ($parent->transCnt) $parent->transCnt -= 1;
$parent->_autocommit = true;
$ret = $parent->Execute('ROLLBACK');
return $ret;
}
// mark newnham
function MetaColumns($tab,$normalize=true))
{
global $ADODB_FETCH_MODE;
$parent = $this->pdoDriver;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($parent->fetchMode !== false) $savem = $parent->SetFetchMode(false);
$rs = $parent->Execute("PRAGMA table_info('$tab')");
if (isset($savem)) $parent->SetFetchMode($savem);
if (!$rs) {
$ADODB_FETCH_MODE = $save;
return $false;
}
$arr = array();
while ($r = $rs->FetchRow()) {
$type = explode('(',$r['type']);
$size = '';
if (sizeof($type)==2)
$size = trim($type[1],')');
$fn = strtoupper($r['name']);
$fld = new ADOFieldObject;
$fld->name = $r['name'];
$fld->type = $type[0];
$fld->max_length = $size;
$fld->not_null = $r['notnull'];
$fld->primary_key = $r['pk'];
$fld->default_value = $r['dflt_value'];
$fld->scale = 0;
if ($save == ADODB_FETCH_NUM) $arr[] = $fld;
else $arr[strtoupper($fld->name)] = $fld;
}
$rs->Close();
$ADODB_FETCH_MODE = $save;
return $arr;
}
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$parent = $this->pdoDriver;
return $parent->GetCol($this->metaTablesSQL);
}
}
?>

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -159,6 +159,7 @@ a different OID if a database must be reloaded. */
// to really return the id, we need the table and column-name, else we can only return the oid != id
return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT CURRVAL('".$table."_".$column."_seq')");
}
// I get this error with PHP before 4.0.6 - jlim
// Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44
function _affectedrows()
@@ -200,7 +201,7 @@ a different OID if a database must be reloaded. */
return @pg_Exec($this->_connectionID, "rollback");
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$info = $this->ServerInfo();
if ($info['version'] >= 7.3) {
@@ -223,7 +224,7 @@ 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);
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
@@ -235,6 +236,8 @@ select viewname,'V' from pg_views where viewname like $mask";
// if magic quotes disabled, use pg_escape_string()
function qstr($s,$magic_quotes=false)
{
if (is_bool($s)) return $s ? 'true' : 'false';
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x5200) {
return "'".pg_escape_string($this->_connectionID,$s)."'";
@@ -463,7 +466,7 @@ select viewname,'V' from pg_views where viewname like $mask";
// for schema support, pass in the $table param "$schema.$tabname".
// converts field names to lowercase, $upper is ignored
// see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
function &MetaColumns($table,$normalize=true)
function MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
@@ -477,8 +480,8 @@ select viewname,'V' from pg_views where viewname like $mask";
$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 ($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;
@@ -491,11 +494,11 @@ select viewname,'V' from pg_views where viewname like $mask";
// 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;
$this->fetchMode = ADODB_FETCH_ASSOC;
$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
// fetch all result in once for performance.
$keys =& $rskey->GetArray();
$keys = $rskey->GetArray();
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
@@ -505,7 +508,7 @@ select viewname,'V' from pg_views where viewname like $mask";
$rsdefa = array();
if (!empty($this->metaDefaultsSQL)) {
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$this->fetchMode = ADODB_FETCH_ASSOC;
$sql = sprintf($this->metaDefaultsSQL, ($table));
$rsdef = $this->Execute($sql);
if (isset($savem)) $this->SetFetchMode($savem);
@@ -577,7 +580,7 @@ select viewname,'V' from pg_views where viewname like $mask";
}
function &MetaIndexes ($table, $primary = FALSE)
function MetaIndexes ($table, $primary = FALSE)
{
global $ADODB_FETCH_MODE;
@@ -712,7 +715,7 @@ WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$this->_errorMsg = false;
if ($inputarr) {
@@ -885,10 +888,10 @@ class ADORecordSet_postgres64 extends ADORecordSet{
$this->ADORecordSet($queryID);
}
function &GetRowAssoc($upper=true)
function GetRowAssoc($upper=true)
{
if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
$row =& ADORecordSet::GetRowAssoc($upper);
$row = ADORecordSet::GetRowAssoc($upper);
return $row;
}
@@ -924,7 +927,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{
return $this->fields[$this->bind[strtoupper($colname)]];
}
function &FetchField($off = 0)
function FetchField($off = 0)
{
// offsets begin at 0
@@ -942,6 +945,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{
function _decode($blob)
{
if ($blob === NULL) return NULL;
eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
return $realblob;
}
@@ -1060,4 +1064,4 @@ class ADORecordSet_postgres64 extends ADORecordSet{
}
}
?>
?>

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -34,14 +34,14 @@ class ADODB_postgres7 extends ADODB_postgres64 {
// the following should be compat with postgresql 7.2,
// which makes obsolete the LIMIT limit,offset syntax
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET ".((integer)$offset) : '';
$limitStr = ($nrows >= 0) ? " LIMIT ".((integer)$nrows) : '';
if ($secs2cache)
$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
$rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
$rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
@@ -56,9 +56,58 @@ class ADODB_postgres7 extends ADODB_postgres64 {
}
*/
// from Edward Jaramilla, improved version - works on pg 7.4
/*
I discovered that the MetaForeignKeys method no longer worked for Postgres 8.3.
I went ahead and modified it to work for both 8.2 and 8.3.
Please feel free to include this change in your next release of adodb.
William Kolodny [William.Kolodny#gt-t.net]
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql="
SELECT fum.ftblname AS lookup_table, split_part(fum.rf, ')'::text, 1) AS lookup_field,
fum.ltable AS dep_table, split_part(fum.lf, ')'::text, 1) AS dep_field
FROM (
SELECT fee.ltable, fee.ftblname, fee.consrc, split_part(fee.consrc,'('::text, 2) AS lf,
split_part(fee.consrc, '('::text, 3) AS rf
FROM (
SELECT foo.relname AS ltable, foo.ftblname,
pg_get_constraintdef(foo.oid) AS consrc
FROM (
SELECT c.oid, c.conname AS name, t.relname, ft.relname AS ftblname
FROM pg_constraint c
JOIN pg_class t ON (t.oid = c.conrelid)
JOIN pg_class ft ON (ft.oid = c.confrelid)
JOIN pg_namespace nft ON (nft.oid = ft.relnamespace)
LEFT JOIN pg_description ds ON (ds.objoid = c.oid)
JOIN pg_namespace n ON (n.oid = t.relnamespace)
WHERE c.contype = 'f'::\"char\"
ORDER BY t.relname, n.nspname, c.conname, c.oid
) foo
) fee) fum
WHERE fum.ltable='".strtolower($table)."'
ORDER BY fum.ftblname, fum.ltable, split_part(fum.lf, ')'::text, 1)
";
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$a = array();
while (!$rs->EOF) {
if ($upper) {
$a[strtoupper($rs->Fields('lookup_table'))][] = strtoupper(str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field')));
} else {
$a[$rs->Fields('lookup_table')][] = str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field'));
}
$rs->MoveNext();
}
return $a;
}
// from Edward Jaramilla, improved version - works on pg 7.4
function _old_MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = 'SELECT t.tgargs as args
FROM
@@ -72,11 +121,11 @@ class ADODB_postgres7 extends ADODB_postgres64 {
ORDER BY
t.tgrelid';
$rs =& $this->Execute($sql);
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$a = array();
foreach($arr as $v) {
$data = explode(chr(0), $v['args']);
@@ -91,7 +140,7 @@ class ADODB_postgres7 extends ADODB_postgres64 {
return $a;
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (! $this->_bindInputArray) {
// We don't have native support for parameterized queries, so let's emulate it at the parent

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -53,7 +53,7 @@ class ADODB_SAPDB extends ADODB_odbc {
return $this->GetCol("SELECT columnname FROM COLUMNS WHERE tablename=$table AND mode='KEY' ORDER BY pos");
}
function &MetaIndexes ($table, $primary = FALSE)
function MetaIndexes ($table, $primary = FALSE)
{
$table = $this->Quote(strtoupper($table));
@@ -92,7 +92,7 @@ class ADODB_SAPDB extends ADODB_odbc {
return $indexes;
}
function &MetaColumns ($table)
function MetaColumns ($table)
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;

View File

@@ -1,6 +1,6 @@
<?php
/*
version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights
version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -78,7 +78,7 @@ class ADODB_sqlite extends ADOConnection {
}
// mark newnham
function &MetaColumns($tab)
function MetaColumns($tab)
{
global $ADODB_FETCH_MODE;
$false = false;
@@ -190,14 +190,14 @@ class ADODB_sqlite extends ADOConnection {
return $rez;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
if ($secs2cache)
$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
$rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
$rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
@@ -261,7 +261,7 @@ class ADODB_sqlite extends ADOConnection {
return @sqlite_close($this->_connectionID);
}
function &MetaIndexes($table, $primary = FALSE, $owner=false)
function MetaIndexes($table, $primary = FALSE, $owner=false)
{
$false = false;
// save old fetch mode
@@ -350,7 +350,7 @@ class ADORecordset_sqlite extends ADORecordSet {
}
function &FetchField($fieldOffset = -1)
function FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fld->name = sqlite_field_name($this->_queryID, $fieldOffset);

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.94 23 Jan 2007 (c) 2000-2007 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 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.
@@ -123,6 +123,12 @@ class ADODB_sybase extends ADOConnection {
{
if (!function_exists('sybase_connect')) return null;
if ($this->charSet) {
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword, $this->charSet);
} else {
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
}
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
@@ -133,14 +139,18 @@ class ADODB_sybase extends ADOConnection {
{
if (!function_exists('sybase_connect')) return null;
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
if ($this->charSet) {
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword, $this->charSet);
} else {
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
}
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
@@ -151,10 +161,10 @@ class ADODB_sybase extends ADOConnection {
}
// See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
return $rs;
}
@@ -165,7 +175,7 @@ class ADODB_sybase extends ADOConnection {
if ($offset > 0 && $cnt) $cnt += $offset;
$this->Execute("set rowcount $cnt");
$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0);
$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0);
$this->Execute("set rowcount 0");
return $rs;
@@ -177,12 +187,12 @@ class ADODB_sybase extends ADOConnection {
return @sybase_close($this->_connectionID);
}
function UnixDate($v)
static function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
@@ -211,7 +221,7 @@ class ADODB_sybase extends ADOConnection {
$s .= "convert(char(3),$col,0)";
break;
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
$s .= "str_replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
@@ -219,21 +229,21 @@ class ADODB_sybase extends ADOConnection {
break;
case 'D':
case 'd':
$s .= "replace(str(datepart(dd,$col),2),' ','0')";
$s .= "str_replace(str(datepart(dd,$col),2),' ','0')";
break;
case 'h':
$s .= "substring(convert(char(14),$col,0),13,2)";
break;
case 'H':
$s .= "replace(str(datepart(hh,$col),2),' ','0')";
$s .= "str_replace(str(datepart(hh,$col),2),' ','0')";
break;
case 'i':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
$s .= "str_replace(str(datepart(mi,$col),2),' ','0')";
break;
case 's':
$s .= "replace(str(datepart(ss,$col),2),' ','0')";
$s .= "str_replace(str(datepart(ss,$col),2),' ','0')";
break;
case 'a':
case 'A':
@@ -300,7 +310,7 @@ class ADORecordset_sybase extends ADORecordSet {
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
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) {
$o = @sybase_fetch_field($this->_queryID, $fieldOffset);
@@ -353,12 +363,12 @@ class ADORecordset_sybase extends ADORecordSet {
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
static function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
@@ -371,12 +381,12 @@ class ADORecordSet_array_sybase extends ADORecordSet_array {
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
static function UnixDate($v)
{
global $ADODB_sybase_mths;
//Dec 30 2000 12:00AM
if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
if (!preg_match( "/([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})/"
,$v, $rr)) return parent::UnixDate($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
@@ -388,12 +398,12 @@ class ADORecordSet_array_sybase extends ADORecordSet_array {
return mktime(0,0,0,$themth,$rr[2],$rr[3]);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
global $ADODB_sybase_mths;
//11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com
//Changed [0-9] to [0-9 ] in day conversion
if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
if (!preg_match( "/([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})/"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -25,7 +25,7 @@ class ADODB_sybase_ase extends ADODB_sybase {
}
// split the Views, Tables and procedures.
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$false = false;
if ($this->metaTablesSQL) {
@@ -43,7 +43,7 @@ class ADODB_sybase_ase extends ADODB_sybase {
if ($rs === false || !method_exists($rs, 'GetArray')){
return $false;
}
$arr =& $rs->GetArray();
$arr = $rs->GetArray();
$arr2 = array();
foreach($arr as $key=>$value){
@@ -71,7 +71,7 @@ class ADODB_sybase_ase extends ADODB_sybase {
}
// fix a bug which prevent the metaColumns query to be executed for Sybase ASE
function &MetaColumns($table,$upper=false)
function MetaColumns($table,$upper=false)
{
$false = false;
if (!empty($this->metaColumnsSQL)) {
@@ -81,7 +81,7 @@ class ADODB_sybase_ase extends ADODB_sybase {
$retarr = array();
while (!$rs->EOF) {
$fld =& new ADOFieldObject();
$fld = new ADOFieldObject();
$fld->name = $rs->Fields('field_name');
$fld->type = $rs->Fields('type');
$fld->max_length = $rs->Fields('width');

View File

@@ -1,6 +1,6 @@
<?php
/*
V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). 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.
@@ -55,7 +55,7 @@ class ADODB_vfp extends ADODB_odbc {
// TOP requires ORDER BY for VFP
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
$this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false;
$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);

View File

@@ -30,5 +30,4 @@ $ADODB_LANG_ARRAY = array (
DB_ERROR_NOSUCHDB => 'ليس هنالك قاعدة بيانات بهذا الاسم',
DB_ERROR_ACCESS_VIOLATION => 'سماحيات غير كافية'
);
?>
?>

View File

@@ -34,5 +34,4 @@ $ADODB_LANG_ARRAY = array (
DB_ERROR_NOSUCHDB => 'несъществуваща база данни',
DB_ERROR_ACCESS_VIOLATION => 'нямате достатъчно права'
);
?>
?>

View File

@@ -34,5 +34,4 @@ $ADODB_LANG_ARRAY = array (
DB_ERROR_NOSUCHDB => 'несъществуваща база данни',
DB_ERROR_ACCESS_VIOLATION => 'нямате достатъчно права'
);
?>
?>

View File

@@ -1,35 +1,34 @@
<?php
// Catalan language
// contributed by "Josep Lladonosa" jlladono#pie.xtec.es
$ADODB_LANG_ARRAY = array (
'LANG' => 'ca',
DB_ERROR => 'error desconegut',
DB_ERROR_ALREADY_EXISTS => 'ja existeix',
DB_ERROR_CANNOT_CREATE => 'no es pot crear',
DB_ERROR_CANNOT_DELETE => 'no es pot esborrar',
DB_ERROR_CANNOT_DROP => 'no es pot eliminar',
DB_ERROR_CONSTRAINT => 'violació de constraint',
DB_ERROR_DIVZERO => 'divisió per zero',
DB_ERROR_INVALID => 'no és vàlid',
DB_ERROR_INVALID_DATE => 'la data o l\'hora no són vàlides',
DB_ERROR_INVALID_NUMBER => 'el nombre no és vàlid',
DB_ERROR_MISMATCH => 'no hi ha coincidència',
DB_ERROR_NODBSELECTED => 'cap base de dades seleccionada',
DB_ERROR_NOSUCHFIELD => 'camp inexistent',
DB_ERROR_NOSUCHTABLE => 'taula inexistent',
DB_ERROR_NOT_CAPABLE => 'l\'execució secundària de DB no pot',
DB_ERROR_NOT_FOUND => 'no trobat',
DB_ERROR_NOT_LOCKED => 'no blocat',
DB_ERROR_SYNTAX => 'error de sintaxi',
DB_ERROR_UNSUPPORTED => 'no suportat',
DB_ERROR_VALUE_COUNT_ON_ROW => 'el nombre de columnes no coincideix amb el nombre de valors en la fila',
DB_ERROR_INVALID_DSN => 'el DSN no és vàlid',
DB_ERROR_CONNECT_FAILED => 'connexió fallida',
0 => 'cap error', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'les dades subministrades són insuficients',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extensió no trobada',
DB_ERROR_NOSUCHDB => 'base de dades inexistent',
DB_ERROR_ACCESS_VIOLATION => 'permisos insuficients'
);
?>
<?php
// Catalan language
// contributed by "Josep Lladonosa" jlladono#pie.xtec.es
$ADODB_LANG_ARRAY = array (
'LANG' => 'ca',
DB_ERROR => 'error desconegut',
DB_ERROR_ALREADY_EXISTS => 'ja existeix',
DB_ERROR_CANNOT_CREATE => 'no es pot crear',
DB_ERROR_CANNOT_DELETE => 'no es pot esborrar',
DB_ERROR_CANNOT_DROP => 'no es pot eliminar',
DB_ERROR_CONSTRAINT => 'violació de constraint',
DB_ERROR_DIVZERO => 'divisió per zero',
DB_ERROR_INVALID => 'no és vàlid',
DB_ERROR_INVALID_DATE => 'la data o l\'hora no són vàlides',
DB_ERROR_INVALID_NUMBER => 'el nombre no és vàlid',
DB_ERROR_MISMATCH => 'no hi ha coincidència',
DB_ERROR_NODBSELECTED => 'cap base de dades seleccionada',
DB_ERROR_NOSUCHFIELD => 'camp inexistent',
DB_ERROR_NOSUCHTABLE => 'taula inexistent',
DB_ERROR_NOT_CAPABLE => 'l\'execució secundària de DB no pot',
DB_ERROR_NOT_FOUND => 'no trobat',
DB_ERROR_NOT_LOCKED => 'no blocat',
DB_ERROR_SYNTAX => 'error de sintaxi',
DB_ERROR_UNSUPPORTED => 'no suportat',
DB_ERROR_VALUE_COUNT_ON_ROW => 'el nombre de columnes no coincideix amb el nombre de valors en la fila',
DB_ERROR_INVALID_DSN => 'el DSN no és vàlid',
DB_ERROR_CONNECT_FAILED => 'connexió fallida',
0 => 'cap error', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'les dades subministrades són insuficients',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extensió no trobada',
DB_ERROR_NOSUCHDB => 'base de dades inexistent',
DB_ERROR_ACCESS_VIOLATION => 'permisos insuficients'
);
?>

View File

@@ -30,5 +30,4 @@ $ADODB_LANG_ARRAY = array (
DB_ERROR_NOSUCHDB => 'no such database',
DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions'
);
?>
?>

View File

@@ -0,0 +1,35 @@
<?php
/* Farsi - by "Peyman Hooshmandi Raad" <phooshmand#gmail.com> */
$ADODB_LANG_ARRAY = array (
'LANG' => 'fa',
DB_ERROR => 'خطای ناشناخته',
DB_ERROR_ALREADY_EXISTS => 'وجود دارد',
DB_ERROR_CANNOT_CREATE => 'امکان create وجود ندارد',
DB_ERROR_CANNOT_DELETE => 'امکان حذف وجود ندارد',
DB_ERROR_CANNOT_DROP => 'امکان 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 => 'backend بانک اطلاعاتی قادر نیست',
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=> 'extension پیدا نشد',
DB_ERROR_NOSUCHDB => 'چنین بانک اطلاعاتی وجود ندارد',
DB_ERROR_ACCESS_VIOLATION => 'حق دسترسی ناکافی'
);
?>

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