Index: adodb-active-record.inc.php
===================================================================
--- adodb-active-record.inc.php	(revision 13354)
+++ adodb-active-record.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 /*
 
-@version V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+@version V5.11 5 May 2010   (c) 2000-2010 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,24 @@
   
   Active Record implementation. Superset of Zend Framework's.
   
-  Version 0.04
+  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;
+$ADODB_ACTIVE_CACHESECS = 0;
 
-
 class ADODB_Active_DB {
 	var $db; // ADOConnection
 	var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
@@ -33,28 +38,45 @@
 	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;
 	
 		foreach($_ADODB_ACTIVE_DBS as $k => $d) {
-			if ($d->db == $db) return $k;
+			if (PHP_VERSION >= 5) {
+				if ($d->db === $db) return $k;
+			} else {
+				if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) 
+					return $k;
+			}
 		}
 		
 		$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 $_quoteNames = false;
+	
+	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]
@@ -62,17 +84,27 @@
 	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
-	
+
+	var $foreignName; // CFR: class name when in a relationship
+
+	static function UseDefaultValues($bool=null)
+	{
+	global $ADODB_ACTIVE_DEFVALS;
+		if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+		return $ADODB_ACTIVE_DEFVALS;
+	}
+
 	// should be static
-	function SetDatabaseAdapter(&$db) 
+	static function SetDatabaseAdapter(&$db, $index=false) 
 	{
-		return ADODB_SetDatabaseAdapter($db);
+		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
@@ -89,21 +121,31 @@
 			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);
 	}
 	
+	function __wakeup()
+	{
+  		$class = get_class($this);
+  		new $class;
+	}
+	
 	function _pluralize($table)
 	{
+		if (!ADODB_Active_Record::$_changeNames) return $table;
+
 		$ut = strtoupper($table);
 		$len = strlen($table);
 		$lastc = $ut[$len-1];
@@ -123,26 +165,196 @@
 		}
 	}
 	
+	// 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) 
+
+			$acttab = $tables[$tableat];
+			foreach($acttab->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');
@@ -152,6 +364,14 @@
 			if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) { 
 				// abs(rand()) randomizes deletion, reducing contention to delete/refresh file
 				// ideally, you should cache at least 32 secs
+				
+				foreach($acttab->flds as $name => $fld) {
+					if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) 
+						$this->$name = $fld->default_value;
+					else
+						$this->$name = null;
+				}
+	
 				$activedb->tables[$table] = $acttab;
 				
 				//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
@@ -163,8 +383,15 @@
 		$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;
@@ -191,7 +418,10 @@
 		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) {
@@ -202,7 +432,11 @@
 		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;
 			}
 			
@@ -212,12 +446,16 @@
 			break;
 		default:
 			foreach($cols as $name => $fldobj) {
-				$name = ($name);
-				$this->$name = null;
+				$name = ($fldobj->name);
+                
+                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) {
-				$keys[$name] = ($name);
+				$keys[$name] = $cols[$name]->name;
 			}
 			break;
 		}
@@ -231,6 +469,12 @@
 			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;
 	}
 	
@@ -250,7 +494,7 @@
 		if ($this->_dbat < 0) $db = false;
 		else {
 			$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
-			$db =& $activedb->db;
+			$db = $activedb->db;
 		}
 		
 		if (function_exists('adodb_throw')) {	
@@ -274,8 +518,17 @@
 		return $this->_lasterr;
 	}
 	
+	function ErrorNo() 
+	{
+		if ($this->_dbat < 0) return -9999; // no database connection...
+		$db = $this->DB();
+		
+		return (int) $db->ErrorNo();
+	}
+
+
 	// retrieve ADOConnection from _ADODB_Active_DBs
-	function &DB()
+	function DB()
 	{
 	global $_ADODB_ACTIVE_DBS;
 	
@@ -285,7 +538,7 @@
 			return $false;
 		}
 		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
-		$db =& $activedb->db;
+		$db = $activedb->db;
 		return $db;
 	}
 	
@@ -293,16 +546,29 @@
 	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)
 	{
-		$db =& $this->DB();
+	global $ACTIVE_RECORD_SAFETY;
+	
+		$db = $this->DB();
 		
 		if (!$row) {
 			$this->_saved = false;		
@@ -311,18 +577,36 @@
 		
 		$this->_saved = true;
 		
-		$table =& $this->TableInfo();
-		if (sizeof($table->flds) != sizeof($row)) {
+		$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;
+            # </AP>
+		}
+        else
+			$keys = array_keys($row);
+			
+        # <AP>
+        reset($keys);
+        $this->_original = array();
 		foreach($table->flds as $name=>$fld) {
-			$this->$name = $row[$cnt];
-			$cnt += 1;
+            $value = $row[current($keys)];
+			$this->$name = $value;
+            $this->_original[] = $value;
+            next($keys);
 		}
-		$this->_original = $row;
+
+        # </AP>
 		return true;
 	}
 	
@@ -345,15 +629,20 @@
 	function doquote(&$db, $val,$t)
 	{
 		switch($t) {
-		case 'D':
+		case 'L':
+			if (strpos($db->databaseType,'postgres') !== false) return $db->qstr($val);
+		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;
 			}
@@ -379,20 +668,57 @@
 	}
 	
 	
+	function _QName($n,$db=false)
+	{
+		if (!ADODB_Active_Record::$_quoteNames) return $n;
+		if (!$db) $db = $this->DB(); if (!$db) return false;
+		return $db->nameQuote.$n.$db->nameQuote;
+	}
+	
 	//------------------------------------------------------------ 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()
 	{
@@ -402,29 +728,36 @@
 		return $ok;
 	}
 	
+	
 	// 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();
+		$valstr = array();
 
 		foreach($table->flds as $name=>$fld) {
 			$val = $this->$name;
-			/*
-			if (is_null($val)) {
-				if (isset($fld->not_null) && $fld->not_null) {
-					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
-					else $this->Error("Cannot insert null into $name","Insert");
-				}
-			}*/
-			
-			$valarr[] = $val;
-			$names[] = $name;
-			$valstr[] = $db->Param($cnt);
-			$cnt += 1;
+			if(!is_array($val) || !is_null($val) || !array_key_exists($name, $table->keys)) {
+				$valarr[] = $val;
+				$names[] = $this->_QName($name,$db);
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
 		}
 		
+		if (empty($names)){
+			foreach($table->flds as $name=>$fld) {
+				$valarr[] = null;
+				$names[] = $name;
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
+		}
 		$sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
 		$ok = $db->Execute($sql,$valarr);
 		
@@ -449,19 +782,21 @@
 	
 	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;
-		$db->Execute($sql);
+		$ok = $db->Execute($sql);
+		
+		return $ok ? true : false;
 	}
 	
 	// 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;
 	}
 	
@@ -470,8 +805,8 @@
 	{
 	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;
 		
@@ -490,6 +825,9 @@
 			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;
@@ -501,7 +839,7 @@
 		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);
 				
@@ -522,7 +860,7 @@
 				}
 			}
 			
-			$this->_original =& $valarr;
+			$this->_original = $valarr;
 		} 
 		return $ok;
 	}
@@ -530,8 +868,8 @@
 	// 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);
 		
@@ -549,11 +887,9 @@
 			$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) {
 					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
@@ -563,12 +899,12 @@
 					}
 				}
 			}
-			
-			if ( $val == $this->_original[$i]) {
+
+			if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) {
 				continue;
-			}			
+			}
 			$valarr[] = $val;
-			$pairs[] = $name.'='.$db->Param($cnt);
+			$pairs[] = $this->_QName($name,$db).'='.$db->Param($cnt);
 			$cnt += 1;
 		}
 		
@@ -577,7 +913,7 @@
 		$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;
@@ -585,11 +921,72 @@
 	
 	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'],$bindarr);
+		} else {
+			$rs = $db->SelectLimit($qry, $extra['limit'],-1,$bindarr);
+		}
+		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;
+}
 ?>
\ No newline at end of file
Index: adodb-active-recordx.inc.php
===================================================================
--- adodb-active-recordx.inc.php	(revision 0)
+++ adodb-active-recordx.inc.php	(revision 0)
@@ -0,0 +1,1421 @@
+<?php
+/*
+
+@version V5.06 29 Sept 2008   (c) 2000-2010 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. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Active Record implementation. Superset of Zend Framework's.
+  
+  This is "Active Record eXtended" to support JOIN, WORK and LAZY mode by Chris Ravenscroft  chris#voilaweb.com 
+  
+  Version 0.9
+  
+  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord 
+  	for info on Ruby on Rails Active Record implementation
+*/
+
+
+	// CFR: Active Records Definitions
+define('ADODB_JOIN_AR', 0x01);
+define('ADODB_WORK_AR', 0x02);
+define('ADODB_LAZY_AR', 0x03);
+
+
+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; // CFR: disabled while playing with relations
+$ADODB_ACTIVE_DEFVALS = false;
+
+class ADODB_Active_DB {
+	var $db; // ADOConnection
+	var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
+}
+
+class ADODB_Active_Table {
+	var $name; // table name
+	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();
+	var $_colsCount; // total columns count, including relations
+
+	function updateColsCount()
+	{
+		$this->_colsCount = sizeof($this->flds);
+		foreach($this->_belongsTo as $foreignTable)
+			$this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
+		foreach($this->_hasMany as $foreignTable)
+			$this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
+	}
+}
+
+// returns index into $_ADODB_ACTIVE_DBS
+function ADODB_SetDatabaseAdapter(&$db)
+{
+	global $_ADODB_ACTIVE_DBS;
+	
+		foreach($_ADODB_ACTIVE_DBS as $k => $d) {
+			if (PHP_VERSION >= 5) {
+				if ($d->db === $db) return $k;
+			} else {
+				if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) 
+					return $k;
+			}
+		}
+		
+		$obj = new ADODB_Active_DB();
+		$obj->db = $db;
+		$obj->tables = array();
+		
+		$_ADODB_ACTIVE_DBS[] = $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 $_sTable; // singularized table name
+	var $_pTable; // pluralized table name
+	var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
+	var $_where; // where clause set in Load()
+	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
+
+	var $foreignName; // CFR: class name when in a relationship
+
+	static function UseDefaultValues($bool=null)
+	{
+	global $ADODB_ACTIVE_DEFVALS;
+		if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+		return $ADODB_ACTIVE_DEFVALS;
+	}
+
+	// should be static
+	static function SetDatabaseAdapter(&$db) 
+	{
+		return ADODB_SetDatabaseAdapter($db);
+	}
+	
+	
+	public function __set($name, $value)
+	{
+		$name = str_replace(' ', '_', $name);
+		$this->$name = $value;
+	}
+	
+	// php5 constructor
+	// Note: if $table is defined, then we will use it as our table name
+	// Otherwise we will use our classname...
+	// In our database, table names are pluralized (because there can be
+	// more than one row!)
+	// Similarly, if $table is defined here, it has to be plural form.
+	//
+	// $options is an array that allows us to tweak the constructor's behaviour
+	// if $options['refresh'] is true, we re-scan our metadata information
+	// if $options['new'] is true, we forget all relations
+	function __construct($table = false, $pkeyarr=false, $db=false, $options=array())
+	{
+	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
+	
+		if ($db == false && is_object($pkeyarr)) {
+			$db = $pkeyarr;
+			$pkeyarr = false;
+		}
+		
+		if($table)
+		{
+			// table argument exists. It is expected to be
+			// already plural form.
+			$this->_pTable = $table;
+			$this->_sTable = $this->_singularize($this->_pTable);
+		}
+		else
+		{
+			// We will use current classname as table name.
+			// We need to pluralize it for the real table name.
+			$this->_sTable = strtolower(get_class($this));
+			$this->_pTable = $this->_pluralize($this->_sTable);
+		}
+		$this->_table = &$this->_pTable;
+
+		$this->foreignName = $this->_sTable; // CFR: default foreign name (singular)
+
+		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');
+		
+		$this->_tableat = $this->_table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
+
+		// CFR: Just added this option because UpdateActiveTable() can refresh its information
+		// but there was no way to ask it to do that.
+		$forceUpdate = (isset($options['refresh']) && true === $options['refresh']);
+		$this->UpdateActiveTable($pkeyarr, $forceUpdate);
+		if(isset($options['new']) && true === $options['new'])
+		{
+			$table =& $this->TableInfo();
+			unset($table->_hasMany);
+			unset($table->_belongsTo);
+			$table->_hasMany = array();
+			$table->_belongsTo = array();
+		}
+	}
+	
+	function __wakeup()
+	{
+  		$class = get_class($this);
+  		new $class;
+	}
+	
+	// CFR: Constants found in Rails
+	static $IrregularP = array(
+		'PERSON'    => 'people',
+		'MAN'       => 'men',
+		'WOMAN'     => 'women',
+		'CHILD'     => 'children',
+		'COW'       => 'kine',
+	);
+
+	static $IrregularS = array(
+		'PEOPLE'    => 'PERSON',
+		'MEN'       => 'man',
+		'WOMEN'     => 'woman',
+		'CHILDREN'  => 'child',
+		'KINE'      => 'cow',
+	);
+
+	static $WeIsI = array(
+		'EQUIPMENT' => true,
+		'INFORMATION'   => true,
+		'RICE'      => true,
+		'MONEY'     => true,
+		'SPECIES'   => true,
+		'SERIES'    => true,
+		'FISH'      => true,
+		'SHEEP'     => true,
+	);
+
+	function _pluralize($table)
+	{
+		if (!ADODB_Active_Record::$_changeNames) return $table;
+
+		$ut = strtoupper($table);
+		if(isset(self::$WeIsI[$ut]))
+		{
+			return $table;
+		}
+		if(isset(self::$IrregularP[$ut]))
+		{
+			return self::$IrregularP[$ut];
+		}
+		$len = strlen($table);
+		$lastc = $ut[$len-1];
+		$lastc2 = substr($ut,$len-2);
+		switch ($lastc) {
+		case 'S':
+			return $table.'es';	
+		case 'Y':
+			return substr($table,0,$len-1).'ies';
+		case 'X':	
+			return $table.'es';
+		case 'H': 
+			if ($lastc2 == 'CH' || $lastc2 == 'SH')
+				return $table.'es';
+		default:
+			return $table.'s';
+		}
+	}
+	
+	// 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($table)
+	{
+	
+		if (!ADODB_Active_Record::$_changeNames) return $table;
+	
+		$ut = strtoupper($table);
+		if(isset(self::$WeIsI[$ut]))
+		{
+			return $table;
+		}
+		if(isset(self::$IrregularS[$ut]))
+		{
+			return self::$IrregularS[$ut];
+		}
+		$len = strlen($table);
+		if($ut[$len-1] != 'S')
+			return $table; // I know...forget oxen
+		if($ut[$len-2] != 'E')
+			return substr($table, 0, $len-1);
+		switch($ut[$len-3])
+		{
+			case 'S':
+			case 'X':
+				return substr($table, 0, $len-2);
+			case 'I':
+				return substr($table, 0, $len-3) . 'y';
+			case 'H';
+				if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
+					return substr($table, 0, $len-2);
+			default:
+				return substr($table, 0, $len-1); // ?
+		}
+	}
+
+	/*
+	 * ar->foreignName will contain the name of the tables associated with this table because
+	 * these other tables' rows may also be referenced by this table using theirname_id or the provided
+	 * foreign keys (this index name is stored in ar->foreignKey)
+	 *
+	 * this-table.id = other-table-#1.this-table_id
+	 *               = other-table-#2.this-table_id
+	 */
+	function hasMany($foreignRef,$foreignKey=false)
+	{
+		$ar = new ADODB_Active_Record($foreignRef);
+		$ar->foreignName = $foreignRef;
+		$ar->UpdateActiveTable();
+		$ar->foreignKey = ($foreignKey) ? $foreignKey : strtolower(get_class($this)) . self::$_foreignSuffix;
+
+		$table =& $this->TableInfo();
+		if(!isset($table->_hasMany[$foreignRef]))
+		{
+			$table->_hasMany[$foreignRef] = $ar;
+			$table->updateColsCount();
+		}
+# @todo Can I make this guy be lazy?
+		$this->$foreignRef = $table->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
+	}
+
+	/**
+	 * ar->foreignName will contain the name of the tables associated with this table because
+	 * this table's rows may also be referenced by those tables using thistable_id or the provided
+	 * foreign keys (this index name is stored in ar->foreignKey)
+	 *
+	 * this-table.other-table_id = other-table.id
+	 */
+	function belongsTo($foreignRef,$foreignKey=false)
+	{
+		global $inflector;
+
+		$ar = new ADODB_Active_Record($this->_pluralize($foreignRef));
+		$ar->foreignName = $foreignRef;
+		$ar->UpdateActiveTable();
+		$ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
+		
+		$table =& $this->TableInfo();
+		if(!isset($table->_belongsTo[$foreignRef]))
+		{
+			$table->_belongsTo[$foreignRef] = $ar;
+			$table->updateColsCount();
+		}
+		$this->$foreignRef = $table->_belongsTo[$foreignRef];
+	}
+
+	/**
+	 * __get Access properties - used for lazy loading
+	 * 
+	 * @param mixed $name 
+	 * @access protected
+	 * @return void
+	 */
+	function __get($name)
+	{
+		return $this->LoadRelations($name, '', -1. -1);
+	}
+
+	function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
+	{
+		$extras = array();
+		if($offset >= 0) $extras['offset'] = $offset;
+		if($limit >= 0) $extras['limit'] = $limit;
+		$table =& $this->TableInfo();
+		
+		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(($k = reset($obj->TableInfo()->keys)))
+					$belongsToId = $k;
+				else
+					$belongsToId = 'id';
+				
+				$arrayOfOne =
+					$obj->Find(
+						$belongsToId.'='.$this->$columnName.' '.$whereOrderBy, false, false, $extras);
+				$this->$name = $arrayOfOne[0];
+			}
+			return $this->$name;
+		}
+		if(!empty($table->_hasMany[$name]))
+		{
+			$obj = $table->_hasMany[$name];
+			if(($k = reset($table->keys)))
+				$hasManyId   = $k;
+			else
+				$hasManyId   = 'id';			
+
+			$this->$name =
+				$obj->Find(
+					$obj->foreignKey.'='.$this->$hasManyId.' '.$whereOrderBy, false, false, $extras);
+			return $this->$name;
+		}
+	}
+	//////////////////////////////////
+	
+	// update metadata
+	function UpdateActiveTable($pkeys=false,$forceUpdate=false)
+	{
+	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
+	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) {
+			if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) 
+				$this->$name = $fld->default_value;
+			else
+				$this->$name = null;
+			}
+			return;
+		}
+		
+		$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');
+			@flock($fp, LOCK_SH);
+			$acttab = unserialize(fread($fp,100000));
+			fclose($fp);
+			if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) { 
+				// abs(rand()) randomizes deletion, reducing contention to delete/refresh file
+				// ideally, you should cache at least 32 secs
+				$activedb->tables[$table] = $acttab;
+				
+				//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
+			  	return;
+			} else if ($db->debug) {
+				ADOConnection::outp("Refreshing cached active record file: $fname");
+			}
+		}
+		$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;
+		}
+		$fld = reset($cols);
+		if (!$pkeys) {
+			if (isset($fld->primary_key)) {
+				$pkeys = array();
+				foreach($cols as $name => $fld) {
+					if (!empty($fld->primary_key)) $pkeys[] = $name;
+				}
+			} else	
+				$pkeys = $this->GetPrimaryKeys($db, $table);
+		}
+		if (empty($pkeys)) {
+			$this->Error("No primary key found for table $table",'UpdateActiveTable');
+			return false;
+		}
+		
+		$attr = array();
+		$keys = array();
+		
+		switch($ADODB_ASSOC_CASE) {
+		case 0:
+			foreach($cols as $name => $fldobj) {
+				$name = strtolower($name);
+                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) {
+				$keys[strtolower($name)] = strtolower($name);
+			}
+			break;
+			
+		case 1: 
+			foreach($cols as $name => $fldobj) {
+				$name = strtoupper($name);
+               
+                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) {
+				$keys[strtoupper($name)] = strtoupper($name);
+			}
+			break;
+		default:
+			foreach($cols as $name => $fldobj) {
+				$name = ($fldobj->name);
+                
+                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) {
+				$keys[$name] = $cols[$name]->name;
+			}
+			break;
+		}
+		
+		$activetab->keys = $keys;
+		$activetab->flds = $attr;
+		$activetab->updateColsCount();
+
+		if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
+			$activetab->_created = time();
+			$s = serialize($activetab);
+			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;
+	}
+	
+	function GetPrimaryKeys(&$db, $table)
+	{
+		return $db->MetaPrimaryKeys($table);
+	}
+	
+	// error handler for both PHP4+5. 
+	function Error($err,$fn)
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		$fn = get_class($this).'::'.$fn;
+		$this->_lasterr = $fn.': '.$err;
+		
+		if ($this->_dbat < 0) $db = false;
+		else {
+			$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+			$db = $activedb->db;
+		}
+		
+		if (function_exists('adodb_throw')) {	
+			if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
+			else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
+		} else
+			if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
+		
+	}
+	
+	// return last error message
+	function ErrorMsg()
+	{
+		if (!function_exists('adodb_throw')) {
+			if ($this->_dbat < 0) $db = false;
+			else $db = $this->DB();
+		
+			// last error could be database error too
+			if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+		}
+		return $this->_lasterr;
+	}
+	
+	function ErrorNo() 
+	{
+		if ($this->_dbat < 0) return -9999; // no database connection...
+		$db = $this->DB();
+		
+		return (int) $db->ErrorNo();
+	}
+
+
+	// retrieve ADOConnection from _ADODB_Active_DBs
+	function DB()
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		if ($this->_dbat < 0) {
+			$false = false;
+			$this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
+			return $false;
+		}
+		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+		$db = $activedb->db;
+		return $db;
+	}
+	
+	// retrieve ADODB_Active_Table
+	function &TableInfo()
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+		$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();
+		
+		if (!$row) {
+			$this->_saved = false;		
+			return false;
+		}
+		
+		$this->_saved = true;
+		
+		$table = $this->TableInfo();
+		$sizeofFlds = sizeof($table->flds);
+		$sizeofRow  = sizeof($row);
+		if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
+            # <AP>
+            $bad_size = TRUE;
+	if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
+                // 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;
+		}
+            # </AP>
+		}
+        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;
+            if(!next($keys)) break;
+		}
+		$table =& $this->TableInfo();
+		foreach($table->_belongsTo as $foreignTable)
+		{
+			$ft = $foreignTable->TableInfo();
+			$propertyName = $ft->name;
+			foreach($ft->flds as $name=>$fld)
+			{
+				$value = $row[current($keys)];
+				$foreignTable->$name = $value;
+				$foreignTable->_original[] = $value;
+				if(!next($keys)) break;
+			}
+		}
+		foreach($table->_hasMany as $foreignTable)
+		{
+			$ft = $foreignTable->TableInfo();
+			foreach($ft->flds as $name=>$fld)
+			{
+				$value = $row[current($keys)];
+				$foreignTable->$name = $value;
+				$foreignTable->_original[] = $value;
+				if(!next($keys)) break;
+			}
+		}
+        # </AP>
+		return true;
+	}
+	
+	// get last inserted id for INSERT
+	function LastInsertID(&$db,$fieldname)
+	{
+		if ($db->hasInsertID)
+			$val = $db->Insert_ID($this->_table,$fieldname);
+		else
+			$val = false;
+			
+		if (is_null($val) || $val === false) {
+			// this might not work reliably in multi-user environment
+			return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
+		}
+		return $val;
+	}
+	
+	// quote data in where clause
+	function doquote(&$db, $val,$t)
+	{
+		switch($t) {
+		case 'D':
+		case 'T':
+			if (empty($val)) return 'null';
+			
+		case 'C':
+		case 'X':
+			if (is_null($val)) return 'null';
+			
+			if (strlen($val)>1 && 
+				(strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) { 
+				return $db->qstr($val);
+				break;
+			}
+		default:
+			return $val;
+			break;
+		}
+	}
+	
+	// generate where clause for an UPDATE/SELECT
+	function GenWhere(&$db, &$table)
+	{
+		$keys = $table->keys;
+		$parr = array();
+		
+		foreach($keys as $k) {
+			$f = $table->flds[$k];
+			if ($f) {
+				$parr[] = $k.' = '.$this->doquote($db,$this->$k,$db->MetaType($f->type));
+			}
+		}
+		return implode(' and ', $parr);
+	}
+	
+	
+	//------------------------------------------------------------ Public functions below
+	
+	function Load($where=null,$bindarr=false)
+	{
+		$db = $this->DB(); if (!$db) return false;
+		$this->_where = $where;
+		
+		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
+		$qry = "select * from ".$this->_table;
+		$table =& $this->TableInfo();
+
+		if(($k = reset($table->keys)))
+			$hasManyId   = $k;
+		else
+			$hasManyId   = 'id';
+		
+		foreach($table->_belongsTo as $foreignTable)
+		{
+			if(($k = reset($foreignTable->TableInfo()->keys)))
+			{
+				$belongsToId = $k;
+			}
+			else
+			{
+				$belongsToId = 'id';
+			}
+			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
+				$this->_table.'.'.$foreignTable->foreignKey.'='.
+				$foreignTable->_table.'.'.$belongsToId;
+		}
+		foreach($table->_hasMany as $foreignTable)
+		{
+			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
+				$this->_table.'.'.$hasManyId.'='.
+				$foreignTable->_table.'.'.$foreignTable->foreignKey;
+		}
+		if($where)
+			$qry .= ' WHERE '.$where;
+		
+		// Simple case: no relations. Load row and return.
+		if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
+		{
+			$row = $db->GetRow($qry,$bindarr);
+			if(!$row)
+				return false;
+			$db->SetFetchMode($save);
+			return $this->Set($row);
+		}
+		
+		// More complex case when relations have to be collated
+		$rows = $db->GetAll($qry,$bindarr);
+		if(!$rows)
+			return false;
+		$db->SetFetchMode($save);
+		if(count($rows) < 1)
+			return false;
+		$class = get_class($this);
+		$isFirstRow = true;
+		
+		if(($k = reset($this->TableInfo()->keys)))
+			$myId   = $k;
+		else
+			$myId   = 'id';
+		$index = 0; $found = false;
+		/** @todo Improve by storing once and for all in table metadata */
+		/** @todo Also re-use info for hasManyId */
+		foreach($this->TableInfo()->flds as $fld)
+		{
+			if($fld->name == $myId)
+			{
+				$found = true;
+				break;
+			}
+			$index++;
+		}
+		if(!$found)
+			$this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
+		
+		foreach($rows as $row)
+		{
+			$rowId = intval($row[$index]);
+			if($rowId > 0)
+			{
+				if($isFirstRow)
+				{
+					$isFirstRow = false;
+					if(!$this->Set($row))
+						return false;
+				}
+				$obj = new $class($table,false,$db);
+				$obj->Set($row);
+				// TODO Copy/paste code below: bad!
+				if(count($table->_hasMany) > 0)
+				{
+					foreach($table->_hasMany as $foreignTable)
+					{
+						$foreignName = $foreignTable->foreignName;
+						if(!empty($obj->$foreignName))
+						{
+							if(!is_array($this->$foreignName))
+							{
+								$foreignObj = $this->$foreignName;
+								$this->$foreignName = array(clone($foreignObj));
+							}
+							else
+							{
+								$foreignObj = $obj->$foreignName;
+								array_push($this->$foreignName, clone($foreignObj));
+							}
+						}
+					}
+				}
+				if(count($table->_belongsTo) > 0)
+				{
+					foreach($table->_belongsTo as $foreignTable)
+					{
+						$foreignName = $foreignTable->foreignName;
+						if(!empty($obj->$foreignName))
+						{
+							if(!is_array($this->$foreignName))
+							{
+								$foreignObj = $this->$foreignName;
+								$this->$foreignName = array(clone($foreignObj));
+							}
+							else
+							{
+								$foreignObj = $obj->$foreignName;
+								array_push($this->$foreignName, clone($foreignObj));
+							}
+						}
+					}
+				}				
+			}
+		}
+		return true;
+	}
+	
+	// false on error
+	function Save()
+	{
+		if ($this->_saved) $ok = $this->Update();
+		else $ok = $this->Insert();
+		
+		return $ok;
+	}
+	
+	// CFR: Sometimes we may wish to consider that an object is not to be replaced but inserted.
+	// Sample use case: an 'undo' command object (after a delete())
+	function Dirty()
+	{
+		$this->_saved = false;
+	}
+
+	// false on error
+	function Insert()
+	{
+		$db = $this->DB(); if (!$db) return false;
+		$cnt = 0;
+		$table = $this->TableInfo();
+		
+		$valarr = array();
+		$names = array();
+		$valstr = array();
+
+		foreach($table->flds as $name=>$fld) {
+			$val = $this->$name;
+			if(!is_null($val) || !array_key_exists($name, $table->keys)) {
+				$valarr[] = $val;
+				$names[] = $name;
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
+		}
+		
+		if (empty($names)){
+			foreach($table->flds as $name=>$fld) {
+				$valarr[] = null;
+				$names[] = $name;
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
+		}
+		$sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
+		$ok = $db->Execute($sql,$valarr);
+		
+		if ($ok) {
+			$this->_saved = true;
+			$autoinc = false;
+			foreach($table->keys as $k) {
+				if (is_null($this->$k)) {
+					$autoinc = true;
+					break;
+				}
+			}
+			if ($autoinc && sizeof($table->keys) == 1) {
+				$k = reset($table->keys);
+				$this->$k = $this->LastInsertID($db,$k);
+			}
+		}
+		
+		$this->_original = $valarr;
+		return !empty($ok);
+	}
+	
+	function Delete()
+	{
+		$db = $this->DB(); if (!$db) return false;
+		$table = $this->TableInfo();
+		
+		$where = $this->GenWhere($db,$table);
+		$sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
+		$ok = $db->Execute($sql);
+		
+		return $ok ? true : false;
+	}
+	
+	// returns an array of active record objects
+	function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
+	{
+		$db = $this->DB(); if (!$db || empty($this->_table)) return false;
+		$table =& $this->TableInfo();
+		$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
+			array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
+		return $arr;
+	}
+	
+	// CFR: In introduced this method to ensure that inner workings are not disturbed by
+	// subclasses...for instance when GetActiveRecordsClass invokes Find()
+	// Why am I not invoking parent::Find?
+	// Shockingly because I want to preserve PHP4 compatibility.
+	function packageFind($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
+	{
+		$db = $this->DB(); if (!$db || empty($this->_table)) return false;
+		$table =& $this->TableInfo();
+		$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
+			array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
+		return $arr;
+	}
+
+	// returns 0 on error, 1 on update, 2 on insert
+	function Replace()
+	{
+	global $ADODB_ASSOC_CASE;
+		
+		$db = $this->DB(); if (!$db) return false;
+		$table = $this->TableInfo();
+		
+		$pkey = $table->keys;
+		
+		foreach($table->flds as $name=>$fld) {
+			$val = $this->$name;
+			/*
+			if (is_null($val)) {
+				if (isset($fld->not_null) && $fld->not_null) {
+					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+					else {
+						$this->Error("Cannot update null into $name","Replace");
+						return false;
+					}
+				}
+			}*/
+			if (is_null($val) && !empty($fld->auto_increment)) {
+            	continue;
+            }
+			$t = $db->MetaType($fld->type);
+			$arr[$name] = $this->doquote($db,$val,$t);
+			$valarr[] = $val;
+		}
+		
+		if (!is_array($pkey)) $pkey = array($pkey);
+		
+		
+		if ($ADODB_ASSOC_CASE == 0) 
+			foreach($pkey as $k => $v)
+				$pkey[$k] = strtolower($v);
+		elseif ($ADODB_ASSOC_CASE == 1) 
+			foreach($pkey as $k => $v)
+				$pkey[$k] = strtoupper($v);
+				
+		$ok = $db->Replace($this->_table,$arr,$pkey);
+		if ($ok) {
+			$this->_saved = true; // 1= update 2=insert
+			if ($ok == 2) {
+				$autoinc = false;
+				foreach($table->keys as $k) {
+					if (is_null($this->$k)) {
+						$autoinc = true;
+						break;
+					}
+				}
+				if ($autoinc && sizeof($table->keys) == 1) {
+					$k = reset($table->keys);
+					$this->$k = $this->LastInsertID($db,$k);
+				}
+			}
+			
+			$this->_original = $valarr;
+		} 
+		return $ok;
+	}
+
+	// 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();
+		
+		$where = $this->GenWhere($db, $table);
+		
+		if (!$where) {
+			$this->error("Where missing for table $table", "Update");
+			return false;
+		}
+		$valarr = array(); 
+		$neworig = array();
+		$pairs = array();
+		$i = -1;
+		$cnt = 0;
+		foreach($table->flds as $name=>$fld) {
+			$i += 1;
+			$val = $this->$name;
+			$neworig[] = $val;
+			
+			if (isset($table->keys[$name])) {
+				continue;
+			}
+			
+			if (is_null($val)) {
+				if (isset($fld->not_null) && $fld->not_null) {
+					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+					else {
+						$this->Error("Cannot set field $name to NULL","Update");
+						return false;
+					}
+				}
+			}
+			
+			if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
+				continue;
+			}			
+			$valarr[] = $val;
+			$pairs[] = $name.'='.$db->Param($cnt);
+			$cnt += 1;
+		}
+		
+		
+		if (!$cnt) return -1;
+		$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
+		$ok = $db->Execute($sql,$valarr);
+		if ($ok) {
+			$this->_original = $neworig;
+			return 1;
+		}
+		return 0;
+	}
+	
+	function GetAttributeNames()
+	{
+		$table = $this->TableInfo();
+		if (!$table) return false;
+		return array_keys($table->flds);
+	}
+	
+};
+
+function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bindarr, $primkeyArr,
+			$extra, $relations)
+{
+	global $_ADODB_ACTIVE_DBS;
+	
+		if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
+		
+		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
+		$table = &$tableObj->_table;
+		$tableInfo =& $tableObj->TableInfo();
+		if(($k = reset($tableInfo->keys)))
+			$myId   = $k;
+		else
+			$myId   = 'id';
+		$index = 0; $found = false;
+		/** @todo Improve by storing once and for all in table metadata */
+		/** @todo Also re-use info for hasManyId */
+		foreach($tableInfo->flds as $fld)
+		{
+			if($fld->name == $myId)
+			{
+				$found = true;
+				break;
+			}
+			$index++;
+		}
+		if(!$found)
+			$db->outp_throw("Unable to locate key $myId for $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
+		
+		$qry = "select * from ".$table;
+		if(ADODB_JOIN_AR == $extra['loading'])
+		{
+			if(!empty($relations['belongsTo']))
+			{
+				foreach($relations['belongsTo'] as $foreignTable)
+				{
+					if(($k = reset($foreignTable->TableInfo()->keys)))
+					{
+						$belongsToId = $k;
+					}
+					else
+					{
+						$belongsToId = 'id';
+					}
+
+					$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
+						$table.'.'.$foreignTable->foreignKey.'='.
+						$foreignTable->_table.'.'.$belongsToId;
+				}
+			}
+			if(!empty($relations['hasMany']))
+			{
+				if(empty($relations['foreignName']))
+					$db->outp_throw("Missing foreignName is relation specification in GetActiveRecordsClass()",'GetActiveRecordsClass');
+				if(($k = reset($tableInfo->keys)))
+					$hasManyId   = $k;
+				else
+					$hasManyId   = 'id';
+
+				foreach($relations['hasMany'] as $foreignTable)
+				{
+					$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
+						$table.'.'.$hasManyId.'='.
+						$foreignTable->_table.'.'.$foreignTable->foreignKey;
+				}
+			}
+		}
+		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 (!isset($_ADODB_ACTIVE_DBS)) {
+			include(ADODB_DIR.'/adodb-active-record.inc.php');
+		}	
+		if (!class_exists($class)) {
+			$db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
+			return $false;
+		}
+		$uniqArr = array(); // CFR Keep track of records for relations
+		$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);
+			// CFR: FIXME: Insane assumption here:
+			// If the first column returned is an integer, then it's a 'id' field
+			// And to make things a bit worse, I use intval() rather than is_int() because, in fact,
+			// $row[0] is not an integer.
+			//
+			// So, what does this whole block do?
+			// When relationships are found, we perform JOINs. This is fast. But not accurate:
+			// instead of returning n objects with their n' associated cousins,
+			// we get n*n' objects. This code fixes this.
+			// Note: to-many relationships mess around with the 'limit' parameter
+			$rowId = intval($row[$index]);
+
+			if(ADODB_WORK_AR == $extra['loading'])
+			{
+				$arrRef[$rowId] = $obj;
+				$arr[] = &$arrRef[$rowId];
+				if(!isset($indices))
+					$indices = $rowId;
+				else
+					$indices .= ','.$rowId;
+				if(!empty($relations['belongsTo']))
+				{
+					foreach($relations['belongsTo'] as $foreignTable)
+					{
+						$foreignTableRef = $foreignTable->foreignKey;
+						// First array: list of foreign ids we are looking for
+						if(empty($bTos[$foreignTableRef]))
+							$bTos[$foreignTableRef] = array();
+						// Second array: list of ids found
+						if(empty($obj->$foreignTableRef))
+							continue;
+						if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef]))
+							$bTos[$foreignTableRef][$obj->$foreignTableRef] = array();
+						$bTos[$foreignTableRef][$obj->$foreignTableRef][] = $obj;
+					}
+				}
+				continue;
+			}
+
+			if($rowId>0)
+			{
+				if(ADODB_JOIN_AR == $extra['loading'])
+				{
+					$isNewObj = !isset($uniqArr['_'.$row[0]]); 
+					if($isNewObj)
+						$uniqArr['_'.$row[0]] = $obj;
+
+					// TODO Copy/paste code below: bad!
+					if(!empty($relations['hasMany']))
+					{
+						foreach($relations['hasMany'] as $foreignTable)
+						{
+							$foreignName = $foreignTable->foreignName;
+							if(!empty($obj->$foreignName))
+							{
+								$masterObj = &$uniqArr['_'.$row[0]];
+								// Assumption: this property exists in every object since they are instances of the same class
+								if(!is_array($masterObj->$foreignName))
+								{
+									// Pluck!
+									$foreignObj = $masterObj->$foreignName;
+									$masterObj->$foreignName = array(clone($foreignObj));
+								}
+								else
+								{
+									// Pluck pluck!
+									$foreignObj = $obj->$foreignName;
+									array_push($masterObj->$foreignName, clone($foreignObj));
+								}
+							}
+						}
+					}
+					if(!empty($relations['belongsTo']))
+					{
+						foreach($relations['belongsTo'] as $foreignTable)
+						{
+							$foreignName = $foreignTable->foreignName;
+							if(!empty($obj->$foreignName))
+							{
+								$masterObj = &$uniqArr['_'.$row[0]];
+								// Assumption: this property exists in every object since they are instances of the same class
+								if(!is_array($masterObj->$foreignName))
+								{
+									// Pluck!
+									$foreignObj = $masterObj->$foreignName;
+									$masterObj->$foreignName = array(clone($foreignObj));
+								}
+								else
+								{
+									// Pluck pluck!
+									$foreignObj = $obj->$foreignName;
+									array_push($masterObj->$foreignName, clone($foreignObj));
+								}
+							}
+						}
+					}
+					if(!$isNewObj)
+						unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array					
+				}
+				else if(ADODB_LAZY_AR == $extra['loading'])
+				{
+					// Lazy loading: we need to give AdoDb a hint that we have not really loaded
+					// anything, all the while keeping enough information on what we wish to load.
+					// Let's do this by keeping the relevant info in our relationship arrays
+					// but get rid of the actual properties.
+					// We will then use PHP's __get to load these properties on-demand.
+					if(!empty($relations['hasMany']))
+					{
+						foreach($relations['hasMany'] as $foreignTable)
+						{
+							$foreignName = $foreignTable->foreignName;
+							if(!empty($obj->$foreignName))
+							{
+								unset($obj->$foreignName);
+							}
+						}
+					}
+					if(!empty($relations['belongsTo']))
+					{
+						foreach($relations['belongsTo'] as $foreignTable)
+						{
+							$foreignName = $foreignTable->foreignName;
+							if(!empty($obj->$foreignName))
+							{
+								unset($obj->$foreignName);
+							}
+						}
+					}
+				}
+			}
+
+			if(isset($obj))
+				$arr[] = $obj;
+		}
+
+		if(ADODB_WORK_AR == $extra['loading'])
+		{
+			// The best of both worlds?
+			// Here, the number of queries is constant: 1 + n*relationship.
+			// The second query will allow us to perform a good join
+			// while preserving LIMIT etc.
+			if(!empty($relations['hasMany']))
+			{
+				foreach($relations['hasMany'] as $foreignTable)
+				{
+					$foreignName = $foreignTable->foreignName;
+					$className = ucfirst($foreignTable->_singularize($foreignName));
+					$obj = new $className();
+					$dbClassRef = $foreignTable->foreignKey;
+					$objs = $obj->packageFind($dbClassRef.' IN ('.$indices.')');
+					foreach($objs as $obj)
+					{
+						if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName))
+							$arrRef[$obj->$dbClassRef]->$foreignName = array();
+						array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
+					}
+				}
+				
+			}
+			if(!empty($relations['belongsTo']))
+			{
+				foreach($relations['belongsTo'] as $foreignTable)
+				{
+					$foreignTableRef = $foreignTable->foreignKey;
+					if(empty($bTos[$foreignTableRef]))
+						continue;
+					if(($k = reset($foreignTable->TableInfo()->keys)))
+					{
+						$belongsToId = $k;
+					}
+					else
+					{
+						$belongsToId = 'id';
+					}						
+					$origObjsArr = $bTos[$foreignTableRef];
+					$bTosString = implode(',', array_keys($bTos[$foreignTableRef]));
+					$foreignName = $foreignTable->foreignName;
+					$className = ucfirst($foreignTable->_singularize($foreignName));
+					$obj = new $className();
+					$objs = $obj->packageFind($belongsToId.' IN ('.$bTosString.')');
+					foreach($objs as $obj)
+					{
+						foreach($origObjsArr[$obj->$belongsToId] as $idx=>$origObj)
+						{
+							$origObj->$foreignName = $obj;
+						}
+					}
+				}
+			}
+		}
+
+		return $arr;
+}
+?>

Property changes on: adodb-active-recordx.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: adodb-csvlib.inc.php
===================================================================
--- adodb-csvlib.inc.php	(revision 13354)
+++ adodb-csvlib.inc.php	(working copy)
@@ -8,7 +8,7 @@
 
 /* 
 
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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 @@
 		$line = "====1,$tt,$sql\n";
 		
 		if ($rs->databaseType == 'array') {
-			$rows =& $rs->_array;
+			$rows = $rs->_array;
 		} else {
 			$rows = array();
 			while (!$rs->EOF) {	
@@ -64,13 +64,14 @@
 		}
 		
 		for($i=0; $i < $max; $i++) {
-			$o =& $rs->FetchField($i);
+			$o = $rs->FetchField($i);
 			$flds[] = $o;
 		}
 	
 		$savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
 		$class = $rs->connection->arrayClass;
 		$rs2 = new $class();
+		$rs2->timeCreated = $rs->timeCreated; # memcache fix
 		$rs2->sql = $rs->sql;
 		$rs2->oldProvider = $rs->dataProvider; 
 		$rs2->InitArrayFields($rows,$flds);
@@ -90,7 +91,7 @@
 *			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 +262,7 @@
 
 	/**
 	* 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 +282,31 @@
 			$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) {
+				@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'));
+				}
 			}
-			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");
Index: adodb-datadict.inc.php
===================================================================
--- adodb-datadict.inc.php	(revision 13354)
+++ adodb-datadict.inc.php	(working copy)
@@ -1,820 +1,1049 @@
-<?php
-
-/**
-  V4.90 8 June 2006  (c) 2000-2006 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.
- 
- 	DOCUMENTATION:
-	
-		See adodb/tests/test-datadict.php for docs and examples.
-*/
-
-/*
-	Test script for parser
-*/
-
-// security - hide paths
-if (!defined('ADODB_DIR')) die();
-
-function Lens_ParseTest()
-{
-$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
-print "<p>$str</p>";
-$a= Lens_ParseArgs($str);
-print "<pre>";
-print_r($a);
-print "</pre>";
-}
-
-
-if (!function_exists('ctype_alnum')) {
-	function ctype_alnum($text) {
-		return preg_match('/^[a-z0-9]*$/i', $text);
-	}
-}
-
-//Lens_ParseTest();
-
-/**
-	Parse arguments, treat "text" (text) and 'text' as quotation marks.
-	To escape, use "" or '' or ))
-	
-	Will read in "abc def" sans quotes, as: abc def
-	Same with 'abc def'.
-	However if `abc def`, then will read in as `abc def`
-	
-	@param endstmtchar    Character that indicates end of statement
-	@param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
-	@returns 2 dimensional array containing parsed tokens.
-*/
-function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
-{
-	$pos = 0;
-	$intoken = false;
-	$stmtno = 0;
-	$endquote = false;
-	$tokens = array();
-	$tokens[$stmtno] = array();
-	$max = strlen($args);
-	$quoted = false;
-	$tokarr = array();
-	
-	while ($pos < $max) {
-		$ch = substr($args,$pos,1);
-		switch($ch) {
-		case ' ':
-		case "\t":
-		case "\n":
-		case "\r":
-			if (!$quoted) {
-				if ($intoken) {
-					$intoken = false;
-					$tokens[$stmtno][] = implode('',$tokarr);
-				}
-				break;
-			}
-			
-			$tokarr[] = $ch;
-			break;
-		
-		case '`':
-			if ($intoken) $tokarr[] = $ch;
-		case '(':
-		case ')':	
-		case '"':
-		case "'":
-			
-			if ($intoken) {
-				if (empty($endquote)) {
-					$tokens[$stmtno][] = implode('',$tokarr);
-					if ($ch == '(') $endquote = ')';
-					else $endquote = $ch;
-					$quoted = true;
-					$intoken = true;
-					$tokarr = array();
-				} else if ($endquote == $ch) {
-					$ch2 = substr($args,$pos+1,1);
-					if ($ch2 == $endquote) {
-						$pos += 1;
-						$tokarr[] = $ch2;
-					} else {
-						$quoted = false;
-						$intoken = false;
-						$tokens[$stmtno][] = implode('',$tokarr);
-						$endquote = '';
-					}
-				} else
-					$tokarr[] = $ch;
-					
-			}else {
-			
-				if ($ch == '(') $endquote = ')';
-				else $endquote = $ch;
-				$quoted = true;
-				$intoken = true;
-				$tokarr = array();
-				if ($ch == '`') $tokarr[] = '`';
-			}
-			break;
-			
-		default:
-			
-			if (!$intoken) {
-				if ($ch == $endstmtchar) {
-					$stmtno += 1;
-					$tokens[$stmtno] = array();
-					break;
-				}
-			
-				$intoken = true;
-				$quoted = false;
-				$endquote = false;
-				$tokarr = array();
-	
-			}
-			
-			if ($quoted) $tokarr[] = $ch;
-			else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
-			else {
-				if ($ch == $endstmtchar) {			
-					$tokens[$stmtno][] = implode('',$tokarr);
-					$stmtno += 1;
-					$tokens[$stmtno] = array();
-					$intoken = false;
-					$tokarr = array();
-					break;
-				}
-				$tokens[$stmtno][] = implode('',$tokarr);
-				$tokens[$stmtno][] = $ch;
-				$intoken = false;
-			}
-		}
-		$pos += 1;
-	}
-	if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
-	
-	return $tokens;
-}
-
-
-class ADODB_DataDict {
-	var $connection;
-	var $debug = false;
-	var $dropTable = 'DROP TABLE %s';
-	var $renameTable = 'RENAME TABLE %s TO %s'; 
-	var $dropIndex = 'DROP INDEX %s';
-	var $addCol = ' ADD';
-	var $alterCol = ' ALTER COLUMN';
-	var $dropCol = ' DROP COLUMN';
-	var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s';	// table, old-column, new-column, column-definitions (not used by default)
-	var $nameRegex = '\w';
-	var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
-	var $schema = false;
-	var $serverInfo = array();
-	var $autoIncrement = false;
-	var $dataProvider;
-	var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
-	var $blobSize = 100; 	/// any varchar/char field this size or greater is treated as a blob
-							/// in other words, we use a text area for editting.
-	
-	function GetCommentSQL($table,$col)
-	{
-		return false;
-	}
-	
-	function SetCommentSQL($table,$col,$cmt)
-	{
-		return false;
-	}
-	
-	function MetaTables()
-	{
-		if (!$this->connection->IsConnected()) return array();
-		return $this->connection->MetaTables();
-	}
-	
-	function MetaColumns($tab, $upper=true, $schema=false)
-	{
-		if (!$this->connection->IsConnected()) return array();
-		return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
-	}
-	
-	function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
-	{
-		if (!$this->connection->IsConnected()) return array();
-		return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
-	}
-	
-	function MetaIndexes($table, $primary = false, $owner = false)
-	{
-		if (!$this->connection->IsConnected()) return array();
-		return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
-	}
-	
-	function MetaType($t,$len=-1,$fieldobj=false)
-	{
-		return ADORecordSet::MetaType($t,$len,$fieldobj);
-	}
-	
-	function NameQuote($name = NULL,$allowBrackets=false)
-	{
-		if (!is_string($name)) {
-			return FALSE;
-		}
-		
-		$name = trim($name);
-		
-		if ( !is_object($this->connection) ) {
-			return $name;
-		}
-		
-		$quote = $this->connection->nameQuote;
-		
-		// if name is of the form `name`, quote it
-		if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
-			return $quote . $matches[1] . $quote;
-		}
-		
-		// if name contains special characters, quote it
-		$regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
-		
-		if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
-			return $quote . $name . $quote;
-		}
-		
-		return $name;
-	}
-	
-	function TableName($name)
-	{
-		if ( $this->schema ) {
-			return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
-		}
-		return $this->NameQuote($name);
-	}
-	
-	// Executes the sql array returned by GetTableSQL and GetIndexSQL
-	function ExecuteSQLArray($sql, $continueOnError = true)
-	{
-		global $log;
-		$rez = 2;
-		$conn = &$this->connection;
-		$saved = $conn->debug;
-		foreach($sql as $line) {
-			
-			if ($this->debug) $conn->debug = true;
-			$log->debug($line);
-			$ok = $conn->Execute($line);
-			$conn->debug = $saved;
-			if (!$ok) {
-				$log->fatal("Table Creation Error: Query Failed");
-				$log->fatal(" ");
-				if ($this->debug)
-			       	{
-					$log->fatal("InstallError: ".$conn->ErrorMsg());
-					ADOConnection::outp($conn->ErrorMsg());
-				}		
-				if (!$continueOnError) return 0;
-				$rez = 1;
-			}
-		}
-		return $rez;
-	}
-	
-	/*
-	 	Returns the actual type given a character code.
-		
-		C:  varchar
-		X:  CLOB (character large object) or largest varchar size if CLOB is not supported
-		C2: Multibyte varchar
-		X2: Multibyte CLOB
-		
-		B:  BLOB (binary large object)
-		
-		D:  Date
-		T:  Date-time 
-		L:  Integer field suitable for storing booleans (0 or 1)
-		I:  Integer
-		F:  Floating point number
-		N:  Numeric or decimal number
-	*/
-	
-	function ActualType($meta)
-	{
-		return $meta;
-	}
-	
-	function CreateDatabase($dbname,$options=false)
-	{
-		$options = $this->_Options($options);
-		$sql = array();
-		
-		$s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
-		if (isset($options[$this->upperName]))
-			$s .= ' '.$options[$this->upperName];
-		
-		$sql[] = $s;
-		return $sql;
-	}
-	
-	/*
-	 Generates the SQL to create index. Returns an array of sql strings.
-	*/
-	function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
-	{
-		if (!is_array($flds)) {
-			$flds = explode(',',$flds);
-		}
-		
-		foreach($flds as $key => $fld) {
-			# some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
-			$flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
-		}
-		
-		return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
-	}
-	
-	function DropIndexSQL ($idxname, $tabname = NULL)
-	{
-		return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
-	}
-	
-	function SetSchema($schema)
-	{
-		$this->schema = $schema;
-	}
-	
-	function AddColumnSQL($tabname, $flds)
-	{
-		$tabname = $this->TableName ($tabname);
-		$sql = array();
-		list($lines,$pkey) = $this->_GenFields($flds);
-		$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
-		foreach($lines as $v) {
-			$sql[] = $alter . $v;
-		}
-		return $sql;
-	}
-	
-	/**
-	 * Change the definition of one column
-	 *
-	 * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
-	 * to allow, recreating the table and copying the content over to the new table
-	 * @param string $tabname table-name
-	 * @param string $flds column-name and type for the changed column
-	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
-	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
-	 * @return array with SQL strings
-	 */
-	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
-	{
-		$tabname = $this->TableName ($tabname);
-		$sql = array();
-		list($lines,$pkey) = $this->_GenFields($flds);
-		$alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
-		foreach($lines as $v) {
-			$sql[] = $alter . $v;
-		}
-		return $sql;
-	}
-	
-	/**
-	 * Rename one column
-	 *
-	 * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
-	 * @param string $tabname table-name
-	 * @param string $oldcolumn column-name to be renamed
-	 * @param string $newcolumn new column-name
-	 * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
-	 * @return array with SQL strings
-	 */
-	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
-	{
-		$tabname = $this->TableName ($tabname);
-		if ($flds) {
-			list($lines,$pkey) = $this->_GenFields($flds);
-			list(,$first) = each($lines);
-			list(,$column_def) = split("[\t ]+",$first,2);
-		}
-		return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
-	}
-		
-	/**
-	 * Drop one column
-	 *
-	 * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
-	 * to allow, recreating the table and copying the content over to the new table
-	 * @param string $tabname table-name
-	 * @param string $flds column-name and type for the changed column
-	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
-	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
-	 * @return array with SQL strings
-	 */
-	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
-	{
-		$tabname = $this->TableName ($tabname);
-		if (!is_array($flds)) $flds = explode(',',$flds);
-		$sql = array();
-		$alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
-		foreach($flds as $v) {
-			$sql[] = $alter . $this->NameQuote($v);
-		}
-		return $sql;
-	}
-	
-	function DropTableSQL($tabname)
-	{
-		return array (sprintf($this->dropTable, $this->TableName($tabname)));
-	}
-	
-	function RenameTableSQL($tabname,$newname)
-	{
-		return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
-	}	
-	
-	/*
-	 Generate the SQL to create table. Returns an array of sql strings.
-	*/
-	function CreateTableSQL($tabname, $flds, $tableoptions=false)
-	{
-		if (!$tableoptions) $tableoptions = array();
-		
-		list($lines,$pkey) = $this->_GenFields($flds, true);
-		
-		$taboptions = $this->_Options($tableoptions);
-		$tabname = $this->TableName ($tabname);
-		$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
-		
-		$tsql = $this->_Triggers($tabname,$taboptions);
-		foreach($tsql as $s) $sql[] = $s;
-		
-		return $sql;
-	}
-	
-	function _GenFields($flds,$widespacing=false)
-	{
-		if (is_string($flds)) {
-			$padding = '     ';
-			$txt = $flds.$padding;
-			$flds = array();
-			$flds0 = Lens_ParseArgs($txt,',');
-			$hasparam = false;
-			foreach($flds0 as $f0) {
-				$f1 = array();
-				foreach($f0 as $token) {
-					switch (strtoupper($token)) {
-					case 'CONSTRAINT':
-					case 'DEFAULT': 
-						$hasparam = $token;
-						break;
-					default:
-						if ($hasparam) $f1[$hasparam] = $token;
-						else $f1[] = $token;
-						$hasparam = false;
-						break;
-					}
-				}
-				$flds[] = $f1;
-				
-			}
-		}
-		$this->autoIncrement = false;
-		$lines = array();
-		$pkey = array();
-		foreach($flds as $fld) {
-			$fld = _array_change_key_case($fld);
-		
-			$fname = false;
-			$fdefault = false;
-			$fautoinc = false;
-			$ftype = false;
-			$fsize = false;
-			$fprec = false;
-			$fprimary = false;
-			$fnoquote = false;
-			$fdefts = false;
-			$fdefdate = false;
-			$fconstraint = false;
-			$fnotnull = false;
-			$funsigned = false;
-			
-			//-----------------
-			// Parse attributes
-			foreach($fld as $attr => $v) {
-				if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
-				else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
-				
-				switch($attr) {
-				case '0':
-				case 'NAME': 	$fname = $v; break;
-				case '1':
-				case 'TYPE': 	$ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
-				
-				case 'SIZE': 	
-								$dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
-								if ($dotat === false) $fsize = $v;
-								else {
-									$fsize = substr($v,0,$dotat);
-									$fprec = substr($v,$dotat+1);
-								}
-								break;
-				case 'UNSIGNED': $funsigned = true; break;
-				case 'AUTOINCREMENT':
-				case 'AUTO':	$fautoinc = true; $fnotnull = true; break;
-				case 'KEY':
-				case 'PRIMARY':	$fprimary = $v; $fnotnull = true; break;
-				case 'DEF':
-				case 'DEFAULT': $fdefault = $v; break;
-				case 'NOTNULL': $fnotnull = $v; break;
-				case 'NOQUOTE': $fnoquote = $v; break;
-				case 'DEFDATE': $fdefdate = $v; break;
-				case 'DEFTIMESTAMP': $fdefts = $v; break;
-				case 'CONSTRAINT': $fconstraint = $v; break;
-				} //switch
-			} // foreach $fld
-			
-			//--------------------
-			// VALIDATE FIELD INFO
-			if (!strlen($fname)) {
-				if ($this->debug) ADOConnection::outp("Undefined NAME");
-				return false;
-			}
-			
-			$fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
-			$fname = $this->NameQuote($fname);
-			
-			if (!strlen($ftype)) {
-				if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
-				return false;
-			} else {
-				$ftype = strtoupper($ftype);
-			}
-			
-			$ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
-			
-			if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
-			
-			if ($fprimary) $pkey[] = $fname;
-			
-			// some databases do not allow blobs to have defaults
-			if ($ty == 'X') $fdefault = false;
-			
-			//--------------------
-			// CONSTRUCT FIELD SQL
-			if ($fdefts) {
-				if (substr($this->connection->databaseType,0,5) == 'mysql') {
-					$ftype = 'TIMESTAMP';
-				} else {
-					$fdefault = $this->connection->sysTimeStamp;
-				}
-			} else if ($fdefdate) {
-				if (substr($this->connection->databaseType,0,5) == 'mysql') {
-					$ftype = 'TIMESTAMP';
-				} else {
-					$fdefault = $this->connection->sysDate;
-				}
-			} else if ($fdefault !== false && !$fnoquote)
-				if ($ty == 'C' or $ty == 'X' or 
-					( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
-					if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
-						$fdefault = trim($fdefault);
-					else if (strtolower($fdefault) != 'null')
-						$fdefault = $this->connection->qstr($fdefault);
-			$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
-			
-			if ($widespacing) $fname = str_pad($fname,24);
-			$lines[$fid] = $fname.' '.$ftype.$suffix;
-			
-			if ($fautoinc) $this->autoIncrement = true;
-		} // foreach $flds
-		
-		return array($lines,$pkey);
-	}
-	/*
-		 GENERATE THE SIZE PART OF THE DATATYPE
-			$ftype is the actual type
-			$ty is the type defined originally in the DDL
-	*/
-	function _GetSize($ftype, $ty, $fsize, $fprec)
-	{
-		if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
-			$ftype .= "(".$fsize;
-			if (strlen($fprec)) $ftype .= ",".$fprec;
-			$ftype .= ')';
-		}
-		return $ftype;
-	}
-	
-	
-	// return string must begin with space
-	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
-	{	
-		$suffix = '';
-		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-		if ($fnotnull) $suffix .= ' NOT NULL';
-		if ($fconstraint) $suffix .= ' '.$fconstraint;
-		return $suffix;
-	}
-	
-	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
-	{
-		$sql = array();
-		
-		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
-			$sql[] = sprintf ($this->dropIndex, $idxname);
-			if ( isset($idxoptions['DROP']) )
-				return $sql;
-		}
-		
-		if ( empty ($flds) ) {
-			return $sql;
-		}
-		
-		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
-	
-		$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
-		
-		if ( isset($idxoptions[$this->upperName]) )
-			$s .= $idxoptions[$this->upperName];
-		
-		if ( is_array($flds) )
-			$flds = implode(', ',$flds);
-		$s .= '(' . $flds . ')';
-		$sql[] = $s;
-		
-		return $sql;
-	}
-	
-	function _DropAutoIncrement($tabname)
-	{
-		return false;
-	}
-	
-	function _TableSQL($tabname,$lines,$pkey,$tableoptions)
-	{
-		$sql = array();
-		
-		if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
-			$sql[] = sprintf($this->dropTable,$tabname);
-			if ($this->autoIncrement) {
-				$sInc = $this->_DropAutoIncrement($tabname);
-				if ($sInc) $sql[] = $sInc;
-			}
-			if ( isset ($tableoptions['DROP']) ) {
-				return $sql;
-			}
-		}
-		$s = "CREATE TABLE $tabname (\n";
-		$s .= implode(",\n", $lines);
-		if (sizeof($pkey)>0) {
-			$s .= ",\n                 PRIMARY KEY (";
-			$s .= implode(", ",$pkey).")";
-		}
-		if (isset($tableoptions['CONSTRAINTS'])) 
-			$s .= "\n".$tableoptions['CONSTRAINTS'];
-		
-		if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
-			$s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
-		
-		$s .= "\n)";
-		if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
-		$sql[] = $s;
-		
-		return $sql;
-	}
-	
-	/*
-		GENERATE TRIGGERS IF NEEDED
-		used when table has auto-incrementing field that is emulated using triggers
-	*/
-	function _Triggers($tabname,$taboptions)
-	{
-		return array();
-	}
-	
-	/*
-		Sanitize options, so that array elements with no keys are promoted to keys
-	*/
-	function _Options($opts)
-	{
-		if (!is_array($opts)) return array();
-		$newopts = array();
-		foreach($opts as $k => $v) {
-			if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
-			else $newopts[strtoupper($k)] = $v;
-		}
-		return $newopts;
-	}
-	
-	/*
-	"Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
-	
-	This function changes/adds new fields to your table. You don't
-	have to know if the col is new or not. It will check on its own.
-	*/
-	function ChangeTableSQL($tablename, $flds, $tableoptions = false, $forceAlter = false) // GS Fix for constraint impl - forceAlter
-	{
-	global $ADODB_FETCH_MODE;
-	
-		$save = $ADODB_FETCH_MODE;
-		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-		if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
-		
-		// check table exists
-		$save_handler = $this->connection->raiseErrorFn;
-		$this->connection->raiseErrorFn = '';
-		$cols = $this->MetaColumns($tablename);
-		$this->connection->raiseErrorFn = $save_handler;
-		
-		if (isset($savem)) $this->connection->SetFetchMode($savem);
-		$ADODB_FETCH_MODE = $save;
-		
-		if ( $forceAlter == false && empty($cols)) { // GS Fix for constraint impl
-			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
-		}
-		
-		if (is_array($flds)) {
-		// Cycle through the update fields, comparing
-		// existing fields to fields to update.
-		// if the Metatype and size is exactly the
-		// same, ignore - by Mark Newham
-			$holdflds = array();
-			foreach($flds as $k=>$v) {
-				if ( isset($cols[$k]) && is_object($cols[$k]) ) {
-					// If already not allowing nulls, then don't change
-					$obj = $cols[$k];
-					if (isset($obj->not_null) && $obj->not_null)
-						$v = str_replace('NOT NULL','',$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']) {
-						$holdflds[$k] = $v;
-					}
-				} else {
-					$holdflds[$k] = $v;
-				}		
-			}
-			$flds = $holdflds;
-		}
-	
-
-		// already exists, alter table instead
-		list($lines,$pkey) = $this->_GenFields($flds);
-		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
-		$sql = array();
-
-		foreach ( $lines as $id => $v ) {
-			if ( isset($cols[$id]) && is_object($cols[$id]) ) {
-			
-				$flds = Lens_ParseArgs($v,',');
-				
-				//  We are trying to change the size of the field, if not allowed, simply ignore the request.
-				if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) continue;	 
-	 		
-				$sql[] = $alter . $this->alterCol . ' ' . $v;
-			} else {
-				$sql[] = $alter . $this->addCol . ' ' . $v;
-			}
-		}
-
-		// GS Fix for constraint impl -- start
-		if($forceAlter == false) return $sql;
-		$sqlarray = array();
-
-		$alter .= implode(",\n", $sql);
-		if (sizeof($pkey)>0) {
-			$alter .= ",\n PRIMARY KEY (";
-			$alter .= implode(", ",$pkey).")";
-		}
-		
-		if (isset($tableoptions['CONSTRAINTS'])) 
-			$alter .= "\n".$tableoptions['CONSTRAINTS'];
-
-		if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
-			$alter .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
-
-		if (isset($tableoptions[$this->upperName])) $alter .= $tableoptions[$this->upperName];
-			$sqlarray[] = $alter;
-
-		
-		$taboptions = $this->_Options($tableoptions);
-		$tsql = $this->_Triggers($this->TableName($tablename),$taboptions);
-		foreach($tsql as $s) $sqlarray[] = $s;
-
-		// GS Fix for constraint impl -- end
-		
-		return $sqlarray;
-
-		
-	}
-} // class
-?>
+<?php
+
+/**
+  V5.11 5 May 2010   (c) 2000-2010 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.
+ 
+ 	DOCUMENTATION:
+	
+		See adodb/tests/test-datadict.php for docs and examples.
+*/
+
+/*
+	Test script for parser
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+function Lens_ParseTest()
+{
+$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
+print "<p>$str</p>";
+$a= Lens_ParseArgs($str);
+print "<pre>";
+print_r($a);
+print "</pre>";
+}
+
+
+if (!function_exists('ctype_alnum')) {
+	function ctype_alnum($text) {
+		return preg_match('/^[a-z0-9]*$/i', $text);
+	}
+}
+
+//Lens_ParseTest();
+
+/**
+	Parse arguments, treat "text" (text) and 'text' as quotation marks.
+	To escape, use "" or '' or ))
+	
+	Will read in "abc def" sans quotes, as: abc def
+	Same with 'abc def'.
+	However if `abc def`, then will read in as `abc def`
+	
+	@param endstmtchar    Character that indicates end of statement
+	@param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
+	@returns 2 dimensional array containing parsed tokens.
+*/
+function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
+{
+	$pos = 0;
+	$intoken = false;
+	$stmtno = 0;
+	$endquote = false;
+	$tokens = array();
+	$tokens[$stmtno] = array();
+	$max = strlen($args);
+	$quoted = false;
+	$tokarr = array();
+	
+	while ($pos < $max) {
+		$ch = substr($args,$pos,1);
+		switch($ch) {
+		case ' ':
+		case "\t":
+		case "\n":
+		case "\r":
+			if (!$quoted) {
+				if ($intoken) {
+					$intoken = false;
+					$tokens[$stmtno][] = implode('',$tokarr);
+				}
+				break;
+			}
+			
+			$tokarr[] = $ch;
+			break;
+		
+		case '`':
+			if ($intoken) $tokarr[] = $ch;
+		case '(':
+		case ')':	
+		case '"':
+		case "'":
+			
+			if ($intoken) {
+				if (empty($endquote)) {
+					$tokens[$stmtno][] = implode('',$tokarr);
+					if ($ch == '(') $endquote = ')';
+					else $endquote = $ch;
+					$quoted = true;
+					$intoken = true;
+					$tokarr = array();
+				} else if ($endquote == $ch) {
+					$ch2 = substr($args,$pos+1,1);
+					if ($ch2 == $endquote) {
+						$pos += 1;
+						$tokarr[] = $ch2;
+					} else {
+						$quoted = false;
+						$intoken = false;
+						$tokens[$stmtno][] = implode('',$tokarr);
+						$endquote = '';
+					}
+				} else
+					$tokarr[] = $ch;
+					
+			}else {
+			
+				if ($ch == '(') $endquote = ')';
+				else $endquote = $ch;
+				$quoted = true;
+				$intoken = true;
+				$tokarr = array();
+				if ($ch == '`') $tokarr[] = '`';
+			}
+			break;
+			
+		default:
+			
+			if (!$intoken) {
+				if ($ch == $endstmtchar) {
+					$stmtno += 1;
+					$tokens[$stmtno] = array();
+					break;
+				}
+			
+				$intoken = true;
+				$quoted = false;
+				$endquote = false;
+				$tokarr = array();
+	
+			}
+			
+			if ($quoted) $tokarr[] = $ch;
+			else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
+			else {
+				if ($ch == $endstmtchar) {			
+					$tokens[$stmtno][] = implode('',$tokarr);
+					$stmtno += 1;
+					$tokens[$stmtno] = array();
+					$intoken = false;
+					$tokarr = array();
+					break;
+				}
+				$tokens[$stmtno][] = implode('',$tokarr);
+				$tokens[$stmtno][] = $ch;
+				$intoken = false;
+			}
+		}
+		$pos += 1;
+	}
+	if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
+	
+	return $tokens;
+}
+
+
+class ADODB_DataDict {
+	var $connection;
+	var $debug = false;
+	var $dropTable = 'DROP TABLE %s';
+	var $renameTable = 'RENAME TABLE %s TO %s'; 
+	var $dropIndex = 'DROP INDEX %s';
+	var $addCol = ' ADD';
+	var $alterCol = ' ALTER COLUMN';
+	var $dropCol = ' DROP COLUMN';
+	var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s';	// table, old-column, new-column, column-definitions (not used by default)
+	var $nameRegex = '\w';
+	var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
+	var $schema = false;
+	var $serverInfo = array();
+	var $autoIncrement = false;
+	var $dataProvider;
+	var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
+	var $blobSize = 100; 	/// any varchar/char field this size or greater is treated as a blob
+							/// in other words, we use a text area for editting.
+	
+	function GetCommentSQL($table,$col)
+	{
+		return false;
+	}
+	
+	function SetCommentSQL($table,$col,$cmt)
+	{
+		return false;
+	}
+	
+	function MetaTables()
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaTables();
+	}
+	
+	function MetaColumns($tab, $upper=true, $schema=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
+	}
+	
+	function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
+	}
+	
+	function MetaIndexes($table, $primary = false, $owner = false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
+	}
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{		
+		static $typeMap = array(
+		'VARCHAR' => 'C',
+		'VARCHAR2' => 'C',
+		'CHAR' => 'C',
+		'C' => 'C',
+		'STRING' => 'C',
+		'NCHAR' => 'C',
+		'NVARCHAR' => 'C',
+		'VARYING' => 'C',
+		'BPCHAR' => 'C',
+		'CHARACTER' => 'C',
+		'INTERVAL' => 'C',  # Postgres
+		'MACADDR' => 'C', # postgres
+		'VAR_STRING' => 'C', # mysql
+		##
+		'LONGCHAR' => 'X',
+		'TEXT' => 'X',
+		'NTEXT' => 'X',
+		'M' => 'X',
+		'X' => 'X',
+		'CLOB' => 'X',
+		'NCLOB' => 'X',
+		'LVARCHAR' => 'X',
+		##
+		'BLOB' => 'B',
+		'IMAGE' => 'B',
+		'BINARY' => 'B',
+		'VARBINARY' => 'B',
+		'LONGBINARY' => 'B',
+		'B' => 'B',
+		##
+		'YEAR' => 'D', // mysql
+		'DATE' => 'D',
+		'D' => 'D',
+		##
+		'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
+		##
+		'TIME' => 'T',
+		'TIMESTAMP' => 'T',
+		'DATETIME' => 'T',
+		'TIMESTAMPTZ' => 'T',
+		'SMALLDATETIME' => 'T',
+		'T' => 'T',
+		'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
+		##
+		'BOOL' => 'L',
+		'BOOLEAN' => 'L', 
+		'BIT' => 'L',
+		'L' => 'L',
+		##
+		'COUNTER' => 'R',
+		'R' => 'R',
+		'SERIAL' => 'R', // ifx
+		'INT IDENTITY' => 'R',
+		##
+		'INT' => 'I',
+		'INT2' => 'I',
+		'INT4' => 'I',
+		'INT8' => 'I',
+		'INTEGER' => 'I',
+		'INTEGER UNSIGNED' => 'I',
+		'SHORT' => 'I',
+		'TINYINT' => 'I',
+		'SMALLINT' => 'I',
+		'I' => 'I',
+		##
+		'LONG' => 'N', // interbase is numeric, oci8 is blob
+		'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
+		'DECIMAL' => 'N',
+		'DEC' => 'N',
+		'REAL' => 'N',
+		'DOUBLE' => 'N',
+		'DOUBLE PRECISION' => 'N',
+		'SMALLFLOAT' => 'N',
+		'FLOAT' => 'N',
+		'NUMBER' => 'N',
+		'NUM' => 'N',
+		'NUMERIC' => 'N',
+		'MONEY' => 'N',
+		
+		## informix 9.2
+		'SQLINT' => 'I', 
+		'SQLSERIAL' => 'I', 
+		'SQLSMINT' => 'I', 
+		'SQLSMFLOAT' => 'N', 
+		'SQLFLOAT' => 'N', 
+		'SQLMONEY' => 'N', 
+		'SQLDECIMAL' => 'N', 
+		'SQLDATE' => 'D', 
+		'SQLVCHAR' => 'C', 
+		'SQLCHAR' => 'C', 
+		'SQLDTIME' => 'T', 
+		'SQLINTERVAL' => 'N', 
+		'SQLBYTES' => 'B', 
+		'SQLTEXT' => 'X',
+		 ## informix 10
+		"SQLINT8" => 'I8',
+		"SQLSERIAL8" => 'I8',
+		"SQLNCHAR" => 'C',
+		"SQLNVCHAR" => 'C',
+		"SQLLVARCHAR" => 'X',
+		"SQLBOOL" => 'L'
+		);
+		
+		if (!$this->connection->IsConnected()) {
+			$t = strtoupper($t);
+			if (isset($typeMap[$t])) return $typeMap[$t];
+			return 'N';
+		}
+		return $this->connection->MetaType($t,$len,$fieldobj);
+	}
+	
+	function NameQuote($name = NULL,$allowBrackets=false)
+	{
+		if (!is_string($name)) {
+			return FALSE;
+		}
+		
+		$name = trim($name);
+		
+		if ( !is_object($this->connection) ) {
+			return $name;
+		}
+		
+		$quote = $this->connection->nameQuote;
+		
+		// if name is of the form `name`, quote it
+		if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
+			return $quote . $matches[1] . $quote;
+		}
+		
+		// if name contains special characters, quote it
+		$regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
+		
+		if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
+			return $quote . $name . $quote;
+		}
+		
+		return $name;
+	}
+	
+	function TableName($name)
+	{
+		if ( $this->schema ) {
+			return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
+		}
+		return $this->NameQuote($name);
+	}
+	
+	// Executes the sql array returned by GetTableSQL and GetIndexSQL
+	function ExecuteSQLArray($sql, $continueOnError = true)
+	{
+		$rez = 2;
+		$conn = $this->connection;
+		$saved = $conn->debug;
+		foreach($sql as $line) {
+			
+			if ($this->debug) $conn->debug = true;
+			$ok = $conn->Execute($line);
+			$conn->debug = $saved;
+			if (!$ok) {
+				if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
+				if (!$continueOnError) return 0;
+				$rez = 1;
+			}
+		}
+		return $rez;
+	}
+	
+	/**
+	 	Returns the actual type given a character code.
+		
+		C:  varchar
+		X:  CLOB (character large object) or largest varchar size if CLOB is not supported
+		C2: Multibyte varchar
+		X2: Multibyte CLOB
+		
+		B:  BLOB (binary large object)
+		
+		D:  Date
+		T:  Date-time 
+		L:  Integer field suitable for storing booleans (0 or 1)
+		I:  Integer
+		F:  Floating point number
+		N:  Numeric or decimal number
+	*/
+	
+	function ActualType($meta)
+	{
+		return $meta;
+	}
+	
+	function CreateDatabase($dbname,$options=false)
+	{
+		$options = $this->_Options($options);
+		$sql = array();
+		
+		$s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
+		if (isset($options[$this->upperName]))
+			$s .= ' '.$options[$this->upperName];
+		
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	/*
+	 Generates the SQL to create index. Returns an array of sql strings.
+	*/
+	function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
+	{
+		if (!is_array($flds)) {
+			$flds = explode(',',$flds);
+		}
+		
+		foreach($flds as $key => $fld) {
+			# some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
+			$flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
+		}
+		
+		return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
+	}
+	
+	function DropIndexSQL ($idxname, $tabname = NULL)
+	{
+		return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
+	}
+	
+	function SetSchema($schema)
+	{
+		$this->schema = $schema;
+	}
+	
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines  == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
+		foreach($lines as $v) {
+			$sql[] = $alter . $v;
+		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
+		return $sql;
+	}
+	
+	/**
+	 * Change the definition of one column
+	 *
+	 * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
+		foreach($lines as $v) {
+			$sql[] = $alter . $v;
+		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+
+		}
+		return $sql;
+	}
+	
+	/**
+	 * Rename one column
+	 *
+	 * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
+	 * @param string $tabname table-name
+	 * @param string $oldcolumn column-name to be renamed
+	 * @param string $newcolumn new column-name
+	 * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
+	 * @return array with SQL strings
+	 */
+	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
+	{
+		$tabname = $this->TableName ($tabname);
+		if ($flds) {
+			list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+			// genfields can return FALSE at times
+			if ($lines == null) $lines = array();
+			list(,$first) = each($lines);
+			list(,$column_def) = preg_split("/[\t ]+/",$first,2);
+		}
+		return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
+	}
+		
+	/**
+	 * Drop one column
+	 *
+	 * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		$tabname = $this->TableName ($tabname);
+		if (!is_array($flds)) $flds = explode(',',$flds);
+		$sql = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
+		foreach($flds as $v) {
+			$sql[] = $alter . $this->NameQuote($v);
+		}
+		return $sql;
+	}
+	
+	function DropTableSQL($tabname)
+	{
+		return array (sprintf($this->dropTable, $this->TableName($tabname)));
+	}
+	
+	function RenameTableSQL($tabname,$newname)
+	{
+		return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
+	}	
+	
+	/**
+	 Generate the SQL to create table. Returns an array of sql strings.
+	*/
+	function CreateTableSQL($tabname, $flds, $tableoptions=array())
+	{
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		
+		$taboptions = $this->_Options($tableoptions);
+		$tabname = $this->TableName ($tabname);
+		$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
+		
+		// ggiunta - 2006/10/12 - KLUDGE:
+        // if we are on autoincrement, and table options includes REPLACE, the
+        // autoincrement sequence has already been dropped on table creation sql, so
+        // we avoid passing REPLACE to trigger creation code. This prevents
+        // creating sql that double-drops the sequence
+        if ($this->autoIncrement && isset($taboptions['REPLACE']))
+        	unset($taboptions['REPLACE']);
+		$tsql = $this->_Triggers($tabname,$taboptions);
+		foreach($tsql as $s) $sql[] = $s;
+		
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname,  $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
+
+		return $sql;
+	}
+		
+	
+	
+	function _GenFields($flds,$widespacing=false)
+	{
+		if (is_string($flds)) {
+			$padding = '     ';
+			$txt = $flds.$padding;
+			$flds = array();
+			$flds0 = Lens_ParseArgs($txt,',');
+			$hasparam = false;
+			foreach($flds0 as $f0) {
+				$f1 = array();
+				foreach($f0 as $token) {
+					switch (strtoupper($token)) {
+					case 'INDEX':
+						$f1['INDEX'] = '';
+						// fall through intentionally
+					case 'CONSTRAINT':
+					case 'DEFAULT': 
+						$hasparam = $token;
+						break;
+					default:
+						if ($hasparam) $f1[$hasparam] = $token;
+						else $f1[] = $token;
+						$hasparam = false;
+						break;
+					}
+				}
+				// 'index' token without a name means single column index: name it after column
+				if (array_key_exists('INDEX', $f1) && $f1['INDEX'] == '') {
+					$f1['INDEX'] = isset($f0['NAME']) ? $f0['NAME'] : $f0[0];
+					// check if column name used to create an index name was quoted
+					if (($f1['INDEX'][0] == '"' || $f1['INDEX'][0] == "'" || $f1['INDEX'][0] == "`") &&
+						($f1['INDEX'][0] == substr($f1['INDEX'], -1))) {
+						$f1['INDEX'] = $f1['INDEX'][0].'idx_'.substr($f1['INDEX'], 1, -1).$f1['INDEX'][0];
+					}
+					else
+						$f1['INDEX'] = 'idx_'.$f1['INDEX'];
+				}
+				// reset it, so we don't get next field 1st token as INDEX...
+				$hasparam = false;
+
+				$flds[] = $f1;
+				
+			}
+		}
+		$this->autoIncrement = false;
+		$lines = array();
+		$pkey = array();
+		$idxs = array();
+		foreach($flds as $fld) {
+			$fld = _array_change_key_case($fld);
+			
+			$fname = false;
+			$fdefault = false;
+			$fautoinc = false;
+			$ftype = false;
+			$fsize = false;
+			$fprec = false;
+			$fprimary = false;
+			$fnoquote = false;
+			$fdefts = false;
+			$fdefdate = false;
+			$fconstraint = false;
+			$fnotnull = false;
+			$funsigned = false;
+			$findex = '';
+			$funiqueindex = false;
+			
+			//-----------------
+			// Parse attributes
+			foreach($fld as $attr => $v) {
+				if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
+				else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
+				
+				switch($attr) {
+				case '0':
+				case 'NAME': 	$fname = $v; break;
+				case '1':
+				case 'TYPE': 	$ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
+				
+				case 'SIZE': 	
+								$dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
+								if ($dotat === false) $fsize = $v;
+								else {
+									$fsize = substr($v,0,$dotat);
+									$fprec = substr($v,$dotat+1);
+								}
+								break;
+				case 'UNSIGNED': $funsigned = true; break;
+				case 'AUTOINCREMENT':
+				case 'AUTO':	$fautoinc = true; $fnotnull = true; break;
+				case 'KEY':
+                // a primary key col can be non unique in itself (if key spans many cols...)
+				case 'PRIMARY':	$fprimary = $v; $fnotnull = true; /*$funiqueindex = true;*/ break;
+				case 'DEF':
+				case 'DEFAULT': $fdefault = $v; break;
+				case 'NOTNULL': $fnotnull = $v; break;
+				case 'NOQUOTE': $fnoquote = $v; break;
+				case 'DEFDATE': $fdefdate = $v; break;
+				case 'DEFTIMESTAMP': $fdefts = $v; break;
+				case 'CONSTRAINT': $fconstraint = $v; break;
+				// let INDEX keyword create a 'very standard' index on column
+				case 'INDEX': $findex = $v; break;
+				case 'UNIQUE': $funiqueindex = true; break;
+				} //switch
+			} // foreach $fld
+			
+			//--------------------
+			// VALIDATE FIELD INFO
+			if (!strlen($fname)) {
+				if ($this->debug) ADOConnection::outp("Undefined NAME");
+				return false;
+			}
+			
+			$fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
+			$fname = $this->NameQuote($fname);
+			
+			if (!strlen($ftype)) {
+				if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
+				return false;
+			} else {
+				$ftype = strtoupper($ftype);
+			}
+			
+			$ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
+			
+			if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
+			
+			if ($fprimary) $pkey[] = $fname;
+			
+			// some databases do not allow blobs to have defaults
+			if ($ty == 'X') $fdefault = false;
+			
+			// build list of indexes
+			if ($findex != '') {
+				if (array_key_exists($findex, $idxs)) {
+					$idxs[$findex]['cols'][] = ($fname);
+					if (in_array('UNIQUE', $idxs[$findex]['opts']) != $funiqueindex) {
+						if ($this->debug) ADOConnection::outp("Index $findex defined once UNIQUE and once not");
+					}
+					if ($funiqueindex && !in_array('UNIQUE', $idxs[$findex]['opts']))
+						$idxs[$findex]['opts'][] = 'UNIQUE';
+				}
+				else
+				{
+					$idxs[$findex] = array();
+					$idxs[$findex]['cols'] = array($fname);
+					if ($funiqueindex)
+						$idxs[$findex]['opts'] = array('UNIQUE');
+					else
+						$idxs[$findex]['opts'] = array();
+				}
+			}
+
+			//--------------------
+			// CONSTRUCT FIELD SQL
+			if ($fdefts) {
+				if (substr($this->connection->databaseType,0,5) == 'mysql') {
+					$ftype = 'TIMESTAMP';
+				} else {
+					$fdefault = $this->connection->sysTimeStamp;
+				}
+			} else if ($fdefdate) {
+				if (substr($this->connection->databaseType,0,5) == 'mysql') {
+					$ftype = 'TIMESTAMP';
+				} else {
+					$fdefault = $this->connection->sysDate;
+				}
+			} else if ($fdefault !== false && !$fnoquote) {
+				if ($ty == 'C' or $ty == 'X' or 
+					( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
+
+					if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
+						// convert default date into database-aware code
+						if ($ty == 'T')
+						{
+							$fdefault = $this->connection->DBTimeStamp($fdefault);
+						}
+						else
+						{
+							$fdefault = $this->connection->DBDate($fdefault);
+						}
+					}
+					else
+					if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
+						$fdefault = trim($fdefault);
+					else if (strtolower($fdefault) != 'null')
+						$fdefault = $this->connection->qstr($fdefault);
+				}
+			}
+			$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
+			
+			// add index creation
+			if ($widespacing) $fname = str_pad($fname,24);
+			
+			 // check for field names appearing twice
+            if (array_key_exists($fid, $lines)) {
+            	 ADOConnection::outp("Field '$fname' defined twice");
+            }
+			
+			$lines[$fid] = $fname.' '.$ftype.$suffix;
+			
+			if ($fautoinc) $this->autoIncrement = true;
+		} // foreach $flds
+		
+		return array($lines,$pkey,$idxs);
+	}
+
+	/**
+		 GENERATE THE SIZE PART OF THE DATATYPE
+			$ftype is the actual type
+			$ty is the type defined originally in the DDL
+	*/
+	function _GetSize($ftype, $ty, $fsize, $fprec)
+	{
+		if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
+			$ftype .= "(".$fsize;
+			if (strlen($fprec)) $ftype .= ",".$fprec;
+			$ftype .= ')';
+		}
+		return $ftype;
+	}
+	
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{	
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+	
+		$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s .= '(' . $flds . ')';
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	function _DropAutoIncrement($tabname)
+	{
+		return false;
+	}
+	
+	function _TableSQL($tabname,$lines,$pkey,$tableoptions)
+	{
+		$sql = array();
+		
+		if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
+			$sql[] = sprintf($this->dropTable,$tabname);
+			if ($this->autoIncrement) {
+				$sInc = $this->_DropAutoIncrement($tabname);
+				if ($sInc) $sql[] = $sInc;
+			}
+			if ( isset ($tableoptions['DROP']) ) {
+				return $sql;
+			}
+		}
+		$s = "CREATE TABLE $tabname (\n";
+		$s .= implode(",\n", $lines);
+		if (sizeof($pkey)>0) {
+			$s .= ",\n                 PRIMARY KEY (";
+			$s .= implode(", ",$pkey).")";
+		}
+		if (isset($tableoptions['CONSTRAINTS'])) 
+			$s .= "\n".$tableoptions['CONSTRAINTS'];
+		
+		if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
+			$s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
+		
+		$s .= "\n)";
+		if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	/**
+		GENERATE TRIGGERS IF NEEDED
+		used when table has auto-incrementing field that is emulated using triggers
+	*/
+	function _Triggers($tabname,$taboptions)
+	{
+		return array();
+	}
+	
+	/**
+		Sanitize options, so that array elements with no keys are promoted to keys
+	*/
+	function _Options($opts)
+	{
+		if (!is_array($opts)) return array();
+		$newopts = array();
+		foreach($opts as $k => $v) {
+			if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
+			else $newopts[strtoupper($k)] = $v;
+		}
+		return $newopts;
+	}
+	
+	
+	function _getSizePrec($size)
+	{
+		$fsize = false;
+		$fprec = false;
+		$dotat = strpos($size,'.');
+		if ($dotat === false) $dotat = strpos($size,',');
+		if ($dotat === false) $fsize = $size;
+		else {
+			$fsize = substr($size,0,$dotat);
+			$fprec = substr($size,$dotat+1);
+		}
+		return array($fsize, $fprec);
+	}
+	
+	/**
+	"Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
+	
+	This function changes/adds new fields to your table. You don't
+	have to know if the col is new or not. It will check on its own.
+	*/
+	function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false, $forceAlter = false) // GS Fix for constraint impl - forceAlter
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+		if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
+		
+		// check table exists
+		$save_handler = $this->connection->raiseErrorFn;
+		$this->connection->raiseErrorFn = '';
+		$cols = $this->MetaColumns($tablename);
+		$this->connection->raiseErrorFn = $save_handler;
+		
+		if (isset($savem)) $this->connection->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if ( $forceAlter == false && empty($cols)) { // GS Fix for constraint impl
+			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
+		}
+		
+		if (is_array($flds)) {
+		// Cycle through the update fields, comparing
+		// existing fields to fields to update.
+		// if the Metatype and size is exactly the
+		// same, ignore - by Mark Newham
+			$holdflds = array();
+			foreach($flds as $k=>$v) {
+				if ( isset($cols[$k]) && is_object($cols[$k]) ) {
+					// If already not allowing nulls, then don't change
+					$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 (isset($c->scale)) $sc = $c->scale;
+					else $sc = 99; // always force change if scale not known.
+					
+					if ($sc == -1) $sc = false;
+					list($fsize, $fprec) = $this->_getSizePrec($v['SIZE']);
+
+					if ($ml == -1) $ml = '';
+					if ($mt == 'X') $ml = $v['SIZE'];
+					if (($mt != $v['TYPE']) || ($ml != $fsize || $sc != $fprec) || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
+						$holdflds[$k] = $v;
+					}
+				} else {
+					$holdflds[$k] = $v;
+				}		
+			}
+			$flds = $holdflds;
+		}
+	
+
+		// already exists, alter table instead
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
+		$sql = array();
+
+		foreach ( $lines as $id => $v ) {
+			if ( isset($cols[$id]) && is_object($cols[$id]) ) {
+			
+				$flds = Lens_ParseArgs($v,',');
+				
+				//  We are trying to change the size of the field, if not allowed, simply ignore the request.
+				// $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;
+			} else {
+				$sql[] = $alter . $this->addCol . ' ' . $v;
+			}
+		}
+		
+		if ($dropOldFlds) {
+			foreach ( $cols as $id => $v )
+			    if ( !isset($lines[$id]) ) 
+					$sql[] = $alter . $this->dropCol . ' ' . $v->name;
+		}
+
+		// GS Fix for constraint impl -- start		
+        if($forceAlter == false) return $sql;		
+        $sqlarray = array();		
+        $alter .= implode(",\n", $sql);		
+        if (sizeof($pkey)>0) {
+            $alter .= ",\n PRIMARY KEY (";
+			$alter .= implode(", ",$pkey).")";
+        }
+        if (isset($tableoptions['CONSTRAINTS'])) $alter .= "\n".$tableoptions['CONSTRAINTS'];
+        if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) $alter .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
+        if (isset($tableoptions[$this->upperName])) $alter .= $tableoptions[$this->upperName];
+        $sqlarray[] = $alter;
+        $taboptions = $this->_Options($tableoptions);
+        $tsql = $this->_Triggers($this->TableName($tablename),$taboptions);
+        foreach($tsql as $s) $sqlarray[] = $s;
+        // GS Fix for constraint impl -- end
+        return $sqlarray;
+    }
+} // class
+?>
\ No newline at end of file
Index: adodb-error.inc.php
===================================================================
--- adodb-error.inc.php	(revision 13354)
+++ adodb-error.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 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 @@
 {
 	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);
Index: adodb-errorhandler.inc.php
===================================================================
--- adodb-errorhandler.inc.php	(revision 13354)
+++ adodb-errorhandler.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @version V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.11 5 May 2010   (c) 2000-2010 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.
Index: adodb-errorpear.inc.php
===================================================================
--- adodb-errorpear.inc.php	(revision 13354)
+++ adodb-errorpear.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 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 @@
 * 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;
 
Index: adodb-exceptions.inc.php
===================================================================
--- adodb-exceptions.inc.php	(revision 13354)
+++ adodb-exceptions.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
- * @version V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.11 5 May 2010   (c) 2000-2010 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.
Index: adodb-iterator.inc.php
===================================================================
--- adodb-iterator.inc.php	(revision 13354)
+++ adodb-iterator.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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);
-	}
-} 
-
-
 ?>
\ No newline at end of file
Index: adodb-lib.inc.php
===================================================================
--- adodb-lib.inc.php	(revision 13354)
+++ adodb-lib.inc.php	(working copy)
@@ -1,5 +1,8 @@
 <?php
 
+
+
+
 // security - hide paths
 if (!defined('ADODB_DIR')) die();
 
@@ -7,7 +10,7 @@
 $ADODB_INCLUDED_LIB = 1;
 
 /* 
- @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim\@natsoft.com.my). All rights reserved.
+ @version V5.06 16 Oct 2008  (c) 2000-2010 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,7 +19,106 @@
   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
+	$types = array();
+	if ($probe > sizeof($array)) $max = sizeof($array);
+	else $max = $probe;
+	
+	
+	for ($j=0;$j < $max; $j++) {
+		$row = $array[$j];
+		if (!$row) break;
+		$i = -1;
+		foreach($row as $v) {
+			$i += 1;
+
+			if (isset($types[$i]) && $types[$i]=='C') continue;
+			
+			//print " ($i ".$types[$i]. "$v) ";
+			$v = trim($v);
+			
+			if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) {
+				$types[$i] = 'C'; // once C, always C
+				
+				continue;
+			}
+			if ($j == 0) { 
+			// If empty string, we presume is character
+			// test for integer for 1st row only
+			// after that it is up to testing other rows to prove
+			// that it is not an integer
+				if (strlen($v) == 0) $types[$i] = 'C';
+				if (strpos($v,'.') !== false) $types[$i] = 'N';
+				else  $types[$i] = 'I';
+				continue;
+			}
+			
+			if (strpos($v,'.') !== false) $types[$i] = 'N';
+			
+		}
+	}
+	
+}
+
+function  adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
+{
+	$oldX = sizeof(reset($arr));
+	$oldY = sizeof($arr);	
+	
+	if ($hdr) {
+		$startx = 1;
+		$hdr = array('Fields');
+		for ($y = 0; $y < $oldY; $y++) {
+			$hdr[] = $arr[$y][0];
+		}
+	} else
+		$startx = 0;
+
+	for ($x = $startx; $x < $oldX; $x++) {
+		if ($fobjs) {
+			$o = $fobjs[$x];
+			$newarr[] = array($o->name);
+		} else
+			$newarr[] = array();
+			
+		for ($y = 0; $y < $oldY; $y++) {
+			$newarr[$x-$startx][] = $arr[$y][$x];
+		}
+	}
+}
+
 // Force key to upper. 
 // See also http://www.php.net/manual/en/function.array-change-key-case.php
 function _array_change_key_case($an_array)
@@ -42,7 +144,10 @@
 			$keyCol = array($keyCol);
 		}
 		foreach($fieldArray as $k => $v) {
-			if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=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;
 			}
@@ -54,7 +159,7 @@
 			} else
 				$uSet .= ",$k=$v";
 		}
-		 
+		
 		$where = false;
 		foreach ($keyCol as $v) {
 			if (isset($fieldArray[$v])) {
@@ -156,7 +261,7 @@
 		if ($fieldsize > 2) {
             $group = rtrim($zthis->fields[2]);
         }
- 
+/* 
         if ($optgroup != $group) {
             $optgroup = $group;
             if ($firstgroup) {
@@ -167,7 +272,7 @@
                 $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
             }
 		}
-	
+*/
 		if ($hasvalue) 
 			$value = " value='".htmlspecialchars($zval2)."'";
 		
@@ -297,49 +402,38 @@
 {
 	$qryRecs = 0;
 	
-	 if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || 
+	 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)  {
-			
-			$info = $zthis->ServerInfo();
-			if (substr($info['version'],0,3) >= 7.1) { // good till version 999
-				$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql);
-				$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
-			}
+		} 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
@@ -357,13 +451,17 @@
 	
 	// 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);
-	if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
-	
+	if ($secs2cache) {
+		$rstest = $zthis->CacheExecute($secs2cache,$rewritesql,$inputarr);
+		if (!$rstest) $rstest = $zthis->CacheExecute($secs2cache,$sql,$inputarr);
+	} else {
+		$rstest = $zthis->Execute($rewritesql,$inputarr);
+		if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
+	}
 	if ($rstest) {
 	  		$qryRecs = $rstest->RecordCount();
 		if ($qryRecs == -1) { 
@@ -383,7 +481,6 @@
 		$rstest->Close();
 		if ($qryRecs == -1) return 0;
 	}
-	
 	return $qryRecs;
 }
 
@@ -396,7 +493,7 @@
 	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;
@@ -432,9 +529,9 @@
 	// 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
@@ -450,7 +547,7 @@
 }
 
 // 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;
@@ -466,16 +563,16 @@
 	// 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();
 	}
@@ -487,8 +584,8 @@
 	
 	// 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) {
@@ -502,6 +599,8 @@
 
 function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2)
 {
+	global $ADODB_QUOTE_FIELDNAMES;
+
 		if (!$rs) {
 			printf(ADODB_BAD_RS,'GetUpdateSQL');
 			return false;
@@ -548,7 +647,7 @@
 						$type = 'C';
 					}
 					
-					if (strpos($upperfname,' ') !== false)
+					if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
 						$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
 					else
 						$fnameq = $upperfname;
@@ -558,7 +657,7 @@
                 //********************************************************//
                 if (is_null($arrFields[$upperfname])
 					|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
-                    || $arrFields[$upperfname] === 'null'
+                    || $arrFields[$upperfname] === $zthis->null2null
                     )
                 {
                     switch ($force) {
@@ -580,7 +679,7 @@
 						default:
                         case 3:
                             //Set the value that was given in array, so you can give both null and empty values
-                            if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') {
+                            if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
                                 $setFields .= $field->name . " = null, ";
                             } else {
                                 $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
@@ -662,6 +761,7 @@
 static $cacheRS = false;
 static $cacheSig = 0;
 static $cacheCols;
+	global $ADODB_QUOTE_FIELDNAMES;
 
 	$tableName = '';
 	$values = '';
@@ -680,10 +780,10 @@
 		//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;
@@ -691,7 +791,7 @@
 		}
 	} 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);
@@ -699,7 +799,7 @@
 			$cacheCols = $columns;
 			$rs->insertSig = $cacheSig++;
 		}
-		$recordSet =& $rs;
+		$recordSet = $rs;
 	
 	} else {
 		printf(ADODB_BAD_RS,'GetInsertSQL');
@@ -711,7 +811,7 @@
 		$upperfname = strtoupper($field->name);
 		if (adodb_key_exists($upperfname,$arrFields,$force)) {
 			$bad = false;
-			if (strpos($upperfname,' ') !== false)
+			if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
 				$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
 			else
 				$fnameq = $upperfname;
@@ -721,7 +821,7 @@
             /********************************************************/
             if (is_null($arrFields[$upperfname])
                 || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
-                || $arrFields[$upperfname] === 'null'
+                || $arrFields[$upperfname] === $zthis->null2null
 				)
                {
                     switch ($force) {
@@ -743,7 +843,7 @@
 						default:
                         case 3:
                             //Set the value that was given in array, so you can give both null and empty values
-							if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') { 
+							if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { 
 								$values  .= "null, ";
 							} else {
                         		$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
@@ -904,9 +1004,20 @@
 		case "T":
 			$val = $zthis->DBTimeStamp($arrFields[$fname]);
 			break;
+			
+		case "N":
+		    $val = $arrFields[$fname];
+			if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
+		    break;
 
+		case "I":
+		case "R":
+		    $val = $arrFields[$fname];
+			if (!is_numeric($val)) $val = (integer) $val;
+		    break;
+
 		default:
-			$val = $arrFields[$fname];
+			$val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic sql injection defence
 			if (empty($val)) $val = '0';
 			break;
 	}
@@ -926,7 +1037,8 @@
 	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 ]";
 	}
@@ -945,11 +1057,13 @@
 			$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);
@@ -960,10 +1074,21 @@
 	*/
 	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());
 	}
 	
@@ -972,11 +1097,13 @@
 }
 
 # 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;
@@ -1007,7 +1134,7 @@
 			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;
 			}
Index: adodb-memcache.lib.inc.php
===================================================================
--- adodb-memcache.lib.inc.php	(revision 0)
+++ adodb-memcache.lib.inc.php	(revision 0)
@@ -0,0 +1,190 @@
+<?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-2010 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($this->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;
+		}
+	}
+
+?>
\ No newline at end of file

Property changes on: adodb-memcache.lib.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: adodb-pager.inc.php
===================================================================
--- adodb-pager.inc.php	(revision 13354)
+++ adodb-pager.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-	V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+	V5.11 5 May 2010   (c) 2000-2010 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 @@
 	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 @@
 		$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;
Index: adodb-pear.inc.php
===================================================================
--- adodb-pear.inc.php	(revision 13354)
+++ adodb-pear.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 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 @@
 	 * 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 @@
 	 * @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 @@
 			 @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 @@
 	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');
 	}
Index: adodb-perf.inc.php
===================================================================
--- adodb-perf.inc.php	(revision 13354)
+++ adodb-perf.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 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()
 {
@@ -53,39 +57,43 @@
 	return number_format($n, $prec, '.', '');
 }
 
-/* return microtime value as a float */
+/* obsolete: return microtime value as a float. Retained for backward compat */
 function adodb_microtime()
 {
-	$t = microtime();
-	$t = explode(' ',$t);
-	return (float)$t[1]+ (float)$t[0];
+	return microtime(true);
 }
 
 /* sql code timing */
-function& adodb_log_sql(&$conn,$sql,$inputarr)
+function adodb_log_sql(&$connx,$sql,$inputarr)
 {
-	
     $perf_table = adodb_perf::table();
-	$conn->fnExecute = false;
-	$t0 = microtime();
-	$rs =& $conn->Execute($sql,$inputarr);
-	$t1 = microtime();
+	$connx->fnExecute = false;
+	$a0 = microtime(true);
+	$rs = $connx->Execute($sql,$inputarr);
+	$a1 = microtime(true);
 
-	if (!empty($conn->_logsql)) {
+	if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
+	global $ADODB_LOG_CONN;
+	
+		if (!empty($ADODB_LOG_CONN)) {
+			$conn = $ADODB_LOG_CONN;
+			if ($conn->databaseType != $connx->databaseType)
+				$prefix = '/*dbx='.$connx->databaseType .'*/ ';
+			else
+				$prefix = '';
+		} else {
+			$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) {
-			$errM = $conn->ErrorMsg();
-			$errN = $conn->ErrorNo();
+			$errM = $connx->ErrorMsg();
+			$errN = $connx->ErrorNo();
 			$conn->lastInsID = 0;
 			$tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
 		} else {
@@ -101,9 +109,9 @@
 		}
 		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);
@@ -126,6 +134,7 @@
 		}
 		
 		if (is_array($sql)) $sql = $sql[0];
+		if ($prefix) $sql = $prefix.$sql;
 		$arr = array('b'=>strlen($sql).'.'.crc32($sql),
 					'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
 		//var_dump($arr);
@@ -136,7 +145,7 @@
 		if (empty($d)) $d = date("'Y-m-d H:i:s'");
 		if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
 			$isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
-		} else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || $dbT == 'odbtp') {
+		} else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || strncmp($dbT,'odbtp',4)==0) {
 			$timer = $arr['f'];
 			if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
 
@@ -149,10 +158,16 @@
 			if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
 			$arr = false;
 		} else {
+			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) {
@@ -160,7 +175,7 @@
 		} 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 {
@@ -177,10 +192,10 @@
 				$conn->_logsql = false;
 			}
 		}
-		$conn->_errorMsg = $errM;
-		$conn->_errorCode = $errN;
+		$connx->_errorMsg = $errM;
+		$connx->_errorCode = $errN;
 	} 
-	$conn->fnExecute = 'adodb_log_sql';
+	$connx->fnExecute = 'adodb_log_sql';
 	return $rs;
 }
 
@@ -214,7 +229,7 @@
 	var $maxLength = 2000;
 	
     // Sets the tablename to be used            
-    function table($newtable = false)
+    static function table($newtable = false)
     {
         static $_table;
 
@@ -241,7 +256,7 @@
 
 */
 		// 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;
@@ -249,14 +264,33 @@
 			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;
 			
-			$info[0] = $c->PercentProcessorTime;
-			$info[1] = 0;
-			$info[2] = 0;
-			$info[3] = $c->TimeStamp_Sys100NS;
-			//print_r($info);
+			$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;
+			}
+			
 			return $info;
 		}
 		
@@ -319,27 +353,26 @@
 	{
 		$info = $this->_CPULoad();
 		if (!$info) return false;
+		
+		if (strncmp(PHP_OS,'WIN',3)==0) {
+			return (integer) $info[0];
+		}else {
+			if (empty($this->_lastLoad)) {
+				sleep(1);
+				$this->_lastLoad = $info;
+				$info = $this->_CPULoad();
+			}
 			
-		if (empty($this->_lastLoad)) {
-			sleep(1);
+			$last = $this->_lastLoad;
 			$this->_lastLoad = $info;
-			$info = $this->_CPULoad();
-		}
+			
+			$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);
 		
-		$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);
-		}else {
 			$total=$d_user+$d_nice+$d_system+$d_idle;
 			if ($total<1) $total=1;
 			return 100*($d_user+$d_nice+$d_system)/$total; 
@@ -395,7 +428,7 @@
 		$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);
@@ -429,7 +462,7 @@
 			$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')
@@ -508,7 +541,7 @@
 			$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')
@@ -557,7 +590,7 @@
 	/*
 		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');
@@ -627,6 +660,11 @@
 		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
 	/***********************************************************************************************/
@@ -634,6 +672,7 @@
 	
 	function UI($pollsecs=5)
 	{
+	global $ADODB_LOG_CONN;
 	
     $perf_table = adodb_perf::table();
 	$conn = $this->conn;
@@ -646,7 +685,7 @@
 	$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);
 	
@@ -675,6 +714,8 @@
 	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>
@@ -689,13 +730,16 @@
 	 	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>";
@@ -730,13 +774,13 @@
 		//$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);
@@ -862,7 +906,6 @@
 		
 		$table = $this->table();
 		$sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
-		
 		$savelog = $this->conn->LogSQL(false);
 		$ok = $this->conn->Execute($sql);
 		$this->conn->LogSQL($savelog);
@@ -873,7 +916,7 @@
 	{
 	
 		
-		$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'];
Index: adodb-php4.inc.php
===================================================================
--- adodb-php4.inc.php	(revision 13354)
+++ adodb-php4.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
Index: adodb-time.inc.php
===================================================================
--- adodb-time.inc.php	(revision 13354)
+++ adodb-time.inc.php	(working copy)
@@ -241,6 +241,24 @@
 
 
 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,8 +386,10 @@
 /*
 	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 
 	also with Linux, RH 7.3 and later!
@@ -387,10 +407,13 @@
 
 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 @@
 	
 	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 @@
 	// 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 @@
 	
 	// 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 @@
 	return $y;
 }
 
+function adodb_get_gmt_diff_ts($ts) 
+{
+	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
+ get local time zone offset from GMT. Does not handle historical timezones before 1970.
 */
-function adodb_get_gmt_diff() 
+function adodb_get_gmt_diff($y,$m,$d) 
 {
-static $TZ;
-	if (isset($TZ)) return $TZ;
+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 @@
 {
 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 @@
 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,7 +992,23 @@
 		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)
 {
 	return adodb_date($fmt,$d,true);
@@ -958,6 +1039,7 @@
 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,17 @@
 	*/
 	for ($i=0; $i < $max; $i++) {
 		switch($fmt[$i]) {
-		case 'T': $dates .= date('T');break;
+		case 'e':
+			$dates .= date('e');
+			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 +1100,11 @@
 			
 			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 +1131,11 @@
 			
 		// 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 +1217,21 @@
 		
 		// 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 = (1970 < $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 +1248,7 @@
 	$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) {
Index: adodb-xmlschema.inc.php
===================================================================
--- adodb-xmlschema.inc.php	(revision 13354)
+++ adodb-xmlschema.inc.php	(working copy)
@@ -1,2227 +1,2229 @@
-<?php
-// Copyright (c) 2004 ars Cognita Inc., 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. 
-*******************************************************************************/
-/**
- * xmlschema is a class that allows the user to quickly and easily
- * build a database on any ADOdb-supported platform using a simple
- * XML schema.
- *
- * Last Editor: $Author: jlim $
- * @author Richard Tango-Lowy & Dan Cech
- * @version $Revision: 1.12 $
- *
- * @package axmls
- * @tutorial getting_started.pkg
- */
- 
-function _file_get_contents($file) 
-{
- 	if (function_exists('file_get_contents')) return file_get_contents($file);
-	
-	$f = fopen($file,'r');
-	if (!$f) return '';
-	$t = '';
-	
-	while ($s = fread($f,100000)) $t .= $s;
-	fclose($f);
-	return $t;
-}
-
-
-/**
-* Debug on or off
-*/
-if( !defined( 'XMLS_DEBUG' ) ) {
-	define( 'XMLS_DEBUG', FALSE );
-}
-
-/**
-* Default prefix key
-*/
-if( !defined( 'XMLS_PREFIX' ) ) {
-	define( 'XMLS_PREFIX', '%%P' );
-}
-
-/**
-* Maximum length allowed for object prefix
-*/
-if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
-	define( 'XMLS_PREFIX_MAXLEN', 10 );
-}
-
-/**
-* Execute SQL inline as it is generated
-*/
-if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
-	define( 'XMLS_EXECUTE_INLINE', FALSE );
-}
-
-/**
-* Continue SQL Execution if an error occurs?
-*/
-if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
-	define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
-}
-
-/**
-* Current Schema Version
-*/
-if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
-	define( 'XMLS_SCHEMA_VERSION', '0.2' );
-}
-
-/**
-* Default Schema Version.  Used for Schemas without an explicit version set.
-*/
-if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
-	define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
-}
-
-/**
-* Default Schema Version.  Used for Schemas without an explicit version set.
-*/
-if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
-	define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
-}
-
-/**
-* Include the main ADODB library
-*/
-if( !defined( '_ADODB_LAYER' ) ) {
-	require( 'adodb.inc.php' );
-	require( 'adodb-datadict.inc.php' );
-}
-
-/**
-* Abstract DB Object. This class provides basic methods for database objects, such
-* as tables and indexes.
-*
-* @package axmls
-* @access private
-*/
-class dbObject {
-	
-	/**
-	* var object Parent
-	*/
-	var $parent;
-	
-	/**
-	* var string current element
-	*/
-	var $currentElement;
-	
-	/**
-	* NOP
-	*/
-	function dbObject( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
-	}
-	
-	/**
-	* XML Callback to process start elements
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*
-	* @access private
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-		
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	*/
-	function _tag_close( &$parser, $tag ) {
-		
-	}
-	
-	function create() {
-		return array();
-	}
-	
-	/**
-	* Destroys the object
-	*/
-	function destroy() {
-		unset( $this );
-	}
-	
-	/**
-	* Checks whether the specified RDBMS is supported by the current
-	* database object or its ranking ancestor.
-	*
-	* @param string $platform RDBMS platform name (from ADODB platform list).
-	* @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
-	*/
-	function supportedPlatform( $platform = NULL ) {
-		return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
-	}
-	
-	/**
-	* Returns the prefix set by the ranking ancestor of the database object.
-	*
-	* @param string $name Prefix string.
-	* @return string Prefix.
-	*/
-	function prefix( $name = '' ) {
-		return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
-	}
-	
-	/**
-	* Extracts a field ID from the specified field.
-	*
-	* @param string $field Field.
-	* @return string Field ID.
-	*/
-	function FieldID( $field ) {
-		return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
-	}
-}
-
-/**
-* Creates a table object in ADOdb's datadict format
-*
-* This class stores information about a database table. As charactaristics
-* of the table are loaded from the external source, methods and properties
-* of this class are used to build up the table description in ADOdb's
-* datadict format.
-*
-* @package axmls
-* @access private
-*/
-class dbTable extends dbObject {
-	
-	/**
-	* @var string Table name
-	*/
-	var $name;
-	
-	/**
-	* @var array Field specifier: Meta-information about each field
-	*/
-	var $fields = array();
-	
-	/**
-	* @var array List of table indexes.
-	*/
-	var $indexes = array();
-	
-	/**
-	* @var array Table options: Table-level options
-	*/
-	var $opts = array();
-	
-	/**
-	* @var string Field index: Keeps track of which field is currently being processed
-	*/
-	var $current_field;
-	
-	/**
-	* @var boolean Mark table for destruction
-	* @access private
-	*/
-	var $drop_table;
-	
-	/**
-	* @var boolean Mark field for destruction (not yet implemented)
-	* @access private
-	*/
-	var $drop_field = array();
-	var $alter; // GS Fix for constraint impl
-	
-	/**
-	* Iniitializes a new table object.
-	*
-	* @param string $prefix DB Object prefix
-	* @param array $attributes Array of table attributes.
-	*/
-	function dbTable( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
-		$this->name = $this->prefix($attributes['NAME']);
-		// GS Fix for constraint impl
-		if(isset($attributes['ALTER']))
-		{
-			$this->alter = $attributes['ALTER'];
-		}
-	}
-	
-	/**
-	* XML Callback to process start elements. Elements currently 
-	* processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. 
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		$this->currentElement = strtoupper( $tag );
-		
-		switch( $this->currentElement ) {
-			case 'INDEX':
-				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
-					xml_set_object( $parser, $this->addIndex( $attributes ) );
-				}
-				break;
-			case 'DATA':
-				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
-					xml_set_object( $parser, $this->addData( $attributes ) );
-				}
-				break;
-			case 'DROP':
-				$this->drop();
-				break;
-			case 'FIELD':
-				// Add a field
-				$fieldName = $attributes['NAME'];
-				$fieldType = $attributes['TYPE'];
-				$fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
-				$fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
-				
-				$this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
-				break;
-			case 'KEY':
-			case 'NOTNULL':
-			case 'AUTOINCREMENT':
-				// Add a field option
-				$this->addFieldOpt( $this->current_field, $this->currentElement );
-				break;
-			case 'DEFAULT':
-				// Add a field option to the table object
-				
-				// Work around ADOdb datadict issue that misinterprets empty strings.
-				if( $attributes['VALUE'] == '' ) {
-					$attributes['VALUE'] = " '' ";
-				}
-				
-				$this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
-				break;
-			case 'DEFDATE':
-			case 'DEFTIMESTAMP':
-				// Add a field option to the table object
-				$this->addFieldOpt( $this->current_field, $this->currentElement );
-				break;
-			default:
-				// print_r( array( $tag, $attributes ) );
-		}
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*
-	* @access private
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-		switch( $this->currentElement ) {
-			// Table constraint
-			case 'CONSTRAINT':
-				if( isset( $this->current_field ) ) {
-					$this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
-				} else {
-					$this->addTableOpt('CONSTRAINTS', $cdata ); // GS Fix for constraint impl
-				}
-				break;
-			// Table option
-			case 'OPT':
-				$this->addTableOpt('mysql', $cdata ); // GS Fix for constraint impl
-				break;
-			default:
-				
-		}
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	*/
-	function _tag_close( &$parser, $tag ) {
-		$this->currentElement = '';
-		
-		switch( strtoupper( $tag ) ) {
-			case 'TABLE':
-				$this->parent->addSQL( $this->create( $this->parent ) );
-				xml_set_object( $parser, $this->parent );
-				$this->destroy();
-				break;
-			case 'FIELD':
-				unset($this->current_field);
-				break;
-
-		}
-	}
-	
-	/**
-	* Adds an index to a table object
-	*
-	* @param array $attributes Index attributes
-	* @return object dbIndex object
-	*/
-	function &addIndex( $attributes ) {
-		$name = strtoupper( $attributes['NAME'] );
-		$this->indexes[$name] =& new dbIndex( $this, $attributes );
-		return $this->indexes[$name];
-	}
-	
-	/**
-	* Adds data to a table object
-	*
-	* @param array $attributes Data attributes
-	* @return object dbData object
-	*/
-	function &addData( $attributes ) {
-		if( !isset( $this->data ) ) {
-			$this->data =& new dbData( $this, $attributes );
-		}
-		return $this->data;
-	}
-	
-	/**
-	* Adds a field to a table object
-	*
-	* $name is the name of the table to which the field should be added. 
-	* $type is an ADODB datadict field type. The following field types
-	* are supported as of ADODB 3.40:
-	* 	- C:  varchar
-	*	- X:  CLOB (character large object) or largest varchar size
-	*	   if CLOB is not supported
-	*	- C2: Multibyte varchar
-	*	- X2: Multibyte CLOB
-	*	- B:  BLOB (binary large object)
-	*	- D:  Date (some databases do not support this, and we return a datetime type)
-	*	- T:  Datetime or Timestamp
-	*	- L:  Integer field suitable for storing booleans (0 or 1)
-	*	- I:  Integer (mapped to I4)
-	*	- I1: 1-byte integer
-	*	- I2: 2-byte integer
-	*	- I4: 4-byte integer
-	*	- I8: 8-byte integer
-	*	- F:  Floating point number
-	*	- N:  Numeric or decimal number
-	*
-	* @param string $name Name of the table to which the field will be added.
-	* @param string $type	ADODB datadict field type.
-	* @param string $size	Field size
-	* @param array $opts	Field options array
-	* @return array Field specifier array
-	*/
-	function addField( $name, $type, $size = NULL, $opts = NULL ) {
-		$field_id = $this->FieldID( $name );
-		
-		// Set the field index so we know where we are
-		$this->current_field = $field_id;
-		
-		// Set the field name (required)
-		$this->fields[$field_id]['NAME'] = $name;
-		
-		// Set the field type (required)
-		$this->fields[$field_id]['TYPE'] = $type;
-		
-		// Set the field size (optional)
-		if( isset( $size ) ) {
-			$this->fields[$field_id]['SIZE'] = $size;
-		}
-		
-		// Set the field options
-		if( isset( $opts ) ) {
-			$this->fields[$field_id]['OPTS'][] = $opts;
-		}
-	}
-	
-	/**
-	* Adds a field option to the current field specifier
-	*
-	* This method adds a field option allowed by the ADOdb datadict 
-	* and appends it to the given field.
-	*
-	* @param string $field	Field name
-	* @param string $opt ADOdb field option
-	* @param mixed $value Field option value
-	* @return array Field specifier array
-	*/
-	function addFieldOpt( $field, $opt, $value = NULL ) {
-		if( !isset( $value ) ) {
-			$this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
-		// Add the option and value
-		} else {
-			$this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
-		}
-	}
-	
-	/**
-	* Adds an option to the table
-	*
-	* This method takes a comma-separated list of table-level options
-	* and appends them to the table object.
-	*
-	* @param string $opt Table option
-	* @return array Options
-	*/
-	function addTableOpt($key, $opt ) { // GS Fix for constraint impl
-		//$this->opts[] = $opt;
-		$this->opts[$key] = $opt;
-		
-		return $this->opts;
-	}
-	
-	/**
-	* Generates the SQL that will create the table in the database
-	*
-	* @param object $xmls adoSchema object
-	* @return array Array containing table creation SQL
-	*/
-	function create( &$xmls ) {
-		$sql = array();
-		
-		// drop any existing indexes
-		if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
-			foreach( $legacy_indexes as $index => $index_details ) {
-				$sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
-			}
-		}
-		
-		// remove fields to be dropped from table object
-		foreach( $this->drop_field as $field ) {
-			unset( $this->fields[$field] );
-		}
-		
-		// if table exists
-		if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
-			// drop table
-			if( $this->drop_table ) {
-				$sql[] = $xmls->dict->DropTableSQL( $this->name );
-				
-				return $sql;
-			}
-			
-			// drop any existing fields not in schema
-			foreach( $legacy_fields as $field_id => $field ) {
-				if( !isset( $this->fields[$field_id] ) ) {
-					$sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' );
-				}
-			}
-		// if table doesn't exist
-		} else {
-			if( $this->drop_table ) {
-				return $sql;
-			}
-			
-			$legacy_fields = array();
-		}
-		
-		// Loop through the field specifier array, building the associative array for the field options
-		$fldarray = array();
-		
-		foreach( $this->fields as $field_id => $finfo ) {
-			// Set an empty size if it isn't supplied
-			if( !isset( $finfo['SIZE'] ) ) {
-				$finfo['SIZE'] = '';
-			}
-			
-			// Initialize the field array with the type and size
-			$fldarray[$field_id] = array(
-				'NAME' => $finfo['NAME'],
-				'TYPE' => $finfo['TYPE'],
-				'SIZE' => $finfo['SIZE']
-			);
-			
-			// Loop through the options array and add the field options. 
-			if( isset( $finfo['OPTS'] ) ) {
-				foreach( $finfo['OPTS'] as $opt ) {
-					// Option has an argument.
-					if( is_array( $opt ) ) {
-						$key = key( $opt );
-						$value = $opt[key( $opt )];
-						@$fldarray[$field_id][$key] .= $value;
-					// Option doesn't have arguments
-					} else {
-						$fldarray[$field_id][$opt] = $opt;
-					}
-				}
-			}
-		}		
-		if( empty( $legacy_fields ) && !isset($this->alter)) { // GS Fix for constraint impl
-			// Create the new table
-			$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
-			logMsg( end( $sql ), 'Generated CreateTableSQL' );
-		} else {
-			// Upgrade an existing table
-			logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
-			switch( $xmls->upgrade ) {
-				// Use ChangeTableSQL
-				case 'ALTER':
-					logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
-					$sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts, $this->alter ); // GS Fix for constraint impl
-					break;
-				case 'REPLACE':
-					logMsg( 'Doing upgrade REPLACE (testing)' );
-					$sql[] = $xmls->dict->DropTableSQL( $this->name );
-					$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
-					break;
-				// ignore table
-				default:
-					return array();
-			}
-		}
-		
-		foreach( $this->indexes as $index ) {
-			$sql[] = $index->create( $xmls );
-		}
-		
-		if( isset( $this->data ) ) {
-			$sql[] = $this->data->create( $xmls );
-		}
-		
-		return $sql;
-	}
-	
-	/**
-	* Marks a field or table for destruction
-	*/
-	function drop() {
-		if( isset( $this->current_field ) ) {
-			// Drop the current field
-			logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
-			// $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
-			$this->drop_field[$this->current_field] = $this->current_field;
-		} else {
-			// Drop the current table
-			logMsg( "Dropping table '{$this->name}'" );
-			// $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
-			$this->drop_table = TRUE;
-		}
-	}
-}
-
-/**
-* Creates an index object in ADOdb's datadict format
-*
-* This class stores information about a database index. As charactaristics
-* of the index are loaded from the external source, methods and properties
-* of this class are used to build up the index description in ADOdb's
-* datadict format.
-*
-* @package axmls
-* @access private
-*/
-class dbIndex extends dbObject {
-	
-	/**
-	* @var string	Index name
-	*/
-	var $name;
-	
-	/**
-	* @var array	Index options: Index-level options
-	*/
-	var $opts = array();
-	
-	/**
-	* @var array	Indexed fields: Table columns included in this index
-	*/
-	var $columns = array();
-	
-	/**
-	* @var boolean Mark index for destruction
-	* @access private
-	*/
-	var $drop = FALSE;
-	
-	/**
-	* Initializes the new dbIndex object.
-	*
-	* @param object $parent Parent object
-	* @param array $attributes Attributes
-	*
-	* @internal
-	*/
-	function dbIndex( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
-		
-		$this->name = $this->prefix ($attributes['NAME']);
-	}
-	
-	/**
-	* XML Callback to process start elements
-	*
-	* Processes XML opening tags. 
-	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		$this->currentElement = strtoupper( $tag );
-		
-		switch( $this->currentElement ) {
-			case 'DROP':
-				$this->drop();
-				break;
-			case 'CLUSTERED':
-			case 'BITMAP':
-			case 'UNIQUE':
-			case 'FULLTEXT':
-			case 'HASH':
-				// Add index Option
-				$this->addIndexOpt( $this->currentElement );
-				break;
-			default:
-				// print_r( array( $tag, $attributes ) );
-		}
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*
-	* Processes XML cdata.
-	*
-	* @access private
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-		switch( $this->currentElement ) {
-			// Index field name
-			case 'COL':
-				$this->addField( $cdata );
-				break;
-			default:
-				
-		}
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	*/
-	function _tag_close( &$parser, $tag ) {
-		$this->currentElement = '';
-		
-		switch( strtoupper( $tag ) ) {
-			case 'INDEX':
-				xml_set_object( $parser, $this->parent );
-				break;
-		}
-	}
-	
-	/**
-	* Adds a field to the index
-	*
-	* @param string $name Field name
-	* @return string Field list
-	*/
-	function addField( $name ) {
-		$this->columns[$this->FieldID( $name )] = $name;
-		
-		// Return the field list
-		return $this->columns;
-	}
-	
-	/**
-	* Adds options to the index
-	*
-	* @param string $opt Comma-separated list of index options.
-	* @return string Option list
-	*/
-	function addIndexOpt( $opt ) {
-		$this->opts[] = $opt;
-		
-		// Return the options list
-		return $this->opts;
-	}
-	
-	/**
-	* Generates the SQL that will create the index in the database
-	*
-	* @param object $xmls adoSchema object
-	* @return array Array containing index creation SQL
-	*/
-	function create( &$xmls ) {
-		if( $this->drop ) {
-			return NULL;
-		}
-		
-		// eliminate any columns that aren't in the table
-		foreach( $this->columns as $id => $col ) {
-			if( !isset( $this->parent->fields[$id] ) ) {
-				unset( $this->columns[$id] );
-			}
-		}
-		
-		return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
-	}
-	
-	/**
-	* Marks an index for destruction
-	*/
-	function drop() {
-		$this->drop = TRUE;
-	}
-}
-
-/**
-* Creates a data object in ADOdb's datadict format
-*
-* This class stores information about table data.
-*
-* @package axmls
-* @access private
-*/
-class dbData extends dbObject {
-	
-	var $data = array();
-	
-	var $row;
-	
-	/**
-	* Initializes the new dbIndex object.
-	*
-	* @param object $parent Parent object
-	* @param array $attributes Attributes
-	*
-	* @internal
-	*/
-	function dbData( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
-	}
-	
-	/**
-	* XML Callback to process start elements
-	*
-	* Processes XML opening tags. 
-	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		$this->currentElement = strtoupper( $tag );
-		
-		switch( $this->currentElement ) {
-			case 'ROW':
-				$this->row = count( $this->data );
-				$this->data[$this->row] = array();
-				break;
-			case 'F':
-				$this->addField($attributes);
-			default:
-				// print_r( array( $tag, $attributes ) );
-		}
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*
-	* Processes XML cdata.
-	*
-	* @access private
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-		switch( $this->currentElement ) {
-			// Index field name
-			case 'F':
-				$this->addData( $cdata );
-				break;
-			default:
-				
-		}
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	*/
-	function _tag_close( &$parser, $tag ) {
-		$this->currentElement = '';
-		
-		switch( strtoupper( $tag ) ) {
-			case 'DATA':
-				xml_set_object( $parser, $this->parent );
-				break;
-		}
-	}
-	
-	/**
-	* Adds a field to the index
-	*
-	* @param string $name Field name
-	* @return string Field list
-	*/
-	function addField( $attributes ) {
-		if( isset( $attributes['NAME'] ) ) {
-			$name = $attributes['NAME'];
-		} else {
-			$name = count($this->data[$this->row]);
-		}
-		
-		// Set the field index so we know where we are
-		$this->current_field = $this->FieldID( $name );
-	}
-	
-	/**
-	* Adds options to the index
-	*
-	* @param string $opt Comma-separated list of index options.
-	* @return string Option list
-	*/
-	function addData( $cdata ) {
-		if( !isset( $this->data[$this->row] ) ) {
-			$this->data[$this->row] = array();
-		}
-		
-		if( !isset( $this->data[$this->row][$this->current_field] ) ) {
-			$this->data[$this->row][$this->current_field] = '';
-		}
-		
-		$this->data[$this->row][$this->current_field] .= $cdata;
-	}
-	
-	/**
-	* Generates the SQL that will create the index in the database
-	*
-	* @param object $xmls adoSchema object
-	* @return array Array containing index creation SQL
-	*/
-	function create( &$xmls ) {
-		$table = $xmls->dict->TableName($this->parent->name);
-		$table_field_count = count($this->parent->fields);
-		$sql = array();
-		
-		// eliminate any columns that aren't in the table
-		foreach( $this->data as $row ) {
-			$table_fields = $this->parent->fields;
-			$fields = array();
-			
-			foreach( $row as $field_id => $field_data ) {
-				if( !array_key_exists( $field_id, $table_fields ) ) {
-					if( is_numeric( $field_id ) ) {
-						$field_id = reset( array_keys( $table_fields ) );
-					} else {
-						continue;
-					}
-				}
-				
-				$name = $table_fields[$field_id]['NAME'];
-				
-				switch( $table_fields[$field_id]['TYPE'] ) {
-					case 'C':
-					case 'C2':
-					case 'X':
-					case 'X2':
-						$fields[$name] = $xmls->db->qstr( $field_data );
-						break;
-					case 'I':
-					case 'I1':
-					case 'I2':
-					case 'I4':
-					case 'I8':
-						$fields[$name] = intval($field_data);
-						break;
-					default:
-						$fields[$name] = $field_data;
-				}
-				
-				unset($table_fields[$field_id]);
-			}
-			
-			// check that at least 1 column is specified
-			if( empty( $fields ) ) {
-				continue;
-			}
-			
-			// check that no required columns are missing
-			if( count( $fields ) < $table_field_count ) {
-				foreach( $table_fields as $field ) {
-					if (isset( $field['OPTS'] ))
-						if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
-							continue(2);
-						}
-				}
-			}
-			
-			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
-		}
-		
-		return $sql;
-	}
-}
-
-/**
-* Creates the SQL to execute a list of provided SQL queries
-*
-* @package axmls
-* @access private
-*/
-class dbQuerySet extends dbObject {
-	
-	/**
-	* @var array	List of SQL queries
-	*/
-	var $queries = array();
-	
-	/**
-	* @var string	String used to build of a query line by line
-	*/
-	var $query;
-	
-	/**
-	* @var string	Query prefix key
-	*/
-	var $prefixKey = '';
-	
-	/**
-	* @var boolean	Auto prefix enable (TRUE)
-	*/
-	var $prefixMethod = 'AUTO';
-	
-	/**
-	* Initializes the query set.
-	*
-	* @param object $parent Parent object
-	* @param array $attributes Attributes
-	*/
-	function dbQuerySet( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
-			
-		// Overrides the manual prefix key
-		if( isset( $attributes['KEY'] ) ) {
-			$this->prefixKey = $attributes['KEY'];
-		}
-		
-		$prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
-		
-		// Enables or disables automatic prefix prepending
-		switch( $prefixMethod ) {
-			case 'AUTO':
-				$this->prefixMethod = 'AUTO';
-				break;
-			case 'MANUAL':
-				$this->prefixMethod = 'MANUAL';
-				break;
-			case 'NONE':
-				$this->prefixMethod = 'NONE';
-				break;
-		}
-	}
-	
-	/**
-	* XML Callback to process start elements. Elements currently 
-	* processed are: QUERY. 
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		$this->currentElement = strtoupper( $tag );
-		
-		switch( $this->currentElement ) {
-			case 'QUERY':
-				// Create a new query in a SQL queryset.
-				// Ignore this query set if a platform is specified and it's different than the 
-				// current connection platform.
-				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
-					$this->newQuery();
-				} else {
-					$this->discardQuery();
-				}
-				break;
-			default:
-				// print_r( array( $tag, $attributes ) );
-		}
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-		switch( $this->currentElement ) {
-			// Line of queryset SQL data
-			case 'QUERY':
-				$this->buildQuery( $cdata );
-				break;
-			default:
-				
-		}
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	*/
-	function _tag_close( &$parser, $tag ) {
-		$this->currentElement = '';
-		
-		switch( strtoupper( $tag ) ) {
-			case 'QUERY':
-				// Add the finished query to the open query set.
-				$this->addQuery();
-				break;
-			case 'SQL':
-				$this->parent->addSQL( $this->create( $this->parent ) );
-				xml_set_object( $parser, $this->parent );
-				$this->destroy();
-				break;
-			default:
-				
-		}
-	}
-	
-	/**
-	* Re-initializes the query.
-	*
-	* @return boolean TRUE
-	*/
-	function newQuery() {
-		$this->query = '';
-		
-		return TRUE;
-	}
-	
-	/**
-	* Discards the existing query.
-	*
-	* @return boolean TRUE
-	*/
-	function discardQuery() {
-		unset( $this->query );
-		
-		return TRUE;
-	}
-	
-	/** 
-	* Appends a line to a query that is being built line by line
-	*
-	* @param string $data Line of SQL data or NULL to initialize a new query
-	* @return string SQL query string.
-	*/
-	function buildQuery( $sql = NULL ) {
-		if( !isset( $this->query ) OR empty( $sql ) ) {
-			return FALSE;
-		}
-		
-		$this->query .= $sql;
-		
-		return $this->query;
-	}
-	
-	/**
-	* Adds a completed query to the query list
-	*
-	* @return string	SQL of added query
-	*/
-	function addQuery() {
-		if( !isset( $this->query ) ) {
-			return FALSE;
-		}
-		
-		$this->queries[] = $return = trim($this->query);
-		
-		unset( $this->query );
-		
-		return $return;
-	}
-	
-	/**
-	* Creates and returns the current query set
-	*
-	* @param object $xmls adoSchema object
-	* @return array Query set
-	*/
-	function create( &$xmls ) {
-		foreach( $this->queries as $id => $query ) {
-			switch( $this->prefixMethod ) {
-				case 'AUTO':
-					// Enable auto prefix replacement
-					
-					// Process object prefix.
-					// Evaluate SQL statements to prepend prefix to objects
-					$query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
-					$query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
-					$query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
-					
-					// SELECT statements aren't working yet
-					#$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
-					
-				case 'MANUAL':
-					// If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
-					// If prefixKey is not set, we use the default constant XMLS_PREFIX
-					if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
-						// Enable prefix override
-						$query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
-					} else {
-						// Use default replacement
-						$query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
-					}
-			}
-			
-			$this->queries[$id] = trim( $query );
-		}
-		
-		// Return the query set array
-		return $this->queries;
-	}
-	
-	/**
-	* Rebuilds the query with the prefix attached to any objects
-	*
-	* @param string $regex Regex used to add prefix
-	* @param string $query SQL query string
-	* @param string $prefix Prefix to be appended to tables, indices, etc.
-	* @return string Prefixed SQL query string.
-	*/
-	function prefixQuery( $regex, $query, $prefix = NULL ) {
-		if( !isset( $prefix ) ) {
-			return $query;
-		}
-		
-		if( preg_match( $regex, $query, $match ) ) {
-			$preamble = $match[1];
-			$postamble = $match[5];
-			$objectList = explode( ',', $match[3] );
-			// $prefix = $prefix . '_';
-			
-			$prefixedList = '';
-			
-			foreach( $objectList as $object ) {
-				if( $prefixedList !== '' ) {
-					$prefixedList .= ', ';
-				}
-				
-				$prefixedList .= $prefix . trim( $object );
-			}
-			
-			$query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
-		}
-		
-		return $query;
-	}
-}
-
-/**
-* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
-* 
-* This class is used to load and parse the XML file, to create an array of SQL statements
-* that can be used to build a database, and to build the database using the SQL array.
-*
-* @tutorial getting_started.pkg
-*
-* @author Richard Tango-Lowy & Dan Cech
-* @version $Revision: 1.12 $
-*
-* @package axmls
-*/
-class adoSchema {
-	
-	/**
-	* @var array	Array containing SQL queries to generate all objects
-	* @access private
-	*/
-	var $sqlArray;
-	
-	/**
-	* @var object	ADOdb connection object
-	* @access private
-	*/
-	var $db;
-	
-	/**
-	* @var object	ADOdb Data Dictionary
-	* @access private
-	*/
-	var $dict;
-	
-	/**
-	* @var string Current XML element
-	* @access private
-	*/
-	var $currentElement = '';
-	
-	/**
-	* @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
-	* @access private
-	*/
-	var $upgrade = '';
-	
-	/**
-	* @var string Optional object prefix
-	* @access private
-	*/
-	var $objectPrefix = '';
-	
-	/**
-	* @var long	Original Magic Quotes Runtime value
-	* @access private
-	*/
-	var $mgq;
-	
-	/**
-	* @var long	System debug
-	* @access private
-	*/
-	var $debug;
-	
-	/**
-	* @var string Regular expression to find schema version
-	* @access private
-	*/
-	var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
-	
-	/**
-	* @var string Current schema version
-	* @access private
-	*/
-	var $schemaVersion;
-	
-	/**
-	* @var int	Success of last Schema execution
-	*/
-	var $success;
-	
-	/**
-	* @var bool	Execute SQL inline as it is generated
-	*/
-	var $executeInline;
-	
-	/**
-	* @var bool	Continue SQL execution if errors occur
-	*/
-	var $continueOnError;
-	
-	/**
-	* Creates an adoSchema object
-	*
-	* Creating an adoSchema object is the first step in processing an XML schema.
-	* The only parameter is an ADOdb database connection object, which must already
-	* have been created.
-	*
-	* @param object $db ADOdb database connection object.
-	*/
-	function adoSchema( &$db ) {
-		// Initialize the environment
-		$this->mgq = get_magic_quotes_runtime();
-		set_magic_quotes_runtime(0);
-		
-		$this->db =& $db;
-		$this->debug = $this->db->debug;
-		$this->dict = NewDataDictionary( $this->db );
-		$this->sqlArray = array();
-		$this->schemaVersion = XMLS_SCHEMA_VERSION;
-		$this->executeInline( XMLS_EXECUTE_INLINE );
-		$this->continueOnError( XMLS_CONTINUE_ON_ERROR );
-		$this->setUpgradeMethod();
-	}
-	
-	/**
-	* Sets the method to be used for upgrading an existing database
-	*
-	* Use this method to specify how existing database objects should be upgraded.
-	* The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
-	* alter each database object directly, REPLACE attempts to rebuild each object
-	* from scratch, BEST attempts to determine the best upgrade method for each
-	* object, and NONE disables upgrading.
-	*
-	* This method is not yet used by AXMLS, but exists for backward compatibility.
-	* The ALTER method is automatically assumed when the adoSchema object is
-	* instantiated; other upgrade methods are not currently supported.
-	*
-	* @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
-	* @returns string Upgrade method used
-	*/
-	function SetUpgradeMethod( $method = '' ) {
-		if( !is_string( $method ) ) {
-			return FALSE;
-		}
-		
-		$method = strtoupper( $method );
-		
-		// Handle the upgrade methods
-		switch( $method ) {
-			case 'ALTER':
-				$this->upgrade = $method;
-				break;
-			case 'REPLACE':
-				$this->upgrade = $method;
-				break;
-			case 'BEST':
-				$this->upgrade = 'ALTER';
-				break;
-			case 'NONE':
-				$this->upgrade = 'NONE';
-				break;
-			default:
-				// Use default if no legitimate method is passed.
-				$this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
-		}
-		
-		return $this->upgrade;
-	}
-	
-	/**
-	* Enables/disables inline SQL execution.
-	*
-	* Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
-	* AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
-	* is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
-	* to apply the schema to the database.
-	*
-	* @param bool $mode execute
-	* @return bool current execution mode
-	*
-	* @see ParseSchema(), ExecuteSchema()
-	*/
-	function ExecuteInline( $mode = NULL ) {
-		if( is_bool( $mode ) ) {
-			$this->executeInline = $mode;
-		}
-		
-		return $this->executeInline;
-	}
-	
-	/**
-	* Enables/disables SQL continue on error.
-	*
-	* Call this method to enable or disable continuation of SQL execution if an error occurs.
-	* If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
-	* If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
-	* of the schema will continue.
-	*
-	* @param bool $mode execute
-	* @return bool current continueOnError mode
-	*
-	* @see addSQL(), ExecuteSchema()
-	*/
-	function ContinueOnError( $mode = NULL ) {
-		if( is_bool( $mode ) ) {
-			$this->continueOnError = $mode;
-		}
-		
-		return $this->continueOnError;
-	}
-	
-	/**
-	* Loads an XML schema from a file and converts it to SQL.
-	*
-	* Call this method to load the specified schema (see the DTD for the proper format) from
-	* the filesystem and generate the SQL necessary to create the database described. 
-	* @see ParseSchemaString()
-	*
-	* @param string $file Name of XML schema file.
-	* @param bool $returnSchema Return schema rather than parsing.
-	* @return array Array of SQL queries, ready to execute
-	*/
-	function ParseSchema( $filename, $returnSchema = FALSE ) {
-		return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
-	}
-	
-	/**
-	* Loads an XML schema from a file and converts it to SQL.
-	*
-	* Call this method to load the specified schema from a file (see the DTD for the proper format) 
-	* and generate the SQL necessary to create the database described by the schema.
-	*
-	* @param string $file Name of XML schema file.
-	* @param bool $returnSchema Return schema rather than parsing.
-	* @return array Array of SQL queries, ready to execute.
-	*
-	* @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
-	* @see ParseSchema(), ParseSchemaString()
-	*/
-	function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
-		// Open the file
-		if( !($fp = fopen( $filename, 'r' )) ) {
-			// die( 'Unable to open file' );
-			return FALSE;
-		}
-		
-		// do version detection here
-		if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
-			return FALSE;
-		}
-		
-		if ( $returnSchema )
-		{
-			$xmlstring = '';
-			while( $data = fread( $fp, 100000 ) ) {
-				$xmlstring .= $data;
-			}
-			return $xmlstring;
-		}
-		
-		$this->success = 2;
-		
-		$xmlParser = $this->create_parser();
-		
-		// Process the file
-		while( $data = fread( $fp, 4096 ) ) {
-			if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
-				die( sprintf(
-					"XML error: %s at line %d",
-					xml_error_string( xml_get_error_code( $xmlParser) ),
-					xml_get_current_line_number( $xmlParser)
-				) );
-			}
-		}
-		
-		xml_parser_free( $xmlParser );
-		
-		return $this->sqlArray;
-	}
-	
-	/**
-	* Converts an XML schema string to SQL.
-	*
-	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
-	* and generate the SQL necessary to create the database described by the schema. 
-	* @see ParseSchema()
-	*
-	* @param string $xmlstring XML schema string.
-	* @param bool $returnSchema Return schema rather than parsing.
-	* @return array Array of SQL queries, ready to execute.
-	*/
-	function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
-		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
-			return FALSE;
-		}
-		
-		// do version detection here
-		if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
-			return FALSE;
-		}
-		
-		if ( $returnSchema )
-		{
-			return $xmlstring;
-		}
-		
-		$this->success = 2;
-		
-		$xmlParser = $this->create_parser();
-		
-		if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
-			die( sprintf(
-				"XML error: %s at line %d",
-				xml_error_string( xml_get_error_code( $xmlParser) ),
-				xml_get_current_line_number( $xmlParser)
-			) );
-		}
-		
-		xml_parser_free( $xmlParser );
-		
-		return $this->sqlArray;
-	}
-	
-	/**
-	* Loads an XML schema from a file and converts it to uninstallation SQL.
-	*
-	* Call this method to load the specified schema (see the DTD for the proper format) from
-	* the filesystem and generate the SQL necessary to remove the database described.
-	* @see RemoveSchemaString()
-	*
-	* @param string $file Name of XML schema file.
-	* @param bool $returnSchema Return schema rather than parsing.
-	* @return array Array of SQL queries, ready to execute
-	*/
-	function RemoveSchema( $filename, $returnSchema = FALSE ) {
-		return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
-	}
-	
-	/**
-	* Converts an XML schema string to uninstallation SQL.
-	*
-	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
-	* and generate the SQL necessary to uninstall the database described by the schema. 
-	* @see RemoveSchema()
-	*
-	* @param string $schema XML schema string.
-	* @param bool $returnSchema Return schema rather than parsing.
-	* @return array Array of SQL queries, ready to execute.
-	*/
-	function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
-		
-		// grab current version
-		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
-			return FALSE;
-		}
-		
-		return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
-	}
-	
-	/**
-	* Applies the current XML schema to the database (post execution).
-	*
-	* Call this method to apply the current schema (generally created by calling 
-	* ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, 
-	* and executing other SQL specified in the schema) after parsing.
-	* @see ParseSchema(), ParseSchemaString(), ExecuteInline()
-	*
-	* @param array $sqlArray Array of SQL statements that will be applied rather than
-	*		the current schema.
-	* @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
-	* @returns integer 0 if failure, 1 if errors, 2 if successful.
-	*/
-	function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {
-		if( !is_bool( $continueOnErr ) ) {
-			$continueOnErr = $this->ContinueOnError();
-		}
-		
-		if( !isset( $sqlArray ) ) {
-			$sqlArray = $this->sqlArray;
-		}
-		
-		if( !is_array( $sqlArray ) ) {
-			$this->success = 0;
-		} else {
-			$this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
-		}
-		
-		return $this->success;
-	}
-	
-	/**
-	* Returns the current SQL array. 
-	*
-	* Call this method to fetch the array of SQL queries resulting from 
-	* ParseSchema() or ParseSchemaString(). 
-	*
-	* @param string $format Format: HTML, TEXT, or NONE (PHP array)
-	* @return array Array of SQL statements or FALSE if an error occurs
-	*/
-	function PrintSQL( $format = 'NONE' ) {
-		$sqlArray = null;
-		return $this->getSQL( $format, $sqlArray );
-	}
-	
-	/**
-	* Saves the current SQL array to the local filesystem as a list of SQL queries.
-	*
-	* Call this method to save the array of SQL queries (generally resulting from a
-	* parsed XML schema) to the filesystem.
-	*
-	* @param string $filename Path and name where the file should be saved.
-	* @return boolean TRUE if save is successful, else FALSE. 
-	*/
-	function SaveSQL( $filename = './schema.sql' ) {
-		
-		if( !isset( $sqlArray ) ) {
-			$sqlArray = $this->sqlArray;
-		}
-		if( !isset( $sqlArray ) ) {
-			return FALSE;
-		}
-		
-		$fp = fopen( $filename, "w" );
-		
-		foreach( $sqlArray as $key => $query ) {
-			fwrite( $fp, $query . ";\n" );
-		}
-		fclose( $fp );
-	}
-	
-	/**
-	* Create an xml parser
-	*
-	* @return object PHP XML parser object
-	*
-	* @access private
-	*/
-	function &create_parser() {
-		// Create the parser
-		$xmlParser = xml_parser_create();
-		xml_set_object( $xmlParser, $this );
-		
-		// Initialize the XML callback functions
-		xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
-		xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
-		
-		return $xmlParser;
-	}
-	
-	/**
-	* XML Callback to process start elements
-	*
-	* @access private
-	*/
-	function _tag_open( &$parser, $tag, $attributes ) {
-		switch( strtoupper( $tag ) ) {
-			case 'TABLE':
-				$this->obj = new dbTable( $this, $attributes );
-				xml_set_object( $parser, $this->obj );
-				break;
-			case 'SQL':
-				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
-					$this->obj = new dbQuerySet( $this, $attributes );
-					xml_set_object( $parser, $this->obj );
-				}
-				break;
-			default:
-				// print_r( array( $tag, $attributes ) );
-		}
-		
-	}
-	
-	/**
-	* XML Callback to process CDATA elements
-	*
-	* @access private
-	*/
-	function _tag_cdata( &$parser, $cdata ) {
-	}
-	
-	/**
-	* XML Callback to process end elements
-	*
-	* @access private
-	* @internal
-	*/
-	function _tag_close( &$parser, $tag ) {
-		
-	}
-	
-	/**
-	* Converts an XML schema string to the specified DTD version.
-	*
-	* Call this method to convert a string containing an XML schema to a different AXMLS
-	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
-	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
-	* parameter is specified, the schema will be converted to the current DTD version. 
-	* If the newFile parameter is provided, the converted schema will be written to the specified
-	* file.
-	* @see ConvertSchemaFile()
-	*
-	* @param string $schema String containing XML schema that will be converted.
-	* @param string $newVersion DTD version to convert to.
-	* @param string $newFile File name of (converted) output file.
-	* @return string Converted XML schema or FALSE if an error occurs.
-	*/
-	function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
-		
-		// grab current version
-		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
-			return FALSE;
-		}
-		
-		if( !isset ($newVersion) ) {
-			$newVersion = $this->schemaVersion;
-		}
-		
-		if( $version == $newVersion ) {
-			$result = $schema;
-		} else {
-			$result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
-		}
-		
-		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
-			fwrite( $fp, $result );
-			fclose( $fp );
-		}
-		
-		return $result;
-	}
-	
-	// compat for pre-4.3 - jlim
-	function _file_get_contents($path)
-	{
-		if (function_exists('file_get_contents')) return file_get_contents($path);
-		return join('',file($path));
-	}
-	
-	/**
-	* Converts an XML schema file to the specified DTD version.
-	*
-	* Call this method to convert the specified XML schema file to a different AXMLS
-	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
-	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
-	* parameter is specified, the schema will be converted to the current DTD version. 
-	* If the newFile parameter is provided, the converted schema will be written to the specified
-	* file.
-	* @see ConvertSchemaString()
-	*
-	* @param string $filename Name of XML schema file that will be converted.
-	* @param string $newVersion DTD version to convert to.
-	* @param string $newFile File name of (converted) output file.
-	* @return string Converted XML schema or FALSE if an error occurs.
-	*/
-	function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
-		
-		// grab current version
-		if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
-			return FALSE;
-		}
-		
-		if( !isset ($newVersion) ) {
-			$newVersion = $this->schemaVersion;
-		}
-		
-		if( $version == $newVersion ) {
-			$result = _file_get_contents( $filename );
-			
-			// remove unicode BOM if present
-			if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
-				$result = substr( $result, 3 );
-			}
-		} else {
-			$result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
-		}
-		
-		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
-			fwrite( $fp, $result );
-			fclose( $fp );
-		}
-		
-		return $result;
-	}
-	
-	function TransformSchema( $schema, $xsl, $schematype='string' )
-	{
-		// Fail if XSLT extension is not available
-		if( ! function_exists( 'xslt_create' ) ) {
-			return FALSE;
-		}
-		
-		$xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl';
-		
-		// look for xsl
-		if( !is_readable( $xsl_file ) ) {
-			return FALSE;
-		}
-		
-		switch( $schematype )
-		{
-			case 'file':
-				if( !is_readable( $schema ) ) {
-					return FALSE;
-				}
-				
-				$schema = _file_get_contents( $schema );
-				break;
-			case 'string':
-			default:
-				if( !is_string( $schema ) ) {
-					return FALSE;
-				}
-		}
-		
-		$arguments = array (
-			'/_xml' => $schema,
-			'/_xsl' => _file_get_contents( $xsl_file )
-		);
-		
-		// create an XSLT processor
-		$xh = xslt_create ();
-		
-		// set error handler
-		xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
-		
-		// process the schema
-		$result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); 
-		
-		xslt_free ($xh);
-		
-		return $result;
-	}
-	
-	/**
-	* Processes XSLT transformation errors
-	*
-	* @param object $parser XML parser object
-	* @param integer $errno Error number
-	* @param integer $level Error level
-	* @param array $fields Error information fields
-	*
-	* @access private
-	*/
-	function xslt_error_handler( $parser, $errno, $level, $fields ) {
-		if( is_array( $fields ) ) {
-			$msg = array(
-				'Message Type' => ucfirst( $fields['msgtype'] ),
-				'Message Code' => $fields['code'],
-				'Message' => $fields['msg'],
-				'Error Number' => $errno,
-				'Level' => $level
-			);
-			
-			switch( $fields['URI'] ) {
-				case 'arg:/_xml':
-					$msg['Input'] = 'XML';
-					break;
-				case 'arg:/_xsl':
-					$msg['Input'] = 'XSL';
-					break;
-				default:
-					$msg['Input'] = $fields['URI'];
-			}
-			
-			$msg['Line'] = $fields['line'];
-		} else {
-			$msg = array(
-				'Message Type' => 'Error',
-				'Error Number' => $errno,
-				'Level' => $level,
-				'Fields' => var_export( $fields, TRUE )
-			);
-		}
-		
-		$error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
-					   . '<table>' . "\n";
-		
-		foreach( $msg as $label => $details ) {
-			$error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
-		}
-		
-		$error_details .= '</table>';
-		
-		trigger_error( $error_details, E_USER_ERROR );
-	}
-	
-	/**
-	* Returns the AXMLS Schema Version of the requested XML schema file.
-	*
-	* Call this method to obtain the AXMLS DTD version of the requested XML schema file.
-	* @see SchemaStringVersion()
-	*
-	* @param string $filename AXMLS schema file
-	* @return string Schema version number or FALSE on error
-	*/
-	function SchemaFileVersion( $filename ) {
-		// Open the file
-		if( !($fp = fopen( $filename, 'r' )) ) {
-			// die( 'Unable to open file' );
-			return FALSE;
-		}
-		
-		// Process the file
-		while( $data = fread( $fp, 4096 ) ) {
-			if( preg_match( $this->versionRegex, $data, $matches ) ) {
-				return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
-			}
-		}
-		
-		return FALSE;
-	}
-	
-	/**
-	* Returns the AXMLS Schema Version of the provided XML schema string.
-	*
-	* Call this method to obtain the AXMLS DTD version of the provided XML schema string.
-	* @see SchemaFileVersion()
-	*
-	* @param string $xmlstring XML schema string
-	* @return string Schema version number or FALSE on error
-	*/
-	function SchemaStringVersion( $xmlstring ) {
-		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
-			return FALSE;
-		}
-		
-		if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {
-			return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
-		}
-		
-		return FALSE;
-	}
-	
-	/**
-	* Extracts an XML schema from an existing database.
-	*
-	* Call this method to create an XML schema string from an existing database.
-	* If the data parameter is set to TRUE, AXMLS will include the data from the database
-	* in the schema. 
-	*
-	* @param boolean $data Include data in schema dump
-	* @return string Generated XML schema
-	*/
-	function ExtractSchema( $data = FALSE ) {
-		$old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
-		
-		$schema = '<?xml version="1.0"?>' . "\n"
-				. '<schema version="' . $this->schemaVersion . '">' . "\n";
-		
-		if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {
-			foreach( $tables as $table ) {
-				$schema .= '	<table name="' . $table . '">' . "\n";
-				
-				// grab details from database
-				$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' );
-				$fields = $this->db->MetaColumns( $table );
-				$indexes = $this->db->MetaIndexes( $table );
-				
-				if( is_array( $fields ) ) {
-					foreach( $fields as $details ) {
-						$extra = '';
-						$content = array();
-						
-						if( $details->max_length > 0 ) {
-							$extra .= ' size="' . $details->max_length . '"';
-						}
-						
-						if( $details->primary_key ) {
-							$content[] = '<KEY/>';
-						} elseif( $details->not_null ) {
-							$content[] = '<NOTNULL/>';
-						}
-						
-						if( $details->has_default ) {
-							$content[] = '<DEFAULT value="' . $details->default_value . '"/>';
-						}
-						
-						if( $details->auto_increment ) {
-							$content[] = '<AUTOINCREMENT/>';
-						}
-						
-						// this stops the creation of 'R' columns,
-						// AUTOINCREMENT is used to create auto columns
-						$details->primary_key = 0;
-						$type = $rs->MetaType( $details );
-						
-						$schema .= '		<field name="' . $details->name . '" type="' . $type . '"' . $extra . '>';
-						
-						if( !empty( $content ) ) {
-							$schema .= "\n			" . implode( "\n			", $content ) . "\n		";
-						}
-						
-						$schema .= '</field>' . "\n";
-					}
-				}
-				
-				if( is_array( $indexes ) ) {
-					foreach( $indexes as $index => $details ) {
-						$schema .= '		<index name="' . $index . '">' . "\n";
-						
-						if( $details['unique'] ) {
-							$schema .= '			<UNIQUE/>' . "\n";
-						}
-						
-						foreach( $details['columns'] as $column ) {
-							$schema .= '			<col>' . $column . '</col>' . "\n";
-						}
-						
-						$schema .= '		</index>' . "\n";
-					}
-				}
-				
-				if( $data ) {
-					$rs = $this->db->Execute( 'SELECT * FROM ' . $table );
-					
-					if( is_object( $rs ) ) {
-						$schema .= '		<data>' . "\n";
-						
-						while( $row = $rs->FetchRow() ) {
-							foreach( $row as $key => $val ) {
-								$row[$key] = htmlentities($val);
-							}
-							
-							$schema .= '			<row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";
-						}
-						
-						$schema .= '		</data>' . "\n";
-					}
-				}
-				
-				$schema .= '	</table>' . "\n";
-			}
-		}
-		
-		$this->db->SetFetchMode( $old_mode );
-		
-		$schema .= '</schema>';
-		return $schema;
-	}
-	
-	/**
-	* Sets a prefix for database objects
-	*
-	* Call this method to set a standard prefix that will be prepended to all database tables 
-	* and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
-	*
-	* @param string $prefix Prefix that will be prepended.
-	* @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
-	* @return boolean TRUE if successful, else FALSE
-	*/
-	function SetPrefix( $prefix = '', $underscore = TRUE ) {
-		switch( TRUE ) {
-			// clear prefix
-			case empty( $prefix ):
-				logMsg( 'Cleared prefix' );
-				$this->objectPrefix = '';
-				return TRUE;
-			// prefix too long
-			case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:
-			// prefix contains invalid characters
-			case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
-				logMsg( 'Invalid prefix: ' . $prefix );
-				return FALSE;
-		}
-		
-		if( $underscore AND substr( $prefix, -1 ) != '_' ) {
-			$prefix .= '_';
-		}
-		
-		// prefix valid
-		logMsg( 'Set prefix: ' . $prefix );
-		$this->objectPrefix = $prefix;
-		return TRUE;
-	}
-	
-	/**
-	* Returns an object name with the current prefix prepended.
-	*
-	* @param string	$name Name
-	* @return string	Prefixed name
-	*
-	* @access private
-	*/
-	function prefix( $name = '' ) {
-		// if prefix is set
-		if( !empty( $this->objectPrefix ) ) {
-			// Prepend the object prefix to the table name
-			// prepend after quote if used
-			return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );
-		}
-		
-		// No prefix set. Use name provided.
-		return $name;
-	}
-	
-	/**
-	* Checks if element references a specific platform
-	*
-	* @param string $platform Requested platform
-	* @returns boolean TRUE if platform check succeeds
-	*
-	* @access private
-	*/
-	function supportedPlatform( $platform = NULL ) {
-		$regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/';
-		
-		if( !isset( $platform ) OR preg_match( $regex, $platform ) ) {
-			logMsg( "Platform $platform is supported" );
-			return TRUE;
-		} else {
-			logMsg( "Platform $platform is NOT supported" );
-			return FALSE;
-		}
-	}
-	
-	/**
-	* Clears the array of generated SQL.
-	*
-	* @access private
-	*/
-	function clearSQL() {
-		$this->sqlArray = array();
-	}
-	
-	/**
-	* Adds SQL into the SQL array.
-	*
-	* @param mixed $sql SQL to Add
-	* @return boolean TRUE if successful, else FALSE.
-	*
-	* @access private
-	*/	
-	function addSQL( $sql = NULL ) {
-		if( is_array( $sql ) ) {
-			foreach( $sql as $line ) {
-				$this->addSQL( $line );
-			}
-			
-			return TRUE;
-		}
-		
-		if( is_string( $sql ) ) {
-			$this->sqlArray[] = $sql;
-			
-			// if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
-			if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {
-				$saved = $this->db->debug;
-				$this->db->debug = $this->debug;
-				$ok = $this->db->Execute( $sql );
-				$this->db->debug = $saved;
-				
-				if( !$ok ) {
-					if( $this->debug ) {
-						ADOConnection::outp( $this->db->ErrorMsg() );
-					}
-					
-					$this->success = 1;
-				}
-			}
-			
-			return TRUE;
-		}
-		
-		return FALSE;
-	}
-	
-	/**
-	* Gets the SQL array in the specified format.
-	*
-	* @param string $format Format
-	* @return mixed SQL
-	*	
-	* @access private
-	*/
-	function getSQL( $format = NULL, $sqlArray = NULL ) {
-		if( !is_array( $sqlArray ) ) {
-			$sqlArray = $this->sqlArray;
-		}
-		
-		if( !is_array( $sqlArray ) ) {
-			return FALSE;
-		}
-		
-		switch( strtolower( $format ) ) {
-			case 'string':
-			case 'text':
-				return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';
-			case'html':
-				return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
-		}
-		
-		return $this->sqlArray;
-	}
-	
-	/**
-	* Destroys an adoSchema object.
-	*
-	* Call this method to clean up after an adoSchema object that is no longer in use.
-	* @deprecated adoSchema now cleans up automatically.
-	*/
-	function Destroy() {
-		set_magic_quotes_runtime( $this->mgq );
-		unset( $this );
-	}
-}
-
-/**
-* Message logging function
-*
-* @access private
-*/
-function logMsg( $msg, $title = NULL, $force = FALSE ) {
-	if( XMLS_DEBUG or $force ) {
-		echo '<pre>';
-		
-		if( isset( $title ) ) {
-			echo '<h3>' . htmlentities( $title ) . '</h3>';
-		}
-		
-		if( is_object( $this ) ) {
-			echo '[' . get_class( $this ) . '] ';
-		}
-		
-		print_r( $msg );
-		
-		echo '</pre>';
-	}
-}
-?>
+<?php
+// Copyright (c) 2004 ars Cognita Inc., 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. 
+*******************************************************************************/
+/**
+ * xmlschema is a class that allows the user to quickly and easily
+ * build a database on any ADOdb-supported platform using a simple
+ * XML schema.
+ *
+ * Last Editor: $Author: jlim $
+ * @author Richard Tango-Lowy & Dan Cech
+ * @version $Revision: 1.12 $
+ *
+ * @package axmls
+ * @tutorial getting_started.pkg
+ */
+ 
+function _file_get_contents($file) 
+{
+ 	if (function_exists('file_get_contents')) return file_get_contents($file);
+	
+	$f = fopen($file,'r');
+	if (!$f) return '';
+	$t = '';
+	
+	while ($s = fread($f,100000)) $t .= $s;
+	fclose($f);
+	return $t;
+}
+
+
+/**
+* Debug on or off
+*/
+if( !defined( 'XMLS_DEBUG' ) ) {
+	define( 'XMLS_DEBUG', FALSE );
+}
+
+/**
+* Default prefix key
+*/
+if( !defined( 'XMLS_PREFIX' ) ) {
+	define( 'XMLS_PREFIX', '%%P' );
+}
+
+/**
+* Maximum length allowed for object prefix
+*/
+if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
+	define( 'XMLS_PREFIX_MAXLEN', 10 );
+}
+
+/**
+* Execute SQL inline as it is generated
+*/
+if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
+	define( 'XMLS_EXECUTE_INLINE', FALSE );
+}
+
+/**
+* Continue SQL Execution if an error occurs?
+*/
+if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
+	define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
+}
+
+/**
+* Current Schema Version
+*/
+if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_SCHEMA_VERSION', '0.2' );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
+	define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
+}
+
+/**
+* Include the main ADODB library
+*/
+if( !defined( '_ADODB_LAYER' ) ) {
+	require( 'adodb.inc.php' );
+	require( 'adodb-datadict.inc.php' );
+}
+
+/**
+* Abstract DB Object. This class provides basic methods for database objects, such
+* as tables and indexes.
+*
+* @package axmls
+* @access private
+*/
+class dbObject {
+	
+	/**
+	* var object Parent
+	*/
+	var $parent;
+	
+	/**
+	* var string current element
+	*/
+	var $currentElement;
+	
+	/**
+	* NOP
+	*/
+	function dbObject( &$parent, $attributes = NULL ) {
+		$this->parent = $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	function create(&$xmls) {
+		return array();
+	}
+	
+	/**
+	* Destroys the object
+	*/
+	function destroy() {
+		unset( $this );
+	}
+	
+	/**
+	* Checks whether the specified RDBMS is supported by the current
+	* database object or its ranking ancestor.
+	*
+	* @param string $platform RDBMS platform name (from ADODB platform list).
+	* @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
+	}
+	
+	/**
+	* Returns the prefix set by the ranking ancestor of the database object.
+	*
+	* @param string $name Prefix string.
+	* @return string Prefix.
+	*/
+	function prefix( $name = '' ) {
+		return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
+	}
+	
+	/**
+	* Extracts a field ID from the specified field.
+	*
+	* @param string $field Field.
+	* @return string Field ID.
+	*/
+	function FieldID( $field ) {
+		return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
+	}
+}
+
+/**
+* Creates a table object in ADOdb's datadict format
+*
+* This class stores information about a database table. As charactaristics
+* of the table are loaded from the external source, methods and properties
+* of this class are used to build up the table description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbTable extends dbObject {
+	
+	/**
+	* @var string Table name
+	*/
+	var $name;
+	
+	/**
+	* @var array Field specifier: Meta-information about each field
+	*/
+	var $fields = array();
+	
+	/**
+	* @var array List of table indexes.
+	*/
+	var $indexes = array();
+	
+	/**
+	* @var array Table options: Table-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var string Field index: Keeps track of which field is currently being processed
+	*/
+	var $current_field;
+	
+	/**
+	* @var boolean Mark table for destruction
+	* @access private
+	*/
+	var $drop_table;
+	
+	/**
+	* @var boolean Mark field for destruction (not yet implemented)
+	* @access private
+	*/
+	var $drop_field = array();
+	var $alter; // GS Fix for constraint impl
+	
+	/**
+	* Iniitializes a new table object.
+	*
+	* @param string $prefix DB Object prefix
+	* @param array $attributes Array of table attributes.
+	*/
+	function dbTable( &$parent, $attributes = NULL ) {
+		$this->parent = $parent;
+		$this->name = $this->prefix($attributes['NAME']);
+		// GS Fix for constraint impl
+		if(isset($attributes['ALTER']))
+		{
+			$this->alter = $attributes['ALTER'];
+		}
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'INDEX':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addIndex( $attributes ) );
+				}
+				break;
+			case 'DATA':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addData( $attributes ) );
+				}
+				break;
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'FIELD':
+				// Add a field
+				$fieldName = $attributes['NAME'];
+				$fieldType = $attributes['TYPE'];
+				$fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
+				$fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
+				
+				$this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
+				break;
+			case 'KEY':
+			case 'NOTNULL':
+			case 'AUTOINCREMENT':
+				// Add a field option
+				$this->addFieldOpt( $this->current_field, $this->currentElement );
+				break;
+			case 'DEFAULT':
+				// Add a field option to the table object
+				
+				// Work around ADOdb datadict issue that misinterprets empty strings.
+				if( $attributes['VALUE'] == '' ) {
+					$attributes['VALUE'] = " '' ";
+				}
+				
+				$this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
+				break;
+			case 'DEFDATE':
+			case 'DEFTIMESTAMP':
+				// Add a field option to the table object
+				$this->addFieldOpt( $this->current_field, $this->currentElement );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Table constraint
+			case 'CONSTRAINT':
+				if( isset( $this->current_field ) ) {
+					$this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
+				} else {
+					$this->addTableOpt('CONSTRAINTS', $cdata ); // GS Fix for constraint impl
+				}
+				break;
+			// Table option
+			case 'OPT':
+				$this->addTableOpt('mysql', $cdata ); // GS Fix for constraint impl
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			case 'FIELD':
+				unset($this->current_field);
+				break;
+
+		}
+	}
+	
+	/**
+	* Adds an index to a table object
+	*
+	* @param array $attributes Index attributes
+	* @return object dbIndex object
+	*/
+	function addIndex( $attributes ) {
+		$name = strtoupper( $attributes['NAME'] );
+		$this->indexes[$name] = new dbIndex( $this, $attributes );
+		return $this->indexes[$name];
+	}
+	
+	/**
+	* Adds data to a table object
+	*
+	* @param array $attributes Data attributes
+	* @return object dbData object
+	*/
+	function addData( $attributes ) {
+		if( !isset( $this->data ) ) {
+			$this->data = new dbData( $this, $attributes );
+		}
+		return $this->data;
+	}
+	
+	/**
+	* Adds a field to a table object
+	*
+	* $name is the name of the table to which the field should be added. 
+	* $type is an ADODB datadict field type. The following field types
+	* are supported as of ADODB 3.40:
+	* 	- C:  varchar
+	*	- X:  CLOB (character large object) or largest varchar size
+	*	   if CLOB is not supported
+	*	- C2: Multibyte varchar
+	*	- X2: Multibyte CLOB
+	*	- B:  BLOB (binary large object)
+	*	- D:  Date (some databases do not support this, and we return a datetime type)
+	*	- T:  Datetime or Timestamp
+	*	- L:  Integer field suitable for storing booleans (0 or 1)
+	*	- I:  Integer (mapped to I4)
+	*	- I1: 1-byte integer
+	*	- I2: 2-byte integer
+	*	- I4: 4-byte integer
+	*	- I8: 8-byte integer
+	*	- F:  Floating point number
+	*	- N:  Numeric or decimal number
+	*
+	* @param string $name Name of the table to which the field will be added.
+	* @param string $type	ADODB datadict field type.
+	* @param string $size	Field size
+	* @param array $opts	Field options array
+	* @return array Field specifier array
+	*/
+	function addField( $name, $type, $size = NULL, $opts = NULL ) {
+		$field_id = $this->FieldID( $name );
+		
+		// Set the field index so we know where we are
+		$this->current_field = $field_id;
+		
+		// Set the field name (required)
+		$this->fields[$field_id]['NAME'] = $name;
+		
+		// Set the field type (required)
+		$this->fields[$field_id]['TYPE'] = $type;
+		
+		// Set the field size (optional)
+		if( isset( $size ) ) {
+			$this->fields[$field_id]['SIZE'] = $size;
+		}
+		
+		// Set the field options
+		if( isset( $opts ) ) {
+			$this->fields[$field_id]['OPTS'][] = $opts;
+		}
+	}
+	
+	/**
+	* Adds a field option to the current field specifier
+	*
+	* This method adds a field option allowed by the ADOdb datadict 
+	* and appends it to the given field.
+	*
+	* @param string $field	Field name
+	* @param string $opt ADOdb field option
+	* @param mixed $value Field option value
+	* @return array Field specifier array
+	*/
+	function addFieldOpt( $field, $opt, $value = NULL ) {
+		if( !isset( $value ) ) {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
+		// Add the option and value
+		} else {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
+		}
+	}
+	
+	/**
+	* Adds an option to the table
+	*
+	* This method takes a comma-separated list of table-level options
+	* and appends them to the table object.
+	*
+	* @param string $opt Table option
+	* @return array Options
+	*/
+	function addTableOpt($key, $opt ) { // GS Fix for constraint impl
+		//$this->opts[] = $opt;
+		$this->opts[$key] = $opt;
+		
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the table in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing table creation SQL
+	*/
+	function create( &$xmls ) {
+		$sql = array();
+		
+		// drop any existing indexes
+		if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
+			foreach( $legacy_indexes as $index => $index_details ) {
+				$sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
+			}
+		}
+		
+		// remove fields to be dropped from table object
+		foreach( $this->drop_field as $field ) {
+			unset( $this->fields[$field] );
+		}
+		
+		// if table exists
+		if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
+			// drop table
+			if( $this->drop_table ) {
+				$sql[] = $xmls->dict->DropTableSQL( $this->name );
+				
+				return $sql;
+			}
+			
+			// drop any existing fields not in schema
+			foreach( $legacy_fields as $field_id => $field ) {
+				if( !isset( $this->fields[$field_id] ) ) {
+					$sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' );
+				}
+			}
+		// if table doesn't exist
+		} else {
+			if( $this->drop_table ) {
+				return $sql;
+			}
+			
+			$legacy_fields = array();
+		}
+		
+		// Loop through the field specifier array, building the associative array for the field options
+		$fldarray = array();
+		
+		foreach( $this->fields as $field_id => $finfo ) {
+			// Set an empty size if it isn't supplied
+			if( !isset( $finfo['SIZE'] ) ) {
+				$finfo['SIZE'] = '';
+			}
+			
+			// Initialize the field array with the type and size
+			$fldarray[$field_id] = array(
+				'NAME' => $finfo['NAME'],
+				'TYPE' => $finfo['TYPE'],
+				'SIZE' => $finfo['SIZE']
+			);
+			
+			// Loop through the options array and add the field options. 
+			if( isset( $finfo['OPTS'] ) ) {
+				foreach( $finfo['OPTS'] as $opt ) {
+					// Option has an argument.
+					if( is_array( $opt ) ) {
+						$key = key( $opt );
+						$value = $opt[key( $opt )];
+						@$fldarray[$field_id][$key] .= $value;
+					// Option doesn't have arguments
+					} else {
+						$fldarray[$field_id][$opt] = $opt;
+					}
+				}
+			}
+		}
+		if( empty( $legacy_fields ) && !isset($this->alter)) { // GS Fix for constraint impl
+			// Create the new table
+			$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+			logMsg( end( $sql ), 'Generated CreateTableSQL' );
+		} else {
+			// Upgrade an existing table
+			logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
+			switch( $xmls->upgrade ) {
+				// Use ChangeTableSQL
+				case 'ALTER':
+					logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
+					$sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts, false, $this->alter ); // GS Fix for constraint impl
+					break;
+				case 'REPLACE':
+					logMsg( 'Doing upgrade REPLACE (testing)' );
+					$sql[] = $xmls->dict->DropTableSQL( $this->name );
+					$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+					break;
+				// ignore table
+				default:
+					return array();
+			}
+		}
+		
+		foreach( $this->indexes as $index ) {
+			$sql[] = $index->create( $xmls );
+		}
+		
+		if( isset( $this->data ) ) {
+			$sql[] = $this->data->create( $xmls );
+		}
+		
+		return $sql;
+	}
+	
+	/**
+	* Marks a field or table for destruction
+	*/
+	function drop() {
+		if( isset( $this->current_field ) ) {
+			// Drop the current field
+			logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
+			// $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
+			$this->drop_field[$this->current_field] = $this->current_field;
+		} else {
+			// Drop the current table
+			logMsg( "Dropping table '{$this->name}'" );
+			// $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
+			$this->drop_table = TRUE;
+		}
+	}
+}
+
+/**
+* Creates an index object in ADOdb's datadict format
+*
+* This class stores information about a database index. As charactaristics
+* of the index are loaded from the external source, methods and properties
+* of this class are used to build up the index description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbIndex extends dbObject {
+	
+	/**
+	* @var string	Index name
+	*/
+	var $name;
+	
+	/**
+	* @var array	Index options: Index-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var array	Indexed fields: Table columns included in this index
+	*/
+	var $columns = array();
+	
+	/**
+	* @var boolean Mark index for destruction
+	* @access private
+	*/
+	var $drop = FALSE;
+	
+	/**
+	* Initializes the new dbIndex object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbIndex( &$parent, $attributes = NULL ) {
+		$this->parent = $parent;
+		
+		$this->name = $this->prefix ($attributes['NAME']);
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'CLUSTERED':
+			case 'BITMAP':
+			case 'UNIQUE':
+			case 'FULLTEXT':
+			case 'HASH':
+				// Add index Option
+				$this->addIndexOpt( $this->currentElement );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'COL':
+				$this->addField( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'INDEX':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the index
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $name ) {
+		$this->columns[$this->FieldID( $name )] = $name;
+		
+		// Return the field list
+		return $this->columns;
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addIndexOpt( $opt ) {
+		$this->opts[] = $opt;
+		
+		// Return the options list
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the index in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		if( $this->drop ) {
+			return NULL;
+		}
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->columns as $id => $col ) {
+			if( !isset( $this->parent->fields[$id] ) ) {
+				unset( $this->columns[$id] );
+			}
+		}
+		
+		return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
+	}
+	
+	/**
+	* Marks an index for destruction
+	*/
+	function drop() {
+		$this->drop = TRUE;
+	}
+}
+
+/**
+* Creates a data object in ADOdb's datadict format
+*
+* This class stores information about table data.
+*
+* @package axmls
+* @access private
+*/
+class dbData extends dbObject {
+	
+	var $data = array();
+	
+	var $row;
+	
+	/**
+	* Initializes the new dbIndex object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbData( &$parent, $attributes = NULL ) {
+		$this->parent = $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'ROW':
+				$this->row = count( $this->data );
+				$this->data[$this->row] = array();
+				break;
+			case 'F':
+				$this->addField($attributes);
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'F':
+				$this->addData( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'DATA':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the index
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $attributes ) {
+		if( isset( $attributes['NAME'] ) ) {
+			$name = $attributes['NAME'];
+		} else {
+			$name = count($this->data[$this->row]);
+		}
+		
+		// Set the field index so we know where we are
+		$this->current_field = $this->FieldID( $name );
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addData( $cdata ) {
+		if( !isset( $this->data[$this->row] ) ) {
+			$this->data[$this->row] = array();
+		}
+		
+		if( !isset( $this->data[$this->row][$this->current_field] ) ) {
+			$this->data[$this->row][$this->current_field] = '';
+		}
+		
+		$this->data[$this->row][$this->current_field] .= $cdata;
+	}
+	
+	/**
+	* Generates the SQL that will create the index in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		$table = $xmls->dict->TableName($this->parent->name);
+		$table_field_count = count($this->parent->fields);
+		$sql = array();
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->data as $row ) {
+			$table_fields = $this->parent->fields;
+			$fields = array();
+			
+			foreach( $row as $field_id => $field_data ) {
+				if( !array_key_exists( $field_id, $table_fields ) ) {
+					if( is_numeric( $field_id ) ) {
+						$field_id = reset( array_keys( $table_fields ) );
+					} else {
+						continue;
+					}
+				}
+				
+				$name = $table_fields[$field_id]['NAME'];
+				
+				switch( $table_fields[$field_id]['TYPE'] ) {
+					case 'C':
+					case 'C2':
+					case 'X':
+					case 'X2':
+						$fields[$name] = $xmls->db->qstr( $field_data );
+						break;
+					case 'I':
+					case 'I1':
+					case 'I2':
+					case 'I4':
+					case 'I8':
+						$fields[$name] = intval($field_data);
+						break;
+					default:
+						$fields[$name] = $field_data;
+				}
+				
+				unset($table_fields[$field_id]);
+			}
+			
+			// check that at least 1 column is specified
+			if( empty( $fields ) ) {
+				continue;
+			}
+			
+			// check that no required columns are missing
+			if( count( $fields ) < $table_field_count ) {
+				foreach( $table_fields as $field ) {
+					if (isset( $field['OPTS'] ))
+						if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
+							continue(2);
+						}
+				}
+			}
+			
+			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
+		}
+		
+		return $sql;
+	}
+}
+
+/**
+* Creates the SQL to execute a list of provided SQL queries
+*
+* @package axmls
+* @access private
+*/
+class dbQuerySet extends dbObject {
+	
+	/**
+	* @var array	List of SQL queries
+	*/
+	var $queries = array();
+	
+	/**
+	* @var string	String used to build of a query line by line
+	*/
+	var $query;
+	
+	/**
+	* @var string	Query prefix key
+	*/
+	var $prefixKey = '';
+	
+	/**
+	* @var boolean	Auto prefix enable (TRUE)
+	*/
+	var $prefixMethod = 'AUTO';
+	
+	/**
+	* Initializes the query set.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*/
+	function dbQuerySet( &$parent, $attributes = NULL ) {
+		$this->parent = $parent;
+			
+		// Overrides the manual prefix key
+		if( isset( $attributes['KEY'] ) ) {
+			$this->prefixKey = $attributes['KEY'];
+		}
+		
+		$prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
+		
+		// Enables or disables automatic prefix prepending
+		switch( $prefixMethod ) {
+			case 'AUTO':
+				$this->prefixMethod = 'AUTO';
+				break;
+			case 'MANUAL':
+				$this->prefixMethod = 'MANUAL';
+				break;
+			case 'NONE':
+				$this->prefixMethod = 'NONE';
+				break;
+		}
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: QUERY. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'QUERY':
+				// Create a new query in a SQL queryset.
+				// Ignore this query set if a platform is specified and it's different than the 
+				// current connection platform.
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->newQuery();
+				} else {
+					$this->discardQuery();
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Line of queryset SQL data
+			case 'QUERY':
+				$this->buildQuery( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'QUERY':
+				// Add the finished query to the open query set.
+				$this->addQuery();
+				break;
+			case 'SQL':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* Re-initializes the query.
+	*
+	* @return boolean TRUE
+	*/
+	function newQuery() {
+		$this->query = '';
+		
+		return TRUE;
+	}
+	
+	/**
+	* Discards the existing query.
+	*
+	* @return boolean TRUE
+	*/
+	function discardQuery() {
+		unset( $this->query );
+		
+		return TRUE;
+	}
+	
+	/** 
+	* Appends a line to a query that is being built line by line
+	*
+	* @param string $data Line of SQL data or NULL to initialize a new query
+	* @return string SQL query string.
+	*/
+	function buildQuery( $sql = NULL ) {
+		if( !isset( $this->query ) OR empty( $sql ) ) {
+			return FALSE;
+		}
+		
+		$this->query .= $sql;
+		
+		return $this->query;
+	}
+	
+	/**
+	* Adds a completed query to the query list
+	*
+	* @return string	SQL of added query
+	*/
+	function addQuery() {
+		if( !isset( $this->query ) ) {
+			return FALSE;
+		}
+		
+		$this->queries[] = $return = trim($this->query);
+		
+		unset( $this->query );
+		
+		return $return;
+	}
+	
+	/**
+	* Creates and returns the current query set
+	*
+	* @param object $xmls adoSchema object
+	* @return array Query set
+	*/
+	function create( &$xmls ) {
+		foreach( $this->queries as $id => $query ) {
+			switch( $this->prefixMethod ) {
+				case 'AUTO':
+					// Enable auto prefix replacement
+					
+					// Process object prefix.
+					// Evaluate SQL statements to prepend prefix to objects
+					$query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					
+					// SELECT statements aren't working yet
+					#$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
+					
+				case 'MANUAL':
+					// If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
+					// If prefixKey is not set, we use the default constant XMLS_PREFIX
+					if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
+						// Enable prefix override
+						$query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
+					} else {
+						// Use default replacement
+						$query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
+					}
+			}
+			
+			$this->queries[$id] = trim( $query );
+		}
+		
+		// Return the query set array
+		return $this->queries;
+	}
+	
+	/**
+	* Rebuilds the query with the prefix attached to any objects
+	*
+	* @param string $regex Regex used to add prefix
+	* @param string $query SQL query string
+	* @param string $prefix Prefix to be appended to tables, indices, etc.
+	* @return string Prefixed SQL query string.
+	*/
+	function prefixQuery( $regex, $query, $prefix = NULL ) {
+		if( !isset( $prefix ) ) {
+			return $query;
+		}
+		
+		if( preg_match( $regex, $query, $match ) ) {
+			$preamble = $match[1];
+			$postamble = $match[5];
+			$objectList = explode( ',', $match[3] );
+			// $prefix = $prefix . '_';
+			
+			$prefixedList = '';
+			
+			foreach( $objectList as $object ) {
+				if( $prefixedList !== '' ) {
+					$prefixedList .= ', ';
+				}
+				
+				$prefixedList .= $prefix . trim( $object );
+			}
+			
+			$query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
+		}
+		
+		return $query;
+	}
+}
+
+/**
+* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
+* 
+* This class is used to load and parse the XML file, to create an array of SQL statements
+* that can be used to build a database, and to build the database using the SQL array.
+*
+* @tutorial getting_started.pkg
+*
+* @author Richard Tango-Lowy & Dan Cech
+* @version $Revision: 1.12 $
+*
+* @package axmls
+*/
+class adoSchema {
+	
+	/**
+	* @var array	Array containing SQL queries to generate all objects
+	* @access private
+	*/
+	var $sqlArray;
+	
+	/**
+	* @var object	ADOdb connection object
+	* @access private
+	*/
+	var $db;
+	
+	/**
+	* @var object	ADOdb Data Dictionary
+	* @access private
+	*/
+	var $dict;
+	
+	/**
+	* @var string Current XML element
+	* @access private
+	*/
+	var $currentElement = '';
+	
+	/**
+	* @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
+	* @access private
+	*/
+	var $upgrade = '';
+	
+	/**
+	* @var string Optional object prefix
+	* @access private
+	*/
+	var $objectPrefix = '';
+	
+	/**
+	* @var long	Original Magic Quotes Runtime value
+	* @access private
+	*/
+	var $mgq;
+	
+	/**
+	* @var long	System debug
+	* @access private
+	*/
+	var $debug;
+	
+	/**
+	* @var string Regular expression to find schema version
+	* @access private
+	*/
+	var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
+	
+	/**
+	* @var string Current schema version
+	* @access private
+	*/
+	var $schemaVersion;
+	
+	/**
+	* @var int	Success of last Schema execution
+	*/
+	var $success;
+	
+	/**
+	* @var bool	Execute SQL inline as it is generated
+	*/
+	var $executeInline;
+	
+	/**
+	* @var bool	Continue SQL execution if errors occur
+	*/
+	var $continueOnError;
+	
+	/**
+	* Creates an adoSchema object
+	*
+	* Creating an adoSchema object is the first step in processing an XML schema.
+	* The only parameter is an ADOdb database connection object, which must already
+	* have been created.
+	*
+	* @param object $db ADOdb database connection object.
+	*/
+	function adoSchema( $db ) {
+		// Initialize the environment
+		$this->mgq = get_magic_quotes_runtime();
+		ini_set("magic_quotes_runtime", 0);
+		#set_magic_quotes_runtime(0);
+		
+		$this->db = $db;
+		$this->debug = $this->db->debug;
+		$this->dict = NewDataDictionary( $this->db );
+		$this->sqlArray = array();
+		$this->schemaVersion = XMLS_SCHEMA_VERSION;
+		$this->executeInline( XMLS_EXECUTE_INLINE );
+		$this->continueOnError( XMLS_CONTINUE_ON_ERROR );
+		$this->setUpgradeMethod();
+	}
+	
+	/**
+	* Sets the method to be used for upgrading an existing database
+	*
+	* Use this method to specify how existing database objects should be upgraded.
+	* The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
+	* alter each database object directly, REPLACE attempts to rebuild each object
+	* from scratch, BEST attempts to determine the best upgrade method for each
+	* object, and NONE disables upgrading.
+	*
+	* This method is not yet used by AXMLS, but exists for backward compatibility.
+	* The ALTER method is automatically assumed when the adoSchema object is
+	* instantiated; other upgrade methods are not currently supported.
+	*
+	* @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
+	* @returns string Upgrade method used
+	*/
+	function SetUpgradeMethod( $method = '' ) {
+		if( !is_string( $method ) ) {
+			return FALSE;
+		}
+		
+		$method = strtoupper( $method );
+		
+		// Handle the upgrade methods
+		switch( $method ) {
+			case 'ALTER':
+				$this->upgrade = $method;
+				break;
+			case 'REPLACE':
+				$this->upgrade = $method;
+				break;
+			case 'BEST':
+				$this->upgrade = 'ALTER';
+				break;
+			case 'NONE':
+				$this->upgrade = 'NONE';
+				break;
+			default:
+				// Use default if no legitimate method is passed.
+				$this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
+		}
+		
+		return $this->upgrade;
+	}
+	
+	/**
+	* Enables/disables inline SQL execution.
+	*
+	* Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
+	* AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
+	* is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
+	* to apply the schema to the database.
+	*
+	* @param bool $mode execute
+	* @return bool current execution mode
+	*
+	* @see ParseSchema(), ExecuteSchema()
+	*/
+	function ExecuteInline( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->executeInline = $mode;
+		}
+		
+		return $this->executeInline;
+	}
+	
+	/**
+	* Enables/disables SQL continue on error.
+	*
+	* Call this method to enable or disable continuation of SQL execution if an error occurs.
+	* If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
+	* If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
+	* of the schema will continue.
+	*
+	* @param bool $mode execute
+	* @return bool current continueOnError mode
+	*
+	* @see addSQL(), ExecuteSchema()
+	*/
+	function ContinueOnError( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->continueOnError = $mode;
+		}
+		
+		return $this->continueOnError;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to create the database described. 
+	* @see ParseSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function ParseSchema( $filename, $returnSchema = FALSE ) {
+		return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema from a file (see the DTD for the proper format) 
+	* and generate the SQL necessary to create the database described by the schema.
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*
+	* @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
+	* @see ParseSchema(), ParseSchemaString()
+	*/
+	function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			// die( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
+			return FALSE;
+		}
+		
+		if ( $returnSchema )
+		{
+			$xmlstring = '';
+			while( $data = fread( $fp, 100000 ) ) {
+				$xmlstring .= $data;
+			}
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
+				die( sprintf(
+					"XML error: %s at line %d",
+					xml_error_string( xml_get_error_code( $xmlParser) ),
+					xml_get_current_line_number( $xmlParser)
+				) );
+			}
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Converts an XML schema string to SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to create the database described by the schema. 
+	* @see ParseSchema()
+	*
+	* @param string $xmlstring XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
+			return FALSE;
+		}
+		
+		if ( $returnSchema )
+		{
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
+			die( sprintf(
+				"XML error: %s at line %d",
+				xml_error_string( xml_get_error_code( $xmlParser) ),
+				xml_get_current_line_number( $xmlParser)
+			) );
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to uninstallation SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to remove the database described.
+	* @see RemoveSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function RemoveSchema( $filename, $returnSchema = FALSE ) {
+		return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Converts an XML schema string to uninstallation SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to uninstall the database described by the schema. 
+	* @see RemoveSchema()
+	*
+	* @param string $schema XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
+	}
+	
+	/**
+	* Applies the current XML schema to the database (post execution).
+	*
+	* Call this method to apply the current schema (generally created by calling 
+	* ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, 
+	* and executing other SQL specified in the schema) after parsing.
+	* @see ParseSchema(), ParseSchemaString(), ExecuteInline()
+	*
+	* @param array $sqlArray Array of SQL statements that will be applied rather than
+	*		the current schema.
+	* @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
+	* @returns integer 0 if failure, 1 if errors, 2 if successful.
+	*/
+	function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {
+		if( !is_bool( $continueOnErr ) ) {
+			$continueOnErr = $this->ContinueOnError();
+		}
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			$this->success = 0;
+		} else {
+			$this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
+		}
+		
+		return $this->success;
+	}
+	
+	/**
+	* Returns the current SQL array. 
+	*
+	* Call this method to fetch the array of SQL queries resulting from 
+	* ParseSchema() or ParseSchemaString(). 
+	*
+	* @param string $format Format: HTML, TEXT, or NONE (PHP array)
+	* @return array Array of SQL statements or FALSE if an error occurs
+	*/
+	function PrintSQL( $format = 'NONE' ) {
+		$sqlArray = null;
+		return $this->getSQL( $format, $sqlArray );
+	}
+	
+	/**
+	* Saves the current SQL array to the local filesystem as a list of SQL queries.
+	*
+	* Call this method to save the array of SQL queries (generally resulting from a
+	* parsed XML schema) to the filesystem.
+	*
+	* @param string $filename Path and name where the file should be saved.
+	* @return boolean TRUE if save is successful, else FALSE. 
+	*/
+	function SaveSQL( $filename = './schema.sql' ) {
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		if( !isset( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		$fp = fopen( $filename, "w" );
+		
+		foreach( $sqlArray as $key => $query ) {
+			fwrite( $fp, $query . ";\n" );
+		}
+		fclose( $fp );
+	}
+	
+	/**
+	* Create an xml parser
+	*
+	* @return object PHP XML parser object
+	*
+	* @access private
+	*/
+	function create_parser() {
+		// Create the parser
+		$xmlParser = xml_parser_create();
+		xml_set_object( $xmlParser, $this );
+		
+		// Initialize the XML callback functions
+		xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
+		xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
+		
+		return $xmlParser;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				$this->obj = new dbTable( $this, $attributes );
+				xml_set_object( $parser, $this->obj );
+				break;
+			case 'SQL':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->obj = new dbQuerySet( $this, $attributes );
+					xml_set_object( $parser, $this->obj );
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	* @internal
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	/**
+	* Converts an XML schema string to the specified DTD version.
+	*
+	* Call this method to convert a string containing an XML schema to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaFile()
+	*
+	* @param string $schema String containing XML schema that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = $schema;
+		} else {
+			$result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+	
+	// compat for pre-4.3 - jlim
+	function _file_get_contents($path)
+	{
+		if (function_exists('file_get_contents')) return file_get_contents($path);
+		return join('',file($path));
+	}
+	
+	/**
+	* Converts an XML schema file to the specified DTD version.
+	*
+	* Call this method to convert the specified XML schema file to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaString()
+	*
+	* @param string $filename Name of XML schema file that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = _file_get_contents( $filename );
+			
+			// remove unicode BOM if present
+			if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
+				$result = substr( $result, 3 );
+			}
+		} else {
+			$result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+	
+	function TransformSchema( $schema, $xsl, $schematype='string' )
+	{
+		// Fail if XSLT extension is not available
+		if( ! function_exists( 'xslt_create' ) ) {
+			return FALSE;
+		}
+		
+		$xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl';
+		
+		// look for xsl
+		if( !is_readable( $xsl_file ) ) {
+			return FALSE;
+		}
+		
+		switch( $schematype )
+		{
+			case 'file':
+				if( !is_readable( $schema ) ) {
+					return FALSE;
+				}
+				
+				$schema = _file_get_contents( $schema );
+				break;
+			case 'string':
+			default:
+				if( !is_string( $schema ) ) {
+					return FALSE;
+				}
+		}
+		
+		$arguments = array (
+			'/_xml' => $schema,
+			'/_xsl' => _file_get_contents( $xsl_file )
+		);
+		
+		// create an XSLT processor
+		$xh = xslt_create ();
+		
+		// set error handler
+		xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
+		
+		// process the schema
+		$result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); 
+		
+		xslt_free ($xh);
+		
+		return $result;
+	}
+	
+	/**
+	* Processes XSLT transformation errors
+	*
+	* @param object $parser XML parser object
+	* @param integer $errno Error number
+	* @param integer $level Error level
+	* @param array $fields Error information fields
+	*
+	* @access private
+	*/
+	function xslt_error_handler( $parser, $errno, $level, $fields ) {
+		if( is_array( $fields ) ) {
+			$msg = array(
+				'Message Type' => ucfirst( $fields['msgtype'] ),
+				'Message Code' => $fields['code'],
+				'Message' => $fields['msg'],
+				'Error Number' => $errno,
+				'Level' => $level
+			);
+			
+			switch( $fields['URI'] ) {
+				case 'arg:/_xml':
+					$msg['Input'] = 'XML';
+					break;
+				case 'arg:/_xsl':
+					$msg['Input'] = 'XSL';
+					break;
+				default:
+					$msg['Input'] = $fields['URI'];
+			}
+			
+			$msg['Line'] = $fields['line'];
+		} else {
+			$msg = array(
+				'Message Type' => 'Error',
+				'Error Number' => $errno,
+				'Level' => $level,
+				'Fields' => var_export( $fields, TRUE )
+			);
+		}
+		
+		$error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
+					   . '<table>' . "\n";
+		
+		foreach( $msg as $label => $details ) {
+			$error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
+		}
+		
+		$error_details .= '</table>';
+		
+		trigger_error( $error_details, E_USER_ERROR );
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the requested XML schema file.
+	*
+	* Call this method to obtain the AXMLS DTD version of the requested XML schema file.
+	* @see SchemaStringVersion()
+	*
+	* @param string $filename AXMLS schema file
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaFileVersion( $filename ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			// die( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( preg_match( $this->versionRegex, $data, $matches ) ) {
+				return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+			}
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the provided XML schema string.
+	*
+	* Call this method to obtain the AXMLS DTD version of the provided XML schema string.
+	* @see SchemaFileVersion()
+	*
+	* @param string $xmlstring XML schema string
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaStringVersion( $xmlstring ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			return FALSE;
+		}
+		
+		if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {
+			return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Extracts an XML schema from an existing database.
+	*
+	* Call this method to create an XML schema string from an existing database.
+	* If the data parameter is set to TRUE, AXMLS will include the data from the database
+	* in the schema. 
+	*
+	* @param boolean $data Include data in schema dump
+	* @return string Generated XML schema
+	*/
+	function ExtractSchema( $data = FALSE ) {
+		$old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
+		
+		$schema = '<?xml version="1.0"?>' . "\n"
+				. '<schema version="' . $this->schemaVersion . '">' . "\n";
+		
+		if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {
+			foreach( $tables as $table ) {
+				$schema .= '	<table name="' . $table . '">' . "\n";
+				
+				// grab details from database
+				$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' );
+				$fields = $this->db->MetaColumns( $table );
+				$indexes = $this->db->MetaIndexes( $table );
+				
+				if( is_array( $fields ) ) {
+					foreach( $fields as $details ) {
+						$extra = '';
+						$content = array();
+						
+						if( $details->max_length > 0 ) {
+							$extra .= ' size="' . $details->max_length . '"';
+						}
+						
+						if( $details->primary_key ) {
+							$content[] = '<KEY/>';
+						} elseif( $details->not_null ) {
+							$content[] = '<NOTNULL/>';
+						}
+						
+						if( $details->has_default ) {
+							$content[] = '<DEFAULT value="' . $details->default_value . '"/>';
+						}
+						
+						if( $details->auto_increment ) {
+							$content[] = '<AUTOINCREMENT/>';
+						}
+						
+						// this stops the creation of 'R' columns,
+						// AUTOINCREMENT is used to create auto columns
+						$details->primary_key = 0;
+						$type = $rs->MetaType( $details );
+						
+						$schema .= '		<field name="' . $details->name . '" type="' . $type . '"' . $extra . '>';
+						
+						if( !empty( $content ) ) {
+							$schema .= "\n			" . implode( "\n			", $content ) . "\n		";
+						}
+						
+						$schema .= '</field>' . "\n";
+					}
+				}
+				
+				if( is_array( $indexes ) ) {
+					foreach( $indexes as $index => $details ) {
+						$schema .= '		<index name="' . $index . '">' . "\n";
+						
+						if( $details['unique'] ) {
+							$schema .= '			<UNIQUE/>' . "\n";
+						}
+						
+						foreach( $details['columns'] as $column ) {
+							$schema .= '			<col>' . $column . '</col>' . "\n";
+						}
+						
+						$schema .= '		</index>' . "\n";
+					}
+				}
+				
+				if( $data ) {
+					$rs = $this->db->Execute( 'SELECT * FROM ' . $table );
+					
+					if( is_object( $rs ) ) {
+						$schema .= '		<data>' . "\n";
+						
+						while( $row = $rs->FetchRow() ) {
+							foreach( $row as $key => $val ) {
+								$row[$key] = htmlentities($val);
+							}
+							
+							$schema .= '			<row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";
+						}
+						
+						$schema .= '		</data>' . "\n";
+					}
+				}
+				
+				$schema .= '	</table>' . "\n";
+			}
+		}
+		
+		$this->db->SetFetchMode( $old_mode );
+		
+		$schema .= '</schema>';
+		return $schema;
+	}
+	
+	/**
+	* Sets a prefix for database objects
+	*
+	* Call this method to set a standard prefix that will be prepended to all database tables 
+	* and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
+	*
+	* @param string $prefix Prefix that will be prepended.
+	* @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
+	* @return boolean TRUE if successful, else FALSE
+	*/
+	function SetPrefix( $prefix = '', $underscore = TRUE ) {
+		switch( TRUE ) {
+			// clear prefix
+			case empty( $prefix ):
+				logMsg( 'Cleared prefix' );
+				$this->objectPrefix = '';
+				return TRUE;
+			// prefix too long
+			case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:
+			// prefix contains invalid characters
+			case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
+				logMsg( 'Invalid prefix: ' . $prefix );
+				return FALSE;
+		}
+		
+		if( $underscore AND substr( $prefix, -1 ) != '_' ) {
+			$prefix .= '_';
+		}
+		
+		// prefix valid
+		logMsg( 'Set prefix: ' . $prefix );
+		$this->objectPrefix = $prefix;
+		return TRUE;
+	}
+	
+	/**
+	* Returns an object name with the current prefix prepended.
+	*
+	* @param string	$name Name
+	* @return string	Prefixed name
+	*
+	* @access private
+	*/
+	function prefix( $name = '' ) {
+		// if prefix is set
+		if( !empty( $this->objectPrefix ) ) {
+			// Prepend the object prefix to the table name
+			// prepend after quote if used
+			return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );
+		}
+		
+		// No prefix set. Use name provided.
+		return $name;
+	}
+	
+	/**
+	* Checks if element references a specific platform
+	*
+	* @param string $platform Requested platform
+	* @returns boolean TRUE if platform check succeeds
+	*
+	* @access private
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		$regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/';
+		
+		if( !isset( $platform ) OR preg_match( $regex, $platform ) ) {
+			logMsg( "Platform $platform is supported" );
+			return TRUE;
+		} else {
+			logMsg( "Platform $platform is NOT supported" );
+			return FALSE;
+		}
+	}
+	
+	/**
+	* Clears the array of generated SQL.
+	*
+	* @access private
+	*/
+	function clearSQL() {
+		$this->sqlArray = array();
+	}
+	
+	/**
+	* Adds SQL into the SQL array.
+	*
+	* @param mixed $sql SQL to Add
+	* @return boolean TRUE if successful, else FALSE.
+	*
+	* @access private
+	*/	
+	function addSQL( $sql = NULL ) {
+		if( is_array( $sql ) ) {
+			foreach( $sql as $line ) {
+				$this->addSQL( $line );
+			}
+			
+			return TRUE;
+		}
+		
+		if( is_string( $sql ) ) {
+			$this->sqlArray[] = $sql;
+			
+			// if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
+			if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {
+				$saved = $this->db->debug;
+				$this->db->debug = $this->debug;
+				$ok = $this->db->Execute( $sql );
+				$this->db->debug = $saved;
+				
+				if( !$ok ) {
+					if( $this->debug ) {
+						ADOConnection::outp( $this->db->ErrorMsg() );
+					}
+					
+					$this->success = 1;
+				}
+			}
+			
+			return TRUE;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Gets the SQL array in the specified format.
+	*
+	* @param string $format Format
+	* @return mixed SQL
+	*	
+	* @access private
+	*/
+	function getSQL( $format = NULL, $sqlArray = NULL ) {
+		if( !is_array( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		switch( strtolower( $format ) ) {
+			case 'string':
+			case 'text':
+				return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';
+			case'html':
+				return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
+		}
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Destroys an adoSchema object.
+	*
+	* Call this method to clean up after an adoSchema object that is no longer in use.
+	* @deprecated adoSchema now cleans up automatically.
+	*/
+	function Destroy() {
+		ini_set("magic_quotes_runtime", $this->mgq );
+		#set_magic_quotes_runtime( $this->mgq );
+		unset( $this );
+	}
+}
+
+/**
+* Message logging function
+*
+* @access private
+*/
+function logMsg( $msg, $title = NULL, $force = FALSE ) {
+	if( XMLS_DEBUG or $force ) {
+		echo '<pre>';
+		
+		if( isset( $title ) ) {
+			echo '<h3>' . htmlentities( $title ) . '</h3>';
+		}
+		
+		if( is_object( $this ) ) {
+			echo '[' . get_class( $this ) . '] ';
+		}
+		
+		print_r( $msg );
+		
+		echo '</pre>';
+	}
+}
+?>
\ No newline at end of file
Index: adodb-xmlschema03.inc.php
===================================================================
--- adodb-xmlschema03.inc.php	(revision 13354)
+++ adodb-xmlschema03.inc.php	(working copy)
@@ -137,7 +137,7 @@
 	* NOP
 	*/
 	function dbObject( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
+		$this->parent = $parent;
 	}
 	
 	/**
@@ -167,7 +167,7 @@
 		
 	}
 	
-	function create() {
+	function create(&$xmls) {
 		return array();
 	}
 	
@@ -274,7 +274,7 @@
 	* @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 @@
 	* @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 @@
 	* @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 @@
 	* @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 @@
 	* @internal
 	*/
 	function dbIndex( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
+		$this->parent = $parent;
 		
 		$this->name = $this->prefix ($attributes['NAME']);
 	}
@@ -828,7 +829,7 @@
 	* @internal
 	*/
 	function dbData( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
+		$this->parent = $parent;
 	}
 	
 	/**
@@ -1084,7 +1085,7 @@
 	* @param array $attributes Attributes
 	*/
 	function dbQuerySet( &$parent, $attributes = NULL ) {
-		$this->parent =& $parent;
+		$this->parent = $parent;
 			
 		// Overrides the manual prefix key
 		if( isset( $attributes['KEY'] ) ) {
@@ -1404,12 +1405,13 @@
 	*
 	* @param object $db ADOdb database connection object.
 	*/
-	function adoSchema( &$db ) {
+	function adoSchema( $db ) {
 		// Initialize the environment
 		$this->mgq = get_magic_quotes_runtime();
-		set_magic_quotes_runtime(0);
+		#set_magic_quotes_runtime(0);
+		ini_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 +1499,7 @@
 					$mode = XMLS_MODE_INSERT;
 					break;
 				default:
-					$mode = XMLS_EXISITNG_DATA;
+					$mode = XMLS_EXISTING_DATA;
 					break;
 			}
 			$this->existingData = $mode;
@@ -1785,7 +1787,7 @@
 	*
 	* @access private
 	*/
-	function &create_parser() {
+	function create_parser() {
 		// Create the parser
 		$xmlParser = xml_parser_create();
 		xml_set_object( $xmlParser, $this );
@@ -2092,16 +2094,20 @@
 	* in the schema. 
 	*
 	* @param boolean $data Include data in schema dump
+	* @indent string indentation to use
+	* @prefix string extract only tables with given prefix
+	* @stripprefix strip prefix string when storing in XML schema
 	* @return string Generated XML schema
 	*/
-	function ExtractSchema( $data = FALSE, $indent = '  ' ) {
+	function ExtractSchema( $data = FALSE, $indent = '  ', $prefix = '' , $stripprefix=false) {
 		$old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
 		
 		$schema = '<?xml version="1.0"?>' . "\n"
 				. '<schema version="' . $this->schemaVersion . '">' . "\n";
 		
-		if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {
+		if( is_array( $tables = $this->db->MetaTables( 'TABLES' , ($prefix) ? $prefix.'%' : '') ) ) {
 			foreach( $tables as $table ) {
+				if ($stripprefix) $table = str_replace(str_replace('\\_', '_', $pfx ), '', $table);
 				$schema .= $indent . '<table name="' . htmlentities( $table ) . '">' . "\n";
 				
 				// grab details from database
@@ -2369,7 +2375,8 @@
 	* @deprecated adoSchema now cleans up automatically.
 	*/
 	function Destroy() {
-		set_magic_quotes_runtime( $this->mgq );
+		ini_set("magic_quotes_runtime", $this->mgq );
+		#set_magic_quotes_runtime( $this->mgq );
 		unset( $this );
 	}
 }
Index: adodb.inc.php
===================================================================
--- adodb.inc.php	(revision 13354)
+++ adodb.inc.php	(working copy)
@@ -12,9 +12,9 @@
  */
 
 /**
-	\mainpage 	
+	\mainpage
 	
-	 @version V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+	 @version V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
 
 	Released under both BSD license and Lesser GPL library license. You can choose which license
 	you prefer.
@@ -54,9 +54,13 @@
 		$ADODB_vers, 		// database version
 		$ADODB_COUNTRECS,	// count number of records returned - slows down query
 		$ADODB_CACHE_DIR,	// directory to cache recordsets
+		$ADODB_CACHE,
+		$ADODB_CACHE_CLASS,
 		$ADODB_EXTENSION,   // ADODB extension installed
 		$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
-	 	$ADODB_FETCH_MODE;	// DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+	 	$ADODB_FETCH_MODE,	// DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+		$ADODB_GETONE_EOF,
+		$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.	
 	
 	//==============================================================================================	
 	// GLOBAL SETUP
@@ -110,19 +114,15 @@
 	
 		// PHP's version scheme makes converting to numbers difficult - workaround
 		$_adodb_ver = (float) PHP_VERSION;
-		if ($_adodb_ver >= 5.0) {
+		if ($_adodb_ver >= 5.2) {
+			define('ADODB_PHPVER',0x5200);
+		} else if ($_adodb_ver >= 5.0) {
 			define('ADODB_PHPVER',0x5000);
-		} else if ($_adodb_ver > 4.299999) { # 4.3
-			define('ADODB_PHPVER',0x4300);
-		} else if ($_adodb_ver > 4.199999) { # 4.2
-			define('ADODB_PHPVER',0x4200);
-		} else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
-			define('ADODB_PHPVER',0x4050);
-		} else {
-			define('ADODB_PHPVER',0x4000);
-		}
+		} else 
+			die("PHP5 or later required. You are running ".PHP_VERSION);
 	}
 	
+	
 	//if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
 
 	
@@ -150,12 +150,17 @@
 		$ADODB_COUNTRECS,	// count number of records returned - slows down query
 		$ADODB_CACHE_DIR,	// directory to cache recordsets
 	 	$ADODB_FETCH_MODE,
-		$ADODB_FORCE_TYPE;
+		$ADODB_CACHE,
+		$ADODB_CACHE_CLASS,
+		$ADODB_FORCE_TYPE,
+		$ADODB_GETONE_EOF,
+		$ADODB_QUOTE_FIELDNAMES;
 		
+		if (empty($ADODB_CACHE_CLASS)) $ADODB_CACHE_CLASS =  'ADODB_Cache_File' ;
 		$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
 		$ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
+		$ADODB_GETONE_EOF = null;
 
-
 		if (!isset($ADODB_CACHE_DIR)) {
 			$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
 		} else {
@@ -166,12 +171,13 @@
 		
 			
 		// Initialize random number generator for randomizing cache flushes
-		srand(((double)microtime())*1000000);
+		// -- note Since PHP 4.2.0, the seed  becomes optional and defaults to a random value if omitted.
+		 srand(((double)microtime())*1000000);
 		
 		/**
 		 * ADODB version as a string.
 		 */
-		$ADODB_vers = 'V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
+		$ADODB_vers = 'V5.11 5 May 2010  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
 	
 		/**
 		 * Determines whether recordset->RecordCount() is used. 
@@ -210,7 +216,7 @@
 */
 	}
 	
-
+	// for transaction handling
 	
 	function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
 	{
@@ -222,6 +228,95 @@
 		}
 	}
 	
+	//------------------
+	// class for caching
+	class ADODB_Cache_File {
+	
+		var $createdir = true; // requires creation of temp dirs
+		
+		function ADODB_Cache_File()
+		{
+		global $ADODB_INCLUDED_CSV;
+			if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+		}
+		
+		// write serialised recordset to cache item/file
+		function writecache($filename, $contents,  $debug, $secs2cache)
+		{
+			return adodb_write_file($filename, $contents,$debug);
+		}
+		
+		// load serialised recordset and unserialise it
+		function &readcache($filename, &$err, $secs2cache, $rsClass)
+		{
+			$rs = csv2rs($filename,$err,$secs2cache,$rsClass);
+			return $rs;
+		}
+		
+		// flush all items in cache
+		function flushall($debug=false)
+		{
+		global $ADODB_CACHE_DIR;
+
+		$rez = false;
+		
+			if (strlen($ADODB_CACHE_DIR) > 1) {
+				$rez = $this->_dirFlush($ADODB_CACHE_DIR);
+	         	if ($debug) ADOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
+	   		}
+			return $rez;
+		}
+		
+		// flush one file in cache
+		function flushcache($f, $debug=false)
+		{
+			if (!@unlink($f)) {
+		   		if ($debug) ADOConnection::outp( "flushcache: failed for $f");
+			}
+		}
+		
+		function getdirname($hash)
+		{
+		global $ADODB_CACHE_DIR;
+			if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
+			return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
+		}
+		
+		// create temp directories
+		function createdir($hash, $debug)
+		{
+			$dir = $this->getdirname($hash);
+			if ($this->notSafeMode && !file_exists($dir)) {
+				$oldu = umask(0);
+				if (!@mkdir($dir,0771)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
+				umask($oldu);
+			}
+		
+			return $dir;
+		}
+		
+		/**
+		* Private function to erase all of the files and subdirectories in a directory.
+		*
+		* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
+		* Note: $kill_top_level is used internally in the function to flush subdirectories.
+		*/
+		function _dirFlush($dir, $kill_top_level = false) 
+		{
+		   if(!$dh = @opendir($dir)) return;
+		   
+		   while (($obj = readdir($dh))) {
+		   		if($obj=='.' || $obj=='..') continue;
+				$f = $dir.'/'.$obj;
+		
+				if (strpos($obj,'.cache')) @unlink($f);
+				if (is_dir($f)) $this->_dirFlush($f, true);
+		   }
+		   if ($kill_top_level === true) @rmdir($dir);
+		   return true;
+		}
+	}
+	
 	//==============================================================================================	
 	// CLASS ADOConnection
 	//==============================================================================================	
@@ -273,8 +368,16 @@
 	var $raiseErrorFn = false; 	/// error function to call
 	var $isoDates = false; /// accepts dates in ISO format
 	var $cacheSecs = 3600; /// cache for 1 hour
+
+	// memcache
+	var $memCache = false; /// should we use memCache instead of caching in files
+	var $memCacheHost; /// memCache host
+	var $memCachePort = 11211; /// memCache port
+	var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
+
 	var $sysDate = false; /// name of function that returns the current date
 	var $sysTimeStamp = false; /// name of function that returns the current timestamp
+	var $sysUTimeStamp = false; // name of function that returns the current timestamp accurate to the microsecond or nearest fraction
 	var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
 	
 	var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
@@ -298,6 +401,9 @@
 	var $transCnt = 0; 			/// count of nested transactions
 	
 	var $fetchMode=false;
+	
+	var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
+	var $bulkBind = false; // enable 2D Execute array
 	 //
 	 // PRIVATE VARS
 	 //
@@ -316,6 +422,8 @@
 	var $_logsql = false;
 	var $_transmode = ''; // transaction mode
 	
+
+	
 	/**
 	 * Constructor
 	 */
@@ -324,11 +432,13 @@
 		die('Virtual Class -- cannot instantiate');
 	}
 	
-	function Version()
+	static function Version()
 	{
 	global $ADODB_vers;
 	
-		return (float) substr($ADODB_vers,1);
+		$ok = preg_match( '/^[Vv]([0-9\.]+)/', $ADODB_vers, $matches );
+		if (!$ok) return (float) substr($ADODB_vers,1);
+		else return $matches[1];
 	}
 	
 	/**
@@ -357,7 +467,7 @@
 	* All error messages go through this bottleneck function.
 	* You can define your own handler by defining the function name in ADODB_OUTP.
 	*/
-	function outp($msg,$newline=true)
+	static function outp($msg,$newline=true)
 	{
 	global $ADODB_FLUSH,$ADODB_OUTP;
 	
@@ -383,7 +493,7 @@
 	
 	function Time()
 	{
-		$rs =& $this->_Execute("select $this->sysTimeStamp");
+		$rs = $this->_Execute("select $this->sysTimeStamp");
 		if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
 		
 		return false;
@@ -404,14 +514,15 @@
 	{
 		if ($argHostname != "") $this->host = $argHostname;
 		if ($argUsername != "") $this->user = $argUsername;
-		if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
+		if ($argPassword != "") $this->password = 'not stored'; // not stored for security reasons
 		if ($argDatabaseName != "") $this->database = $argDatabaseName;		
 		
 		$this->_isPersistentConnection = false;	
+			
 		if ($forceNew) {
-			if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
+			if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) return true;
 		} else {
-			 if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
+			 if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) return true;
 		}
 		if (isset($rez)) {
 			$err = $this->ErrorMsg();
@@ -463,16 +574,18 @@
 	 */	
 	function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
 	{
+		
 		if (defined('ADODB_NEVER_PERSIST')) 
 			return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
 		
 		if ($argHostname != "") $this->host = $argHostname;
 		if ($argUsername != "") $this->user = $argUsername;
-		if ($argPassword != "") $this->password = $argPassword;
+		if ($argPassword != "") $this->password = 'not stored';
 		if ($argDatabaseName != "") $this->database = $argDatabaseName;		
 			
 		$this->_isPersistentConnection = true;	
-		if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
+		
+		if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) return true;
 		if (isset($rez)) {
 			$err = $this->ErrorMsg();
 			if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
@@ -490,6 +603,30 @@
 		return $ret;
 	}
 
+	function outp_throw($msg,$src='WARN',$sql='')
+	{
+		if (defined('ADODB_ERROR_HANDLER') &&  ADODB_ERROR_HANDLER == 'adodb_throw') {
+			adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
+			return;
+		} 
+		ADOConnection::outp($msg);
+	}
+	
+	// create cache class. Code is backward compat with old memcache implementation
+	function _CreateCache()
+	{
+	global $ADODB_CACHE, $ADODB_CACHE_CLASS;
+	
+		if ($this->memCache) {
+		global $ADODB_INCLUDED_MEMCACHE;
+		
+			if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+				$ADODB_CACHE = new ADODB_Cache_MemCache($this);
+		} else
+				$ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
+		
+	}
+	
 	// Format date column in sql string given an input format that understands Y M D
 	function SQLDate($fmt, $col=false)
 	{	
@@ -516,7 +653,7 @@
 	{
 		return $sql;
 	}
-	
+
 	/**
 	 * Some databases, eg. mssql require a different function for preparing
 	 * stored procedures. So we cannot use Prepare().
@@ -535,7 +672,7 @@
 	{
 		return $this->Prepare($sql,$param);
 	}
-	
+
 	/**
 	* PEAR DB Compat
 	*/
@@ -582,7 +719,7 @@
 	*  @param $table	name of table to lock
 	*  @param $where	where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
 	*/
-	function RowLock($table,$where)
+	function RowLock($table,$where,$col='1 as adodbignore')
 	{
 		return false;
 	}
@@ -622,9 +759,9 @@
 	/**
 	* PEAR DB Compat - do not use internally. 
 	*/
-	function &Query($sql, $inputarr=false)
+	function Query($sql, $inputarr=false)
 	{
-		$rs = &$this->Execute($sql, $inputarr);
+		$rs = $this->Execute($sql, $inputarr);
 		if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
 		return $rs;
 	}
@@ -633,9 +770,9 @@
 	/**
 	* PEAR DB Compat - do not use internally
 	*/
-	function &LimitQuery($sql, $offset, $count, $params=false)
+	function LimitQuery($sql, $offset, $count, $params=false)
 	{
-		$rs = &$this->SelectLimit($sql, $count, $offset, $params); 
+		$rs = $this->SelectLimit($sql, $count, $offset, $params); 
 		if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
 		return $rs;
 	}
@@ -678,6 +815,7 @@
 		return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
 	
 	}
+
 	
 	/* 
 	Usage in oracle
@@ -699,6 +837,19 @@
 		return false;
 	}
 	
+	
+	function IgnoreErrors($saveErrs=false)
+	{
+		if (!$saveErrs) {
+			$saveErrs = array($this->raiseErrorFn,$this->_transOK);
+			$this->raiseErrorFn = false;
+			return $saveErrs;
+		} else {
+			$this->raiseErrorFn = $saveErrs[0];
+			$this->_transOK = $saveErrs[1];
+		}
+	}
+	
 	/**
 		Improved method of initiating a transaction. Used together with CompleteTrans().
 		Advantages include:
@@ -713,7 +864,7 @@
 	{
 		if ($this->transOff > 0) {
 			$this->transOff += 1;
-			return;
+			return true;
 		}
 		
 		$this->_oldRaiseFn = $this->raiseErrorFn;
@@ -721,8 +872,9 @@
 		$this->_transOK = true;
 		
 		if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
-		$this->BeginTrans();
+		$ok = $this->BeginTrans();
 		$this->transOff = 1;
+		return $ok;
 	}
 	
 	
@@ -789,11 +941,11 @@
 	 * @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) {
@@ -801,13 +953,13 @@
 			
 			$element0 = reset($inputarr);
 			# is_object check because oci8 descriptors can be passed in
-			$array_2d = is_array($element0) && !is_object(reset($element0));
+			$array_2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0));
 			//remove extra memory copy of input -mikefedyk
 			unset($element0);
 			
 			if (!is_array($sql) && !$this->_bindInputArray) {
 				$sqlarr = explode('?',$sql);
-					
+				$nparams = sizeof($sqlarr)-1;
 				if (!$array_2d) $inputarr = array($inputarr);
 				foreach($inputarr as $arr) {
 					$sql = ''; $i = 0;
@@ -832,14 +984,16 @@
 						else
 							$sql .= $v;
 						$i += 1;
-					}
+						
+						if ($i == $nparams) break;
+					} // while
 					if (isset($sqlarr[$i])) {
 						$sql .= $sqlarr[$i];
-						if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
+						if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
 					} else if ($i != sizeof($sqlarr))	
-						ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
+						$this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute');
 		
-					$ret =& $this->_Execute($sql);
+					$ret = $this->_Execute($sql);
 					if (!$ret) return $ret;
 				}	
 			} else {
@@ -850,22 +1004,22 @@
 						$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);
+					$ret = $this->_Execute($sql,$inputarr);
 				}
 			}
 		} else {
-			$ret =& $this->_Execute($sql,false);
+			$ret = $this->_Execute($sql,false);
 		}
 
 		return $ret;
 	}
 	
 	
-	function &_Execute($sql,$inputarr=false)
+	function _Execute($sql,$inputarr=false)
 	{
 		if ($this->debug) {
 			global $ADODB_INCLUDED_LIB;
@@ -890,14 +1044,16 @@
 		} 
 		
 		if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
-			$rs =& new ADORecordSet_empty();
+			$rsclass = $this->rsPrefix.'empty';
+			$rs = (class_exists($rsclass)) ? new $rsclass():  new ADORecordSet_empty();
+			
 			return $rs;
 		}
 		
 		// return real recordset from select statement
 		$rsclass = $this->rsPrefix.$this->databaseType;
 		$rs = new $rsclass($this->_queryID,$this->fetchMode);
-		$rs->connection = &$this; // Pablo suggestion
+		$rs->connection = $this; // Pablo suggestion
 		$rs->Init();
 		if (is_array($sql)) $rs->sql = $sql[0];
 		else $rs->sql = $sql;
@@ -905,7 +1061,7 @@
 		global $ADODB_COUNTRECS;
 			if ($ADODB_COUNTRECS) {
 				if (!$rs->EOF) { 
-					$rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
+					$rs = $this->_rs2rs($rs,-1,-1,!is_array($sql));
 					$rs->_queryID = $this->_queryID;
 				} else
 					$rs->_numOfRows = 0;
@@ -1050,7 +1206,7 @@
 	{
 	// owner not used in base class - see oci8
 		$p = array();
-		$objs =& $this->MetaColumns($table);
+		$objs = $this->MetaColumns($table);
 		if ($objs) {
 			foreach($objs as $v) {
 				if (!empty($v->primary_key))
@@ -1099,7 +1255,7 @@
 	* @param [secs2cache]		is a private parameter only used by jlim
 	* @return		the recordset ($rs->databaseType == 'array')
  	*/
-	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
 	{
 		if ($this->hasTop && $nrows > 0) {
 		// suggested by Reinhard Balling. Access requires top after distinct 
@@ -1108,17 +1264,17 @@
 			if ($ismssql) $isaccess = false;
 			else $isaccess = (strpos($this->databaseType,'access') !== false);
 			
-			if ($offset <= 0) {
+			if ($offset <= 	0) {
 				
 					// access includes ties in result
 					if ($isaccess) {
 						$sql = preg_replace(
 						'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
 
-						if ($secs2cache>0) {
-							$ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
+						if ($secs2cache != 0) {
+							$ret = $this->CacheExecute($secs2cache, $sql,$inputarr);
 						} else {
-							$ret =& $this->Execute($sql,$inputarr);
+							$ret = $this->Execute($sql,$inputarr);
 						}
 						return $ret; // PHP5 fix
 					} else if ($ismssql){
@@ -1147,16 +1303,13 @@
 		$savec = $ADODB_COUNTRECS;
 		$ADODB_COUNTRECS = false;
 			
-		if ($offset>0){
-			if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
-			else $rs = &$this->Execute($sql,$inputarr);
-		} else {
-			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);
+		
 		$ADODB_COUNTRECS = $savec;
 		if ($rs && !$rs->EOF) {
-			$rs =& $this->_rs2rs($rs,$nrows,$offset);
+			$rs = $this->_rs2rs($rs,$nrows,$offset);
 		}
 		//print_r($rs);
 		return $rs;
@@ -1167,11 +1320,11 @@
 	*
 	* @param rs			the recordset to serialize
 	*/
-	function &SerializableRS(&$rs)
+	function SerializableRS(&$rs)
 	{
-		$rs2 =& $this->_rs2rs($rs);
+		$rs2 = $this->_rs2rs($rs);
 		$ignore = false;
-		$rs2->connection =& $ignore;
+		$rs2->connection = $ignore;
 		
 		return $rs2;
 	}
@@ -1194,12 +1347,12 @@
 		}
 		$dbtype = $rs->databaseType;
 		if (!$dbtype) {
-			$rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
+			$rs = $rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
 			return $rs;
 		}
 		if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
 			$rs->MoveFirst();
-			$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
+			$rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
 			return $rs;
 		}
 		$flds = array();
@@ -1207,14 +1360,14 @@
 			$flds[] = $rs->FetchField($i);
 		}
 
-		$arr =& $rs->GetArrayLimit($nrows,$offset);
+		$arr = $rs->GetArrayLimit($nrows,$offset);
 		//print_r($arr);
 		if ($close) $rs->Close();
 		
 		$arrayClass = $this->arrayClass;
 		
 		$rs2 = new $arrayClass();
-		$rs2->connection = &$this;
+		$rs2->connection = $this;
 		$rs2->sql = $rs->sql;
 		$rs2->dataProvider = $this->dataProvider;
 		$rs2->InitArrayFields($arr,$flds);
@@ -1225,35 +1378,35 @@
 	/*
 	* Return all rows. Compat with PEAR DB
 	*/
-	function &GetAll($sql, $inputarr=false)
+	function GetAll($sql, $inputarr=false)
 	{
-		$arr =& $this->GetArray($sql,$inputarr);
+		$arr = $this->GetArray($sql,$inputarr);
 		return $arr;
 	}
 	
-	function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
+	function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
 	{
-		$rs =& $this->Execute($sql, $inputarr);
+		$rs = $this->Execute($sql, $inputarr);
 		if (!$rs) {
 			$false = false;
 			return $false;
 		}
-		$arr =& $rs->GetAssoc($force_array,$first2cols);
+		$arr = $rs->GetAssoc($force_array,$first2cols);
 		return $arr;
 	}
 	
-	function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
+	function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
 	{
 		if (!is_numeric($secs2cache)) {
 			$first2cols = $force_array;
 			$force_array = $inputarr;
 		}
-		$rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
+		$rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
 		if (!$rs) {
 			$false = false;
 			return $false;
 		}
-		$arr =& $rs->GetAssoc($force_array,$first2cols);
+		$arr = $rs->GetAssoc($force_array,$first2cols);
 		return $arr;
 	}
 	
@@ -1266,26 +1419,43 @@
 	*/
 	function GetOne($sql,$inputarr=false)
 	{
-	global $ADODB_COUNTRECS;
+	global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
 		$crecs = $ADODB_COUNTRECS;
 		$ADODB_COUNTRECS = false;
 		
 		$ret = false;
-		$rs = &$this->Execute($sql,$inputarr);
+		$rs = $this->Execute($sql,$inputarr);
 		if ($rs) {	
-			if (!$rs->EOF) $ret = reset($rs->fields);
+			if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
+			else $ret = reset($rs->fields);
+			
 			$rs->Close();
 		}
 		$ADODB_COUNTRECS = $crecs;
 		return $ret;
 	}
 	
+	// $where should include 'WHERE fld=value'
+	function GetMedian($table, $field,$where = '')
+	{
+		$total = $this->GetOne("select count(*) from $table $where");
+		if (!$total) return false;
+	
+		$midrow = (integer) ($total/2);
+		$rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
+		if ($rs && !$rs->EOF) return reset($rs->fields);
+		return false;
+	}
+	
+	
 	function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
 	{
+	global $ADODB_GETONE_EOF;
 		$ret = false;
-		$rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
-		if ($rs) {		
-			if (!$rs->EOF) $ret = reset($rs->fields);
+		$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
+		if ($rs) {
+			if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
+			else $ret = reset($rs->fields);
 			$rs->Close();
 		} 
 		
@@ -1294,8 +1464,8 @@
 	
 	function GetCol($sql, $inputarr = false, $trim = false)
 	{
-	  	$rv = false;
-	  	$rs = &$this->Execute($sql, $inputarr);
+	  	
+	  	$rs = $this->Execute($sql, $inputarr);
 	  	if ($rs) {
 			$rv = array();
 	   		if ($trim) {
@@ -1310,15 +1480,16 @@
 		   		}
 			}
 	   		$rs->Close();
-	  	}
+	  	} else
+			$rv = false;
 	  	return $rv;
 	}
 	
 	function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
 	{
-	  	$rv = false;
-	  	$rs = &$this->CacheExecute($secs, $sql, $inputarr);
+	  	$rs = $this->CacheExecute($secs, $sql, $inputarr);
 	  	if ($rs) {
+			$rv = array();
 			if ($trim) {
 				while (!$rs->EOF) {
 					$rv[] = trim(reset($rs->fields));
@@ -1331,9 +1502,21 @@
 		   		}
 			}
 	   		$rs->Close();
-	  	}
+	  	} else
+			$rv = false;
+			
 	  	return $rv;
 	}
+	
+	function Transpose(&$rs,$addfieldnames=true)
+	{
+		$rs2 = $this->_rs2rs($rs);
+		$false = false;
+		if (!$rs2) return $false;
+		
+		$rs2->_transpose($addfieldnames);
+		return $rs2;
+	}
  
 	/*
 		Calculate the offset of a date for a particular database and generate
@@ -1354,13 +1537,13 @@
 	* @param sql			SQL statement
 	* @param [inputarr]		input bind array
 	*/
-	function &GetArray($sql,$inputarr=false)
+	function GetArray($sql,$inputarr=false)
 	{
 	global $ADODB_COUNTRECS;
 		
 		$savec = $ADODB_COUNTRECS;
 		$ADODB_COUNTRECS = false;
-		$rs =& $this->Execute($sql,$inputarr);
+		$rs = $this->Execute($sql,$inputarr);
 		$ADODB_COUNTRECS = $savec;
 		if (!$rs) 
 			if (defined('ADODB_PEAR')) {
@@ -1370,23 +1553,24 @@
 				$false = false;
 				return $false;
 			}
-		$arr =& $rs->GetArray();
+		$arr = $rs->GetArray();
 		$rs->Close();
 		return $arr;
 	}
 	
-	function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
+	function CacheGetAll($secs2cache,$sql=false,$inputarr=false)
 	{
-		return $this->CacheGetArray($secs2cache,$sql,$inputarr);
+		$arr = $this->CacheGetArray($secs2cache,$sql,$inputarr);
+		return $arr;
 	}
 	
-	function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
+	function CacheGetArray($secs2cache,$sql=false,$inputarr=false)
 	{
 	global $ADODB_COUNTRECS;
 		
 		$savec = $ADODB_COUNTRECS;
 		$ADODB_COUNTRECS = false;
-		$rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+		$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
 		$ADODB_COUNTRECS = $savec;
 		
 		if (!$rs) 
@@ -1397,26 +1581,31 @@
 				$false = false;
 				return $false;
 			}
-		$arr =& $rs->GetArray();
+		$arr = $rs->GetArray();
 		$rs->Close();
 		return $arr;
 	}
 	
+	function GetRandRow($sql, $arr= false)
+	{
+		$rezarr = $this->GetAll($sql, $arr);
+		$sz = sizeof($rezarr);
+		return $rezarr[abs(rand()) % $sz];
+	}
 	
-	
 	/**
 	* Return one row of sql statement. Recordset is disposed for you.
 	*
 	* @param sql			SQL statement
 	* @param [inputarr]		input bind array
 	*/
-	function &GetRow($sql,$inputarr=false)
+	function GetRow($sql,$inputarr=false)
 	{
 	global $ADODB_COUNTRECS;
 		$crecs = $ADODB_COUNTRECS;
 		$ADODB_COUNTRECS = false;
 		
-		$rs =& $this->Execute($sql,$inputarr);
+		$rs = $this->Execute($sql,$inputarr);
 		
 		$ADODB_COUNTRECS = $crecs;
 		if ($rs) {
@@ -1430,12 +1619,13 @@
 		return $false;
 	}
 	
-	function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
+	function CacheGetRow($secs2cache,$sql=false,$inputarr=false)
 	{
-		$rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+		$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
 		if ($rs) {
-			$arr = false;
 			if (!$rs->EOF) $arr = $rs->fields;
+			else $arr = array();
+			
 			$rs->Close();
 			return $arr;
 		}
@@ -1490,16 +1680,16 @@
 	* @param [inputarr]	array of bind variables
 	* @return		the recordset ($rs->databaseType == 'array')
  	*/
-	function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
+	function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
 	{	
 		if (!is_numeric($secs2cache)) {
 			if ($sql === false) $sql = -1;
 			if ($offset == -1) $offset = false;
 									  // sql,	nrows, offset,inputarr
-			$rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
+			$rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
 		} else {
-			if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
-			$rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+			if ($sql === false) $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
+			$rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
 		}
 		return $rs;
 	}
@@ -1516,83 +1706,19 @@
     */
 	function CacheFlush($sql=false,$inputarr=false)
 	{
-	global $ADODB_CACHE_DIR;
-	
-		if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
-         /*if (strncmp(PHP_OS,'WIN',3) === 0)
-            $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
-         else */
-            $dir = $ADODB_CACHE_DIR;
-            
-         if ($this->debug) {
-            ADOConnection::outp( "CacheFlush: $dir<br><pre>\n", $this->_dirFlush($dir),"</pre>");
-         } else {
-            $this->_dirFlush($dir);
-         }
-         return;
-      } 
-      
-      global $ADODB_INCLUDED_CSV;
-      if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
-      
-      $f = $this->_gencachename($sql.serialize($inputarr),false);
-      adodb_write_file($f,''); // is adodb_write_file needed?
-      if (!@unlink($f)) {
-         if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
-      }
-   }
-   
-   /**
-   * Private function to erase all of the files and subdirectories in a directory.
-   *
-   * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
-   * Note: $kill_top_level is used internally in the function to flush subdirectories.
-   */
-   function _dirFlush($dir, $kill_top_level = false) {
-      if(!$dh = @opendir($dir)) return;
-      
-      while (($obj = readdir($dh))) {
-         if($obj=='.' || $obj=='..')
-            continue;
-			
-         if (!@unlink($dir.'/'.$obj))
-			  $this->_dirFlush($dir.'/'.$obj, true);
-      }
-      if ($kill_top_level === true)
-         @rmdir($dir);
-      return true;
-   }
-   
-   
-	function xCacheFlush($sql=false,$inputarr=false)
-	{
-	global $ADODB_CACHE_DIR;
-	
-		if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
-			if (strncmp(PHP_OS,'WIN',3) === 0) {
-				$cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
-			} else {
-				//$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
-				$cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; 
-				// old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
-			}
-			if ($this->debug) {
-				ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
-			} else {
-				exec($cmd);
-			}
-			return;
-		} 
+	global $ADODB_CACHE_DIR, $ADODB_CACHE;
 		
-		global $ADODB_INCLUDED_CSV;
-		if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+		if (empty($ADODB_CACHE)) return false;
 		
+		if (!$sql) {
+			 $ADODB_CACHE->flushall($this->debug);
+	         return;
+	    }
+		
 		$f = $this->_gencachename($sql.serialize($inputarr),false);
-		adodb_write_file($f,''); // is adodb_write_file needed?
-		if (!@unlink($f)) {
-			if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
-		}
+		return $ADODB_CACHE->flushcache($f, $this->debug);
 	}
+   
 	
 	/**
 	* Private function to generate filename for caching.
@@ -1610,8 +1736,7 @@
  	*/
 	function _gencachename($sql,$createdir)
 	{
-	global $ADODB_CACHE_DIR;
-	static $notSafeMode;
+	global $ADODB_CACHE, $ADODB_CACHE_DIR;
 		
 		if ($this->fetchMode === false) { 
 		global $ADODB_FETCH_MODE;
@@ -1620,16 +1745,10 @@
 			$mode = $this->fetchMode;
 		}
 		$m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
+		if (!$ADODB_CACHE->createdir) return $m;
+		if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
+		else $dir = $ADODB_CACHE->createdir($m, $this->debug);
 		
-		if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
-		$dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
-			
-		if ($createdir && $notSafeMode && !file_exists($dir)) {
-			$oldu = umask(0);
-			if (!mkdir($dir,0771)) 
-				if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
-			umask($oldu);
-		}
 		return $dir.'/adodb_'.$m.'.cache';
 	}
 	
@@ -1643,10 +1762,12 @@
 	 * @param [inputarr]	holds the input data  to bind to
 	 * @return 		RecordSet or false
 	 */
-	function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
+	function CacheExecute($secs2cache,$sql=false,$inputarr=false)
 	{
-
-			
+	global $ADODB_CACHE;
+	
+		if (empty($ADODB_CACHE)) $this->_CreateCache();
+		
 		if (!is_numeric($secs2cache)) {
 			$inputarr = $sql;
 			$sql = $secs2cache;
@@ -1659,50 +1780,62 @@
 		} else
 			$sqlparam = $sql;
 			
-		global $ADODB_INCLUDED_CSV;
-		if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
 		
 		$md5file = $this->_gencachename($sql.serialize($inputarr),true);
 		$err = '';
 		
 		if ($secs2cache > 0){
-			$rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
+			$rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass);
 			$this->numCacheHits += 1;
 		} else {
 			$err='Timeout 1';
 			$rs = false;
 			$this->numCacheMisses += 1;
 		}
+		
 		if (!$rs) {
 		// no cached rs found
 			if ($this->debug) {
-				if (get_magic_quotes_runtime()) {
+				if (get_magic_quotes_runtime() && !$this->memCache) {
 					ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
 				}
 				if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
 			}
 			
-			$rs = &$this->Execute($sqlparam,$inputarr);
+			$rs = $this->Execute($sqlparam,$inputarr);
 
 			if ($rs) {
+
 				$eof = $rs->EOF;
-				$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
+				$rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
+				$rs->timeCreated = time(); // used by caching
 				$txt = _rs2serialize($rs,false,$sql); // serialize
-		
-				if (!adodb_write_file($md5file,$txt,$this->debug)) {
-					if ($fn = $this->raiseErrorFn) {
-						$fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
+	
+				$ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache);
+				if (!$ok) {
+					if ($ok === false) {
+						$em = 'Cache write error';
+						$en = -32000;
+						
+						if ($fn = $this->raiseErrorFn) {
+							$fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
+						}
+					} else {
+						$em = 'Cache file locked warning';
+						$en = -32001;
+						// do not call error handling for just a warning
 					}
-					if ($this->debug) ADOConnection::outp( " Cache write error");
+					
+					if ($this->debug) ADOConnection::outp( " ".$em);
 				}
 				if ($rs->EOF && !$eof) {
 					$rs->MoveFirst();
-					//$rs = &csv2rs($md5file,$err);		
-					$rs->connection = &$this; // Pablo suggestion
+					//$rs = csv2rs($md5file,$err);		
+					$rs->connection = $this; // Pablo suggestion
 				}  
 				
-			} else
-				@unlink($md5file);
+			} else if (!$this->memCache)
+				$ADODB_CACHE->flushcache($md5file);
 		} else {
 			$this->_errorMsg = '';
 			$this->_errorCode = 0;
@@ -1712,9 +1845,9 @@
 				$fn($this, $secs2cache, $sql, $inputarr);
 			}
 		// ok, set cached object found
-			$rs->connection = &$this; // Pablo suggestion
-			if ($this->debug){ 
-					
+			$rs->connection = $this; // Pablo suggestion
+			if ($this->debug){ 			
+				if ($this->debug == 99) adodb_backtrace();
 				$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
 				$ttl = $rs->timeCreated + $secs2cache - time();
 				$s = is_array($sql) ? $sql[0] : $sql;
@@ -1734,19 +1867,20 @@
 		
 		$forceUpdate means that even if the data has not changed, perform update.
 	 */
-	function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) 
+	function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) 
 	{
 		$false = false;
 		$sql = 'SELECT * FROM '.$table;  
 		if ($where!==FALSE) $sql .= ' WHERE '.$where;
 		else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
-			ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
+			$this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
 			return $false;
 		}
 
-		$rs =& $this->SelectLimit($sql,1);
+		$rs = $this->SelectLimit($sql,1);
 		if (!$rs) return $false; // table does not exist
 		$rs->tableName = $table;
+		$rs->sql = $sql;
 		
 		switch((string) $mode) {
 		case 'UPDATE':
@@ -1758,7 +1892,7 @@
 			$sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
 			break;
 		default:
-			ADOConnection::outp("AutoExecute: Unknown mode=$mode");
+			$this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
 			return $false;
 		}
 		$ret = false;
@@ -1916,8 +2050,8 @@
 		
 		if (empty($this->_metars)) {
 			$rsclass = $this->rsPrefix.$this->databaseType;
-			$this->_metars =& new $rsclass(false,$this->fetchMode); 
-			$this->_metars->connection =& $this;
+			$this->_metars = new $rsclass(false,$this->fetchMode); 
+			$this->_metars->connection = $this;
 		}
 		return $this->_metars->MetaType($t,$len,$fieldobj);
 	}
@@ -1942,6 +2076,7 @@
 				$this->fmtTimeStamp = "'m-d-Y H:i:s'";
 				break;
 				
+			case 'PT_BR': 	
 			case 'NL':
 			case 'FR':
 			case 'RO':
@@ -1962,46 +2097,34 @@
 		}
 	}
 
-	function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
+	/**
+	 * GetActiveRecordsClass Performs an 'ALL' query 
+	 * 
+	 * @param mixed $class This string represents the class of the current active record
+	 * @param mixed $table Table used by the active record object
+	 * @param mixed $whereOrderBy Where, order, by clauses
+	 * @param mixed $bindarr 
+	 * @param mixed $primkeyArr 
+	 * @param array $extra Query extras: limit, offset...
+	 * @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo"
+	 * @access public
+	 * @return void
+	 */
+	function GetActiveRecordsClass(
+			$class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false,
+			$extra=array(),
+			$relations=array())
 	{
 	global $_ADODB_ACTIVE_DBS;
-	
-		$save = $this->SetFetchMode(ADODB_FETCH_NUM);
-		if (empty($whereOrderBy)) $whereOrderBy = '1=1';
-		$rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
-		$this->SetFetchMode($save);
-		
-		$false = false;
-		
-		if ($rows === false) {	
-			return $false;
-		}
-		
-		
-		if (!isset($_ADODB_ACTIVE_DBS)) {
-			include(ADODB_DIR.'/adodb-active-record.inc.php');
-		}	
-		if (!class_exists($class)) {
-			ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()");
-			return $false;
-		}
-		$arr = array();
-		foreach($rows as $row) {
-		
-			$obj =& new $class($table,$primkeyArr,$this);
-			if ($obj->ErrorMsg()){
-				$this->_errorMsg = $obj->ErrorMsg();
-				return $false;
-			}
-			$obj->Set($row);
-			$arr[] =& $obj;
-		}
-		return $arr;
+		## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
+		## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
+		if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
+		return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
 	}
 	
-	function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
+	function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
 	{
-		$arr =& $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
+		$arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
 		return $arr;
 	}
 	
@@ -2020,7 +2143,11 @@
 	 *
 	 * @return true if succeeded or false if database does not support transactions
 	 */
-	function BeginTrans() {return false;}
+	function BeginTrans() 
+	{
+		if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
+		return false;
+	}
 	
 	/* set transaction mode */
 	function SetTransactionMode( $transaction_mode ) 
@@ -2131,7 +2258,7 @@
 	 *
 	 * @return  array of tables for current database.
 	 */ 
-	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	function MetaTables($ttype=false,$showSchema=false,$mask=false) 
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -2151,7 +2278,7 @@
 			$ADODB_FETCH_MODE = $save; 
 			
 			if ($rs === false) return $false;
-			$arr =& $rs->GetArray();
+			$arr = $rs->GetArray();
 			$arr2 = array();
 			
 			if ($hast = ($ttype && isset($arr[0][1]))) { 
@@ -2193,7 +2320,7 @@
 	 *
 	 * @return  array of ADOFieldObjects for current table.
 	 */
-	function &MetaColumns($table,$normalize=true) 
+	function MetaColumns($table,$normalize=true) 
 	{
 	global $ADODB_FETCH_MODE;
 		
@@ -2252,7 +2379,7 @@
 	          )
 		)		
       */
-     function &MetaIndexes($table, $primary = false, $owner = false)
+     function MetaIndexes($table, $primary = false, $owner = false)
      {
 	 		$false = false;
             return $false;
@@ -2264,9 +2391,9 @@
 	 *
 	 * @return  array of column names for current table.
 	 */ 
-	function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) 
+	function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) 
 	{
-		$objarr =& $this->MetaColumns($table);
+		$objarr = $this->MetaColumns($table);
 		if (!is_array($objarr)) {
 			$false = false;
 			return $false;
@@ -2310,10 +2437,14 @@
 	 *
 	 * @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 $d;
+		
+		if (is_object($d)) return $d->format($this->fmtDate);
+		
+		
 		if (is_string($d) && !is_numeric($d)) {
 			if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
 			if ($this->isoDates) return "'$d'";
@@ -2347,10 +2478,12 @@
 	 *
 	 * @return  timestamp string in database timestamp format
 	 */
-	function DBTimeStamp($ts)
+	function DBTimeStamp($ts,$isfld=false)
 	{
 		if (empty($ts) && $ts !== 0) return 'null';
-
+		if ($isfld) return $ts;
+		if (is_object($ts)) return $ts->format($this->fmtTimeStamp);
+		
 		# strlen(14) allows YYYYMMDDHHMMSS format
 		if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) 
 			return adodb_date($this->fmtTimeStamp,$ts);
@@ -2368,7 +2501,7 @@
 	 *
 	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
 	 */
-	function UnixDate($v)
+	static function UnixDate($v)
 	{
 		if (is_object($v)) {
 		// odbtp support
@@ -2392,7 +2525,7 @@
 	 *
 	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
 	 */
-	function UnixTimeStamp($v)
+	static function UnixTimeStamp($v)
 	{
 		if (is_object($v)) {
 		// odbtp support
@@ -2478,7 +2611,7 @@
 		// undo magic quotes for "
 		$s = str_replace('\\"','"',$s);
 		
-		if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+		if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase'))  // ' already quoted, no need to change anything
 			return $s;
 		else {// change \' to '' for sybase/mssql
 			$s = str_replace('\\\\','\\',$s);
@@ -2512,7 +2645,7 @@
 		// undo magic quotes for "
 		$s = str_replace('\\"','"',$s);
 		
-		if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+		if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase'))  // ' already quoted, no need to change anything
 			return "'$s'";
 		else {// change \' to '' for sybase/mssql
 			$s = str_replace('\\\\','\\',$s);
@@ -2538,12 +2671,12 @@
 	* NOTE: phpLens uses a different algorithm and does not use PageExecute().
 	*
 	*/
-	function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
+	function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
 	{
 		global $ADODB_INCLUDED_LIB;
 		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
-		if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
-		else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+		if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+		else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
 		return $rs;
 	}
 	
@@ -2560,7 +2693,7 @@
 	* @param [inputarr]	array of bind variables
 	* @return		the recordset ($rs->databaseType == 'array')
 	*/
-	function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
+	function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
 	{
 		/*switch($this->dataProvider) {
 		case 'postgres':
@@ -2568,7 +2701,7 @@
 			break;
 		default: $secs2cache = 0; break;
 		}*/
-		$rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
+		$rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
 		return $rs;
 	}
 
@@ -2590,10 +2723,54 @@
 	// CLASS ADORecordSet_empty
 	//==============================================================================================	
 	
+	class ADODB_Iterator_empty implements Iterator {
+	
+	    private $rs;
+	
+	    function __construct($rs) 
+		{
+	        $this->rs = $rs;
+	    }
+	    function rewind() 
+		{
+	    }
+	
+		function valid() 
+		{
+	        return !$this->rs->EOF;
+	    }
+		
+	    function key() 
+		{
+	        return false;
+	    }
+		
+	    function current() 
+		{
+	        return false;
+	    }
+		
+	    function next() 
+		{
+	    }
+		
+		function __call($func, $params)
+		{
+			return call_user_func_array(array($this->rs, $func), $params);
+		}
+		
+		function hasMore()
+		{
+			return false;
+		}
+	
+	}
+
+	
 	/**
 	* Lightweight recordset when there are no records to be returned
 	*/
-	class ADORecordSet_empty
+	class ADORecordSet_empty implements IteratorAggregate
 	{
 		var $dataProvider = 'empty';
 		var $databaseType = false;
@@ -2608,6 +2785,7 @@
 		function FetchRow() {return false;}
 		function FieldCount(){ return 0;}
 		function Init() {}
+		function getIterator() {return new ADODB_Iterator_empty($this);}
 	}
 	
 	//==============================================================================================	
@@ -2619,15 +2797,61 @@
 	// CLASS ADORecordSet
 	//==============================================================================================	
 
-	if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
-	else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
+	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;
+		}
+	
+	}
+
+
+
    /**
 	 * RecordSet class that represents the dataset returned by the database.
 	 * To keep memory overhead low, this class holds only the current row in memory.
 	 * No prefetching of data is done, so the RecordCount() can return -1 ( which
 	 * means recordcount not known).
 	 */
-	class ADORecordSet extends ADODB_BASE_RS {
+	class ADORecordSet implements IteratorAggregate {
 	/*
 	 * public variables	
 	 */
@@ -2677,8 +2901,19 @@
 		$this->_queryID = $queryID;
 	}
 	
+	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);
+	}
 	
+	
 	function Init()
 	{
 		if ($this->_inited) return;
@@ -2763,7 +2998,7 @@
 	 *
 	 * @return an array indexed by the rows (0-based) from the recordset
 	 */
-	function &GetArray($nRows = -1) 
+	function GetArray($nRows = -1) 
 	{
 	global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
 		$results = adodb_getall($this,$nRows);
@@ -2779,9 +3014,9 @@
 		return $results;
 	}
 	
-	function &GetAll($nRows = -1)
+	function GetAll($nRows = -1)
 	{
-		$arr =& $this->GetArray($nRows);
+		$arr = $this->GetArray($nRows);
 		return $arr;
 	}
 	
@@ -2803,10 +3038,10 @@
 	 *
 	 * @return an array indexed by the rows (0-based) from the recordset
 	 */
-	function &GetArrayLimit($nrows,$offset=-1) 
+	function GetArrayLimit($nrows,$offset=-1) 
 	{	
 		if ($offset <= 0) {
-			$arr =& $this->GetArray($nrows);
+			$arr = $this->GetArray($nrows);
 			return $arr;
 		} 
 		
@@ -2830,9 +3065,9 @@
 	 *
 	 * @return an array indexed by the rows (0-based) from the recordset
 	 */
-	function &GetRows($nRows = -1) 
+	function GetRows($nRows = -1) 
 	{
-		$arr =& $this->GetArray($nRows);
+		$arr = $this->GetArray($nRows);
 		return $arr;
 	}
 	
@@ -2852,7 +3087,7 @@
 	 * @return an associative array indexed by the first column of the array, 
 	 * 	or false if the  data has less than 2 cols.
 	 */
-	function &GetAssoc($force_array = false, $first2cols = false) 
+	function GetAssoc($force_array = false, $first2cols = false) 
 	{
 	global $ADODB_EXTENSION;
 	
@@ -2873,7 +3108,15 @@
 					}
 				} else {
 					while (!$this->EOF) {
-						$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
+					// Fix for array_slice re-numbering numeric associative keys
+						$keys = array_slice(array_keys($this->fields), 1);
+						$sliced_array = array();
+
+						foreach($keys as $key) {
+							$sliced_array[$key] = $this->fields[$key];
+						}
+						
+						$results[trim(reset($this->fields))] = $sliced_array;
 						adodb_movenext($this);
 					}
 				}
@@ -2885,7 +3128,15 @@
 					}
 				} else {
 					while (!$this->EOF) {
-						$results[trim(reset($this->fields))] = array_slice($this->fields, 1);
+					// Fix for array_slice re-numbering numeric associative keys
+						$keys = array_slice(array_keys($this->fields), 1);
+						$sliced_array = array();
+
+						foreach($keys as $key) {
+							$sliced_array[$key] = $this->fields[$key];
+						}
+						
+						$results[trim(reset($this->fields))] = $sliced_array;
 						$this->MoveNext();
 					}
 				}
@@ -2927,7 +3178,7 @@
 			}
 		}
 		
-		$ref =& $results; # workaround accelerator incompat with PHP 4.4 :(
+		$ref = $results; # workaround accelerator incompat with PHP 4.4 :(
 		return $ref; 
 	}
 	
@@ -2973,7 +3224,7 @@
 	 *
 	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
 	 */
-	function UnixDate($v)
+	static function UnixDate($v)
 	{
 		return ADOConnection::UnixDate($v);
 	}
@@ -2984,7 +3235,7 @@
 	 *
 	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
 	 */
-	function UnixTimeStamp($v)
+	static function UnixTimeStamp($v)
 	{
 		return ADOConnection::UnixTimeStamp($v);
 	}
@@ -3022,7 +3273,7 @@
 	*
 	* @return false or array containing the current record
 	*/
-	function &FetchRow()
+	function FetchRow()
 	{
 		if ($this->EOF) {
 			$false = false;
@@ -3186,7 +3437,7 @@
    *
    * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
    */
-	function &GetRowAssoc($upper=1)
+	function GetRowAssoc($upper=1)
 	{
 		$record = array();
 	 //	if (!$this->fields) return $record;
@@ -3260,7 +3511,7 @@
 		if ($lnumrows == -1 && $this->connection) {
 			IF ($table) {
 				if ($condition) $condition = " WHERE " . $condition; 
-				$resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
+				$resultrows = $this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
 				if ($resultrows) $lnumrows = reset($resultrows->fields);
 			}
 		}
@@ -3294,16 +3545,19 @@
 	 *
 	 * @return the ADOFieldObject for that column, or false.
 	 */
-	function &FetchField($fieldoffset) 
+	function FetchField($fieldoffset = -1) 
 	{
 		// must be defined by child class
+		
+		$false = false;
+		return $false;
 	}	
 	
 	/**
 	 * Get the ADOFieldObjects of all columns in an array.
 	 *
 	 */
-	function& FieldTypesArray()
+	function FieldTypesArray()
 	{
 		$arr = array();
 		for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) 
@@ -3317,9 +3571,9 @@
 	*
 	* @return the object with the properties set to the fields of the current row
 	*/
-	function &FetchObj()
+	function FetchObj()
 	{
-		$o =& $this->FetchObject(false);
+		$o = $this->FetchObject(false);
 		return $o;
 	}
 	
@@ -3331,7 +3585,7 @@
 	*
 	* @return the object with the properties set to the fields of the current row
 	*/
-	function &FetchObject($isupper=true)
+	function FetchObject($isupper=true)
 	{
 		if (empty($this->_obj)) {
 			$this->_obj = new ADOFetchObj();
@@ -3364,9 +3618,9 @@
 	*
 	* Fixed bug reported by tim@orotech.net
 	*/
-	function &FetchNextObj()
+	function FetchNextObj()
 	{
-		$o =& $this->FetchNextObject(false);
+		$o = $this->FetchNextObject(false);
 		return $o;
 	}
 	
@@ -3382,7 +3636,7 @@
 	*
 	* Fixed bug reported by tim@orotech.net
 	*/
-	function &FetchNextObject($isupper=true)
+	function FetchNextObject($isupper=true)
 	{
 		$o = false;
 		if ($this->_numOfRows != 0 && !$this->EOF) {
@@ -3439,6 +3693,7 @@
 		'CHARACTER' => 'C',
 		'INTERVAL' => 'C',  # Postgres
 		'MACADDR' => 'C', # postgres
+		'VAR_STRING' => 'C', # mysql
 		##
 		'LONGCHAR' => 'X',
 		'TEXT' => 'X',
@@ -3460,6 +3715,9 @@
 		'DATE' => 'D',
 		'D' => 'D',
 		##
+		'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
+		##
+		'SMALLDATETIME' => 'T',
 		'TIME' => 'T',
 		'TIMESTAMP' => 'T',
 		'DATETIME' => 'T',
@@ -3516,7 +3774,14 @@
 		'SQLDTIME' => 'T', 
 		'SQLINTERVAL' => 'N', 
 		'SQLBYTES' => 'B', 
-		'SQLTEXT' => 'X' 
+		'SQLTEXT' => 'X',
+		 ## informix 10
+		"SQLINT8" => 'I8',
+		"SQLSERIAL8" => 'I8',
+		"SQLNCHAR" => 'C',
+		"SQLNVCHAR" => 'C',
+		"SQLLVARCHAR" => 'X',
+		"SQLBOOL" => 'L'
 		);
 		
 		$tmap = false;
@@ -3555,6 +3820,7 @@
 		}
 	}
 	
+	
 	function _close() {}
 	
 	/**
@@ -3611,7 +3877,7 @@
 		var $_types;	// the array of types of each column (C B I L M)
 		var $_colnames;	// names of each column in array
 		var $_skiprow1;	// skip 1st row because it holds column names
-		var $_fieldarr; // holds array of field objects
+		var $_fieldobjects; // holds array of field objects
 		var $canSeek = true;
 		var $affectedrows = false;
 		var $insertid = false;
@@ -3631,7 +3897,38 @@
 			$this->fetchMode = $ADODB_FETCH_MODE;
 		}
 		
+		function _transpose($addfieldnames=true)
+		{
+		global $ADODB_INCLUDED_LIB;
+			
+			if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+			$hdr = true;
+			
+			$fobjs = $addfieldnames ? $this->_fieldobjects : false;
+			adodb_transpose($this->_array, $newarr, $hdr, $fobjs);
+			//adodb_pr($newarr);
+			
+			$this->_skiprow1 = false;
+			$this->_array = $newarr;
+			$this->_colnames = $hdr;
+			
+			adodb_probetypes($newarr,$this->_types);
 		
+			$this->_fieldobjects = array();
+			
+			foreach($hdr as $k => $name) {
+				$f = new ADOFieldObject();
+				$f->name = $name;
+				$f->type = $this->_types[$k];
+				$f->max_length = -1;
+				$this->_fieldobjects[] = $f;
+			}
+			$this->fields = reset($this->_array);
+			
+			$this->_initrs();
+			
+		}
+		
 		/**
 		 * Setup the array.
 		 *
@@ -3666,20 +3963,20 @@
 		 */
 		function InitArrayFields(&$array,&$fieldarr)
 		{
-			$this->_array =& $array;
+			$this->_array = $array;
 			$this->_skiprow1= false;
 			if ($fieldarr) {
-				$this->_fieldobjects =& $fieldarr;
+				$this->_fieldobjects = $fieldarr;
 			} 
 			$this->Init();
 		}
 		
-		function &GetArray($nRows=-1)
+		function GetArray($nRows=-1)
 		{
 			if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
 				return $this->_array;
 			} else {
-				$arr =& ADORecordSet::GetArray($nRows);
+				$arr = ADORecordSet::GetArray($nRows);
 				return $arr;
 			}
 		}
@@ -3699,7 +3996,7 @@
 			$mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
 			
 			if ($mode & ADODB_FETCH_ASSOC) {
-				if (!isset($this->fields[$colname])) $colname = strtolower($colname);
+				if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) $colname = strtolower($colname);
 				return $this->fields[$colname];
 			}
 			if (!$this->bind) {
@@ -3712,7 +4009,7 @@
 			return $this->fields[$this->bind[strtoupper($colname)]];
 		}
 		
-		function &FetchField($fieldOffset = -1) 
+		function FetchField($fieldOffset = -1) 
 		{
 			if (isset($this->_fieldobjects)) {
 				return $this->_fieldobjects[$fieldOffset];
@@ -3827,9 +4124,9 @@
 	/**
 	 * synonym for ADONewConnection for people like me who cannot remember the correct name
 	 */
-	function &NewADOConnection($db='')
+	function NewADOConnection($db='')
 	{
-		$tmp =& ADONewConnection($db);
+		$tmp = ADONewConnection($db);
 		return $tmp;
 	}
 	
@@ -3841,38 +4138,56 @@
 	 *
 	 * @return the freshly created instance of the Connection class.
 	 */
-	function &ADONewConnection($db='')
+	function ADONewConnection($db='')
 	{
 	GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
 		
 		if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
 		$errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
 		$false = false;
-		if ($at = strpos($db,'://')) {
+		if (($at = strpos($db,'://')) !== FALSE) {
 			$origdsn = $db;
-			if (PHP_VERSION < 5) $dsna = @parse_url($db);
-			else {
-				$fakedsn = 'fake'.substr($db,$at);
+			$fakedsn = 'fake'.substr($origdsn,$at);
+			if (($at2 = strpos($origdsn,'@/')) !== FALSE) {
+				// special handling of oracle, which might not have host
+				$fakedsn = str_replace('@/','@adodb-fakehost/',$fakedsn);
+			}
+			
+			 if ((strpos($origdsn, 'sqlite')) !== FALSE) {
+             // special handling for SQLite, it only might have the path to the database file.
+             // If you try to connect to a SQLite database using a dsn like 'sqlite:///path/to/database', the 'parse_url' php function
+             // will throw you an exception with a message such as "unable to parse url"
+                list($scheme, $path) = explode('://', $origdsn);
+                $dsna['scheme'] = $scheme;
+				if ($qmark = strpos($path,'?')) {
+					$dsn['query'] = substr($path,$qmark+1);
+					$path = substr($path,0,$qmark);
+				}
+            	$dsna['path'] = '/' . urlencode($path);
+			} else
 				$dsna = @parse_url($fakedsn);
-				$dsna['scheme'] = substr($db,0,$at);
+				
+			if (!$dsna) {
+				return $false;
+			}
+			$dsna['scheme'] = substr($origdsn,0,$at);
+			if ($at2 !== FALSE) {
+				$dsna['host'] = '';
+			}
 			
-				if (strncmp($db,'pdo',3) == 0) {
-					$sch = explode('_',$dsna['scheme']);
-					if (sizeof($sch)>1) {
-						$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
+			if (strncmp($origdsn,'pdo',3) == 0) {
+				$sch = explode('_',$dsna['scheme']);
+				if (sizeof($sch)>1) {
+				
+					$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
+					if ($sch[1] == 'sqlite')
+						$dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host']));
+					else
 						$dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
-						$dsna['scheme'] = 'pdo';
-					}
+					$dsna['scheme'] = 'pdo';
 				}
 			}
 			
-			if (!$dsna) {
-				// special handling of oracle, which might not have host
-				$db = str_replace('@/','@adodb-fakehost/',$db);
-				$dsna = parse_url($db);
-				if (!$dsna) return $false;
-				$dsna['host'] = '';
-			}
 			$db = @$dsna['scheme'];
 			if (!$db) return $false;
 			$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
@@ -3900,8 +4215,10 @@
 		if (!empty($ADODB_NEWCONNECTION)) {
 			$obj = $ADODB_NEWCONNECTION($db);
 
-		} else {
+		} 
 		
+		if(empty($obj)) {
+		
 			if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
 			if (empty($db)) $db = $ADODB_LASTDB;
 			
@@ -3958,6 +4275,18 @@
 					case 'socket': $obj->socket = $v; break;
 					#oci8
 					case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
+					case 'cachesecs': $obj->cacheSecs = $v; break;
+					case 'memcache': 
+						$varr = explode(':',$v);
+						$vlen = sizeof($varr);
+						if ($vlen == 0) break;	
+						$obj->memCache = true;
+						$obj->memCacheHost = explode(',',$varr[0]);
+						if ($vlen == 1) break;	
+						$obj->memCachePort = $varr[1];
+						if ($vlen == 2) break;	
+						$obj->memCacheCompress = $varr[2] ?  true : false;
+						break;
 					}
 				}
 				if (empty($persist))
@@ -4008,7 +4337,7 @@
 		return $drivername;
 	}
 	
-	function &NewPerfMonitor(&$conn)
+	function NewPerfMonitor(&$conn)
 	{
 		$false = false;
 		$drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
@@ -4022,7 +4351,7 @@
 		return $perf;
 	}
 	
-	function &NewDataDictionary(&$conn,$drivername=false)
+	function NewDataDictionary(&$conn,$drivername=false)
 	{
 		$false = false;
 		if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
@@ -4039,7 +4368,7 @@
 		$class = "ADODB2_$drivername";
 		$dict = new $class();
 		$dict->dataProvider = $conn->dataProvider;
-		$dict->connection = &$conn;
+		$dict->connection = $conn;
 		$dict->upperName = strtoupper($drivername);
 		$dict->quote = $conn->nameQuote;
 		if (!empty($conn->_connectionID))
@@ -4075,13 +4404,13 @@
 		@param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
 		@param levels Number of levels to display
 	*/
-	function adodb_backtrace($printOrArr=true,$levels=9999)
+	function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null)
 	{
 		global $ADODB_INCLUDED_LIB;
 		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
-		return _adodb_backtrace($printOrArr,$levels);
+		return _adodb_backtrace($printOrArr,$levels,0,$ishtml);
 	}
 
 
 }
-?>
+?>
\ No newline at end of file
Index: contrib/toxmlrpc.inc.php
===================================================================
--- contrib/toxmlrpc.inc.php	(revision 13354)
+++ contrib/toxmlrpc.inc.php	(working copy)
@@ -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;
+
+    }
+
 ?>
\ No newline at end of file
Index: datadict/datadict-access.inc.php
===================================================================
--- datadict/datadict-access.inc.php	(revision 13354)
+++ datadict/datadict-access.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -30,7 +30,8 @@
 		case 'X2': return 'MEMO';
 		
 		case 'B': return 'BINARY';
-			
+		
+		case 'TS':
 		case 'D': return 'DATETIME';
 		case 'T': return 'DATETIME';
 		
@@ -49,7 +50,7 @@
 	}
 	
 	// 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';
Index: datadict/datadict-db2.inc.php
===================================================================
--- datadict/datadict-db2.inc.php	(revision 13354)
+++ datadict/datadict-db2.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -30,6 +30,7 @@
 		case 'B': return 'BLOB';
 
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'TIMESTAMP';
 
 		case 'L': return 'SMALLINT';
@@ -47,7 +48,7 @@
 	}
 	
 	// 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 +84,7 @@
 		$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);
 		}
Index: datadict/datadict-firebird.inc.php
===================================================================
--- datadict/datadict-firebird.inc.php	(revision 13354)
+++ datadict/datadict-firebird.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -30,6 +30,7 @@
 		case 'B': return 'BLOB';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'TIMESTAMP';
 		
 		case 'L': return 'SMALLINT';
@@ -93,7 +94,7 @@
 	}
 	
 
-	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
 	{
 		$suffix = '';
 		
Index: datadict/datadict-generic.inc.php
===================================================================
--- datadict/datadict-generic.inc.php	(revision 13354)
+++ datadict/datadict-generic.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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,6 +32,7 @@
 		case 'B': return 'VARCHAR';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'DATE';
 		
 		case 'L': return 'DECIMAL(1)';
Index: datadict/datadict-ibase.inc.php
===================================================================
--- datadict/datadict-ibase.inc.php	(revision 13354)
+++ datadict/datadict-ibase.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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,6 +32,7 @@
 		case 'B': return 'BLOB';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'TIMESTAMP';
 		
 		case 'L': return 'SMALLINT';
Index: datadict/datadict-informix.inc.php
===================================================================
--- datadict/datadict-informix.inc.php	(revision 13354)
+++ datadict/datadict-informix.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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,7 +32,8 @@
 		case 'B': return 'BLOB';
 			
 		case 'D': return 'DATE';
-		case 'T': return 'DATETIME';
+		case 'TS':
+		case 'T': return 'DATETIME YEAR TO SECOND';
 		
 		case 'L': return 'SMALLINT';
 		case 'I': return 'INTEGER';
@@ -62,7 +63,7 @@
 	}
 	
 	// 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';
Index: datadict/datadict-mssql.inc.php
===================================================================
--- datadict/datadict-mssql.inc.php	(revision 13354)
+++ datadict/datadict-mssql.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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 @@
 		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);
@@ -89,6 +89,8 @@
 		case 'B': return 'IMAGE';
 			
 		case 'D': return 'DATETIME';
+		
+		case 'TS':
 		case 'T': return 'DATETIME';
 		case 'L': return 'BIT';
 		
@@ -151,7 +153,7 @@
 	}
 	
 	// 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";
Index: datadict/datadict-mssqlnative.inc.php
===================================================================
--- datadict/datadict-mssqlnative.inc.php	(revision 0)
+++ datadict/datadict-mssqlnative.inc.php	(revision 0)
@@ -0,0 +1,282 @@
+<?php
+
+/**
+  V5.11 5 May 2010   (c) 2000-2010 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);    
+
+	}
+}
+?>
\ No newline at end of file

Property changes on: datadict\datadict-mssqlnative.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: datadict/datadict-mysql.inc.php
===================================================================
--- datadict/datadict-mysql.inc.php	(revision 13354)
+++ datadict/datadict-mysql.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -89,6 +89,7 @@
 		case 'B': return 'LONGBLOB';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'DATETIME';
 		case 'L': return 'TINYINT';
 		
@@ -107,7 +108,7 @@
 	}
 	
 	// 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';
Index: datadict/datadict-oci8.inc.php
===================================================================
--- datadict/datadict-oci8.inc.php	(revision 13354)
+++ datadict/datadict-oci8.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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,6 +55,9 @@
 		case 'BLOB':
 			return 'B';
 		
+		case 'TIMESTAMP':
+			return 'TS';
+			
 		case 'DATE': 
 			return 'T';
 		
@@ -75,22 +78,26 @@
 		case 'X': return $this->typeX;
 		case 'XL': return $this->typeXL;
 		
-		case 'C2': return 'NVARCHAR';
-		case 'X2': return 'NVARCHAR(2000)';
+		case 'C2': return 'NVARCHAR2';
+		case 'X2': return 'NVARCHAR2(4000)';
 		
 		case 'B': return 'BLOB';
-			
+		
+		case 'TS':
+				return 'TIMESTAMP';
+				
 		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 +163,7 @@
 	}
 	
 	// 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 = '';
 		
@@ -196,6 +203,14 @@
 			$seqname = $this->seqPrefix.$tabname;
 			$trigname = $this->trigPrefix.$seqname;
 		}
+		
+		if (strlen($seqname) > 30) {
+			$seqname = $this->seqPrefix.uniqid('');
+		} // end if
+		if (strlen($trigname) > 30) {
+			$trigname = $this->trigPrefix.uniqid('');
+		} // end if
+
 		if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
 		$seqCache = '';
 		if (isset($tableoptions['SEQUENCE_CACHE'])){$seqCache = $tableoptions['SEQUENCE_CACHE'];}
Index: datadict/datadict-postgres.inc.php
===================================================================
--- datadict/datadict-postgres.inc.php	(revision 13354)
+++ datadict/datadict-postgres.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -100,6 +100,7 @@
 		case 'B': return 'BYTEA';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'TIMESTAMP';
 		
 		case 'L': return 'BOOLEAN';
@@ -150,6 +151,12 @@
 		}
 		return $sql;
 	}
+
+
+	function DropIndexSQL ($idxname, $tabname = NULL)
+	{
+	   return array(sprintf($this->dropIndex, $this->TableName($idxname), $this->TableName($tabname)));
+	}
 	
 	/**
 	 * Change the definition of one column
@@ -162,6 +169,7 @@
 	 * @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
 	 * @return array with SQL strings
 	 */
+	 /*
 	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
 	{
 		if (!$tableflds) {
@@ -169,6 +177,61 @@
 			return array();
 		}
 		return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
+	}*/
+	
+	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+	   // Check if alter single column datatype available - works with 8.0+
+	   $has_alter_column = 8.0 <= (float) @$this->serverInfo['version'];
+	
+	   if ($has_alter_column) {
+	      $tabname = $this->TableName($tabname);
+	      $sql = array();
+	      list($lines,$pkey) = $this->_GenFields($flds);
+	      $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
+	      foreach($lines as $v) {
+	         if ($not_null = preg_match('/NOT NULL/i',$v)) {
+	            $v = preg_replace('/NOT NULL/i','',$v);
+	         }
+	         // this next block doesn't work - there is no way that I can see to 
+	         // explicitly ask a column to be null using $flds
+	         else if ($set_null = preg_match('/NULL/i',$v)) {
+	            // if they didn't specify not null, see if they explicitely asked for null
+	            $v = preg_replace('/\sNULL/i','',$v);
+	         }
+	         
+	         if (preg_match('/^([^ ]+) .*DEFAULT ([^ ]+)/',$v,$matches)) {
+	            list(,$colname,$default) = $matches;
+	            $v = preg_replace('/^' . preg_quote($colname) . '\s/', '', $v);
+	            $sql[] = $alter . $colname . ' TYPE ' . str_replace('DEFAULT '.$default,'',$v);
+	            $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
+	         } 
+	         else {
+	            // drop default?
+	            preg_match ('/^\s*(\S+)\s+(.*)$/',$v,$matches);
+	            list (,$colname,$rest) = $matches;
+	            $sql[] = $alter . $colname . ' TYPE ' . $rest;
+	         }
+	
+	         list($colname) = explode(' ',$v);
+	         if ($not_null) {
+	            // this does not error out if the column is already not null
+	            $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
+	         }
+	         if ($set_null) {
+	            // this does not error out if the column is already null
+	            $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' DROP NOT NULL';
+	         }
+	      }
+	      return $sql;
+	   }
+	
+	   // 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);
 	}
 	
 	/**
@@ -264,7 +327,7 @@
 	}
 
 	// 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';
@@ -293,6 +356,20 @@
 		return "DROP SEQUENCE ".$seq;
 	}
 	
+	function RenameTableSQL($tabname,$newname)
+	{
+		if (!empty($this->schema)) {
+			$rename_from = $this->TableName($tabname);
+			$schema_save = $this->schema;
+			$this->schema = false;
+			$rename_to = $this->TableName($newname);
+			$this->schema = $schema_save;
+			return array (sprintf($this->renameTable, $rename_from, $rename_to));
+		}
+
+		return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
+	}
+	
 	/*
 	CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
 	{ column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
Index: datadict/datadict-sapdb.inc.php
===================================================================
--- datadict/datadict-sapdb.inc.php	(revision 13354)
+++ datadict/datadict-sapdb.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.50 6 July 2004  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V4.50 6 July 2004  (c) 2000-2010 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.
@@ -33,6 +33,7 @@
 		case 'B': return 'LONG';
 			
 		case 'D': return 'DATE';
+		case 'TS':
 		case 'T': return 'TIMESTAMP';
 		
 		case 'L': return 'BOOLEAN';
@@ -80,7 +81,7 @@
 	}
 	
 	// 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';
Index: datadict/datadict-sqlite.inc.php
===================================================================
--- datadict/datadict-sqlite.inc.php	(revision 0)
+++ datadict/datadict-sqlite.inc.php	(revision 0)
@@ -0,0 +1,89 @@
+<?php
+
+/**
+  V5.11 5 May 2010   (c) 2000-2010 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.
+ 
+	SQLite datadict Andrei Besleaga
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_sqlite extends ADODB_DataDict {
+	var $databaseType = 'sqlite';
+	var $seqField = false;
+	var $addCol=' ADD COLUMN';
+	var $dropTable = 'DROP TABLE IF EXISTS %s';
+	var $dropIndex = 'DROP INDEX IF EXISTS %s';
+	var $renameTable = 'ALTER TABLE %s RENAME TO %s';
+	
+	
+
+	function ActualType($meta)
+	{
+		switch(strtoupper($meta)) {
+		case 'C': return 'VARCHAR'; //  TEXT , TEXT affinity
+		case 'XL':return 'LONGTEXT'; //  TEXT , TEXT affinity
+		case 'X': return 'TEXT'; //  TEXT , TEXT affinity
+		
+		case 'C2': return 'VARCHAR'; //  TEXT , TEXT affinity
+		case 'X2': return 'LONGTEXT'; //  TEXT , TEXT affinity
+		
+		case 'B': return 'LONGBLOB'; //  TEXT , NONE affinity , BLOB
+			
+		case 'D': return 'DATE'; // NUMERIC , NUMERIC affinity
+		case 'T': return 'DATETIME'; // NUMERIC , NUMERIC affinity
+		case 'L': return 'TINYINT'; // NUMERIC , INTEGER affinity
+		
+		case 'R': 
+		case 'I4':
+		case 'I': return 'INTEGER'; // NUMERIC , INTEGER affinity
+		case 'I1': return 'TINYINT'; // NUMERIC , INTEGER affinity
+		case 'I2': return 'SMALLINT'; // NUMERIC , INTEGER affinity
+		case 'I8': return 'BIGINT'; // NUMERIC , INTEGER affinity
+		
+		case 'F': return 'DOUBLE'; // NUMERIC , REAL affinity
+		case 'N': return 'NUMERIC'; // NUMERIC , NUMERIC affinity
+		default:
+			return $meta;
+		}
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{	
+		$suffix = '';
+		if ($funsigned) $suffix .= ' UNSIGNED';
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fautoinc) $suffix .= ' AUTOINCREMENT';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported natively by SQLite");
+		return array();
+	}
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported natively by SQLite");
+		return array();
+	}
+	
+	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
+	{
+		if ($this->debug) ADOConnection::outp("RenameColumnSQL not supported natively by SQLite");
+		return array();	
+	}
+	
+}
+?>

Property changes on: datadict\datadict-sqlite.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: datadict/datadict-sybase.inc.php
===================================================================
--- datadict/datadict-sybase.inc.php	(revision 13354)
+++ datadict/datadict-sybase.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /**
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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,6 +55,7 @@
 		case 'B': return 'IMAGE';
 			
 		case 'D': return 'DATETIME';
+		case 'TS':
 		case 'T': return 'DATETIME';
 		case 'L': return 'BIT';
 		
@@ -113,7 +114,7 @@
 	}
 	
 	// 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";
Index: drivers/adodb-access.inc.php
===================================================================
--- drivers/adodb-access.inc.php	(revision 13354)
+++ drivers/adodb-access.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -27,6 +27,7 @@
 	var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
 	var $sysTimeStamp = 'NOW';
 	var $hasTransactions = false;
+	var $upperCase = 'ucase';
 	
 	function ADODB_access()
 	{
@@ -48,7 +49,7 @@
 		return " IIF(IsNull($field), $ifNull, $field) "; // if Access
 	}
 /*
-	function &MetaTables()
+	function MetaTables()
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -61,7 +62,7 @@
 		
 		$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++) {
Index: drivers/adodb-ado.inc.php
===================================================================
--- drivers/adodb-ado.inc.php	(revision 13354)
+++ drivers/adodb-ado.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 
 */
 	
-	function &MetaTables()
+	function MetaTables()
 	{
 		$arr= array();
 		$dbc = $this->_connectionID;
@@ -169,7 +169,7 @@
 		return $arr;
 	}
 	
-	function &MetaColumns($table)
+	function MetaColumns($table, $normalize=true)
 	{
 		$table = strtoupper($table);
 		$arr = array();
@@ -204,7 +204,7 @@
 
 	
 	/* returns queryID or false */
-	function &_query($sql,$inputarr=false) 
+	function _query($sql,$inputarr=false) 
 	{
 		
 		$dbc = $this->_connectionID;
@@ -221,11 +221,27 @@
 			$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 @@
 
 
 	// 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 @@
 				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 @@
 		@$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;
 	}
Index: drivers/adodb-ado5.inc.php
===================================================================
--- drivers/adodb-ado5.inc.php	(revision 13354)
+++ drivers/adodb-ado5.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 		 } else {
 		 	$argDatabasename = '';
 		 	if ($argDBorProvider) $argProvider = $argDBorProvider;
-			else $argProvider = 'MSDASQL';
+			else if (stripos($argHostname,'PROVIDER') === false) /* full conn string is not in $argHostname */ 
+				$argProvider = 'MSDASQL';
 		}
 		
 		
@@ -117,6 +118,7 @@
 		$dbc->CursorLocation = $this->_cursor_location;
 		return  $dbc->State > 0;
 		} catch (exception $e) {
+			if ($this->debug) echo "<pre>",$argHostname,"\n",$e,"</pre>\n";
 		}
 		
 		return false;
@@ -170,7 +172,7 @@
 
 */
 	
-	function &MetaTables()
+	function MetaTables()
 	{
 		$arr= array();
 		$dbc = $this->_connectionID;
@@ -192,7 +194,7 @@
 		return $arr;
 	}
 	
-	function &MetaColumns($table)
+	function MetaColumns($table, $normalize=true)
 	{
 		$table = strtoupper($table);
 		$arr= array();
@@ -224,7 +226,7 @@
 	}
 	
 	/* 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...
 		
@@ -244,13 +246,28 @@
 			$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;
@@ -370,11 +387,13 @@
 
 
 	// 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;
@@ -406,8 +425,12 @@
 	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;
 	}
@@ -617,10 +640,24 @@
 			case 1: // null
 				$this->fields[] = false;
 				break;
+			case 20:
+			case 21: // bigint (64 bit)
+    			$this->fields[] = (float) $f->value; // if 64 bit PHP, could use (int)
+    			break;
 			case 6: // currency is not supported properly;
 				ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
 				$this->fields[] = (float) $f->value;
 				break;
+			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;
@@ -633,7 +670,7 @@
 		@$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;
 	}
@@ -659,7 +696,10 @@
 
 	function _close() {
 		$this->_flds = false;
+		try {
 		@$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
+		} catch (Exception $e) {
+		}
 		$this->_queryID = false;	
 	}
 
Index: drivers/adodb-ado_access.inc.php
===================================================================
--- drivers/adodb-ado_access.inc.php	(revision 13354)
+++ drivers/adodb-ado_access.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -26,18 +26,18 @@
 	var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma
 	var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
 	var $sysTimeStamp = 'NOW';
-	var $hasTransactions = false;
+	var $upperCase = 'ucase';
 	
 	function ADODB_ado_access()
 	{
 		$this->ADODB_ado();
 	}
 	
-	function BeginTrans() { return false;}
+	/*function BeginTrans() { return false;}
 	
 	function CommitTrans() { return false;}
 	
-	function RollbackTrans() { return false;}
+	function RollbackTrans() { return false;}*/
 
 }
 
Index: drivers/adodb-ado_mssql.inc.php
===================================================================
--- drivers/adodb-ado_mssql.inc.php	(revision 13354)
+++ drivers/adodb-ado_mssql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,6 +35,7 @@
 	var $ansiOuter = true; // for mssql7 or later
 	var $substr = "substring";
 	var $length = 'len';
+	var $_dropSeqSQL = "drop table %s";
 	
 	//var $_inTransaction = 1; // always open recordsets, so no transaction problems.
 	
@@ -45,7 +46,7 @@
 	
 	function _insertid()
 	{
-	        return $this->GetOne('select @@identity');
+	        return $this->GetOne('select SCOPE_IDENTITY()');
 	}
 	
 	function _affectedrows()
@@ -64,8 +65,14 @@
 		$this->Execute("SET TRANSACTION ".$transaction_mode);
 	}
 	
-	function MetaColumns($table)
+	function qstr($s,$magic_quotes=false)
 	{
+		$s = ADOConnection::qstr($s, $magic_quotes);
+		return str_replace("\0", "\\\\000", $s);
+	}
+	
+	function MetaColumns($table, $normalize=true)
+	{
         $table = strtoupper($table);
         $arr= array();
         $dbc = $this->_connectionID;
Index: drivers/adodb-ads.inc.php
===================================================================
--- drivers/adodb-ads.inc.php	(revision 0)
+++ drivers/adodb-ads.inc.php	(revision 0)
@@ -0,0 +1,796 @@
+<?php
+/*
+  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Portions Copyright (c) 2007-2009, iAnywhere Solutions, Inc.
+  All rights reserved. All unpublished 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.
+
+
+NOTE: This driver requires the Advantage PHP client libraries, which
+      can be downloaded for free via:
+      http://devzone.advantagedatabase.com/dz/content.aspx?key=20
+
+DELPHI FOR PHP USERS:
+      The following steps can be taken to utilize this driver from the
+      CodeGear Delphi for PHP product:
+        1 - See note above, download and install the Advantage PHP client.
+        2 - Copy the following files to the Delphi for PHP\X.X\php\ext directory:
+              ace32.dll
+              axcws32.dll
+              adsloc32.dll
+              php_advantage.dll (rename the existing php_advantage.dll.5.x.x file)
+        3 - Add the following line to the Delphi for PHP\X.X\php\php.ini.template file:
+              extension=php_advantage.dll
+        4 - To use: enter "ads" as the DriverName on a connection component, and set
+            a Host property similar to "DataDirectory=c:\". See the Advantage PHP
+            help file topic for ads_connect for details on connection path options
+            and formatting.
+        5 - (optional) - Modify the Delphi for PHP\X.X\vcl\packages\database.packages.php
+            file and add ads to the list of strings returned when registering the
+            Database object's DriverName property.
+
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+  define("_ADODB_ADS_LAYER", 2 );
+
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+
+class ADODB_ads extends ADOConnection {
+  var $databaseType = "ads";
+  var $fmt = "'m-d-Y'";
+  var $fmtTimeStamp = "'Y-m-d H:i:s'";
+        var $concat_operator = '';
+  var $replaceQuote = "''"; // string to use to replace quotes
+  var $dataProvider = "ads";
+  var $hasAffectedRows = true;
+  var $binmode = ODBC_BINMODE_RETURN;
+  var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
+                        // breaking backward-compat
+  //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field
+  var $_bindInputArray = false;
+  var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
+  var $_genSeqSQL = "create table %s (id integer)";
+  var $_autocommit = true;
+  var $_haserrorfunctions = true;
+  var $_has_stupid_odbc_fetch_api_change = true;
+  var $_lastAffectedRows = 0;
+  var $uCaseTables = true; // for meta* functions, uppercase table names
+
+
+  function ADODB_ads()
+  {
+    $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
+    $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+  }
+
+  // returns true or false
+  function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+  {
+          global $php_errormsg;
+
+    if (!function_exists('ads_connect')) return null;
+
+    if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {
+      ADOConnection::outp("For Advantage Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+    }
+    if (isset($php_errormsg)) $php_errormsg = '';
+    if ($this->curmode === false) $this->_connectionID = ads_connect($argDSN,$argUsername,$argPassword);
+    else $this->_connectionID = ads_connect($argDSN,$argUsername,$argPassword,$this->curmode);
+    $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+    if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+
+    return $this->_connectionID != false;
+  }
+
+  // returns true or false
+  function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+  {
+  global $php_errormsg;
+
+    if (!function_exists('ads_connect')) return null;
+
+    if (isset($php_errormsg)) $php_errormsg = '';
+    $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+    if ($this->debug && $argDatabasename) {
+            ADOConnection::outp("For PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+    }
+  //  print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
+    if ($this->curmode === false) $this->_connectionID = ads_connect($argDSN,$argUsername,$argPassword);
+    else $this->_connectionID = ads_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
+
+    $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+    if ($this->_connectionID && $this->autoRollback) @ads_rollback($this->_connectionID);
+    if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+
+    return $this->_connectionID != false;
+  }
+
+  // returns the Server version and Description
+  function ServerInfo()
+  {
+
+    if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
+      $stmt = $this->Prepare('EXECUTE PROCEDURE sp_mgGetInstallInfo()');
+                        $res =  $this->Execute($stmt);
+                        if(!$res)
+                                print $this->ErrorMsg();
+                        else{
+                                $ret["version"]= $res->fields[3];
+                                $ret["description"]="Advantage Database Server";
+                                return $ret;
+                        }
+                }
+                else {
+            return ADOConnection::ServerInfo();
+    }
+  }
+
+
+        // returns true or false
+        function CreateSequence( $seqname,$start=1)
+  {
+                $res =  $this->Execute("CREATE TABLE $seqname ( ID autoinc( 1 ) ) IN DATABASE");
+                if(!$res){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                else
+                        return true;
+
+        }
+
+        // returns true or false
+        function DropSequence($seqname)
+  {
+                $res = $this->Execute("DROP TABLE $seqname");
+                if(!$res){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                else
+                        return true;
+        }
+
+
+  // returns the generated ID or false
+        // checks if the table already exists, else creates the table and inserts a record into the table
+        // and gets the ID number of the last inserted record.
+        function GenID($seqname,$start=1)
+        {
+                $go = $this->Execute("select * from $seqname");
+                if (!$go){
+                        $res = $this->Execute("CREATE TABLE $seqname ( ID autoinc( 1 ) ) IN DATABASE");
+                        if(!res){
+                                print $this->ErrorMsg();
+                                return false;
+                        }
+                }
+                $res = $this->Execute("INSERT INTO $seqname VALUES( DEFAULT )");
+                if(!$res){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                else{
+                        $gen = $this->Execute("SELECT LastAutoInc( STATEMENT ) FROM system.iota");
+                        $ret = $gen->fields[0];
+                        return $ret;
+                }
+
+        }
+
+
+
+
+  function ErrorMsg()
+  {
+    if ($this->_haserrorfunctions) {
+      if ($this->_errorMsg !== false) return $this->_errorMsg;
+      if (empty($this->_connectionID)) return @ads_errormsg();
+      return @ads_errormsg($this->_connectionID);
+    } else return ADOConnection::ErrorMsg();
+  }
+
+
+  function ErrorNo()
+  {
+
+                if ($this->_haserrorfunctions) {
+      if ($this->_errorCode !== false) {
+        // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+        return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
+      }
+
+      if (empty($this->_connectionID)) $e = @ads_error();
+      else $e = @ads_error($this->_connectionID);
+
+       // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+       // so we check and patch
+      if (strlen($e)<=2) return 0;
+      return $e;
+    } else return ADOConnection::ErrorNo();
+  }
+
+
+
+  function BeginTrans()
+  {
+    if (!$this->hasTransactions) return false;
+    if ($this->transOff) return true;
+    $this->transCnt += 1;
+    $this->_autocommit = false;
+    return ads_autocommit($this->_connectionID,false);
+  }
+
+  function CommitTrans($ok=true)
+  {
+    if ($this->transOff) return true;
+    if (!$ok) return $this->RollbackTrans();
+    if ($this->transCnt) $this->transCnt -= 1;
+    $this->_autocommit = true;
+    $ret = ads_commit($this->_connectionID);
+    ads_autocommit($this->_connectionID,true);
+    return $ret;
+  }
+
+  function RollbackTrans()
+  {
+    if ($this->transOff) return true;
+    if ($this->transCnt) $this->transCnt -= 1;
+    $this->_autocommit = true;
+    $ret = ads_rollback($this->_connectionID);
+    ads_autocommit($this->_connectionID,true);
+    return $ret;
+  }
+
+
+  // Returns tables,Views or both on succesfull execution. Returns
+        // tables by default on succesfull execustion.
+  function &MetaTables($ttype)
+  {
+          $recordSet1 = $this->Execute("select * from system.tables");
+                if(!$recordSet1){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                $recordSet2 = $this->Execute("select * from system.views");
+                if(!$recordSet2){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                $i=0;
+                while (!$recordSet1->EOF){
+                                 $arr["$i"] = $recordSet1->fields[0];
+                                 $recordSet1->MoveNext();
+                                 $i=$i+1;
+                }
+                if($ttype=='FALSE'){
+                        while (!$recordSet2->EOF){
+                                $arr["$i"] = $recordSet2->fields[0];
+                                $recordSet2->MoveNext();
+                                $i=$i+1;
+                        }
+                        return $arr;
+                }
+                elseif($ttype=='VIEWS'){
+                        while (!$recordSet2->EOF){
+                                $arrV["$i"] = $recordSet2->fields[0];
+                                $recordSet2->MoveNext();
+                                $i=$i+1;
+                        }
+                        return $arrV;
+                }
+                else{
+                        return $arr;
+                }
+
+  }
+
+        function &MetaPrimaryKeys($table)
+  {
+          $recordSet = $this->Execute("select table_primary_key from system.tables where name='$table'");
+                if(!$recordSet){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                $i=0;
+                while (!$recordSet->EOF){
+                                 $arr["$i"] = $recordSet->fields[0];
+                                 $recordSet->MoveNext();
+                                 $i=$i+1;
+                }
+                return $arr;
+        }
+
+/*
+See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp
+/ SQL data type codes /
+#define SQL_UNKNOWN_TYPE  0
+#define SQL_CHAR      1
+#define SQL_NUMERIC    2
+#define SQL_DECIMAL    3
+#define SQL_INTEGER    4
+#define SQL_SMALLINT    5
+#define SQL_FLOAT      6
+#define SQL_REAL      7
+#define SQL_DOUBLE      8
+#if (ODBCVER >= 0x0300)
+#define SQL_DATETIME    9
+#endif
+#define SQL_VARCHAR   12
+
+
+/ One-parameter shortcuts for date/time data types /
+#if (ODBCVER >= 0x0300)
+#define SQL_TYPE_DATE   91
+#define SQL_TYPE_TIME   92
+#define SQL_TYPE_TIMESTAMP 93
+
+#define SQL_UNICODE                             (-95)
+#define SQL_UNICODE_VARCHAR                     (-96)
+#define SQL_UNICODE_LONGVARCHAR                 (-97)
+*/
+  function ODBCTypes($t)
+  {
+    switch ((integer)$t) {
+    case 1:
+    case 12:
+    case 0:
+    case -95:
+    case -96:
+      return 'C';
+    case -97:
+    case -1: //text
+      return 'X';
+    case -4: //image
+      return 'B';
+
+    case 9:
+    case 91:
+      return 'D';
+
+    case 10:
+    case 11:
+    case 92:
+    case 93:
+      return 'T';
+
+    case 4:
+    case 5:
+    case -6:
+      return 'I';
+
+    case -11: // uniqidentifier
+      return 'R';
+    case -7: //bit
+      return 'L';
+
+    default:
+      return 'N';
+    }
+  }
+
+  function &MetaColumns($table)
+  {
+  global $ADODB_FETCH_MODE;
+
+    $false = false;
+    if ($this->uCaseTables) $table = strtoupper($table);
+    $schema = '';
+    $this->_findschema($table,$schema);
+
+    $savem = $ADODB_FETCH_MODE;
+    $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+
+    /*if (false) { // after testing, confirmed that the following does not work becoz of a bug
+      $qid2 = ads_tables($this->_connectionID);
+      $rs = new ADORecordSet_ads($qid2);
+      $ADODB_FETCH_MODE = $savem;
+      if (!$rs) return false;
+      $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+      $rs->_fetch();
+
+      while (!$rs->EOF) {
+        if ($table == strtoupper($rs->fields[2])) {
+          $q = $rs->fields[0];
+          $o = $rs->fields[1];
+          break;
+        }
+        $rs->MoveNext();
+      }
+      $rs->Close();
+
+      $qid = ads_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
+    } */
+
+    switch ($this->databaseType) {
+    case 'access':
+    case 'vfp':
+      $qid = ads_columns($this->_connectionID);#,'%','',strtoupper($table),'%');
+      break;
+
+
+    case 'db2':
+            $colname = "%";
+            $qid = ads_columns($this->_connectionID, "", $schema, $table, $colname);
+            break;
+
+    default:
+      $qid = @ads_columns($this->_connectionID,'%','%',strtoupper($table),'%');
+      if (empty($qid)) $qid = ads_columns($this->_connectionID);
+      break;
+    }
+    if (empty($qid)) return $false;
+
+    $rs = new ADORecordSet_ads($qid);
+    $ADODB_FETCH_MODE = $savem;
+
+    if (!$rs) return $false;
+    $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+    $rs->_fetch();
+
+    $retarr = array();
+
+    /*
+    $rs->fields indices
+    0 TABLE_QUALIFIER
+    1 TABLE_SCHEM
+    2 TABLE_NAME
+    3 COLUMN_NAME
+    4 DATA_TYPE
+    5 TYPE_NAME
+    6 PRECISION
+    7 LENGTH
+    8 SCALE
+    9 RADIX
+    10 NULLABLE
+    11 REMARKS
+    */
+    while (!$rs->EOF) {
+    //  adodb_pr($rs->fields);
+      if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+        $fld = new ADOFieldObject();
+        $fld->name = $rs->fields[3];
+        $fld->type = $this->ODBCTypes($rs->fields[4]);
+
+        // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
+        // access uses precision to store length for char/varchar
+        if ($fld->type == 'C' or $fld->type == 'X') {
+          if ($this->databaseType == 'access')
+            $fld->max_length = $rs->fields[6];
+          else if ($rs->fields[4] <= -95) // UNICODE
+            $fld->max_length = $rs->fields[7]/2;
+          else
+            $fld->max_length = $rs->fields[7];
+        } else
+          $fld->max_length = $rs->fields[7];
+        $fld->not_null = !empty($rs->fields[10]);
+        $fld->scale = $rs->fields[8];
+        $retarr[strtoupper($fld->name)] = $fld;
+      } else if (sizeof($retarr)>0)
+        break;
+      $rs->MoveNext();
+    }
+    $rs->Close(); //-- crashes 4.03pl1 -- why?
+
+    if (empty($retarr)) $retarr = false;
+    return $retarr;
+  }
+
+        // Returns an array of columns names for a given table
+        function &MetaColumnNames($table)
+        {
+                $recordSet = $this->Execute("select name from system.columns where parent='$table'");
+                if(!$recordSet){
+                        print $this->ErrorMsg();
+                        return false;
+                }
+                else{
+                        $i=0;
+                        while (!$recordSet->EOF){
+                                $arr["FIELD$i"] = $recordSet->fields[0];
+                                $recordSet->MoveNext();
+                                $i=$i+1;
+                        }
+                        return $arr;
+                }
+        }
+
+
+  function Prepare($sql)
+  {
+    if (! $this->_bindInputArray) return $sql; // no binding
+    $stmt = ads_prepare($this->_connectionID,$sql);
+    if (!$stmt) {
+      // we don't know whether odbc driver is parsing prepared stmts, so just return sql
+      return $sql;
+    }
+    return array($sql,$stmt,false);
+  }
+
+  /* returns queryID or false */
+  function _query($sql,$inputarr=false)
+  {
+  GLOBAL $php_errormsg;
+    if (isset($php_errormsg)) $php_errormsg = '';
+    $this->_error = '';
+
+                if ($inputarr) {
+      if (is_array($sql)) {
+        $stmtid = $sql[1];
+      } else {
+        $stmtid = ads_prepare($this->_connectionID,$sql);
+
+        if ($stmtid == false) {
+          $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+          return false;
+        }
+      }
+
+      if (! ads_execute($stmtid,$inputarr)) {
+        //@ads_free_result($stmtid);
+        if ($this->_haserrorfunctions) {
+          $this->_errorMsg = ads_errormsg();
+          $this->_errorCode = ads_error();
+        }
+        return false;
+      }
+
+    } else if (is_array($sql)) {
+      $stmtid = $sql[1];
+      if (!ads_execute($stmtid)) {
+        //@ads_free_result($stmtid);
+        if ($this->_haserrorfunctions) {
+          $this->_errorMsg = ads_errormsg();
+          $this->_errorCode = ads_error();
+        }
+        return false;
+      }
+    } else
+                        {
+
+      $stmtid = ads_exec($this->_connectionID,$sql);
+
+                        }
+
+                $this->_lastAffectedRows = 0;
+
+    if ($stmtid)
+                {
+
+      if (@ads_num_fields($stmtid) == 0) {
+        $this->_lastAffectedRows = ads_num_rows($stmtid);
+        $stmtid = true;
+
+      } else {
+
+        $this->_lastAffectedRows = 0;
+        ads_binmode($stmtid,$this->binmode);
+        ads_longreadlen($stmtid,$this->maxblobsize);
+
+      }
+
+      if ($this->_haserrorfunctions)
+                        {
+
+        $this->_errorMsg = '';
+        $this->_errorCode = 0;
+      }
+                        else
+        $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+    }
+                else
+                {
+      if ($this->_haserrorfunctions) {
+        $this->_errorMsg = ads_errormsg();
+        $this->_errorCode = ads_error();
+      } else
+        $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+    }
+
+    return $stmtid;
+
+  }
+
+  /*
+    Insert a null into the blob field of the table first.
+    Then use UpdateBlob to store the blob.
+
+    Usage:
+
+    $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+    $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+   */
+  function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+  {
+                $sql = "UPDATE $table SET $column=? WHERE $where";
+                $stmtid = ads_prepare($this->_connectionID,$sql);
+                if ($stmtid == false){
+                  $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+                  return false;
+          }
+                if (! ads_execute($stmtid,array($val),array(SQL_BINARY) )){
+                        if ($this->_haserrorfunctions){
+                                $this->_errorMsg = ads_errormsg();
+                    $this->_errorCode = ads_error();
+            }
+                        return false;
+           }
+                 return TRUE;
+        }
+
+  // returns true or false
+  function _close()
+  {
+    $ret = @ads_close($this->_connectionID);
+    $this->_connectionID = false;
+    return $ret;
+  }
+
+  function _affectedrows()
+  {
+    return $this->_lastAffectedRows;
+  }
+
+}
+
+/*--------------------------------------------------------------------------------------
+   Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_ads extends ADORecordSet {
+
+  var $bind = false;
+  var $databaseType = "ads";
+  var $dataProvider = "ads";
+  var $useFetchArray;
+  var $_has_stupid_odbc_fetch_api_change;
+
+  function ADORecordSet_ads($id,$mode=false)
+  {
+    if ($mode === false) {
+      global $ADODB_FETCH_MODE;
+      $mode = $ADODB_FETCH_MODE;
+    }
+    $this->fetchMode = $mode;
+
+    $this->_queryID = $id;
+
+    // the following is required for mysql odbc driver in 4.3.1 -- why?
+    $this->EOF = false;
+    $this->_currentRow = -1;
+    //$this->ADORecordSet($id);
+  }
+
+
+  // returns the field object
+  function &FetchField($fieldOffset = -1)
+  {
+
+    $off=$fieldOffset+1; // offsets begin at 1
+
+    $o= new ADOFieldObject();
+    $o->name = @ads_field_name($this->_queryID,$off);
+    $o->type = @ads_field_type($this->_queryID,$off);
+    $o->max_length = @ads_field_len($this->_queryID,$off);
+    if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+    else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+    return $o;
+  }
+
+  /* Use associative array to get fields array */
+  function Fields($colname)
+  {
+    if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+    if (!$this->bind) {
+      $this->bind = array();
+      for ($i=0; $i < $this->_numOfFields; $i++) {
+        $o = $this->FetchField($i);
+        $this->bind[strtoupper($o->name)] = $i;
+      }
+    }
+
+     return $this->fields[$this->bind[strtoupper($colname)]];
+  }
+
+
+  function _initrs()
+  {
+  global $ADODB_COUNTRECS;
+    $this->_numOfRows = ($ADODB_COUNTRECS) ? @ads_num_rows($this->_queryID) : -1;
+    $this->_numOfFields = @ads_num_fields($this->_queryID);
+    // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
+    if ($this->_numOfRows == 0) $this->_numOfRows = -1;
+    //$this->useFetchArray = $this->connection->useFetchArray;
+    $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+  }
+
+  function _seek($row)
+  {
+    return false;
+  }
+
+  // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
+  function &GetArrayLimit($nrows,$offset=-1)
+  {
+    if ($offset <= 0) {
+      $rs =& $this->GetArray($nrows);
+      return $rs;
+    }
+    $savem = $this->fetchMode;
+    $this->fetchMode = ADODB_FETCH_NUM;
+    $this->Move($offset);
+    $this->fetchMode = $savem;
+
+    if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+      $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+    }
+
+    $results = array();
+    $cnt = 0;
+    while (!$this->EOF && $nrows != $cnt) {
+      $results[$cnt++] = $this->fields;
+      $this->MoveNext();
+    }
+
+    return $results;
+  }
+
+
+  function MoveNext()
+  {
+    if ($this->_numOfRows != 0 && !$this->EOF) {
+      $this->_currentRow++;
+
+      if ($this->_has_stupid_odbc_fetch_api_change)
+        $rez = @ads_fetch_into($this->_queryID,$this->fields);
+      else {
+        $row = 0;
+        $rez = @ads_fetch_into($this->_queryID,$row,$this->fields);
+      }
+      if ($rez) {
+        if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+          $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+        }
+        return true;
+      }
+    }
+    $this->fields = false;
+    $this->EOF = true;
+    return false;
+  }
+
+  function _fetch()
+  {
+
+    if ($this->_has_stupid_odbc_fetch_api_change)
+      $rez = @ads_fetch_into($this->_queryID,$this->fields);
+    else {
+      $row = 0;
+      $rez = @ads_fetch_into($this->_queryID,$row,$this->fields);
+    }
+    if ($rez) {
+      if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+        $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+      }
+      return true;
+    }
+    $this->fields = false;
+    return false;
+  }
+
+  function _close()
+  {
+    return @ads_free_result($this->_queryID);
+  }
+
+}
+?>
\ No newline at end of file

Property changes on: drivers\adodb-ads.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-borland_ibase.inc.php
===================================================================
--- drivers/adodb-borland_ibase.inc.php	(revision 13354)
+++ drivers/adodb-borland_ibase.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -20,6 +20,7 @@
 class ADODB_borland_ibase extends ADODB_ibase {
 	var $databaseType = "borland_ibase";	
 	
+	
 	function ADODB_borland_ibase()
 	{
 		$this->ADODB_ibase();
@@ -54,7 +55,7 @@
 	//		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 "; 
Index: drivers/adodb-csv.inc.php
===================================================================
--- drivers/adodb-csv.inc.php	(revision 13354)
+++ drivers/adodb-csv.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 			return $this->_affectedrows;
 	}
   
-  	function &MetaDatabases()
+  	function MetaDatabases()
 	{
 		return false;
 	}
@@ -72,14 +72,14 @@
 		return true;
 	}
 	
- 	function &MetaColumns($table) 
+ 	function MetaColumns($table, $normalize=true) 
 	{
 		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 @@
 		
 			$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 @@
 			$this->_affectedrows = $rs->affectedrows;
 			$this->_insertid = $rs->insertid;
 			$rs->databaseType='csv';
-			$rs->connection = &$this;
+			$rs->connection = $this;
 		}
 		return $rs;
 	}
Index: drivers/adodb-db2.inc.php
===================================================================
--- drivers/adodb-db2.inc.php	(revision 13354)
+++ drivers/adodb-db2.inc.php	(working copy)
@@ -1,13 +1,15 @@
 <?php
 /* 
-  V4.90 8 June 2006  (c) 2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 (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.
+  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
+  higher.
 
-  Tested with PHP 5.1.1 and Apache 2.0.55 on Windows XP SP2.
+  Originally tested with PHP 5.1.1 and Apache 2.0.55 on Windows XP SP2.
+  More recently tested with PHP 5.1.2 and Apache 2.0.55 on Windows XP SP2.
 
-  This file was ported from "adodb-odbc.inc.php" by Larry Menard, "larry.menard@rogers.com".
+  This file was ported from "adodb-odbc.inc.php" by Larry Menard, "larry.menard#rogers.com".
   I ripped out what I believed to be a lot of redundant or obsolete code, but there are
   probably still some remnants of the ODBC support in this file; I'm relying on reviewers
   of this code to point out any other things that can be removed.
@@ -22,6 +24,9 @@
 --------------------------------------------------------------------------------------*/
 
 
+
+
+
 class ADODB_db2 extends ADOConnection {
 	var $databaseType = "db2";	
 	var $fmtDate = "'Y-m-d'";
@@ -31,8 +36,7 @@
 	var $sysDate = 'CURRENT DATE';
 	var $sysTimeStamp = 'CURRENT TIMESTAMP';
 	
-	var $fmtTimeStamp = "'Y-m-d-H.i.s'";
-	#var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
 	var $replaceQuote = "''"; // string to use to replace quotes
 	var $dataProvider = "db2";
 	var $hasAffectedRows = true;
@@ -42,13 +46,16 @@
 	var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
 								// breaking backward-compat
 	var $_bindInputArray = false;	
-	var $_genSeqSQL = "create table %s (id integer)";
+	var $_genIDSQL = "VALUES NEXTVAL FOR %s";
+	var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s NO MAXVALUE NO CYCLE";
+	var $_dropSeqSQL = "DROP SEQUENCE %s";
 	var $_autocommit = true;
 	var $_haserrorfunctions = true;
 	var $_lastAffectedRows = 0;
 	var $uCaseTables = true; // for meta* functions, uppercase table names
 	var $hasInsertID = true;
 	
+	
     function _insertid()
     {
         return ADOConnection::GetOne('VALUES IDENTITY_VAL_LOCAL()');
@@ -65,26 +72,31 @@
 		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().
 		// Replaces the odbc_binmode() call that was in Execute()
 		ini_set('ibm_db2.binmode', $this->binmode);
 
-		if ($argDatabasename) {
-			$this->_connectionID = db2_connect($argDatabasename,$argUsername,$argPassword);
+		if ($argDatabasename && empty($argDSN)) {
+		
+			if (stripos($argDatabasename,'UID=') && stripos($argDatabasename,'PWD=')) $this->_connectionID = db2_connect($argDatabasename,null,null);
+			else $this->_connectionID = db2_connect($argDatabasename,$argUsername,$argPassword);
 		} else {
-			$this->_connectionID = db2_connect($argDSN,$argUsername,$argPassword);
+			if ($argDatabasename) $schema = $argDatabasename;
+			if (stripos($argDSN,'UID=') && stripos($argDSN,'PWD=')) $this->_connectionID = db2_connect($argDSN,null,null);
+			else $this->_connectionID = db2_connect($argDSN,$argUsername,$argPassword);
 		}
 		if (isset($php_errormsg)) $php_errormsg = '';
 
 		// For db2_connect(), there is an optional 4th arg.  If present, it must be
 		// an array of valid options.  So far, we don't use them.
 
-		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		$this->_errorMsg = @db2_conn_errormsg();
 		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
 		
+		if ($this->_connectionID && isset($schema)) $this->Execute("SET SCHEMA=$schema");
 		return $this->_connectionID != false;
 	}
 	
@@ -102,26 +114,43 @@
 		if (isset($php_errormsg)) $php_errormsg = '';
 		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
 		
-		if ($argDatabasename) {
-			$this->_connectionID = db2_pconnect($argDatabasename,$argUsername,$argPassword);
+		if ($argDatabasename && empty($argDSN)) {
+		
+			if (stripos($argDatabasename,'UID=') && stripos($argDatabasename,'PWD=')) $this->_connectionID = db2_pconnect($argDatabasename,null,null);
+			else $this->_connectionID = db2_pconnect($argDatabasename,$argUsername,$argPassword);
 		} else {
-			$this->_connectionID = db2_pconnect($argDSN,$argUsername,$argPassword);
+			if ($argDatabasename) $schema = $argDatabasename;
+			if (stripos($argDSN,'UID=') && stripos($argDSN,'PWD=')) $this->_connectionID = db2_pconnect($argDSN,null,null);
+			else $this->_connectionID = db2_pconnect($argDSN,$argUsername,$argPassword);
 		}
 		if (isset($php_errormsg)) $php_errormsg = '';
 
-		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		$this->_errorMsg = @db2_conn_errormsg();
 		if ($this->_connectionID && $this->autoRollback) @db2_rollback($this->_connectionID);
 		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
 		
+		if ($this->_connectionID && isset($schema)) $this->Execute("SET SCHEMA=$schema");
 		return $this->_connectionID != false;
 	}
 
+	// format and return date string in database timestamp format
+	function DBTimeStamp($ts)
+	{
+		if (empty($ts) && $ts !== 0) return 'null';
+		if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
+		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'YYYY-MM-DD HH24:MI:SS')";
+	}
 	
 	// Format date column in sql string given an input format that understands Y M D
 	function SQLDate($fmt, $col=false)
 	{	
 	// use right() and replace() ?
 		if (!$col) $col = $this->sysDate;
+
+		/* use TO_CHAR() if $fmt is TO_CHAR() allowed fmt */
+		if ($fmt== 'Y-m-d H:i:s')
+			return 'TO_CHAR('.$col.", 'YYYY-MM-DD HH24:MI:SS')";
+
 		$s = '';
 		
 		$len = strlen($fmt);
@@ -131,31 +160,38 @@
 			switch($ch) {
 			case 'Y':
 			case 'y':
+				if ($len==1) return "year($col)";
 				$s .= "char(year($col))";
 				break;
 			case 'M':
+				if ($len==1) return "monthname($col)";
 				$s .= "substr(monthname($col),1,3)";
 				break;
 			case 'm':
+				if ($len==1) return "month($col)";
 				$s .= "right(digits(month($col)),2)";
 				break;
 			case 'D':
 			case 'd':
+				if ($len==1) return "day($col)";
 				$s .= "right(digits(day($col)),2)";
 				break;
 			case 'H':
 			case 'h':
+				if ($len==1) return "hour($col)";
 				if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";	
 				else $s .= "''";
 				break;
 			case 'i':
 			case 'I':
+				if ($len==1) return "minute($col)";
 				if ($col != $this->sysDate)
 					$s .= "right(digits(minute($col)),2)";
 					else $s .= "''";
 				break;
 			case 'S':
 			case 's':
+				if ($len==1) return "second($col)";
 				if ($col != $this->sysDate)
 					$s .= "right(digits(second($col)),2)";
 				else $s .= "''";
@@ -174,50 +210,54 @@
 	
 	function ServerInfo()
 	{
-	
-		if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
-			$dsn = strtoupper($this->host);
-			$first = true;
-			$found = false;
-			
-			if (!function_exists('db2_data_source')) return false;
-			
-			while(true) {
-				
-				$rez = @db2_data_source($this->_connectionID,
-					$first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);
-				$first = false;
-				if (!is_array($rez)) break;
-				if (strtoupper($rez['server']) == $dsn) {
-					$found = true;
-					break;
-				}
-			} 
-			if (!$found) return ADOConnection::ServerInfo();
-			if (!isset($rez['version'])) $rez['version'] = '';
-			return $rez;
+		$row = $this->GetRow("SELECT service_level, fixpack_num FROM TABLE(sysproc.env_get_inst_info()) 
+			as INSTANCEINFO");
+
+		
+		if ($row) {		
+			$info['version'] = $row[0].':'.$row[1];
+			$info['fixpack'] = $row[1];
+			$info['description'] = '';
 		} else {
 			return ADOConnection::ServerInfo();
 		}
+		
+		return $info;
 	}
-
 	
 	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;
-		$start -= 1;
-		return $this->Execute("insert into $seqname values($start)");
+		return true;
 	}
 	
-	var $_dropSeqSQL = 'drop table %s';
 	function DropSequence($seqname)
 	{
 		if (empty($this->_dropSeqSQL)) return false;
 		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
 	}
 	
+	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);
+		} else {
+			if ($offset > 0 && $nrows < 0);
+			else {
+				$nrows += $offset;
+				$sql .=  " FETCH FIRST $nrows ROWS ONLY ";
+			}
+			$rs = ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);
+		}
+		
+		return $rs;
+	}
+	
 	/*
 		This algorithm is not very efficient, but works even if table locking
 		is not available.
@@ -228,28 +268,8 @@
 	{	
 		// 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 = $this->GetOne("select id from $seq");
-			if ($num === false) {
-				$this->Execute(sprintf($this->_genSeqSQL ,$seq));	
-				$start -= 1;
-				$num = '0';
-				$ok = $this->Execute("insert into $seq values($start)");
-				if (!$ok) return false;
-			} 
-			$this->Execute("update $seq set id=id+1 where id=$num");
-			
-			if ($this->affected_rows() > 0) {
-				$num += 1;
-				$this->genID = $num;
+				$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
 				return $num;
-			}
-		}
-		if ($fn = $this->raiseErrorFn) {
-			$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
-		}
-		return false;
 	}
 
 
@@ -257,8 +277,8 @@
 	{
 		if ($this->_haserrorfunctions) {
 			if ($this->_errorMsg !== false) return $this->_errorMsg;
-			if (empty($this->_connectionID)) return @db2_errormsg();
-			return @db2_errormsg($this->_connectionID);
+			if (empty($this->_connectionID)) return @db2_conn_errormsg();
+			return @db2_conn_errormsg($this->_connectionID);
 		} else return ADOConnection::ErrorMsg();
 	}
 	
@@ -271,8 +291,8 @@
 				return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
 			}
 
-			if (empty($this->_connectionID)) $e = @db2_error(); 
-			else $e = @db2_error($this->_connectionID);
+			if (empty($this->_connectionID)) $e = @db2_conn_error(); 
+			else $e = @db2_conn_error($this->_connectionID);
 			
 			 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
 			 // so we check and patch
@@ -334,7 +354,7 @@
 		
 		if (!$rs) return false;
 		
-		$arr =& $rs->GetArray();
+		$arr = $rs->GetArray();
 		$rs->Close();
 		$arr2 = array();
 		for ($i=0; $i < sizeof($arr); $i++) {
@@ -343,9 +363,53 @@
 		return $arr2;
 	}
 	
+	function MetaForeignKeys($table, $owner = FALSE, $upper = FALSE, $asociative = FALSE )
+	{
+	global $ADODB_FETCH_MODE;
 	
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = @db2_foreign_keys($this->_connectionID,'',$schema,$table);
+		if (!$qid) {
+			$ADODB_FETCH_MODE = $savem;
+			return false;
+		}
+		$rs = new ADORecordSet_db2($qid);
+
+		$ADODB_FETCH_MODE = $savem;
+		/*
+		$rs->fields indices
+		0 PKTABLE_CAT
+		1 PKTABLE_SCHEM
+		2 PKTABLE_NAME
+		3 PKCOLUMN_NAME
+		4 FKTABLE_CAT
+		5 FKTABLE_SCHEM
+		6 FKTABLE_NAME
+		7 FKCOLUMN_NAME
+		*/	
+		if (!$rs) return false;
+
+		$foreign_keys = array();	 	 
+		while (!$rs->EOF) {
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				if (!is_array($foreign_keys[$rs->fields[5].'.'.$rs->fields[6]])) 
+					$foreign_keys[$rs->fields[5].'.'.$rs->fields[6]] = array();
+				$foreign_keys[$rs->fields[5].'.'.$rs->fields[6]][$rs->fields[7]] = $rs->fields[3];	 		
+			}
+			$rs->MoveNext();
+		}
+
+		$rs->Close();
+		return $foreign_key;
+	}
 	
-	function &MetaTables($ttype=false)
+	
+	function MetaTables($ttype=false,$schema=false)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -361,8 +425,7 @@
 			return $false;
 		}
 		
-		$arr =& $rs->GetArray();
-		
+		$arr = $rs->GetArray();
 		$rs->Close();
 		$arr2 = array();
 		
@@ -372,11 +435,13 @@
 		for ($i=0; $i < sizeof($arr); $i++) {
 			if (!$arr[$i][2]) continue;
 			$type = $arr[$i][3];
+			$owner = $arr[$i][1];
+			$schemaval = ($schema) ? $arr[$i][1].'.' : '';
 			if ($ttype) { 
 				if ($isview) {
-					if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
-				} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
-			} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
+					if (strncmp($type,'V',1) === 0) $arr2[] = $schemaval.$arr[$i][2];
+				} else if (strncmp($owner,'SYS',3) !== 0) $arr2[] = $schemaval.$arr[$i][2];
+			} else if (strncmp($owner,'SYS',3) !== 0) $arr2[] = $schemaval.$arr[$i][2];
 		}
 		return $arr2;
 	}
@@ -449,7 +514,7 @@
 		}
 	}
 	
-	function &MetaColumns($table)
+	function MetaColumns($table, $normalize=true)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -465,7 +530,7 @@
 	        $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;
@@ -505,17 +570,47 @@
 					$fld->max_length = $rs->fields[7];
 				$fld->not_null = !empty($rs->fields[10]);
 				$fld->scale = $rs->fields[8];
+				$fld->primary_key = false;
 				$retarr[strtoupper($fld->name)] = $fld;	
 			} else if (sizeof($retarr)>0)
 				break;
 			$rs->MoveNext();
 		}
-		$rs->Close(); //-- crashes 4.03pl1 -- why?
+		$rs->Close(); 
+		if (empty($retarr)) $retarr = false;
+
+	      $qid = db2_primary_keys($this->_connectionID, "", $schema, $table);
+		if (empty($qid)) return $false;
 		
+		$rs = new ADORecordSet_db2($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return $retarr;
+		$rs->_fetch();
+		
+		/*
+		$rs->fields indices
+		0 TABLE_CAT
+		1 TABLE_SCHEM
+		2 TABLE_NAME
+		3 COLUMN_NAME
+		4 KEY_SEQ
+		5 PK_NAME
+		*/
+		while (!$rs->EOF) {
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				$retarr[strtoupper($rs->fields[3])]->primary_key = true;
+			} else if (sizeof($retarr)>0)
+				break;
+			$rs->MoveNext();
+		}
+		$rs->Close(); 
+		
 		if (empty($retarr)) $retarr = false;
 		return $retarr;
 	}
 	
+		
 	function Prepare($sql)
 	{
 		if (! $this->_bindInputArray) return $sql; // no binding
@@ -548,8 +643,8 @@
 			
 			if (! db2_execute($stmtid,$inputarr)) {
 				if ($this->_haserrorfunctions) {
-					$this->_errorMsg = db2_errormsg();
-					$this->_errorCode = db2_error();
+					$this->_errorMsg = db2_stmt_errormsg();
+					$this->_errorCode = db2_stmt_error();
 				}
 				return false;
 			}
@@ -558,13 +653,13 @@
 			$stmtid = $sql[1];
 			if (!db2_execute($stmtid)) {
 				if ($this->_haserrorfunctions) {
-					$this->_errorMsg = db2_errormsg();
-					$this->_errorCode = db2_error();
+					$this->_errorMsg = db2_stmt_errormsg();
+					$this->_errorCode = db2_stmt_error();
 				}
 				return false;
 			}
 		} else
-			$stmtid = db2_exec($this->_connectionID,$sql);
+			$stmtid = @db2_exec($this->_connectionID,$sql);
 		
 		$this->_lastAffectedRows = 0;
 		if ($stmtid) {
@@ -586,6 +681,7 @@
 				$this->_errorCode = db2_stmt_error();
 			} else
 				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+
 		}
 		return $stmtid;
 	}
@@ -643,7 +739,7 @@
 
 
 	// returns the field object
-	function &FetchField($offset = -1) 
+	function FetchField($offset = -1) 
 	{
 		$o= new ADOFieldObject();
 		$o->name = @db2_field_name($this->_queryID,$offset);
@@ -685,10 +781,10 @@
 	}
 	
 	// 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;
@@ -697,7 +793,7 @@
 		$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();
@@ -719,7 +815,7 @@
 			$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;
 			}
@@ -735,7 +831,7 @@
 		$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;
 		}
Index: drivers/adodb-db2oci.inc.php
===================================================================
--- drivers/adodb-db2oci.inc.php	(revision 0)
+++ drivers/adodb-db2oci.inc.php	(revision 0)
@@ -0,0 +1,230 @@
+<?php
+/* 
+V5.11 5 May 2010   (c) 2000-2010 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
+  
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+include(ADODB_DIR."/drivers/adodb-db2.inc.php");
+
+
+if (!defined('ADODB_DB2OCI')){
+define('ADODB_DB2OCI',1);
+
+/*
+// regex code for smart remapping of :0, :1 bind vars to ? ?
+function _colontrack($p)
+{
+global $_COLONARR,$_COLONSZ;
+	$v = (integer) substr($p,1);
+	if ($v > $_COLONSZ) return $p;
+	$_COLONARR[] = $v;
+	return '?';
+}
+
+// smart remapping of :0, :1 bind vars to ? ?
+function _colonscope($sql,$arr)
+{
+global $_COLONARR,$_COLONSZ;
+
+	$_COLONARR = array();
+	$_COLONSZ = sizeof($arr);
+	
+	$sql2 = preg_replace("/(:[0-9]+)/e","_colontrack('\\1')",$sql);
+	
+	if (empty($_COLONARR)) return array($sql,$arr);
+	
+	foreach($_COLONARR as $k => $v) {
+		$arr2[] = $arr[$v]; 
+	}
+	
+	return array($sql2,$arr2);
+}
+*/
+
+/*
+	Smart remapping of :0, :1 bind vars to ? ?
+	
+	Handles colons in comments -- and / * * / and in quoted strings.
+*/
+
+function _colonparser($sql,$arr)
+{
+	$lensql = strlen($sql);
+	$arrsize = sizeof($arr);
+	$state = 'NORM';
+	$at = 1;
+	$ch = $sql[0]; 
+	$ch2 = @$sql[1];
+	$sql2 = '';
+	$arr2 = array();
+	$nprev = 0;
+	
+	
+	while (strlen($ch)) {
+	
+		switch($ch) {
+		case '/':
+			if ($state == 'NORM' && $ch2 == '*') {
+				$state = 'COMMENT';
+				
+				$at += 1;
+				$ch = $ch2;
+				$ch2 = $at < $lensql ? $sql[$at] : '';
+			}
+			break;
+			
+		case '*':
+			if ($state == 'COMMENT' && $ch2 == '/') {
+				$state = 'NORM';
+				
+				$at += 1;
+				$ch = $ch2;
+				$ch2 = $at < $lensql ? $sql[$at] : '';
+			}
+			break;
+		
+		case "\n":
+		case "\r":
+			if ($state == 'COMMENT2') $state = 'NORM';
+			break;
+		
+		case "'":
+			do {
+				$at += 1;
+				$ch = $ch2;
+				$ch2 = $at < $lensql ? $sql[$at] : '';
+			} while ($ch !== "'");
+			break;
+			
+		case ':':
+			if ($state == 'COMMENT' || $state == 'COMMENT2') break;
+			
+			//echo "$at=$ch $ch2, ";
+			if ('0' <= $ch2 && $ch2 <= '9') {
+				$n = '';
+				$nat = $at;
+				do {
+					$at += 1;
+					$ch = $ch2;
+					$n .= $ch;
+					$ch2 = $at < $lensql ? $sql[$at] : '';
+				} while ('0' <= $ch && $ch <= '9');
+				#echo "$n $arrsize ] ";
+				$n = (integer) $n;
+				if ($n < $arrsize) {
+					$sql2 .= substr($sql,$nprev,$nat-$nprev-1).'?';
+					$nprev = $at-1;
+					$arr2[] = $arr[$n];
+				}
+			}
+			break;
+			
+		case '-':
+			if ($state == 'NORM') {
+				if ($ch2 == '-') $state = 'COMMENT2';
+				$at += 1;
+				$ch = $ch2;
+				$ch2 = $at < $lensql ? $sql[$at] : '';
+			}
+			break;
+		}
+		
+		$at += 1;
+		$ch = $ch2;
+		$ch2 = $at < $lensql ? $sql[$at] : '';
+	}
+	
+	if ($nprev == 0) {
+		$sql2 = $sql;
+	} else {
+		$sql2 .= substr($sql,$nprev);
+	}
+	
+	return array($sql2,$arr2);
+}
+
+class ADODB_db2oci extends ADODB_db2 {
+	var $databaseType = "db2oci";	
+	var $sysTimeStamp = 'sysdate';
+	var $sysDate = 'trunc(sysdate)';
+	var $_bindInputArray = true;
+	
+	function ADODB_db2oci()
+	{
+		parent::ADODB_db2();
+	}
+	
+	function Param($name,$type=false)
+	{
+		return ':'.$name;
+	}
+	
+	
+	function MetaTables($ttype=false,$schema=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = db2_tables($this->_connectionID);
+		
+		$rs = new ADORecordSet_db2($qid);
+		
+		$ADODB_FETCH_MODE = $savem;
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		
+		$arr = $rs->GetArray();
+		$rs->Close();
+		$arr2 = array();
+	//	adodb_pr($arr);
+		if ($ttype) {
+			$isview = strncmp($ttype,'V',1) === 0;
+		}
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if (!$arr[$i][2]) continue;
+			$type = $arr[$i][3];
+			$schemaval = ($schema) ? $arr[$i][1].'.' : '';
+			$name = $schemaval.$arr[$i][2];
+			$owner = $arr[$i][1];
+			if (substr($name,0,8) == 'EXPLAIN_') continue;
+			if ($ttype) { 
+				if ($isview) {
+					if (strncmp($type,'V',1) === 0) $arr2[] = $name;
+				} else if (strncmp($type,'T',1) === 0 && strncmp($owner,'SYS',3) !== 0) $arr2[] = $name;
+			} else if (strncmp($type,'T',1) === 0 && strncmp($owner,'SYS',3) !== 0) $arr2[] = $name;
+		}
+		return $arr2;
+	}
+	
+	function _Execute($sql, $inputarr=false	)
+	{
+		if ($inputarr) list($sql,$inputarr) = _colonparser($sql, $inputarr);
+		return parent::_Execute($sql, $inputarr);
+	}
+};
+ 
+
+class  ADORecordSet_db2oci extends ADORecordSet_db2 {	
+	
+	var $databaseType = "db2oci";		
+	
+	function ADORecordSet_db2oci($id,$mode=false)
+	{
+		return $this->ADORecordSet_db2($id,$mode);
+	}
+}
+
+} //define
+?>
\ No newline at end of file

Property changes on: drivers\adodb-db2oci.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-db2ora.inc.php
===================================================================
--- drivers/adodb-db2ora.inc.php	(revision 0)
+++ drivers/adodb-db2ora.inc.php	(revision 0)
@@ -0,0 +1,80 @@
+<?php
+/* 
+V5.11 5 May 2010   (c) 2000-2010 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
+  
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+include(ADODB_DIR."/drivers/adodb-db2.inc.php");
+
+
+if (!defined('ADODB_DB2OCI')){
+define('ADODB_DB2OCI',1);
+
+
+function _colontrack($p)
+{
+global $_COLONARR,$_COLONSZ;
+	$v = (integer) substr($p,1);
+	if ($v > $_COLONSZ) return $p;
+	$_COLONARR[] = $v;
+	return '?';
+}
+
+function _colonscope($sql,$arr)
+{
+global $_COLONARR,$_COLONSZ;
+
+	$_COLONARR = array();
+	$_COLONSZ = sizeof($arr);
+	
+	$sql2 = preg_replace("/(:[0-9]+)/e","_colontrack('\\1')",$sql);
+	
+	if (empty($_COLONARR)) return array($sql,$arr);
+	
+	foreach($_COLONARR as $k => $v) {
+		$arr2[] = $arr[$v]; 
+	}
+	
+	return array($sql2,$arr2);
+}
+
+class ADODB_db2oci extends ADODB_db2 {
+	var $databaseType = "db2oci";	
+	var $sysTimeStamp = 'sysdate';
+	var $sysDate = 'trunc(sysdate)';
+	
+	function ADODB_db2oci()
+	{
+		$this->ADODB_db2();
+	}
+	
+	
+	function _Execute($sql, $inputarr)
+	{
+		if ($inputarr) list($sql,$inputarr) = _colonscope($sql, $inputarr);
+		return parent::_Execute($sql, $inputarr);
+	}
+};
+ 
+
+class  ADORecordSet_db2oci extends ADORecordSet_odbc {	
+	
+	var $databaseType = "db2oci";		
+	
+	function ADORecordSet_db2oci($id,$mode=false)
+	{
+		return $this->ADORecordSet_db2($id,$mode);
+	}
+}
+
+} //define
+?>
\ No newline at end of file

Property changes on: drivers\adodb-db2ora.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-fbsql.inc.php
===================================================================
--- drivers/adodb-fbsql.inc.php	(revision 13354)
+++ drivers/adodb-fbsql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
- @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ @version V5.11 5 May 2010  (c) 2000-2010 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 @@
 			return fbsql_affected_rows($this->_connectionID);
 	}
   
-  	function &MetaDatabases()
+  	function MetaDatabases()
 	{
 		$qid = fbsql_list_dbs($this->_connectionID);
 		$arr = array();
@@ -80,7 +80,7 @@
 		return true;	
 	}
 	
- 	function &MetaColumns($table) 
+ 	function MetaColumns($table, $normalize=true) 
 	{
 		if ($this->metaColumnsSQL) {
 			
@@ -127,7 +127,7 @@
 	
 	
 	// returns queryID or false
-	function _query($sql,$inputarr)
+	function _query($sql,$inputarr=false)
 	{
 		return fbsql_query("$sql;",$this->_connectionID);
 	}
@@ -187,7 +187,7 @@
 	
 
 
-	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
Index: drivers/adodb-firebird.inc.php
===================================================================
--- drivers/adodb-firebird.inc.php	(revision 13354)
+++ drivers/adodb-firebird.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -19,7 +19,7 @@
 	var $databaseType = "firebird";	
 	var $dialect = 3;
 	
-	var $sysTimeStamp = "cast('NOW' as timestamp)";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)";
 	
 	function ADODB_firebird()
 	{	
@@ -44,7 +44,7 @@
 	// 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 @@
 		
 		$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;
 	}
Index: drivers/adodb-ibase.inc.php
===================================================================
--- drivers/adodb-ibase.inc.php	(revision 13354)
+++ drivers/adodb-ibase.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.  
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 	var $buffers = 0;
 	var $dialect = 1;
 	var $sysDate = "cast('TODAY' as timestamp)";
-	var $sysTimeStamp = "cast('NOW' as timestamp)";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)";
 	var $ansiOuter = true;
 	var $hasAffectedRows = false;
 	var $poorAffectedRows = true;
@@ -159,17 +159,17 @@
 	
 	// 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 @@
 		return $ret;
 	}
 	
-	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	function MetaIndexes ($table, $primary = FALSE, $owner=false)
 	{
         // save old fetch mode
         global $ADODB_FETCH_MODE;
@@ -242,7 +242,7 @@
 
 	
 	// See http://community.borland.com/article/0,1410,25844,00.html
-	function RowLock($tables,$where,$col)
+	function RowLock($tables,$where,$col=false)
 	{
 		if ($this->autoCommit) $this->BeginTrans();
 		$this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
@@ -326,7 +326,7 @@
 			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 @@
 			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 @@
 	}
 	//OPN STUFF end
 		// returns array of ADOFieldObjects for current table
-	function &MetaColumns($table) 
+	function MetaColumns($table, $normalize=true) 
 	{
 	global $ADODB_FETCH_MODE;
 		
@@ -556,7 +556,7 @@
 	
 	// old blobdecode function
 	// still used to auto-decode all blob's
-	function _BlobDecode( $blob ) 
+	function _BlobDecode_old( $blob ) 
 	{
 		$blobid = ibase_blob_open($this->_connectionID, $blob );
 		$realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
@@ -568,6 +568,32 @@
 		return( $realblob );
 	} 
 	
+	function _BlobDecode( $blob ) 
+    {
+        if  (ADODB_PHPVER >= 0x5000) {
+            $blob_data = ibase_blob_info($this->_connectionID, $blob );
+            $blobid = ibase_blob_open($this->_connectionID, $blob );
+        } else {
+
+            $blob_data = ibase_blob_info( $blob );
+            $blobid = ibase_blob_open( $blob );
+        }
+
+        if( $blob_data[0] > $this->maxblobsize ) {
+
+            $realblob = ibase_blob_get($blobid, $this->maxblobsize);
+
+            while($string = ibase_blob_get($blobid, 8192)){
+                $realblob .= $string; 
+            }
+        } else {
+            $realblob = ibase_blob_get($blobid, $blob_data[0]);
+        }
+
+        ibase_blob_close( $blobid );
+        return( $realblob );
+	}
+	
 	function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
 	{ 
 		$fd = fopen($path,'rb'); 
@@ -717,7 +743,7 @@
 			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);
@@ -796,9 +822,9 @@
 		
 		$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;
 	}
Index: drivers/adodb-informix.inc.php
===================================================================
--- drivers/adodb-informix.inc.php	(revision 13354)
+++ drivers/adodb-informix.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /**
-* @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+* @version V5.11 5 May 2010  (c) 2000-2010 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.
Index: drivers/adodb-informix72.inc.php
===================================================================
--- drivers/adodb-informix72.inc.php	(revision 13354)
+++ drivers/adodb-informix72.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim. All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -58,7 +58,7 @@
 	{
 		// alternatively, use older method:
 		//putenv("DBDATE=Y4MD-");
-
+		
 		// force ISO date format
 		putenv('GL_DATE=%Y-%m-%d');
 		
@@ -123,10 +123,10 @@
 		return true;
 	}
 
-	function RowLock($tables,$where,$flds='1 as ignore')
+	function RowLock($tables,$where,$col='1 as adodbignore')
 	{
 		if ($this->_autocommit) $this->BeginTrans();
-		return $this->GetOne("select $flds from $tables where $where for update");
+		return $this->GetOne("select $col from $tables where $where for update");
 	}
 
 	/*	Returns: the last error message from previous database operation
@@ -147,7 +147,7 @@
 	}
 
    
-    function &MetaColumns($table)
+    function MetaColumns($table, $normalize=true)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -192,14 +192,14 @@
 			}
 
 			$rs->Close();
-			$rspKey->Close(); //!eos
+			$rspkey->Close(); //!eos
 			return $retarr;	
 		}
 
 		return $false;
 	}
 	
-   function &xMetaColumns($table)
+   function xMetaColumns($table)
    {
 		return ADOConnection::MetaColumns($table,false);
    }
@@ -219,7 +219,7 @@
 
 		$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 @@
 	}
 */
 	// returns query ID if successful, otherwise false
-	function _query($sql,$inputarr)
+	function _query($sql,$inputarr=false)
 	{
 	global $ADODB_COUNTRECS;
 	
@@ -362,14 +362,14 @@
 		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);
 			foreach($fp as $k => $v) {
 				$o = new ADOFieldObject;
 				$o->name = $k;
-				$arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"
+				$arr = explode(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"
 				$o->type = $arr[0];
 				$o->max_length = $arr[1];
 				$this->_fieldprops[] = $o;
Index: drivers/adodb-ldap.inc.php
===================================================================
--- drivers/adodb-ldap.inc.php	(revision 13354)
+++ drivers/adodb-ldap.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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 @@
 	# 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 @@
 		
 		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 = explode( ':', $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 @@
 		}
 		
 		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 @@
 	}
 	
 	/* 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 @@
     /*
     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 @@
 		return $results; 
 	}
     
-    function &GetRowAssoc()
+    function GetRowAssoc()
 	{
         $results = array();
         foreach ( $this->fields as $k=>$v ) {
Index: drivers/adodb-mssql.inc.php
===================================================================
--- drivers/adodb-mssql.inc.php	(revision 13354)
+++ drivers/adodb-mssql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -14,6 +14,7 @@
 	
 */
 
+
 // security - hide paths
 if (!defined('ADODB_DIR')) die();
 
@@ -99,9 +100,10 @@
 	var $rightOuter = '=*';
 	var $ansiOuter = true; // for mssql7 or later
 	var $poorAffectedRows = true;
-	var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
+	var $identitySQL = 'select SCOPE_IDENTITY()'; // 'select SCOPE_IDENTITY'; # for mssql 2000
 	var $uniqueOrderBy = true;
 	var $_bindInputArray = true;
+	var $forceNewConnect = false;
 	
 	function ADODB_mssql() 
 	{		
@@ -112,21 +114,23 @@
 	{
 	global $ADODB_FETCH_MODE;
 	
-		$stmt = $this->PrepareSP('sp_server_info');
-		$val = 2;
+	
 		if ($this->fetchMode === false) {
 			$savem = $ADODB_FETCH_MODE;
 			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 		} else 
 			$savem = $this->SetFetchMode(ADODB_FETCH_NUM);
+				
+		if (0) {
+			$stmt = $this->PrepareSP('sp_server_info');
+			$val = 2;
+			$this->Parameter($stmt,$val,'attribute_id');
+			$row = $this->GetRow($stmt);
+		}
 		
+		$row = $this->GetRow("execute sp_server_info 2");
 		
-		$this->Parameter($stmt,$val,'attribute_id');
-		$row = $this->GetRow($stmt);
 		
-		//$row = $this->GetRow("execute sp_server_info 2");
-		
-		
 		if ($this->fetchMode === false) {
 			$ADODB_FETCH_MODE = $savem;
 		} else
@@ -149,9 +153,48 @@
 	// 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.
+        if ($this->lastInsID !== false) {
+            return $this->lastInsID; // InsID from sp_executesql call
+        } else {
 			return $this->GetOne($this->identitySQL);
+		}
 	}
 
+
+
+	/**
+	* Correctly quotes a string so that all strings are escaped. We prefix and append
+	* to the string single-quotes.
+	* An example is  $db->qstr("Don't bother",magic_quotes_runtime());
+	* 
+	* @param s         the string to quote
+	* @param [magic_quotes]    if $s is GET/POST var, set to get_magic_quotes_gpc().
+	*              This undoes the stupidity of magic quotes for GPC.
+	*
+	* @return  quoted string to be sent back to database
+	*/
+	function qstr($s,$magic_quotes=false)
+	{
+ 		if (!$magic_quotes) {
+ 			return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+		}
+
+ 		// undo magic quotes for " unless sybase is on
+ 		$sybase = ini_get('magic_quotes_sybase');
+ 		if (!$sybase) {
+ 			$s = str_replace('\\"','"',$s);
+ 			if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+ 				return "'$s'";
+ 			else {// change \' to '' for sybase/mssql
+ 				$s = str_replace('\\\\','\\',$s);
+ 				return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+ 			}
+ 		} else {
+ 			return "'".$s."'";
+		}
+	}
+// moodle change end - see readme_moodle.txt
+
 	function _affectedrows()
 	{
 		return $this->GetOne('select @@rowcount');
@@ -198,14 +241,18 @@
 	}
 	
 
-	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);
+				
+			if ($secs2cache)
+				$rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
+			else
+				$rs = $this->Execute($sql,$inputarr);
 		} else
-			$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+			$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
 	
 		return $rs;
 	}
@@ -276,8 +323,8 @@
 	{
 		if ($this->transOff) return true; 
 		$this->transCnt += 1;
-	   	$this->Execute('BEGIN TRAN');
-	   	return true;
+	   	$ok = $this->Execute('BEGIN TRAN');
+	   	return $ok;
 	}
 		
 	function CommitTrans($ok=true) 
@@ -285,15 +332,15 @@
 		if ($this->transOff) return true; 
 		if (!$ok) return $this->RollbackTrans();
 		if ($this->transCnt) $this->transCnt -= 1;
-		$this->Execute('COMMIT TRAN');
-		return true;
+		$ok = $this->Execute('COMMIT TRAN');
+		return $ok;
 	}
 	function RollbackTrans()
 	{
 		if ($this->transOff) return true; 
 		if ($this->transCnt) $this->transCnt -= 1;
-		$this->Execute('ROLLBACK TRAN');
-		return true;
+		$ok = $this->Execute('ROLLBACK TRAN');
+		return $ok;
 	}
 	
 	function SetTransactionMode( $transaction_mode ) 
@@ -319,14 +366,15 @@
 		
 		See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
 	*/
-	function RowLock($tables,$where,$flds='top 1 null as ignore') 
+	function RowLock($tables,$where,$col='1 as adodbignore') 
 	{
+		if ($col == '1 as adodbignore') $col = 'top 1 null as ignore';
 		if (!$this->transCnt) $this->BeginTrans();
-		return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
+		return $this->GetOne("select $col from $tables with (ROWLOCK,HOLDLOCK) where $where");
 	}
 	
 	
-	function &MetaIndexes($table,$primary=false)
+	function MetaIndexes($table,$primary=false, $owner=false)
 	{
 		$table = $this->qstr($table);
 
@@ -358,7 +406,7 @@
 
 		$indexes = array();
 		while ($row = $rs->FetchRow()) {
-			if (!$primary && $row[5]) continue;
+			if ($primary && !$row[5]) continue;
 			
             $indexes[$row[0]]['unique'] = $row[6];
             $indexes[$row[0]]['columns'][] = $row[1];
@@ -383,7 +431,7 @@
 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;
 		
@@ -410,7 +458,7 @@
 	{ 
 		if(@mssql_select_db("master")) { 
 				 $qry=$this->metaDatabasesSQL; 
-				 if($rs=@mssql_query($qry)){ 
+				 if($rs=@mssql_query($qry,$this->_connectionID)){ 
 						 $tmpAr=$ar=array(); 
 						 while($tmpAr=@mssql_fetch_row($rs)) 
 								 $ar[]=$tmpAr[0]; 
@@ -429,7 +477,7 @@
 
 	// "Stein-Aksel Basma" <basma@accelero.no>
 	// tested with MSSQL 2000
-	function &MetaPrimaryKeys($table)
+	function MetaPrimaryKeys($table, $owner=false)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -454,14 +502,14 @@
 	}
 
 	
-	function &MetaTables($ttype=false,$showSchema=false,$mask=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);
+		$ret = ADOConnection::MetaTables($ttype,$showSchema);
 		
 		if ($mask) {
 			$this->metaTablesSQL = $save;
@@ -501,11 +549,11 @@
 	   else return -1;
 	}
 	
-	// returns true or false
-	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	// returns true or false, newconnect supported since php 5.1.0.
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$newconnect=false)
 	{
 		if (!function_exists('mssql_pconnect')) return null;
-		$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
+		$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword,$newconnect);
 		if ($this->_connectionID === false) return false;
 		if ($argDatabasename) return $this->SelectDB($argDatabasename);
 		return true;	
@@ -528,6 +576,11 @@
 		return true;	
 	}
 	
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+    {
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
+    }
+
 	function Prepare($sql)
 	{
 		$sqlarr = explode('?',$sql);
@@ -536,10 +589,10 @@
 		for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
 			$sql2 .=  '@P'.($i-1) . $sqlarr[$i];
 		} 
-		return array($sql,$this->qstr($sql2),$max);
+		return array($sql,$this->qstr($sql2),$max,$sql2);
 	}
 	
-	function PrepareSP($sql)
+	function PrepareSP($sql,$param=true)
 	{
 		if (!$this->_has_mssql_init) {
 			ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
@@ -604,7 +657,7 @@
 		if ($type === false) 
 			switch(gettype($var)) {
 			default:
-			case 'string': $type = SQLCHAR; break;
+			case 'string': $type = SQLVARCHAR; break;
 			case 'double': $type = SQLFLT8; break;
 			case 'integer': $type = SQLINT4; break;
 			case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0
@@ -652,7 +705,7 @@
 	}
 	
 	// returns query ID if successful, otherwise false
-	function _query($sql,$inputarr)
+	function _query($sql,$inputarr=false)
 	{
 		$this->_errorMsg = false;
 		if (is_array($inputarr)) {
@@ -660,6 +713,11 @@
 			# bind input params with sp_executesql: 
 			# see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
 			# works only with sql server 7 and newer
+            $getIdentity = false;
+            if (!is_array($sql) && preg_match('/^\\s*insert/i', $sql)) {
+                $getIdentity = true;
+                $sql .= (preg_match('/;\\s*$/i', $sql) ? ' ' : '; ') . $this->identitySQL;
+            }
 			if (!is_array($sql)) $sql = $this->Prepare($sql);
 			$params = '';
 			$decl = '';
@@ -698,14 +756,21 @@
 			}
 			$decl = $this->qstr($decl);
 			if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
-			$rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params");
+			$rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID);
+            if ($getIdentity) {
+                $arr = @mssql_fetch_row($rez);
+                $this->lastInsID = isset($arr[0]) ? $arr[0] : false;
+                @mssql_data_seek($rez, 0);
+            }
 			
 		} else if (is_array($sql)) {
 			# PrepareSP()
 			$rez = mssql_execute($sql[1]);
+            $this->lastInsID = false;
 			
 		} else {
 			$rez = mssql_query($sql,$this->_connectionID);
+            $this->lastInsID = false;
 		}
 		return $rez;
 	}
@@ -720,12 +785,12 @@
 	}
 	
 	// mssql uses a default date like Dec 30 2000 12:00AM
-	function UnixDate($v)
+	static function UnixDate($v)
 	{
 		return ADORecordSet_array_mssql::UnixDate($v);
 	}
 	
-	function UnixTimeStamp($v)
+	static function UnixTimeStamp($v)
 	{
 		return ADORecordSet_array_mssql::UnixTimeStamp($v);
 	}	
@@ -797,7 +862,7 @@
 		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) {
 			$f = @mssql_fetch_field($this->_queryID, $fieldOffset);
@@ -847,11 +912,19 @@
 			if (is_array($this->fields)) {
 				if (ADODB_ASSOC_CASE == 0) {
 					foreach($this->fields as $k=>$v) {
-						$this->fields[strtolower($k)] = $v;
+						$kn = strtolower($k);
+						if ($kn <> $k) {
+							unset($this->fields[$k]);
+							$this->fields[$kn] = $v;
+						}
 					}
 				} else if (ADODB_ASSOC_CASE == 1) {
 					foreach($this->fields as $k=>$v) {
-						$this->fields[strtoupper($k)] = $v;
+						$kn = strtoupper($k);
+						if ($kn <> $k) {
+							unset($this->fields[$k]);
+							$this->fields[$kn] = $v;
+						}
 					}
 				}
 			}
@@ -892,11 +965,19 @@
 			if (!$this->fields) {
 			} else if (ADODB_ASSOC_CASE == 0) {
 				foreach($this->fields as $k=>$v) {
-					$this->fields[strtolower($k)] = $v;
+					$kn = strtolower($k);
+					if ($kn <> $k) {
+						unset($this->fields[$k]);
+						$this->fields[$kn] = $v;
+					}
 				}
 			} else if (ADODB_ASSOC_CASE == 1) {
 				foreach($this->fields as $k=>$v) {
-					$this->fields[strtoupper($k)] = $v;
+					$kn = strtoupper($k);
+					if ($kn <> $k) {
+						unset($this->fields[$k]);
+						$this->fields[$kn] = $v;
+					}
 				}
 			}
 		} else {
@@ -915,12 +996,12 @@
 		return $rez;
 	}
 	// mssql uses a default date like Dec 30 2000 12:00AM
-	function UnixDate($v)
+	static function UnixDate($v)
 	{
 		return ADORecordSet_array_mssql::UnixDate($v);
 	}
 	
-	function UnixTimeStamp($v)
+	static function UnixTimeStamp($v)
 	{
 		return ADORecordSet_array_mssql::UnixTimeStamp($v);
 	}
@@ -935,7 +1016,7 @@
 	}
 	
 		// mssql uses a default date like Dec 30 2000 12:00AM
-	function UnixDate($v)
+	static function UnixDate($v)
 	{
 	
 		if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
@@ -966,7 +1047,7 @@
 		return  mktime(0,0,0,$themth,$theday,$rr[3]);
 	}
 	
-	function UnixTimeStamp($v)
+	static function UnixTimeStamp($v)
 	{
 	
 		if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
Index: drivers/adodb-mssql_n.inc.php
===================================================================
--- drivers/adodb-mssql_n.inc.php	(revision 0)
+++ drivers/adodb-mssql_n.inc.php	(revision 0)
@@ -0,0 +1,171 @@
+<?php
+
+/// $Id $
+
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// NOTICE OF COPYRIGHT                                                   //
+//                                                                       //
+// ADOdb  - Database Abstraction Library for PHP                         //
+//          http://adodb.sourceforge.net/                                //
+//                                                                       //
+// Copyright (c) 2000-2010 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);
+	}
+}
+?>
\ No newline at end of file

Property changes on: drivers\adodb-mssql_n.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-mssqlnative.inc.php
===================================================================
--- drivers/adodb-mssqlnative.inc.php	(revision 0)
+++ drivers/adodb-mssqlnative.inc.php	(revision 0)
@@ -0,0 +1,923 @@
+<?php
+/* 
+V5.11 5 May 2010   (c) 2000-2010 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,$col='1 as adodbignore') 
+	{
+		if ($col == '1 as adodbignore') $col = 'top 1 null as ignore';
+		if (!$this->transCnt) $this->BeginTrans();
+		return $this->GetOne("select $col 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, $owner = 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
+*/
+
+?>
\ No newline at end of file

Property changes on: drivers\adodb-mssqlnative.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-mssqlpo.inc.php
===================================================================
--- drivers/adodb-mssqlpo.inc.php	(revision 13354)
+++ drivers/adodb-mssqlpo.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /**
-* @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+* @version V5.11 5 May 2010  (c) 2000-2010 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 @@
 		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);
Index: drivers/adodb-mysql.inc.php
===================================================================
--- drivers/adodb-mysql.inc.php	(revision 13354)
+++ drivers/adodb-mysql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -24,7 +24,7 @@
 	var $hasInsertID = true;
 	var $hasAffectedRows = true;	
 	var $metaTablesSQL = "SHOW TABLES";	
-	var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
 	var $fmtTimeStamp = "'Y-m-d H:i:s'";
 	var $hasLimit = true;
 	var $hasMoveFirst = true;
@@ -58,7 +58,7 @@
 	}
 	
 	
-	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 @@
 			$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 @@
 	// 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) {
@@ -157,11 +158,12 @@
 	
 	function GetOne($sql,$inputarr=false)
 	{
+	global $ADODB_GETONE_EOF;
 		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;
+				if ($rs->EOF) return $ADODB_GETONE_EOF;
 				return reset($rs->fields);
 			}
 		} else {
@@ -180,10 +182,11 @@
 			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)";
+	var $_genSeqCountSQL = "select count(*) from %s";
 	var $_genSeq2SQL = "insert into %s values (%s)";
 	var $_dropSeqSQL = "drop table %s";
 	
@@ -212,18 +215,22 @@
 			if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
 			$u = strtoupper($seqname);
 			$this->Execute(sprintf($this->_genSeqSQL,$seqname));
-			$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+			$cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
+			if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
 			$rs = $this->Execute($getnext);
 		}
-		$this->genID = mysql_insert_id($this->_connectionID);
 		
-		if ($rs) $rs->Close();
+		if ($rs) {
+			$this->genID = mysql_insert_id($this->_connectionID);
+			$rs->Close();
+		} else
+			$this->genID = 0;
 		
 		$this->_logsql = $savelog;
 		return $this->genID;
 	}
 	
-  	function &MetaDatabases()
+  	function MetaDatabases()
 	{
 		$qid = mysql_list_dbs($this->_connectionID);
 		$arr = array();
@@ -341,8 +348,11 @@
 	function OffsetDate($dayFraction,$date=false)
 	{		
 		if (!$date) $date = $this->sysDate;
+		
 		$fraction = $dayFraction * 24 * 3600;
-		return "from_unixtime(unix_timestamp($date)+$fraction)";
+		return '('. $date . ' + INTERVAL ' .	 $fraction.' SECOND)';
+		
+//		return "from_unixtime(unix_timestamp($date)+$fraction)";
 	}
 	
 	// returns true or false
@@ -385,7 +395,7 @@
 		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
 	}
 	
- 	function &MetaColumns($table) 
+ 	function MetaColumns($table, $normalize=true) 
 	{
 		$this->_findschema($table,$schema);
 		if ($schema) {
@@ -438,9 +448,10 @@
 			$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->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') {
@@ -475,21 +486,21 @@
 	}
 	
 	// 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) 
@@ -549,8 +560,9 @@
             $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();
 
@@ -566,9 +578,12 @@
                  $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 {
@@ -620,28 +635,28 @@
 		$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;
 	}
 	
@@ -723,6 +738,7 @@
 		case 'LONGBLOB': 
 		case 'BLOB':
 		case 'MEDIUMBLOB':
+		case 'BINARY':
 			return !empty($fieldobj->binary) ? 'B' : 'X';
 			
 		case 'YEAR':
@@ -776,4 +792,4 @@
 
 
 }
-?>
+?>
\ No newline at end of file
Index: drivers/adodb-mysqli.inc.php
===================================================================
--- drivers/adodb-mysqli.inc.php	(revision 13354)
+++ drivers/adodb-mysqli.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -14,7 +14,7 @@
 */ 
 
 // security - hide paths
-//if (!defined('ADODB_DIR')) die();
+if (!defined('ADODB_DIR')) die();
 
 if (! defined("_ADODB_MYSQLI_LAYER")) {
  define("_ADODB_MYSQLI_LAYER", 1 );
@@ -32,7 +32,7 @@
 	var $hasInsertID = true;
 	var $hasAffectedRows = true;	
 	var $metaTablesSQL = "SHOW TABLES";	
-	var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
 	var $fmtTimeStamp = "'Y-m-d H:i:s'";
 	var $hasLimit = true;
 	var $hasMoveFirst = true;
@@ -50,6 +50,8 @@
 	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';
+  	var $multiQuery = false;
 	
 	function ADODB_mysqli() 
 	{			
@@ -113,6 +115,7 @@
  	   } else {
 			if ($this->debug) 
 		  		ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
+			$this->_connectionID = null;
 			return false;
 	   }
 	}
@@ -138,6 +141,18 @@
 		return " IFNULL($field, $ifNull) "; // if MySQL
 	}
 	
+	// do not use $ADODB_COUNTRECS
+	function GetOne($sql,$inputarr=false)
+	{
+		$ret = false;
+		$rs = $this->Execute($sql,$inputarr);
+		if ($rs) {	
+			if (!$rs->EOF) $ret = reset($rs->fields);
+			$rs->Close();
+		}
+		return $ret;
+	}
+	
 	function ServerInfo()
 	{
 		$arr['description'] = $this->GetOne("select version()");
@@ -150,7 +165,9 @@
 	{	  
 		if ($this->transOff) return true;
 		$this->transCnt += 1;
-		$this->Execute('SET AUTOCOMMIT=0');
+		
+		//$this->Execute('SET AUTOCOMMIT=0');
+		mysqli_autocommit($this->_connectionID, false);
 		$this->Execute('BEGIN');
 		return true;
 	}
@@ -162,7 +179,9 @@
 		
 		if ($this->transCnt) $this->transCnt -= 1;
 		$this->Execute('COMMIT');
-		$this->Execute('SET AUTOCOMMIT=1');
+		
+		//$this->Execute('SET AUTOCOMMIT=1');
+		mysqli_autocommit($this->_connectionID, true);
 		return true;
 	}
 	
@@ -171,15 +190,16 @@
 		if ($this->transOff) return true;
 		if ($this->transCnt) $this->transCnt -= 1;
 		$this->Execute('ROLLBACK');
-		$this->Execute('SET AUTOCOMMIT=1');
+		//$this->Execute('SET AUTOCOMMIT=1');
+		mysqli_autocommit($this->_connectionID, true);
 		return true;
 	}
 	
-	function RowLock($tables,$where='',$flds='1 as adodb_ignore') 
+	function RowLock($tables,$where='',$col='1 as adodbignore') 
 	{
 		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 $col from $tables $where for update");
 		return !empty($rs); 
 	}
 	
@@ -195,6 +215,7 @@
 	//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) . "'";   
@@ -231,6 +252,7 @@
 	// 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";
 	
@@ -256,20 +278,24 @@
 			if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
 			$u = strtoupper($seqname);
 			$this->Execute(sprintf($this->_genSeqSQL,$seqname));
-			$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+			$cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
+			if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
 			$rs = $this->Execute($getnext);
 		}
-		$this->genID = mysqli_insert_id($this->_connectionID);
 		
-		if ($rs) $rs->Close();
-		
+		if ($rs) {
+			$this->genID = mysqli_insert_id($this->_connectionID);
+			$rs->Close();
+		} else
+			$this->genID = 0;
+			
 		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){
@@ -283,7 +309,7 @@
 	}
 
 	  
-	function &MetaIndexes ($table, $primary = FALSE)
+	function MetaIndexes ($table, $primary = FALSE, $owner = false)
 	{
 		// save old fetch mode
 		global $ADODB_FETCH_MODE;
@@ -430,12 +456,15 @@
 	// dayFraction is a day in floating point
 	function OffsetDate($dayFraction,$date=false)
 	{		
-		if (!$date) 
-		  $date = $this->sysDate;
-		return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
+		if (!$date) $date = $this->sysDate;
+		
+		$fraction = $dayFraction * 24 * 3600;
+		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';
+		
+//		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)) {
@@ -446,7 +475,7 @@
 			$mask = $this->qstr($mask);
 			$this->metaTablesSQL .= " like $mask";
 		}
-		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		$ret = ADOConnection::MetaTables($ttype,$showSchema);
 		
 		$this->metaTablesSQL = $save;
 		return $ret;
@@ -463,8 +492,9 @@
 	       $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();
 	
@@ -480,8 +510,11 @@
 	            $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];
@@ -494,7 +527,7 @@
 	    return  $foreign_keys;
 	}
 	
- 	function &MetaColumns($table) 
+ 	function MetaColumns($table, $normalize=true) 
 	{
 		$false = false;
 		if (!$this->metaColumnsSQL)
@@ -528,8 +561,10 @@
 				$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;
@@ -539,6 +574,7 @@
 			$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
 			$fld->binary = (strpos($type,'blob') !== false);
 			$fld->unsigned = (strpos($type,'unsigned') !== false);
+			$fld->zerofill = (strpos($type,'zerofill') !== false);
 
 			if (!$fld->binary) {
 				$d = $rs->fields[4];
@@ -580,20 +616,19 @@
 	}
 	
 	// 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;
 	}
@@ -602,7 +637,6 @@
 	function Prepare($sql)
 	{
 		return $sql;
-		
 		$stmt = $this->_connectionID->prepare($sql);
 		if (!$stmt) {
 			echo $this->ErrorMsg();
@@ -616,8 +650,18 @@
 	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)) {
 		
-		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) {
@@ -628,16 +672,36 @@
 			
 			$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 ($this->multiQuery) {
+			$rs = mysqli_multi_query($this->_connectionID, $sql.';');
+			if ($rs) {
+				$rs = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->_connectionID ) : @mysqli_use_result( $this->_connectionID );
+				return $rs ? $rs : true; // mysqli_more_results( $this->_connectionID )
+			}
+		} else {
+			$rs = mysqli_query($this->_connectionID, $sql, $ADODB_COUNTRECS ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
+		
+			if ($rs) return $rs;
+		}
+
+		if($this->debug)
+			ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
+		
+		return false;
+		
 	}
 
 	/*	Returns: the last error message from previous database operation	*/	
@@ -787,13 +851,14 @@
 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;
@@ -805,11 +870,11 @@
 		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;
 	}
 	
@@ -842,6 +907,33 @@
 	  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.
@@ -864,6 +956,19 @@
 	
 	function _close() 
 	{
+	    //if results are attached to this pointer from Stored Proceedure calls, the next standard query will die 2014
+        //only a problem with persistant connections
+
+        //mysqli_next_result($this->connection->_connectionID); trashes the DB side attached results.
+
+        while(mysqli_more_results($this->connection->_connectionID)){
+           @mysqli_next_result($this->connection->_connectionID);
+        }
+
+        //Because you can have one attached result, without tripping mysqli_more_results
+        @mysqli_next_result($this->connection->_connectionID);
+
+
 		mysqli_free_result($this->_queryID); 
 	  	$this->_queryID = false;	
 	}
@@ -917,7 +1022,7 @@
 		 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 :
@@ -997,4 +1102,108 @@
  
 }
 
+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
+  
+}
+
 ?>
\ No newline at end of file
Index: drivers/adodb-mysqlpo.inc.php
===================================================================
--- drivers/adodb-mysqlpo.inc.php	(revision 0)
+++ drivers/adodb-mysqlpo.inc.php	(revision 0)
@@ -0,0 +1,138 @@
+<?php
+
+/*
+V5.11 5 May 2010   (c) 2000-2010 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='',$col='1 as adodbignore') 
+	{
+		if ($this->transCnt==0) $this->BeginTrans();
+		if ($where) $where = ' where '.$where;
+		$rs = $this->Execute("select $col 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);
+	}
+}
+
+?>
\ No newline at end of file

Property changes on: drivers\adodb-mysqlpo.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-mysqlt.inc.php
===================================================================
--- drivers/adodb-mysqlt.inc.php	(revision 13354)
+++ drivers/adodb-mysqlt.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 		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') 
+	function RowLock($tables,$where='',$col='1 as adodbignore') 
 	{
 		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 $col from $tables $where for update");
 		return !empty($rs); 
 	}
 	
Index: drivers/adodb-netezza.inc.php
===================================================================
--- drivers/adodb-netezza.inc.php	(revision 13354)
+++ drivers/adodb-netezza.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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 @@
 	
 	}
 	
-	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 @@
 		$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;
 		
Index: drivers/adodb-oci8.inc.php
===================================================================
--- drivers/adodb-oci8.inc.php	(revision 13354)
+++ drivers/adodb-oci8.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 /*
 
-  version V4.90 8 June 2006 (c) 2000-2006 John Lim. All rights reserved.
+  version V5.11 5 May 2010  (c) 2000-2010 John Lim. All rights reserved.
 
   Released under both BSD license and Lesser GPL library license. 
   Whenever there is any discrepancy between the two licenses, 
@@ -58,13 +58,18 @@
 	var $replaceQuote = "''"; // string to use to replace quotes
 	var $concat_operator='||';
 	var $sysDate = "TRUNC(SYSDATE)";
-	var $sysTimeStamp = 'SYSDATE';
+	var $sysTimeStamp = 'SYSDATE'; // requires oracle 9 or later, otherwise use SYSDATE
 	var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
 	var $_stmt;
 	var $_commit = OCI_COMMIT_ON_SUCCESS;
 	var $_initdate = true; // init date to YYYY-MM-DD
-	var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";
+	var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW') and table_name not like 'BIN\$%'"; // bin$ tables are recycle bin tables
 	var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
+	var $metaColumnsSQL2 = "select column_name,data_type,data_length, data_scale, data_precision, 
+    case when nullable = 'Y' then 'NULL'
+    else 'NOT NULL' end as nulls,
+    data_default from all_tab_cols 
+  where owner='%s' and table_name='%s' order by column_id"; // when there is a schema
 	var $_bindInputArray = true;
 	var $hasGenID = true;
 	var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
@@ -75,17 +80,19 @@
 	var $noNullStrings = false;
 	var $connectSID = false;
 	var $_bind = false;
+	var $_nestedSQL = true;
 	var $_hasOCIFetchStatement = false;
 	var $_getarray = false; // currently not working
 	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'; // 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() 
@@ -94,32 +101,38 @@
 		if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
 	}
 	
-	/*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
-	function &MetaColumns($table) 
+	/*  function MetaColumns($table, $normalize=true) added by smondino@users.sourceforge.net*/
+	function MetaColumns($table, $normalize=true) 
 	{
 	global $ADODB_FETCH_MODE;
-	
+		
+		$schema = '';
+		$this->_findschema($table, $schema);
+		
 		$false = false;
 		$save = $ADODB_FETCH_MODE;
 		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+
+		if ($schema)
+			$rs = $this->Execute(sprintf($this->metaColumnsSQL2, strtoupper($schema), strtoupper($table)));
+		else
+			$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
 		
-		$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
-		
 		if (isset($savem)) $this->SetFetchMode($savem);
 		$ADODB_FETCH_MODE = $save;
 		if (!$rs) {
 			return $false;
 		}
 		$retarr = array();
-		while (!$rs->EOF) { //print_r($rs->fields);
+		while (!$rs->EOF) {
 			$fld = new ADOFieldObject();
 	   		$fld->name = $rs->fields[0];
 	   		$fld->type = $rs->fields[1];
 	   		$fld->max_length = $rs->fields[2];
 			$fld->scale = $rs->fields[3];
-			if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
-				$fld->type ='INT';
+			if ($rs->fields[1] == 'NUMBER') {
+				if ($rs->fields[3] == 0) $fld->type = 'INT';
 	     		$fld->max_length = $rs->fields[4];
 	    	}	
 		   	$fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
@@ -139,7 +152,7 @@
 	
 	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;
@@ -182,8 +195,8 @@
 	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
 	{
 		if (!function_exists('OCIPLogon')) return null;
+		#adodb_backtrace(); 
 		
-		
         $this->_errorMsg = false;
 		$this->_errorCode = false;
 		
@@ -198,6 +211,11 @@
 					$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)))";
@@ -210,22 +228,22 @@
  		//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
 		if ($mode==1) {
 			$this->_connectionID = ($this->charSet) ? 
+				OCIPLogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
+				:
 				OCIPLogon($argUsername,$argPassword, $argDatabasename)
-				:
-				OCIPLogon($argUsername,$argPassword, $argDatabasename, $this->charSet)
 				;
 			if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);
 		} else if ($mode==2) {
 			$this->_connectionID = ($this->charSet) ? 
-				OCINLogon($argUsername,$argPassword, $argDatabasename)
+				OCINLogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
 				:
-				OCINLogon($argUsername,$argPassword, $argDatabasename, $this->charSet);
+				OCINLogon($argUsername,$argPassword, $argDatabasename);
 				
 		} else {
 			$this->_connectionID = ($this->charSet) ? 
-				OCILogon($argUsername,$argPassword, $argDatabasename)
+				OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
 				:
-				OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet);
+				OCILogon($argUsername,$argPassword, $argDatabasename);
 		}
 		if (!$this->_connectionID) return false;
 		if ($this->_initdate) {
@@ -270,12 +288,17 @@
 	}
 	
 	// 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->NLS_DATE_FORMAT."')";
+		
+		if (is_object($d)) $ds = $d->format($this->fmtDate);
+		else $ds = adodb_date($this->fmtDate,$d);
+		
+		return "TO_DATE(".$ds.",'".$this->dateformat."')";
 	}
 
 	function BindDate($d)
@@ -286,36 +309,44 @@
 		return substr($d,1,strlen($d)-2);
 	}
 	
-	function BindTimeStamp($d)
+	function BindTimeStamp($ts)
 	{
-		$d = ADOConnection::DBTimeStamp($d);
-		if (strncmp($d,"'",1)) return $d;
+		if (empty($ts) && $ts !== 0) return 'null';
+		if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
 		
-		return substr($d,1,strlen($d)-2);
+		if (is_object($ts)) $tss = $ts->format("'Y-m-d H:i:s'");
+		else $tss = adodb_date("'Y-m-d H:i:s'",$ts);
+		
+		return $tss;
 	}
 	
 	// 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($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+		
+		if (is_object($ts)) $tss = $ts->format("'Y-m-d H:i:s'");
+		else $tss = adodb_date("'Y-m-d H:i:s'",$ts);
+		
+		return 'TO_DATE('.$tss.",'RRRR-MM-DD, HH24:MI:SS')";
 	}
 	
-	function RowLock($tables,$where,$flds='1 as ignore') 
+	function RowLock($tables,$where,$col='1 as adodbignore') 
 	{
 		if ($this->autoCommit) $this->BeginTrans();
-		return $this->GetOne("select $flds from $tables where $where for update");
+		return $this->GetOne("select $col 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;
@@ -324,7 +355,7 @@
 	}
 	
 	// Mark Newnham 
-	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	function MetaIndexes ($table, $primary = FALSE, $owner=false)
 	{
         // save old fetch mode
         global $ADODB_FETCH_MODE;
@@ -397,8 +428,10 @@
 		$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) 
@@ -433,10 +466,10 @@
 	{
 		if ($this->_errorMsg !== false) return $this->_errorMsg;
 
-		if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);
+		if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
 		if (empty($arr)) {
-			$arr = @OCIerror($this->_connectionID);
-			if ($arr === false) $arr = @OCIError();
+			if (is_resource($this->_connectionID)) $arr = @OCIError($this->_connectionID);
+			else $arr = @OCIError();
 			if ($arr === false) return '';
 		}
 		$this->_errorMsg = $arr['message'];
@@ -539,6 +572,12 @@
 		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
@@ -555,7 +594,7 @@
 	 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) {
@@ -565,7 +604,7 @@
 				$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;
@@ -579,7 +618,7 @@
 			}
 			// 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 {
@@ -587,14 +626,14 @@
 			
 			 // 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.
@@ -608,6 +647,7 @@
 							$bindarr[$k] = $v;
 						} else { 				// dynamic sql, so rebind every time
 							OCIBindByName($stmt,":$k",$inputarr[$k],$len);
+							
 						}
 					}
 				}
@@ -626,16 +666,17 @@
 			
 			 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";
@@ -643,8 +684,8 @@
 				$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;
 		}
 	
@@ -702,7 +743,7 @@
 	}
 	
 	/**
-	* 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')
 	{
@@ -737,11 +778,11 @@
 	 * @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) {
@@ -749,6 +790,7 @@
 			
 			$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))
@@ -757,15 +799,48 @@
 					$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;
@@ -782,8 +857,17 @@
 	
 		$stmt = OCIParse($this->_connectionID,$sql);
 
-		if (!$stmt) return false;
-
+		if (!$stmt) {
+			$this->_errorMsg = false;
+			$this->_errorCode = false;
+			$arr = @OCIError($this->_connectionID);
+			if ($arr === false) return false;
+		
+			$this->_errorMsg = $arr['message'];
+			$this->_errorCode = $arr['code'];
+			return false;
+		}
+		
 		$BINDNUM += 1;
 		
 		$sttype = @OCIStatementType($stmt);
@@ -807,7 +891,7 @@
 				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
@@ -824,7 +908,7 @@
 		} 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];
@@ -884,7 +968,7 @@
         	$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");
@@ -959,7 +1043,7 @@
 		  $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];
@@ -970,7 +1054,7 @@
 				$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();
@@ -978,7 +1062,7 @@
 						$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 {
@@ -998,7 +1082,13 @@
 					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;
@@ -1065,6 +1155,32 @@
 		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()
 	{
@@ -1107,7 +1223,7 @@
 
  		$rs = $this->Execute($sql);
 		if ($rs && !$rs->EOF) {
-			$arr =& $rs->GetArray();
+			$arr = $rs->GetArray();
 			$a = array();
 			foreach($arr as $v) {
 				$a[] = reset($v);
@@ -1138,7 +1254,7 @@
 	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]);
@@ -1190,12 +1306,14 @@
 			return  "'".str_replace("'",$this->replaceQuote,$s)."'";
 		}
 		
-		// undo magic quotes for "
-		$s = str_replace('\\"','"',$s);
-		
-		$s = str_replace('\\\\','\\',$s);
-		return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
-		
+		// undo magic quotes for " unless sybase is on
+		if (!ini_get('magic_quotes_sybase')) {
+			$s = str_replace('\\"','"',$s);
+			$s = str_replace('\\\\','\\',$s);
+			return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+		} else {
+			return "'".$s."'";
+		}
 	}
 	
 }
@@ -1279,24 +1397,32 @@
 			  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) ";
-	 	}
+			$fld->scale = $p;
+			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];
 	}
@@ -1334,7 +1460,7 @@
 	
 	/*
 	# 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;
 	
@@ -1353,7 +1479,7 @@
 				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:
@@ -1361,22 +1487,23 @@
 			}
 		}
 			
-		$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();
 		for ($i=1; $i < $offset; $i++) 
-			if (!@OCIFetch($this->_queryID)) return array();
+			if (!@OCIFetch($this->_queryID)) return $arr;
 			
-		if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
+		if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return $arr;;
 		$results = array();
 		$cnt = 0;
 		while (!$this->EOF && $nrows != $cnt) {
@@ -1445,7 +1572,7 @@
 		case 'NCHAR':
 		case 'NVARCHAR':
 		case 'NVARCHAR2':
-				 if (isset($this) && $len <= $this->blobSize) return 'C';
+				 if ($len <= $this->blobSize) return 'C';
 		
 		case 'NCLOB':
 		case 'LONG':
@@ -1498,4 +1625,4 @@
 		return adodb_movenext($this);
 	}
 }
-?>
+?>
\ No newline at end of file
Index: drivers/adodb-oci805.inc.php
===================================================================
--- drivers/adodb-oci805.inc.php	(revision 13354)
+++ drivers/adodb-oci805.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V5.11 5 May 2010  (c) 2000-2010 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 @@
 		$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)
Index: drivers/adodb-oci8po.inc.php
===================================================================
--- drivers/adodb-oci8po.inc.php	(revision 13354)
+++ drivers/adodb-oci8po.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim. All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 	}
 	
 	// 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 @@
 	}
 	
 	// 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 @@
 	}	
 	
 	/* 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);
Index: drivers/adodb-odbc.inc.php
===================================================================
--- drivers/adodb-odbc.inc.php	(revision 13354)
+++ drivers/adodb-odbc.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -161,6 +161,12 @@
 				$num += 1;
 				$this->genID = $num;
 				return $num;
+			} elseif ($this->affected_rows() == 0) {
+				// some drivers do not return a valid value => try with another method
+				$value = $this->GetOne("select id from $seq");
+				if ($value == $num + 1) {
+					return $value;
+				}
 			}
 		}
 		if ($fn = $this->raiseErrorFn) {
@@ -252,7 +258,7 @@
 		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 +270,7 @@
 	
 	
 	
-	function &MetaTables($ttype=false)
+	function MetaTables($ttype=false)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -281,7 +287,7 @@
 		}
 		$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 +376,7 @@
 		}
 	}
 	
-	function &MetaColumns($table)
+	function MetaColumns($table, $normalize=true)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -422,7 +428,7 @@
 		}
 		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 +620,7 @@
 
 
 	// returns the field object
-	function &FetchField($fieldOffset = -1) 
+	function FetchField($fieldOffset = -1) 
 	{
 		
 		$off=$fieldOffset+1; // offsets begin at 1
@@ -661,10 +667,10 @@
 	}
 	
 	// 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 +679,7 @@
 		$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 +706,7 @@
 			}
 			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 +727,7 @@
 		}
 		if ($rez) {
 			if ($this->fetchMode & ADODB_FETCH_ASSOC) {
-				$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+				$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
 			}
 			return true;
 		}
Index: drivers/adodb-odbc_db2.inc.php
===================================================================
--- drivers/adodb-odbc_db2.inc.php	(revision 13354)
+++ drivers/adodb-odbc_db2.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -134,13 +134,13 @@
 		return $this->GetOne($this->identitySQL);
 	}
 	
-	function RowLock($tables,$where,$flds='1 as ignore')
+	function RowLock($tables,$where,$col='1 as adodbignore')
 	{
 		if ($this->_autocommit) $this->BeginTrans();
-		return $this->GetOne("select $flds from $tables where $where for update");
+		return $this->GetOne("select $col 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 @@
 		}
 		$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 @@
 		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 @@
 	} 
  
 	
-	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;
Index: drivers/adodb-odbc_mssql.inc.php
===================================================================
--- drivers/adodb-odbc_mssql.inc.php	(revision 13354)
+++ drivers/adodb-odbc_mssql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,6 +25,7 @@
 	var $fmtDate = "'Y-m-d'";
 	var $fmtTimeStamp = "'Y-m-d H:i:s'";
 	var $_bindInputArray = true;
+	var $metaDatabasesSQL = "select name from 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'))";
 	var $metaColumnsSQL = "select c.name,t.name,c.length 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/interbase SELECT TOP 10 * FROM TABLE
@@ -35,7 +36,7 @@
 	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 SCOPE_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
@@ -93,7 +94,7 @@
 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 +116,14 @@
 		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 +131,55 @@
 		return $ret;
 	}
 	
-	function &MetaColumns($table)
+	function MetaColumns($table, $normalize=true)
 	{
 		$arr = ADOConnection::MetaColumns($table);
 		return $arr;
 	}
 	
-	function _query($sql,$inputarr)
+	
+	function MetaIndexes($table,$primary=false, $owner=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 _query($sql,$inputarr=false)
+	{
 		if (is_string($sql)) $sql = str_replace('||','+',$sql);
 		return ADODB_odbc::_query($sql,$inputarr);
 	}
@@ -155,7 +197,7 @@
 	
 	// "Stein-Aksel Basma" <basma@accelero.no>
 	// tested with MSSQL 2000
-	function &MetaPrimaryKeys($table)
+	function MetaPrimaryKeys($table)
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -179,14 +221,14 @@
 		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;
 	}
Index: drivers/adodb-odbc_oracle.inc.php
===================================================================
--- drivers/adodb-odbc_oracle.inc.php	(revision 13354)
+++ drivers/adodb-odbc_oracle.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 		$this->ADODB_odbc();
 	}
 		
-	function &MetaTables() 
+	function MetaTables() 
 	{
 		$false = false;
 		$rs = $this->Execute($this->metaTablesSQL);
@@ -50,7 +50,7 @@
 		return $arr2;
 	}
 	
-	function &MetaColumns($table) 
+	function MetaColumns($table, $normalize=true) 
 	{
 	global $ADODB_FETCH_MODE;
 	
Index: drivers/adodb-odbtp.inc.php
===================================================================
--- drivers/adodb-odbtp.inc.php	(revision 13354)
+++ drivers/adodb-odbtp.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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 @@
 
 	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()
@@ -149,11 +172,17 @@
 	//if uid & pwd can be separate
     function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
 	{
-		$this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
+		if ($argPassword && stripos($UserOrDSN,'DRIVER=') !== false) {
+			$this->_connectionID = odbtp_connect($HostOrInterface,$UserOrDSN.';PWD='.$argPassword);
+		} else
+			$this->_connectionID = odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
 		if ($this->_connectionID === false) {
 			$this->_errorMsg = $this->ErrorMsg() ;
 			return false;
 		}
+		
+		odbtp_convert_datetime($this->_connectionID,true);
+		
 		if ($this->_dontPoolDBC) {
 			if (function_exists('odbtp_dont_pool_dbc'))
 				@odbtp_dont_pool_dbc($this->_connectionID);
@@ -189,7 +218,7 @@
 				$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;
@@ -215,6 +244,7 @@
 				$this->replaceQuote = "'+chr(39)+'";
 				$this->true = '.T.';
 				$this->false = '.F.';
+
 				break;
 			case 'oracle':
 				$this->databaseType = 'odbtp_oci8';
@@ -236,7 +266,7 @@
 				$this->rightOuter = '=*';
 				$this->hasInsertID = true;
 				$this->hasTransactions = true;
-				$this->identitySQL = 'select @@IDENTITY';
+				$this->identitySQL = 'select SCOPE_IDENTITY()';
 				break;
 			default:
 				$this->databaseType = 'odbtp';
@@ -269,7 +299,7 @@
 		return true;
 	}
 	
-	function &MetaTables($ttype='',$showSchema=false,$mask=false)
+	function MetaTables($ttype='',$showSchema=false,$mask=false)
 	{
 	global $ADODB_FETCH_MODE;
 
@@ -277,7 +307,7 @@
 		$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;
@@ -286,12 +316,12 @@
 		for ($i=0; $i < sizeof($arr); $i++) {
 			if ($arr[$i][3] == 'SYSTEM TABLE' )	continue;
 			if ($arr[$i][2])
-				$arr2[] = $showSchema ? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];
+				$arr2[] = $showSchema && $arr[$i][1]? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];
 		}
 		return $arr2;
 	}
 	
-	function &MetaColumns($table,$upper=true)
+	function MetaColumns($table,$upper=true)
 	{
 	global $ADODB_FETCH_MODE;
 
@@ -322,10 +352,11 @@
 				$fld->max_length = $rs->fields[6];
     			$fld->not_null = !empty($rs->fields[9]);
  				$fld->scale = $rs->fields[7];
- 				if (!is_null($rs->fields[12])) {
- 					$fld->has_default = true;
- 					$fld->default_value = $rs->fields[12];
-				}
+				if (isset($rs->fields[12])) // vfp does not have field 12
+	 				if (!is_null($rs->fields[12])) {
+	 					$fld->has_default = true;
+	 					$fld->default_value = $rs->fields[12];
+					}
 				$retarr[strtoupper($fld->name)] = $fld;
 			} else if (!empty($retarr))
 				break;
@@ -336,13 +367,13 @@
 		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);
@@ -353,13 +384,13 @@
 		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;
@@ -419,19 +450,23 @@
 		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>";
@@ -444,6 +479,9 @@
 	{
 		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);
@@ -506,6 +544,56 @@
 		return @odbtp_execute( $stmt ) != false;
 	}
 
+	function MetaIndexes($table,$primary=false, $owner=false)
+	{
+		switch ( $this->odbc_driver) {
+			case ODB_DRIVER_MSSQL:
+				return $this->MetaIndexes_mssql($table, $primary);
+			default:
+				return array();
+		}
+	}
+	
+	function MetaIndexes_mssql($table,$primary=false, $owner = 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 ) {
@@ -521,6 +609,9 @@
 	{
 	global $php_errormsg;
 	
+        $this->_errorMsg = false;
+		$this->_errorCode = false;
+		
  		if ($inputarr) {
 			if (is_array($sql)) {
 				$stmtid = $sql[1];
@@ -532,10 +623,20 @@
 				}
 			}
 			$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;
 			}
@@ -545,7 +646,7 @@
 				return false;
 			}
 		} else {
-			$stmtid = @odbtp_query($sql,$this->_connectionID);
+			$stmtid = odbtp_query($sql,$this->_connectionID);
    		}
 		$this->_lastAffectedRows = 0;
 		if ($stmtid) {
@@ -597,7 +698,7 @@
 		}
 	}
 
-	function &FetchField($fieldOffset = 0)
+	function FetchField($fieldOffset = 0)
 	{
 		$off=$fieldOffset; // offsets begin at 0
 		$o= new ADOFieldObject();
@@ -640,6 +741,12 @@
             default:
 				$this->fields = @odbtp_fetch_array($this->_queryID, $type);
 		}
+		if ($this->databaseType = 'odbtp_vfp') {
+			if ($this->fields)
+			foreach($this->fields as $k => $v) {
+				if (strncmp($v,'1899-12-30',10) == 0) $this->fields[$k] = '';
+			}
+		}
 		return is_array($this->fields);
 	}
 
Index: drivers/adodb-odbtp_unicode.inc.php
===================================================================
--- drivers/adodb-odbtp_unicode.inc.php	(revision 13354)
+++ drivers/adodb-odbtp_unicode.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-	V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+	V5.11 5 May 2010   (c) 2000-2010 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.
Index: drivers/adodb-oracle.inc.php
===================================================================
--- drivers/adodb-oracle.inc.php	(revision 13354)
+++ drivers/adodb-oracle.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,15 +35,19 @@
 	function DBDate($d)
 	{
 		if (is_string($d)) $d = ADORecordSet::UnixDate($d);
-		return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";
+		if (is_object($d)) $ds = $d->format($this->fmtDate);
+		else $ds = adodb_date($this->fmtDate,$d);
+		return 'TO_DATE('.$ds.",'YYYY-MM-DD')";
 	}
 	
 	// format and return date string in database timestamp format
 	function DBTimeStamp($ts)
 	{
 
-		if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);
-		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+		if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
+		if (is_object($ts)) $ds = $ts->format($this->fmtDate);
+		else $ds = adodb_date($this->fmtTimeStamp,$ts);
+		return 'TO_DATE('.$ds.",'RRRR-MM-DD, HH:MI:SS AM')";
 	}
 	
 	
@@ -150,7 +154,7 @@
 			if ($argDatabasename) $argUsername .= "@$argDatabasename";
 
 		//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
-			if ($mode = 1)
+			if ($mode == 1)
 				$this->_connectionID = ora_plogon($argUsername,$argPassword);
 			else
 				$this->_connectionID = ora_logon($argUsername,$argPassword);
@@ -248,7 +252,7 @@
 			   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);
@@ -286,9 +290,9 @@
    function _fetch($ignore_fields=false) {
 // should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1
 		if ($this->fetchMode & ADODB_FETCH_ASSOC)
-			return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
+			return @ora_fetch_into($this->_queryID,$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
    		else 
-			return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);
+			return @ora_fetch_into($this->_queryID,$this->fields,ORA_FETCHINTO_NULLS);
    }
 
    /*		close() only needs to be called if you are worried about using too much memory while your script
Index: drivers/adodb-pdo.inc.php
===================================================================
--- drivers/adodb-pdo.inc.php	(revision 13354)
+++ drivers/adodb-pdo.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,41 +64,9 @@
 
 
 
-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 {
 	var $databaseType = "pdo";	
 	var $dataProvider = "pdo";
@@ -124,7 +92,7 @@
 	
 	function _UpdatePDO()
 	{
-		$d = &$this->_driver;
+		$d = $this->_driver;
 		$this->fmtDate = $d->fmtDate;
 		$this->fmtTimeStamp = $d->fmtTimeStamp;
 		$this->replaceQuote = $d->replaceQuote;
@@ -133,7 +101,12 @@
 		$this->random = $d->random;
 		$this->concat_operator = $d->concat_operator;
 		$this->nameQuote = $d->nameQuote;
-		
+				
+		$this->hasGenID = $d->hasGenID;
+		$this->_genIDSQL = $d->_genIDSQL;
+		$this->_genSeqSQL = $d->_genSeqSQL;
+		$this->_dropSeqSQL = $d->_dropSeqSQL;
+
 		$d->_init($this);
 	}
 	
@@ -142,7 +115,7 @@
 		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;
@@ -185,6 +158,7 @@
 			case 'mysql':
 			case 'pgsql':
 			case 'mssql':
+			case 'sqlite':
 				include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
 				break;
 			}
@@ -201,6 +175,15 @@
 		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)
 	{
@@ -243,6 +226,10 @@
 		else $obj->bindParam($name, $var);
 	}
 	
+	function OffsetDate($dayFraction,$date=false)
+    {   
+        return $this->_driver->OffsetDate($dayFraction,$date);
+    }
 	
 	function ErrorMsg()
 	{
@@ -275,8 +262,19 @@
 		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;
@@ -287,6 +285,9 @@
 	
 	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();
@@ -300,6 +301,9 @@
 	
 	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;
@@ -325,7 +329,32 @@
 		$obj = new ADOPDOStatement($stmt,$this);
 		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) 
 	{
@@ -334,7 +363,8 @@
 		} else {
 			$stmt = $this->_connectionID->prepare($sql);
 		}
-		
+		#adodb_backtrace();
+		#var_dump($this->_bindInputArray);
 		if ($stmt) {
 			$this->_driver->debug = $this->debug;
 			if ($inputarr) $ok = $stmt->execute($inputarr);
@@ -383,6 +413,40 @@
 	}
 }
 
+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";		
@@ -499,7 +563,7 @@
 	}
 
 	// returns the field object
-	function &FetchField($fieldOffset = -1) 
+	function FetchField($fieldOffset = -1) 
 	{
 		$off=$fieldOffset+1; // offsets begin at 1
 		
@@ -515,7 +579,7 @@
 		}
 		//adodb_pr($arr);
 		$o->name = $arr['name'];
-		if (isset($arr['native_type'])) $o->type = $arr['native_type'];
+		if (isset($arr['native_type']) && $arr['native_type'] <> "null") $o->type = $arr['native_type'];
 		else $o->type = adodb_pdo_type($arr['pdo_type']);
 		$o->max_length = $arr['len'];
 		$o->precision = $arr['precision'];
Index: drivers/adodb-pdo_mssql.inc.php
===================================================================
--- drivers/adodb-pdo_mssql.inc.php	(revision 13354)
+++ drivers/adodb-pdo_mssql.inc.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 		$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;
 	}
Index: drivers/adodb-pdo_mysql.inc.php
===================================================================
--- drivers/adodb-pdo_mysql.inc.php	(revision 13354)
+++ drivers/adodb-pdo_mysql.inc.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -12,20 +12,45 @@
 
 class ADODB_pdo_mysql extends ADODB_pdo {
 	var $metaTablesSQL = "SHOW TABLES";	
-	var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
-	var $_bindInputArray = false;
+	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 = true;
+		#$parentDriver->_bindInputArray = false;
 		$parentDriver->hasInsertID = true;
 		$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
 	}
 	
+		// dayFraction is a day in floating point
+	function OffsetDate($dayFraction,$date=false)
+	{		
+		if (!$date) $date = $this->sysDate;
+		
+		$fraction = $dayFraction * 24 * 3600;
+		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';
+		
+//		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()");
@@ -33,7 +58,7 @@
 		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)) {
@@ -44,7 +69,7 @@
 			$mask = $this->qstr($mask);
 			$this->metaTablesSQL .= " like $mask";
 		}
-		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		$ret = ADOConnection::MetaTables($ttype,$showSchema);
 		
 		$this->metaTablesSQL = $save;
 		return $ret;
@@ -61,7 +86,7 @@
 		$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
 	}
 	
- 	function &MetaColumns($table) 
+ 	function MetaColumns($table,$normalize=true)
 	{
 		$this->_findschema($table,$schema);
 		if ($schema) {
@@ -141,16 +166,16 @@
 		
 	
 	// 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;
 	}
 }
Index: drivers/adodb-pdo_oci.inc.php
===================================================================
--- drivers/adodb-pdo_oci.inc.php	(revision 13354)
+++ drivers/adodb-pdo_oci.inc.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,20 +26,20 @@
 	function _init($parentDriver)
 	{
 		$parentDriver->_bindInputArray = true;
-		
+		$parentDriver->_nestedSQL = true;
 		if ($this->_initdate) {
 			$parentDriver->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
 		}
 	}
 	
-	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 @@
 		return $ret;
 	}
 	
-	function &MetaColumns($table) 
+	function MetaColumns($table,$normalize=true)
 	{
 	global $ADODB_FETCH_MODE;
 	
Index: drivers/adodb-pdo_pgsql.inc.php
===================================================================
--- drivers/adodb-pdo_pgsql.inc.php	(revision 13354)
+++ drivers/adodb-pdo_pgsql.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -59,6 +59,7 @@
 	
 		$parentDriver->hasTransactions = false; ## <<< BUG IN PDO pgsql driver
 		$parentDriver->hasInsertID = true;
+		$parentDriver->_nestedSQL = true;
 	}
 	
 	function ServerInfo()
@@ -68,19 +69,19 @@
 		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) {
@@ -103,7 +104,7 @@
  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;
@@ -111,7 +112,7 @@
 		return $ret;
 	}
 	
-	function &MetaColumns($table,$normalize=true) 
+	function MetaColumns($table,$normalize=true) 
 	{
 	global $ADODB_FETCH_MODE;
 	
@@ -124,8 +125,8 @@
 		$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;
 		
@@ -143,7 +144,7 @@
 			
 			$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;
 			
Index: drivers/adodb-pdo_sqlite.inc.php
===================================================================
--- drivers/adodb-pdo_sqlite.inc.php	(revision 0)
+++ drivers/adodb-pdo_sqlite.inc.php	(revision 0)
@@ -0,0 +1,203 @@
+<?php
+
+/* 
+ V5.11 5 May 2010   (c) 2000-2010 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;
+	var $random='abs(random())';
+    
+	function _init($parentDriver)
+	{
+		$this->pdoDriver = $parentDriver;
+		$parentDriver->_bindInputArray = true;
+		$parentDriver->hasTransactions = false; // // should be set to false because of PDO SQLite driver not supporting changing autocommit mode
+		$parentDriver->hasInsertID = true;
+	}
+
+	function ServerInfo()
+	{
+		$parent = $this->pdoDriver;
+		@($ver = array_pop($parent->GetCol("SELECT sqlite_version()")));
+		@($enc = 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;
+		
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(strtoupper($mask));
+			$this->metaTablesSQL .= " AND name LIKE $mask";
+		}
+		
+		$ret = $parent->GetCol($this->metaTablesSQL);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+   }
+}
+?>
\ No newline at end of file

Property changes on: drivers\adodb-pdo_sqlite.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: drivers/adodb-postgres.inc.php
===================================================================
--- drivers/adodb-postgres.inc.php	(revision 13354)
+++ drivers/adodb-postgres.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
- V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ V5.11 5 May 2010   (c) 2000-2010 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.
Index: drivers/adodb-postgres64.inc.php
===================================================================
--- drivers/adodb-postgres64.inc.php	(revision 13354)
+++ drivers/adodb-postgres64.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
- V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ V5.11 5 May 2010   (c) 2000-2010 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.
@@ -104,7 +104,8 @@
 	var $random = 'random()';		/// random function
 	var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
 							// http://bugs.php.net/bug.php?id=25404
-							
+	
+	var $uniqueIisR = true;
 	var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
 	var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
 	
@@ -169,30 +170,18 @@
    }
    
 	
-	function SetTransactionMode( $transaction_mode ) 
- 	{
- 		if (empty($transaction_mode)) {
- 			$transaction_mode = 'ISOLATION LEVEL SERIALIZABLE';
- 		}
- 		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
- 		$this->_transmode  = $transaction_mode;
- 		return( @pg_Exec($this->_connectionID, "SET SESSION TRANSACTION ".$transaction_mode));
- 	}
- 
-  	function BeginTrans()
-  	{
-  		if ($this->transOff) return true;
-  		$this->transCnt += 1;
- 		if( $this->SetTransactionMode($this->_transmode))
- 		    return @pg_Exec($this->_connectionID, "begin");
- 		else
- 		    return(0);
-  	}
+		// returns true/false
+	function BeginTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		return @pg_Exec($this->_connectionID, "begin ".$this->_transmode);
+	}
 	
-	function RowLock($tables,$where,$flds='1 as ignore') 
+	function RowLock($tables,$where,$col='1 as adodbignore') 
 	{
 		if (!$this->transCnt) $this->BeginTrans();
-		return $this->GetOne("select $flds from $tables where $where for update");
+		return $this->GetOne("select $col from $tables where $where for update");
 	}
 
 	// returns true/false. 
@@ -213,7 +202,7 @@
 		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) {
@@ -236,7 +225,7 @@
  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;
@@ -248,7 +237,12 @@
 	// 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)."'";
+			} 
 			if (ADODB_PHPVER >= 0x4200) {
 				return  "'".pg_escape_string($s)."'";
 			}
@@ -436,6 +430,7 @@
 	*/
 	function BlobEncode($blob)
 	{
+		if (ADODB_PHPVER >= 0x5200) return pg_escape_bytea($this->_connectionID, $blob);
 		if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
 		
 		/*92=backslash, 0=null, 39=single-quote*/
@@ -465,14 +460,17 @@
 			if (10 <= $len && $len <= 12) $date = 'date '.$date;
 			else $date = 'timestamp '.$date;
 		}
-		return "($date+interval'$dayFraction days')";
+		
+		
+		return "($date+interval'".($dayFraction * 1440)." minutes')";
+		#return "($date+interval'$dayFraction days')";
 	}
 	
 
 	// 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;
 	
@@ -486,8 +484,8 @@
 		$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;
 		
@@ -504,7 +502,7 @@
 			
 			$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;
 			
@@ -586,7 +584,7 @@
 		
 	}
 
-	  function &MetaIndexes ($table, $primary = FALSE)
+	  function MetaIndexes ($table, $primary = FALSE, $owner = false)
       {
          global $ADODB_FETCH_MODE;
                 
@@ -667,9 +665,9 @@
 			if (strlen($db) == 0) $db = 'template1';
 			$db = adodb_addslashes($db);
 		   	if ($str)  {
-			 	$host = split(":", $str);
+			 	$host = explode(":", $str);
 				if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
-				else $str = 'host=localhost';
+				else $str = '';
 				if (isset($host[1])) $str .= " port=$host[1]";
 				else if (!empty($this->port)) $str .= " port=".$this->port;
 			}
@@ -695,6 +693,12 @@
 		}
 		if ($this->_connectionID === false) return false;
 		$this->Execute("set datestyle='ISO'");
+		
+		$info = $this->ServerInfo();
+		$this->pgVersion = (float) substr($info['version'],0,3);
+		if ($this->pgVersion >= 7.1) { // good till version 999
+			$this->_nestedSQL = true;
+		}
 		return true;
 	}
 	
@@ -715,7 +719,7 @@
 	
 
 	// returns queryID or false
-	function _query($sql,$inputarr)
+	function _query($sql,$inputarr=false)
 	{
 		$this->_errorMsg = false;
 		if ($inputarr) {
@@ -772,11 +776,11 @@
 				}
 				$s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);		
 				//adodb_pr($s);
-				pg_exec($this->_connectionID,$s);
+				$rez = pg_exec($this->_connectionID,$s);
 				//echo $this->ErrorMsg();
 			}
-			
-			$rez = pg_exec($this->_connectionID,$exsql);
+			if ($rez)
+				$rez = pg_exec($this->_connectionID,$exsql);
 		} else {
 			//adodb_backtrace();
 			$rez = pg_exec($this->_connectionID,$sql);
@@ -888,10 +892,10 @@
 		$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;
 	}
 
@@ -927,7 +931,7 @@
 		 return $this->fields[$this->bind[strtoupper($colname)]];
 	}
 
-	function &FetchField($off = 0) 
+	function FetchField($off = 0) 
 	{
 		// offsets begin at 0
 		
@@ -945,6 +949,7 @@
 	
 	function _decode($blob)
 	{
+		if ($blob === NULL) return NULL;
 		eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
 		return $realblob;	
 	}
@@ -1051,7 +1056,7 @@
 				case 'INT4':
 				case 'INT2':
 					if (isset($fieldobj) &&
-				empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
+				empty($fieldobj->primary_key) && (!$this->connection->uniqueIisR || empty($fieldobj->unique))) return 'I';
 				
 				case 'OID':
 				case 'SERIAL':
@@ -1063,4 +1068,4 @@
 	}
 
 }
-?>
+?>
\ No newline at end of file
Index: drivers/adodb-postgres7.inc.php
===================================================================
--- drivers/adodb-postgres7.inc.php	(revision 13354)
+++ drivers/adodb-postgres7.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
- V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ V5.11 5 May 2010   (c) 2000-2010 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 @@
 	
 	// 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,10 +56,59 @@
 	}
  	*/
 
-
-	// 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
 		pg_trigger t,pg_class c,pg_proc p
@@ -72,26 +121,26 @@
 		ORDER BY
 			t.tgrelid';
 		
-		$rs =& $this->Execute($sql);
+		$rs = $this->Execute($sql);
 		
-		if ($rs && !$rs->EOF) {
-			$arr =& $rs->GetArray();
-			$a = array();
-			foreach($arr as $v)
-			{
-				$data = explode(chr(0), $v['args']);
-				if ($upper) {
-					$a[strtoupper($data[2])][] = strtoupper($data[4].'='.$data[5]);
-				} else {
-				$a[$data[2]][] = $data[4].'='.$data[5];
-				}
+		if (!$rs || $rs->EOF) return false;
+		
+		$arr = $rs->GetArray();
+		$a = array();
+		foreach($arr as $v) {
+			$data = explode(chr(0), $v['args']);
+			$size = count($data)-1; //-1 because the last node is empty
+			for($i = 4; $i < $size; $i++) {
+				if ($upper) 
+					$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
+				else 
+					$a[$data[2]][] = $data[$i].'='.$data[++$i];
 			}
-			return $a;
 		}
-		return false;
+		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
Index: drivers/adodb-postgres8.inc.php
===================================================================
--- drivers/adodb-postgres8.inc.php	(revision 13354)
+++ drivers/adodb-postgres8.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
- V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ V5.11 5 May 2010   (c) 2000-2010 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.
Index: drivers/adodb-proxy.inc.php
===================================================================
--- drivers/adodb-proxy.inc.php	(revision 13354)
+++ drivers/adodb-proxy.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
Index: drivers/adodb-sapdb.inc.php
===================================================================
--- drivers/adodb-sapdb.inc.php	(revision 13354)
+++ drivers/adodb-sapdb.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 		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, $owner = false)
 	{
 		$table = $this->Quote(strtoupper($table));
 
@@ -92,7 +92,7 @@
         return $indexes;
 	}
 	
- 	function &MetaColumns ($table)
+ 	function MetaColumns ($table)
 	{
 		global $ADODB_FETCH_MODE;
 		$save = $ADODB_FETCH_MODE;
Index: drivers/adodb-sqlanywhere.inc.php
===================================================================
--- drivers/adodb-sqlanywhere.inc.php	(revision 13354)
+++ drivers/adodb-sqlanywhere.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-version V4.90 8 June 2006 (c) 2000-2006  John Lim (jlim#natsoft.com.my).  All rights
+version V5.06 16 Oct 2008  (c) 2000-2010  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, 
Index: drivers/adodb-sqlite.inc.php
===================================================================
--- drivers/adodb-sqlite.inc.php	(revision 13354)
+++ drivers/adodb-sqlite.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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,14 +78,14 @@
 	}
 	
 	// mark newnham
-	function &MetaColumns($tab)
+	function MetaColumns($table, $normalize=true) 
 	{
 	  global $ADODB_FETCH_MODE;
 	  $false = false;
 	  $save = $ADODB_FETCH_MODE;
 	  $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
 	  if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-	  $rs = $this->Execute("PRAGMA table_info('$tab')");
+	  $rs = $this->Execute("PRAGMA table_info('$table')");
 	  if (isset($savem)) $this->SetFetchMode($savem);
 	  if (!$rs) {
 	    $ADODB_FETCH_MODE = $save; 
@@ -190,14 +190,14 @@
 		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 @@
 		return @sqlite_close($this->_connectionID);
 	}
 
-	function &MetaIndexes($table, $primary = FALSE, $owner=false)
+	function MetaIndexes($table, $primary = FALSE, $owner=false, $owner = false)
 	{
 		$false = false;
 		// save old fetch mode
@@ -350,7 +350,7 @@
 	}
 
 
-	function &FetchField($fieldOffset = -1)
+	function FetchField($fieldOffset = -1)
 	{
 		$fld = new ADOFieldObject;
 		$fld->name = sqlite_field_name($this->_queryID, $fieldOffset);
Index: drivers/adodb-sqlitepo.inc.php
===================================================================
--- drivers/adodb-sqlitepo.inc.php	(revision 13354)
+++ drivers/adodb-sqlitepo.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
Index: drivers/adodb-sybase.inc.php
===================================================================
--- drivers/adodb-sybase.inc.php	(revision 13354)
+++ drivers/adodb-sybase.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim. All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -86,11 +86,11 @@
 	}
 	
 	// http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
-	function RowLock($tables,$where,$flds='top 1 null as ignore') 
+	function RowLock($tables,$where,$col='top 1 null as ignore') 
 	{
 		if (!$this->_hastrans) $this->BeginTrans();
 		$tables = str_replace(',',' HOLDLOCK,',$tables);
-		return $this->GetOne("select $flds from $tables HOLDLOCK where $where");
+		return $this->GetOne("select $col from $tables HOLDLOCK where $where");
 		
 	}	
 		
@@ -123,6 +123,12 @@
 	{
 		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 @@
 	{
 		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 @@
 	}
 	
 	// 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 @@
 		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 @@
 		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 @@
                 $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 @@
                 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 @@
 		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 @@
 	}
 	
 	// 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 @@
 	}
 	
 		// 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 @@
 		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;
 		
Index: drivers/adodb-sybase_ase.inc.php
===================================================================
--- drivers/adodb-sybase_ase.inc.php	(revision 13354)
+++ drivers/adodb-sybase_ase.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V5.11 5 May 2010   (c) 2000-2010 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.
@@ -9,6 +9,10 @@
   
   Contributed by Interakt Online. Thx Cristian MARIN cristic#interaktonline.com
 */
+
+
+require_once ADODB_DIR."/drivers/adodb-sybase.inc.php";
+
 class ADODB_sybase_ase extends ADODB_sybase {
  	var $databaseType = "sybase_ase";
 	
@@ -21,7 +25,7 @@
 	}
 	
 	// 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) {
@@ -39,7 +43,7 @@
 			if ($rs === false || !method_exists($rs, 'GetArray')){
 					return $false;
 			}
-			$arr =& $rs->GetArray();
+			$arr = $rs->GetArray();
 
 			$arr2 = array();
 			foreach($arr as $key=>$value){
@@ -67,7 +71,7 @@
 	}
 
 	// 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)) {
@@ -77,7 +81,7 @@
 
 			$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');
Index: drivers/adodb-vfp.inc.php
===================================================================
--- drivers/adodb-vfp.inc.php	(revision 13354)
+++ drivers/adodb-vfp.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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 @@
 
 	
 	// 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);
Index: lang/adodb-ar.inc.php
===================================================================
--- lang/adodb-ar.inc.php	(revision 13354)
+++ lang/adodb-ar.inc.php	(working copy)
@@ -30,5 +30,4 @@
 	    DB_ERROR_NOSUCHDB		=> 'áíÓ åäÇáß ÞÇÚÏÉ ÈíÇäÇÊ ÈåÐÇ ÇáÇÓã',
 	    DB_ERROR_ACCESS_VIOLATION	=> 'ÓãÇÍíÇÊ ÛíÑ ßÇÝíÉ'
 );
-?>
-		
+?>
\ No newline at end of file
Index: lang/adodb-bg.inc.php
===================================================================
--- lang/adodb-bg.inc.php	(revision 13354)
+++ lang/adodb-bg.inc.php	(working copy)
@@ -34,5 +34,4 @@
             DB_ERROR_NOSUCHDB           => 'íåñúùåñòâóâàùà áàçà äàííè',
             DB_ERROR_ACCESS_VIOLATION   => 'íÿìàòå äîñòàòú÷íî ïðàâà'
 );
-?>
-		
\ No newline at end of file
+?>
\ No newline at end of file
Index: lang/adodb-bgutf8.inc.php
===================================================================
--- lang/adodb-bgutf8.inc.php	(revision 13354)
+++ lang/adodb-bgutf8.inc.php	(working copy)
@@ -34,5 +34,4 @@
             DB_ERROR_NOSUCHDB           => 'Ð½ÐµÑÑŠÑ‰ÐµÑÑ‚Ð²ÑƒÐ²Ð°Ñ‰Ð° Ð±Ð°Ð·Ð° Ð´Ð°Ð½Ð½Ð¸',
             DB_ERROR_ACCESS_VIOLATION   => 'Ð½ÑÐ¼Ð°Ñ‚Ðµ Ð´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð¿Ñ€Ð°Ð²Ð°'
 );
-?>
-		
\ No newline at end of file
+?>
\ No newline at end of file
Index: lang/adodb-ca.inc.php
===================================================================
--- lang/adodb-ca.inc.php	(revision 13354)
+++ lang/adodb-ca.inc.php	(working copy)
@@ -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'
-);
-?>
-		
\ No newline at end of file
+<?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'
+);
+?>
\ No newline at end of file
Index: lang/adodb-en.inc.php
===================================================================
--- lang/adodb-en.inc.php	(revision 13354)
+++ lang/adodb-en.inc.php	(working copy)
@@ -30,5 +30,4 @@
             DB_ERROR_NOSUCHDB           => 'no such database',
             DB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions'
 );
-?>
-		
\ No newline at end of file
+?>
\ No newline at end of file
Index: lang/adodb-fa.inc.php
===================================================================
--- lang/adodb-fa.inc.php	(revision 0)
+++ lang/adodb-fa.inc.php	(revision 0)
@@ -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   => 'Ø­Ù‚ Ø¯Ø³ØªØ±Ø³ÛŒ Ù†Ø§Ú©Ø§ÙÛŒ'
+);
+?>
\ No newline at end of file

Property changes on: lang\adodb-fa.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: lang/adodb-pl.inc.php
===================================================================
--- lang/adodb-pl.inc.php	(revision 13354)
+++ lang/adodb-pl.inc.php	(working copy)
@@ -32,5 +32,4 @@
             DB_ERROR_NOSUCHDB           => 'nie znaleziono bazy',
             DB_ERROR_ACCESS_VIOLATION   => 'niedostateczne uprawnienia'
 );
-?>
-		
\ No newline at end of file
+?>
\ No newline at end of file
Index: lang/adodb-pt-br.inc.php
===================================================================
--- lang/adodb-pt-br.inc.php	(revision 13354)
+++ lang/adodb-pt-br.inc.php	(working copy)
@@ -1,35 +1,35 @@
-<?php
-// contributed by "Levi Fukumori" levi _AT_ fukumori _DOT_ com _DOT_ br
-// portugese (brazilian)
-$ADODB_LANG_ARRAY = array (
-			'LANG'                      => 'pt-br',
-            DB_ERROR                    => 'erro desconhecido',
-            DB_ERROR_ALREADY_EXISTS     => 'já existe',
-            DB_ERROR_CANNOT_CREATE      => 'impossível criar',
-            DB_ERROR_CANNOT_DELETE      => 'impossível excluír',
-            DB_ERROR_CANNOT_DROP        => 'impossível remover',
-            DB_ERROR_CONSTRAINT         => 'violação do confinamente',
-            DB_ERROR_DIVZERO            => 'divisão por zero',
-            DB_ERROR_INVALID            => 'inválido',
-            DB_ERROR_INVALID_DATE       => 'data ou hora inválida',
-            DB_ERROR_INVALID_NUMBER     => 'número inválido',
-            DB_ERROR_MISMATCH           => 'erro',
-            DB_ERROR_NODBSELECTED       => 'nenhum banco de dados selecionado',
-            DB_ERROR_NOSUCHFIELD        => 'campo inválido',
-            DB_ERROR_NOSUCHTABLE        => 'tabela inexistente',
-            DB_ERROR_NOT_CAPABLE        => 'capacidade inválida para este BD',
-            DB_ERROR_NOT_FOUND          => 'não encontrado',
-            DB_ERROR_NOT_LOCKED         => 'não bloqueado',
-            DB_ERROR_SYNTAX             => 'erro de sintaxe',
-            DB_ERROR_UNSUPPORTED        => 
-'não suportado',
-            DB_ERROR_VALUE_COUNT_ON_ROW => 'a quantidade de colunas não corresponde ao de valores',
-            DB_ERROR_INVALID_DSN        => 'DSN inválido',
-            DB_ERROR_CONNECT_FAILED     => 'falha na conexão',
-            0				=> 'sem erro', // DB_OK
-            DB_ERROR_NEED_MORE_DATA     => 'dados insuficientes',
-            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensão não encontrada',
-            DB_ERROR_NOSUCHDB           => 'banco de dados não encontrado',
-            DB_ERROR_ACCESS_VIOLATION   => 'permissão insuficiente'
-);
-?>
+<?php
+// contributed by "Levi Fukumori" levi _AT_ fukumori _DOT_ com _DOT_ br
+// portugese (brazilian)
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'pt-br',
+            DB_ERROR                    => 'erro desconhecido',
+            DB_ERROR_ALREADY_EXISTS     => 'já existe',
+            DB_ERROR_CANNOT_CREATE      => 'impossível criar',
+            DB_ERROR_CANNOT_DELETE      => 'impossível excluír',
+            DB_ERROR_CANNOT_DROP        => 'impossível remover',
+            DB_ERROR_CONSTRAINT         => 'violação do confinamente',
+            DB_ERROR_DIVZERO            => 'divisão por zero',
+            DB_ERROR_INVALID            => 'inválido',
+            DB_ERROR_INVALID_DATE       => 'data ou hora inválida',
+            DB_ERROR_INVALID_NUMBER     => 'número inválido',
+            DB_ERROR_MISMATCH           => 'erro',
+            DB_ERROR_NODBSELECTED       => 'nenhum banco de dados selecionado',
+            DB_ERROR_NOSUCHFIELD        => 'campo inválido',
+            DB_ERROR_NOSUCHTABLE        => 'tabela inexistente',
+            DB_ERROR_NOT_CAPABLE        => 'capacidade inválida para este BD',
+            DB_ERROR_NOT_FOUND          => 'não encontrado',
+            DB_ERROR_NOT_LOCKED         => 'não bloqueado',
+            DB_ERROR_SYNTAX             => 'erro de sintaxe',
+            DB_ERROR_UNSUPPORTED        => 
+'não suportado',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'a quantidade de colunas não corresponde ao de valores',
+            DB_ERROR_INVALID_DSN        => 'DSN inválido',
+            DB_ERROR_CONNECT_FAILED     => 'falha na conexão',
+            0				=> 'sem erro', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'dados insuficientes',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensão não encontrada',
+            DB_ERROR_NOSUCHDB           => 'banco de dados não encontrado',
+            DB_ERROR_ACCESS_VIOLATION   => 'permissão insuficiente'
+);
+?>
\ No newline at end of file
Index: lang/adodb-ro.inc.php
===================================================================
--- lang/adodb-ro.inc.php	(revision 13354)
+++ lang/adodb-ro.inc.php	(working copy)
@@ -32,5 +32,4 @@
             DB_ERROR_NOSUCHDB           => 'nu exista baza de date',
             DB_ERROR_ACCESS_VIOLATION   => 'permisiuni insuficiente'
 );
-?>
-
+?>
\ No newline at end of file
Index: lang/adodb-uk1251.inc.php
===================================================================
--- lang/adodb-uk1251.inc.php	(revision 13354)
+++ lang/adodb-uk1251.inc.php	(working copy)
@@ -32,4 +32,4 @@
             DB_ERROR_NOSUCHDB           => 'íå ³ñíóº ÁÄ',
             DB_ERROR_ACCESS_VIOLATION   => 'íåäîñòàòíüî ïðàâ äîñòóïà'
 );
-?>
+?>
\ No newline at end of file
Index: lang/adodb_th.inc.php
===================================================================
--- lang/adodb_th.inc.php	(revision 0)
+++ lang/adodb_th.inc.php	(revision 0)
@@ -0,0 +1,33 @@
+<?php
+// by Trirat Petchsingh <rosskouk#gmail.com>
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'th',
+            DB_ERROR                    => 'error à¹„à¸¡à¹ˆà¸£à¸¹à¹‰à¸ªà¸²à¹€à¸«à¸•à¸¸',
+            DB_ERROR_ALREADY_EXISTS     => 'à¸¡à¸µà¹?à¸¥à¹‰à¸§',
+            DB_ERROR_CANNOT_CREATE      => 'à¸ªà¸£à¹‰à¸²à¸‡à¹„à¸¡à¹ˆà¹„à¸”à¹‰',
+            DB_ERROR_CANNOT_DELETE      => 'à¸¥à¸šà¹„à¸¡à¹ˆà¹„à¸”à¹‰',
+            DB_ERROR_CANNOT_DROP        => 'drop à¹„à¸¡à¹ˆà¹„à¸”à¹‰',
+            DB_ERROR_CONSTRAINT         => 'constraint violation',
+            DB_ERROR_DIVZERO            => 'à¸«à¸²à¸?à¸”à¹‰à¸§à¸¢à¸ªà¸¹à¸?',
+            DB_ERROR_INVALID            => 'à¹„à¸¡à¹ˆ valid',
+            DB_ERROR_INVALID_DATE       => 'à¸§à¸±à¸™à¸—à¸µà¹ˆ à¹€à¸§à¸¥à¸² à¹„à¸¡à¹ˆ valid',
+            DB_ERROR_INVALID_NUMBER     => 'à¹€à¸¥à¸‚à¹„à¸¡à¹ˆ valid',
+            DB_ERROR_MISMATCH           => 'mismatch',
+            DB_ERROR_NODBSELECTED       => 'à¹„à¸¡à¹ˆà¹„à¸”à¹‰à¹€à¸¥à¸·à¸­à¸?à¸?à¸²à¸™à¸‚à¹‰à¸­à¸¡à¸¹à¸¥',
+            DB_ERROR_NOSUCHFIELD        => 'à¹„à¸¡à¹ˆà¸¡à¸µà¸Ÿà¸µà¸¥à¸”à¹Œà¸™à¸µà¹‰',
+            DB_ERROR_NOSUCHTABLE        => 'à¹„à¸¡à¹ˆà¸¡à¸µà¸•à¸²à¸£à¸²à¸‡à¸™à¸µà¹‰',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
+            DB_ERROR_NOT_FOUND          => 'à¹„à¸¡à¹ˆà¸žà¸š',
+            DB_ERROR_NOT_LOCKED         => 'à¹„à¸¡à¹ˆà¹„à¸”à¹‰à¸¥à¹Šà¸­à¸?',
+            DB_ERROR_SYNTAX             => 'à¸œà¸´à¸” syntax',
+            DB_ERROR_UNSUPPORTED        => 'à¹„à¸¡à¹ˆ support',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
+            DB_ERROR_INVALID_DSN        => 'invalid DSN',
+            DB_ERROR_CONNECT_FAILED     => 'à¹„à¸¡à¹ˆà¸ªà¸²à¸¡à¸²à¸£à¸– connect',
+            0	                        => 'no error', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'à¸‚à¹‰à¸­à¸¡à¸¹à¸¥à¹„à¸¡à¹ˆà¹€à¸žà¸µà¸¢à¸‡à¸žà¸­',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'à¹„à¸¡à¹ˆà¸žà¸š extension',
+            DB_ERROR_NOSUCHDB           => 'à¹„à¸¡à¹ˆà¸¡à¸µà¸‚à¹‰à¸­à¸¡à¸¹à¸¥à¸™à¸µà¹‰',
+            DB_ERROR_ACCESS_VIOLATION   => 'permissions à¹„à¸¡à¹ˆà¸žà¸­'
+);
+?>
\ No newline at end of file

Property changes on: lang\adodb_th.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: license.txt
===================================================================
--- license.txt	(revision 0)
+++ license.txt	(revision 0)
@@ -0,0 +1,182 @@
+ADOdb is dual licensed using BSD and LGPL. 
+
+In plain English, you do not need to distribute your application  in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license.
+
+For more info about ADOdb, visit http://adodb.sourceforge.net/
+
+BSD Style-License
+=================
+
+Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, 
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list 
+of conditions and the following disclaimer. 
+
+Redistributions in binary form must reproduce the above copyright notice, this list 
+of conditions and the following disclaimer in the documentation and/or other materials 
+provided with the distribution. 
+
+Neither the name of the John Lim nor the names of its contributors may be used to 
+endorse or promote products derived from this software without specific prior written 
+permission. 
+
+DISCLAIMER:
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+==========================================================
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999 
+ 
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+ 
+ 
+Preamble
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. 
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. 
+
+When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. 
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. 
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. 
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. 
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. 
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. 
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. 
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. 
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. 
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. 
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. 
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. 
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. 
+
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". 
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. 
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) 
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. 
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. 
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 
+
+
+a) The modified work must itself be a software library. 
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. 
+c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. 
+d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. 
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) 
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. 
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. 
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. 
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. 
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. 
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. 
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. 
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) 
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. 
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: 
+
+
+a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) 
+b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. 
+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. 
+d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. 
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. 
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: 
+
+
+a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. 
+b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. 
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. 
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 
+
+Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 
+
+NO WARRANTY 
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 
+
+
+END OF TERMS AND CONDITIONS
\ No newline at end of file

Property changes on: license.txt
___________________________________________________________________
Added: svn:eol-style
   + native

Index: pear/Auth/Container/ADOdb.php
===================================================================
--- pear/Auth/Container/ADOdb.php	(revision 13354)
+++ pear/Auth/Container/ADOdb.php	(working copy)
@@ -1,413 +1,405 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// |                                                                      |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Authors: Martin Jansen <mj@php.net>
-// |	Richard Tango-Lowy <richtl@arscognita.com>                                  |
-// +----------------------------------------------------------------------+
-//
-// $Id: ADOdb.php,v 1.3 2005/05/18 06:58:47 jlim Exp $
-//
-
-require_once 'Auth/Container.php';
-require_once 'adodb.inc.php';
-require_once 'adodb-pear.inc.php';
-require_once 'adodb-errorpear.inc.php';
-
-/**
- * Storage driver for fetching login data from a database using ADOdb-PHP.
- *
- * This storage driver can use all databases which are supported
- * by the ADBdb DB abstraction layer to fetch login data.
- * See http://php.weblogs.com/adodb for information on ADOdb.
- * NOTE: The ADOdb directory MUST be in your PHP include_path!
- *
- * @author   Richard Tango-Lowy <richtl@arscognita.com>
- * @package  Auth
- * @version  $Revision: 1.3 $
- */
-class Auth_Container_ADOdb extends Auth_Container
-{
-
-    /**
-     * Additional options for the storage container
-     * @var array
-     */
-    var $options = array();
-
-    /**
-     * DB object
-     * @var object
-     */
-    var $db = null;
-    var $dsn = '';
-	
-    /**
-     * User that is currently selected from the DB.
-     * @var string
-     */
-    var $activeUser = '';
-
-    // {{{ Constructor
-
-    /**
-     * Constructor of the container class
-     *
-     * Initate connection to the database via PEAR::ADOdb
-     *
-     * @param  string Connection data or DB object
-     * @return object Returns an error object if something went wrong
-     */
-    function Auth_Container_ADOdb($dsn)
-    {
-        $this->_setDefaults();
-		
-        if (is_array($dsn)) {
-            $this->_parseOptions($dsn);
-
-            if (empty($this->options['dsn'])) {
-                PEAR::raiseError('No connection parameters specified!');
-            }
-        } else {
-        	// Extract db_type from dsn string.
-            $this->options['dsn'] = $dsn;
-        }
-    }
-
-    // }}}
-    // {{{ _connect()
-
-    /**
-     * Connect to database by using the given DSN string
-     *
-     * @access private
-     * @param  string DSN string
-     * @return mixed  Object on error, otherwise bool
-     */
-     function _connect($dsn)
-    {
-        if (is_string($dsn) || is_array($dsn)) {
-        	if(!$this->db) {
-	        	$this->db = &ADONewConnection($dsn);
-	    		if( $err = ADODB_Pear_error() ) {
-	   	    		return PEAR::raiseError($err);
-	    		}
-        	}
-        	
-        } else {
-            return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
-                                    41,
-                                    PEAR_ERROR_RETURN,
-                                    null,
-                                    null
-                                    );
-        }
-        
-        if(!$this->db) {
-        	return PEAR::raiseError(ADODB_Pear_error());
-        } else {
-        	return true;
-        }
-    }
-
-    // }}}
-    // {{{ _prepare()
-
-    /**
-     * Prepare database connection
-     *
-     * This function checks if we have already opened a connection to
-     * the database. If that's not the case, a new connection is opened.
-     *
-     * @access private
-     * @return mixed True or a DB error object.
-     */
-    function _prepare()
-    {
-    	if(!$this->db) {
-    		$res = $this->_connect($this->options['dsn']);  		
-    	}
-        return true;
-    }
-
-    // }}}
-    // {{{ query()
-
-    /**
-     * Prepare query to the database
-     *
-     * This function checks if we have already opened a connection to
-     * the database. If that's not the case, a new connection is opened.
-     * After that the query is passed to the database.
-     *
-     * @access public
-     * @param  string Query string
-     * @return mixed  a DB_result object or DB_OK on success, a DB
-     *                or PEAR error on failure
-     */
-    function query($query)
-    {
-        $err = $this->_prepare();
-        if ($err !== true) {
-            return $err;
-        }
-        return $this->db->query($query);
-    }
-
-    // }}}
-    // {{{ _setDefaults()
-
-    /**
-     * Set some default options
-     *
-     * @access private
-     * @return void
-     */
-    function _setDefaults()
-    {
-    	$this->options['db_type']	= 'mysql';
-        $this->options['table']       = 'auth';
-        $this->options['usernamecol'] = 'username';
-        $this->options['passwordcol'] = 'password';
-        $this->options['dsn']         = '';
-        $this->options['db_fields']   = '';
-        $this->options['cryptType']   = 'md5';
-    }
-
-    // }}}
-    // {{{ _parseOptions()
-
-    /**
-     * Parse options passed to the container class
-     *
-     * @access private
-     * @param  array
-     */
-    function _parseOptions($array)
-    {
-        foreach ($array as $key => $value) {
-            if (isset($this->options[$key])) {
-                $this->options[$key] = $value;
-            }
-        }
-
-        /* Include additional fields if they exist */
-        if(!empty($this->options['db_fields'])){
-            if(is_array($this->options['db_fields'])){
-                $this->options['db_fields'] = join($this->options['db_fields'], ', ');
-            }
-            $this->options['db_fields'] = ', '.$this->options['db_fields'];
-        }
-    }
-
-    // }}}
-    // {{{ fetchData()
-
-    /**
-     * Get user information from database
-     *
-     * This function uses the given username to fetch
-     * the corresponding login data from the database
-     * table. If an account that matches the passed username
-     * and password is found, the function returns true.
-     * Otherwise it returns false.
-     *
-     * @param   string Username
-     * @param   string Password
-     * @return  mixed  Error object or boolean
-     */
-    function fetchData($username, $password)
-    {
-        // Prepare for a database query
-        $err = $this->_prepare();
-        if ($err !== true) {
-            return PEAR::raiseError($err->getMessage(), $err->getCode());
-        }
-
-        // Find if db_fields contains a *, i so assume all col are selected
-        if(strstr($this->options['db_fields'], '*')){
-            $sql_from = "*";
-        }
-        else{
-            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
-        }
-        
-        $query = "SELECT ".$sql_from.
-                " FROM ".$this->options['table'].
-                " WHERE ".$this->options['usernamecol']." = " . $this->db->Quote($username);
-        
-        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-        $rset = $this->db->Execute( $query );
-        $res = $rset->fetchRow();
-
-        if (DB::isError($res)) {
-            return PEAR::raiseError($res->getMessage(), $res->getCode());
-        }
-        if (!is_array($res)) {
-            $this->activeUser = '';
-            return false;
-        }
-        if ($this->verifyPassword(trim($password, "\r\n"),
-                                  trim($res[$this->options['passwordcol']], "\r\n"),
-                                  $this->options['cryptType'])) {
-            // Store additional field values in the session
-            foreach ($res as $key => $value) {
-                if ($key == $this->options['passwordcol'] ||
-                    $key == $this->options['usernamecol']) {
-                    continue;
-                }
-                // Use reference to the auth object if exists
-                // This is because the auth session variable can change so a static call to setAuthData does not make sence
-                if(is_object($this->_auth_obj)){
-                    $this->_auth_obj->setAuthData($key, $value);
-                } else {
-                    Auth::setAuthData($key, $value);
-                }
-            }
-
-            return true;
-        }
-
-        $this->activeUser = $res[$this->options['usernamecol']];
-        return false;
-    }
-
-    // }}}
-    // {{{ listUsers()
-
-    function listUsers()
-    {
-        $err = $this->_prepare();
-        if ($err !== true) {
-            return PEAR::raiseError($err->getMessage(), $err->getCode());
-        }
-
-        $retVal = array();
-
-        // Find if db_fileds contains a *, i so assume all col are selected
-        if(strstr($this->options['db_fields'], '*')){
-            $sql_from = "*";
-        }
-        else{
-            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
-        }
-
-        $query = sprintf("SELECT %s FROM %s",
-                         $sql_from,
-                         $this->options['table']
-                         );
-        $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC);
-
-        if (DB::isError($res)) {
-            return PEAR::raiseError($res->getMessage(), $res->getCode());
-        } else {
-            foreach ($res as $user) {
-                $user['username'] = $user[$this->options['usernamecol']];
-                $retVal[] = $user;
-            }
-        }
-        return $retVal;
-    }
-
-    // }}}
-    // {{{ addUser()
-
-    /**
-     * Add user to the storage container
-     *
-     * @access public
-     * @param  string Username
-     * @param  string Password
-     * @param  mixed  Additional information that are stored in the DB
-     *
-     * @return mixed True on success, otherwise error object
-     */
-    function addUser($username, $password, $additional = "")
-    {
-        if (function_exists($this->options['cryptType'])) {
-            $cryptFunction = $this->options['cryptType'];
-        } else {
-            $cryptFunction = 'md5';
-        }
-
-        $additional_key   = '';
-        $additional_value = '';
-
-        if (is_array($additional)) {
-            foreach ($additional as $key => $value) {
-                $additional_key .= ', ' . $key;
-                $additional_value .= ", '" . $value . "'";
-            }
-        }
-
-        $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES ('%s', '%s'%s)",
-                         $this->options['table'],
-                         $this->options['usernamecol'],
-                         $this->options['passwordcol'],
-                         $additional_key,
-                         $username,
-                         $cryptFunction($password),
-                         $additional_value
-                         );
-
-        $res = $this->query($query);
-
-        if (DB::isError($res)) {
-           return PEAR::raiseError($res->getMessage(), $res->getCode());
-        } else {
-          return true;
-        }
-    }
-
-    // }}}
-    // {{{ removeUser()
-
-    /**
-     * Remove user from the storage container
-     *
-     * @access public
-     * @param  string Username
-     *
-     * @return mixed True on success, otherwise error object
-     */
-    function removeUser($username)
-    {
-        $query = sprintf("DELETE FROM %s WHERE %s = '%s'",
-                         $this->options['table'],
-                         $this->options['usernamecol'],
-                         $username
-                         );
-
-        $res = $this->query($query);
-
-        if (DB::isError($res)) {
-           return PEAR::raiseError($res->getMessage(), $res->getCode());
-        } else {
-          return true;
-        }
-    }
-
-    // }}}
-}
-
-function showDbg( $string ) {
-	print "
--- $string</P>";
-}
-function dump( $var, $str, $vardump = false ) {
-	print "<H4>$str</H4><pre>";
-	( !$vardump ) ? ( print_r( $var )) : ( var_dump( $var ));
-	print "</pre>";
-}
-?>
+<?php
+/* 
+V5.11 5 May 2010   (c) 2000-2010 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
+  
+	Original Authors: Martin Jansen <mj#php.net>
+	Richard Tango-Lowy <richtl#arscognita.com>                          
+*/
+
+require_once 'Auth/Container.php';
+require_once 'adodb.inc.php';
+require_once 'adodb-pear.inc.php';
+require_once 'adodb-errorpear.inc.php';
+
+/**
+ * Storage driver for fetching login data from a database using ADOdb-PHP.
+ *
+ * This storage driver can use all databases which are supported
+ * by the ADBdb DB abstraction layer to fetch login data.
+ * See http://php.weblogs.com/adodb for information on ADOdb.
+ * NOTE: The ADOdb directory MUST be in your PHP include_path!
+ *
+ * @author   Richard Tango-Lowy <richtl@arscognita.com>
+ * @package  Auth
+ * @version  $Revision: 1.3 $
+ */
+class Auth_Container_ADOdb extends Auth_Container
+{
+
+    /**
+     * Additional options for the storage container
+     * @var array
+     */
+    var $options = array();
+
+    /**
+     * DB object
+     * @var object
+     */
+    var $db = null;
+    var $dsn = '';
+	
+    /**
+     * User that is currently selected from the DB.
+     * @var string
+     */
+    var $activeUser = '';
+
+    // {{{ Constructor
+
+    /**
+     * Constructor of the container class
+     *
+     * Initate connection to the database via PEAR::ADOdb
+     *
+     * @param  string Connection data or DB object
+     * @return object Returns an error object if something went wrong
+     */
+    function Auth_Container_ADOdb($dsn)
+    {
+        $this->_setDefaults();
+		
+        if (is_array($dsn)) {
+            $this->_parseOptions($dsn);
+
+            if (empty($this->options['dsn'])) {
+                PEAR::raiseError('No connection parameters specified!');
+            }
+        } else {
+        	// Extract db_type from dsn string.
+            $this->options['dsn'] = $dsn;
+        }
+    }
+
+    // }}}
+    // {{{ _connect()
+
+    /**
+     * Connect to database by using the given DSN string
+     *
+     * @access private
+     * @param  string DSN string
+     * @return mixed  Object on error, otherwise bool
+     */
+     function _connect($dsn)
+    {
+        if (is_string($dsn) || is_array($dsn)) {
+        	if(!$this->db) {
+	        	$this->db = ADONewConnection($dsn);
+	    		if( $err = ADODB_Pear_error() ) {
+	   	    		return PEAR::raiseError($err);
+	    		}
+        	}
+        	
+        } else {
+            return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
+                                    41,
+                                    PEAR_ERROR_RETURN,
+                                    null,
+                                    null
+                                    );
+        }
+        
+        if(!$this->db) {
+        	return PEAR::raiseError(ADODB_Pear_error());
+        } else {
+        	return true;
+        }
+    }
+
+    // }}}
+    // {{{ _prepare()
+
+    /**
+     * Prepare database connection
+     *
+     * This function checks if we have already opened a connection to
+     * the database. If that's not the case, a new connection is opened.
+     *
+     * @access private
+     * @return mixed True or a DB error object.
+     */
+    function _prepare()
+    {
+    	if(!$this->db) {
+    		$res = $this->_connect($this->options['dsn']);  		
+    	}
+        return true;
+    }
+
+    // }}}
+    // {{{ query()
+
+    /**
+     * Prepare query to the database
+     *
+     * This function checks if we have already opened a connection to
+     * the database. If that's not the case, a new connection is opened.
+     * After that the query is passed to the database.
+     *
+     * @access public
+     * @param  string Query string
+     * @return mixed  a DB_result object or DB_OK on success, a DB
+     *                or PEAR error on failure
+     */
+    function query($query)
+    {
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return $err;
+        }
+        return $this->db->query($query);
+    }
+
+    // }}}
+    // {{{ _setDefaults()
+
+    /**
+     * Set some default options
+     *
+     * @access private
+     * @return void
+     */
+    function _setDefaults()
+    {
+    	$this->options['db_type']	= 'mysql';
+        $this->options['table']       = 'auth';
+        $this->options['usernamecol'] = 'username';
+        $this->options['passwordcol'] = 'password';
+        $this->options['dsn']         = '';
+        $this->options['db_fields']   = '';
+        $this->options['cryptType']   = 'md5';
+    }
+
+    // }}}
+    // {{{ _parseOptions()
+
+    /**
+     * Parse options passed to the container class
+     *
+     * @access private
+     * @param  array
+     */
+    function _parseOptions($array)
+    {
+        foreach ($array as $key => $value) {
+            if (isset($this->options[$key])) {
+                $this->options[$key] = $value;
+            }
+        }
+
+        /* Include additional fields if they exist */
+        if(!empty($this->options['db_fields'])){
+            if(is_array($this->options['db_fields'])){
+                $this->options['db_fields'] = join($this->options['db_fields'], ', ');
+            }
+            $this->options['db_fields'] = ', '.$this->options['db_fields'];
+        }
+    }
+
+    // }}}
+    // {{{ fetchData()
+
+    /**
+     * Get user information from database
+     *
+     * This function uses the given username to fetch
+     * the corresponding login data from the database
+     * table. If an account that matches the passed username
+     * and password is found, the function returns true.
+     * Otherwise it returns false.
+     *
+     * @param   string Username
+     * @param   string Password
+     * @return  mixed  Error object or boolean
+     */
+    function fetchData($username, $password)
+    {
+        // Prepare for a database query
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return PEAR::raiseError($err->getMessage(), $err->getCode());
+        }
+
+        // Find if db_fields contains a *, i so assume all col are selected
+        if(strstr($this->options['db_fields'], '*')){
+            $sql_from = "*";
+        }
+        else{
+            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
+        }
+        
+        $query = "SELECT ".$sql_from.
+                " FROM ".$this->options['table'].
+                " WHERE ".$this->options['usernamecol']." = " . $this->db->Quote($username);
+        
+        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+        $rset = $this->db->Execute( $query );
+        $res = $rset->fetchRow();
+
+        if (DB::isError($res)) {
+            return PEAR::raiseError($res->getMessage(), $res->getCode());
+        }
+        if (!is_array($res)) {
+            $this->activeUser = '';
+            return false;
+        }
+        if ($this->verifyPassword(trim($password, "\r\n"),
+                                  trim($res[$this->options['passwordcol']], "\r\n"),
+                                  $this->options['cryptType'])) {
+            // Store additional field values in the session
+            foreach ($res as $key => $value) {
+                if ($key == $this->options['passwordcol'] ||
+                    $key == $this->options['usernamecol']) {
+                    continue;
+                }
+                // Use reference to the auth object if exists
+                // This is because the auth session variable can change so a static call to setAuthData does not make sence
+                if(is_object($this->_auth_obj)){
+                    $this->_auth_obj->setAuthData($key, $value);
+                } else {
+                    Auth::setAuthData($key, $value);
+                }
+            }
+
+            return true;
+        }
+
+        $this->activeUser = $res[$this->options['usernamecol']];
+        return false;
+    }
+
+    // }}}
+    // {{{ listUsers()
+
+    function listUsers()
+    {
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return PEAR::raiseError($err->getMessage(), $err->getCode());
+        }
+
+        $retVal = array();
+
+        // Find if db_fileds contains a *, i so assume all col are selected
+        if(strstr($this->options['db_fields'], '*')){
+            $sql_from = "*";
+        }
+        else{
+            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
+        }
+
+        $query = sprintf("SELECT %s FROM %s",
+                         $sql_from,
+                         $this->options['table']
+                         );
+        $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC);
+
+        if (DB::isError($res)) {
+            return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+            foreach ($res as $user) {
+                $user['username'] = $user[$this->options['usernamecol']];
+                $retVal[] = $user;
+            }
+        }
+        return $retVal;
+    }
+
+    // }}}
+    // {{{ addUser()
+
+    /**
+     * Add user to the storage container
+     *
+     * @access public
+     * @param  string Username
+     * @param  string Password
+     * @param  mixed  Additional information that are stored in the DB
+     *
+     * @return mixed True on success, otherwise error object
+     */
+    function addUser($username, $password, $additional = "")
+    {
+        if (function_exists($this->options['cryptType'])) {
+            $cryptFunction = $this->options['cryptType'];
+        } else {
+            $cryptFunction = 'md5';
+        }
+
+        $additional_key   = '';
+        $additional_value = '';
+
+        if (is_array($additional)) {
+            foreach ($additional as $key => $value) {
+                $additional_key .= ', ' . $key;
+                $additional_value .= ", '" . $value . "'";
+            }
+        }
+
+        $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES ('%s', '%s'%s)",
+                         $this->options['table'],
+                         $this->options['usernamecol'],
+                         $this->options['passwordcol'],
+                         $additional_key,
+                         $username,
+                         $cryptFunction($password),
+                         $additional_value
+                         );
+
+        $res = $this->query($query);
+
+        if (DB::isError($res)) {
+           return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+          return true;
+        }
+    }
+
+    // }}}
+    // {{{ removeUser()
+
+    /**
+     * Remove user from the storage container
+     *
+     * @access public
+     * @param  string Username
+     *
+     * @return mixed True on success, otherwise error object
+     */
+    function removeUser($username)
+    {
+        $query = sprintf("DELETE FROM %s WHERE %s = '%s'",
+                         $this->options['table'],
+                         $this->options['usernamecol'],
+                         $username
+                         );
+
+        $res = $this->query($query);
+
+        if (DB::isError($res)) {
+           return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+          return true;
+        }
+    }
+
+    // }}}
+}
+
+function showDbg( $string ) {
+	print "
+-- $string</P>";
+}
+function dump( $var, $str, $vardump = false ) {
+	print "<H4>$str</H4><pre>";
+	( !$vardump ) ? ( print_r( $var )) : ( var_dump( $var ));
+	print "</pre>";
+}
+?>
Index: pear/readme.Auth.txt
===================================================================
--- pear/readme.Auth.txt	(revision 0)
+++ pear/readme.Auth.txt	(revision 0)
@@ -0,0 +1,20 @@
+From: Rich Tango-Lowy (richtl#arscognita.com)
+Date: Sat, May 29, 2004 11:20 am
+
+OK, I hacked out an ADOdb container for PEAR-Auth. The error handling's 
+a bit of a mess, but all the methods work.
+
+Copy ADOdb.php to your pear/Auth/Container/ directory.
+
+Use the ADOdb container exactly as you would the DB
+container, but specify 'ADOdb' instead of 'DB':
+
+$dsn = "mysql://myuser:mypass@localhost/authdb";
+$a = new Auth("ADOdb", $dsn, "loginFunction");
+
+
+-------------------
+
+John Lim adds:
+
+See http://pear.php.net/manual/en/package.authentication.php

Property changes on: pear\readme.Auth.txt
___________________________________________________________________
Added: svn:eol-style
   + native

Index: perf/perf-db2.inc.php
===================================================================
--- perf/perf-db2.inc.php	(revision 13354)
+++ perf/perf-db2.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -58,7 +58,7 @@
 
 	function perf_db2(&$conn)
 	{
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 	
 	function Explain($sql,$partial=false)
Index: perf/perf-informix.inc.php
===================================================================
--- perf/perf-informix.inc.php	(revision 13354)
+++ perf/perf-informix.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -63,7 +63,7 @@
 	
 	function perf_informix(&$conn)
 	{
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 
 }
Index: perf/perf-mssql.inc.php
===================================================================
--- perf/perf-mssql.inc.php	(revision 13354)
+++ perf/perf-mssql.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -71,7 +71,7 @@
 			$this->sql1 = 'sql1';
 			//$this->explain = false;
 		}
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 	
 	function Explain($sql,$partial=false)
@@ -96,7 +96,7 @@
 		
 		$save = $ADODB_FETCH_MODE;
 		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-		$rs =& $this->conn->Execute($sql);
+		$rs = $this->conn->Execute($sql);
 		//adodb_printr($rs);
 		$ADODB_FETCH_MODE = $save;
 		if ($rs) {
Index: perf/perf-mssqlnative.inc.php
===================================================================
--- perf/perf-mssqlnative.inc.php	(revision 0)
+++ perf/perf-mssqlnative.inc.php	(revision 0)
@@ -0,0 +1,164 @@
+<?php
+
+/* 
+V5.11 5 May 2010   (c) 2000-2010 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
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+/*
+	MSSQL has moved most performance info to Performance Monitor
+*/
+class perf_mssqlnative extends adodb_perf{
+	var $sql1 = 'cast(sql1 as text)';
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created datetime NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(3000) NOT NULL,
+		  tracer varchar(500) NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)";
+		
+	var $settings = array(
+	'Ratios',
+		'data cache hit ratio' => array('RATIO',
+			"select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",
+			'=WarnCacheRatio'),
+		'prepared sql hit ratio' => array('RATIO',
+			array('dbcc cachestats','Prepared',1,100),
+			''),
+		'adhoc sql hit ratio' => array('RATIO',
+			array('dbcc cachestats','Adhoc',1,100),
+			''),
+	'IO',
+		'data reads' => array('IO',
+		"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),
+		'data writes' => array('IO',
+		"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),
+			
+	'Data Cache',
+		'data cache size' => array('DATAC',
+		"select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",
+			'' ),
+		'data cache blocksize' => array('DATAC',
+			"select 8192",'page size'),
+	'Connections',
+		'current connections' => array('SESS',
+			'=sp_who',
+			''),
+		'max connections' => array('SESS',
+			"SELECT @@MAX_CONNECTIONS",
+			''),
+
+		false
+	);
+	
+	
+	function perf_mssqlnative(&$conn)
+	{
+		if ($conn->dataProvider == 'odbc') {
+			$this->sql1 = 'sql1';
+			//$this->explain = false;
+		}
+		$this->conn =& $conn;
+	}
+	
+	function Explain($sql,$partial=false)
+	{
+		
+		$save = $this->conn->LogSQL(false);
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		
+		$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+		$this->conn->Execute("SET SHOWPLAN_ALL ON;");
+		$sql = str_replace('?',"''",$sql);
+		global $ADODB_FETCH_MODE;
+		
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$rs =& $this->conn->Execute($sql);
+		//adodb_printr($rs);
+		$ADODB_FETCH_MODE = $save;
+		if ($rs) {
+			$rs->MoveNext();
+			$s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>';
+			while (!$rs->EOF) {
+				$s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!
+				$rs->MoveNext();
+			}
+			$s .= '</table>';
+			
+			$rs->NextRecordSet();
+		}
+		
+		$this->conn->Execute("SET SHOWPLAN_ALL OFF;");
+		$this->conn->LogSQL($save);
+		$s .= $this->Tracer($sql);
+		return $s;
+	}
+	
+	function Tables()
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		//$this->conn->debug=1;
+		$s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';
+		$rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");
+		if ($rs1) {
+			while (!$rs1->EOF) {
+				$tab = $rs1->fields[0];
+				$tabq = $this->conn->qstr($tab);
+				$rs2 = $this->conn->Execute("sp_spaceused $tabq");
+				if ($rs2) {
+					$s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';
+					$rs2->Close();
+				}
+				$rs1->MoveNext();
+			}
+			$rs1->Close();
+		}
+		$ADODB_FETCH_MODE = $save;
+		return $s.'</table>';
+	}
+	
+	function sp_who()
+	{
+		$arr = $this->conn->GetArray('sp_who');
+		return sizeof($arr);
+	}
+	
+	function HealthCheck($cli=false)
+	{
+		
+		$this->conn->Execute('dbcc traceon(3604)');
+		$html =  adodb_perf::HealthCheck($cli);
+		$this->conn->Execute('dbcc traceoff(3604)');
+		return $html;
+	}
+	
+	
+}
+
+?>
\ No newline at end of file

Property changes on: perf\perf-mssqlnative.inc.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: perf/perf-mysql.inc.php
===================================================================
--- perf/perf-mysql.inc.php	(revision 13354)
+++ perf/perf-mysql.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -83,7 +83,7 @@
 	
 	function perf_mysql(&$conn)
 	{
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 	
 	function Explain($sql,$partial=false)
Index: perf/perf-oci8.inc.php
===================================================================
--- perf/perf-oci8.inc.php	(revision 13354)
+++ perf/perf-oci8.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -16,11 +16,14 @@
 if (!defined('ADODB_DIR')) die();
 
 class perf_oci8 extends ADODB_perf{
+
+	var $noShowIxora = 15; // if the sql for suspicious sql is taking too long, then disable ixora
 	
 	var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents 
 	   group by segment_name,tablespace_name";
 	 
 	var $version;
+	
 	var $createTableSQL = "CREATE TABLE adodb_logsql (
 		  created date NOT NULL,
 		  sql0 varchar(250) NOT NULL,
@@ -68,6 +71,7 @@
 		"select value from v\$sysstat where name='physical writes'"),
 	
 	'Data Cache',
+	
 		'data cache buffers' => array( 'DATAC',
 		"select a.value/b.value  from v\$parameter a, v\$parameter b 
 			where a.name = 'db_cache_size' and b.name= 'db_block_size'",
@@ -75,8 +79,24 @@
 		'data cache blocksize' => array('DATAC',
 			"select value from v\$parameter where name='db_block_size'",
 			'' ),			
+	
 	'Memory Pools',
-		'data cache size' => array('DATAC',
+		'Mem Max Target (11g+)' => array( 'DATAC',
+		"select value from v\$parameter where name = 'memory_max_target'",
+			'The memory_max_size is the maximum value to which memory_target can be set.' ),
+	'Memory target (11g+)' => array( 'DATAC',
+		"select value from v\$parameter where name = 'memory_target'",
+			'If memory_target is defined then SGA and PGA targets are consolidated into one memory_target.' ),
+		'SGA Max Size' => array( 'DATAC',
+		"select nvl(value,0)/1024.0/1024 || 'M' from v\$parameter where name = 'sga_max_size'",
+			'The sga_max_size is the maximum value to which sga_target can be set.' ),
+	'SGA target' => array( 'DATAC',
+		"select nvl(value,0)/1024.0/1024 || 'M'  from v\$parameter where name = 'sga_target'",
+			'If sga_target is defined then data cache, shared, java and large pool size can be 0. This is because all these pools are consolidated into one sga_target.' ),
+	'PGA aggr target' => array( 'DATAC',
+		"select value from v\$parameter where name = 'pga_aggregate_target'",
+			'If pga_aggregate_target is defined then this is the maximum memory that can be allocated for cursor operations such as sorts, group by, joins, merges. When in doubt, set it to 20% of sga_target.' ),
+	'data cache size' => array('DATAC',
 			"select value from v\$parameter where name = 'db_cache_size'",
 			'db_cache_size' ),
 		'shared pool size' => array('DATAC',
@@ -93,6 +113,7 @@
 			"select value from v\$parameter where name='pga_aggregate_target'",
 			'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ),
 
+		'dynamic memory usage' => array('CACHE', "select '-' from dual", '=DynMemoryUsage'),
 		
 		'Connections',
 		'current connections' => array('SESS',
@@ -109,8 +130,8 @@
 			where name = 'free memory' and pool = 'shared pool'",
 		'Percentage of data cache actually in use - should be over 85%'),
 		
-		'shared pool utilization ratio' => array('RATIOU',
-		'select round((sga.bytes/p.value)*100,2)
+		'shared pool utilization ratio' => array('RATIOU', 
+		'select round((sga.bytes/case when p.value=0 then sga.bytes else to_number(p.value) end)*100,2)
 		from v$sgastat sga, v$parameter p
 		where sga.name = \'free memory\' and sga.pool = \'shared pool\'
 		and p.name = \'shared_pool_size\'',
@@ -157,6 +178,31 @@
 			"select value from v\$parameter where name = 'optimizer_index_cost_adj'",
 			'=WarnPageCost'),
 		
+	'Backup',
+		'Achivelog Mode' => array('BACKUP', 'select log_mode from v$database', 'To turn on archivelog:<br>
+	<pre>
+        SQLPLUS> connect sys as sysdba;
+        SQLPLUS> shutdown immediate;
+
+        SQLPLUS> startup mount exclusive;
+        SQLPLUS> alter database archivelog;
+        SQLPLUS> archive log start;
+        SQLPLUS> alter database open;
+</pre>'),
+	
+		'DBID' => array('BACKUP','select dbid from v$database','Primary key of database, used for recovery with an RMAN Recovery Catalog'),
+		'Archive Log Dest' => array('BACKUP', "SELECT NVL(v1.value,v2.value) 
+FROM v\$parameter v1, v\$parameter v2 WHERE v1.name='log_archive_dest' AND v2.name='log_archive_dest_10'", ''),
+	
+		'Flashback Area' => array('BACKUP', "select nvl(value,'Flashback Area not used') from v\$parameter where name=lower('DB_RECOVERY_FILE_DEST')", 'Flashback area is a folder where all backup data and logs can be stored and managed by Oracle. If Error: message displayed, then it is not in use.'),
+	
+		'Flashback Usage' => array('BACKUP', "select nvl('-','Flashback Area not used') from v\$parameter where name=lower('DB_RECOVERY_FILE_DEST')", '=FlashUsage', 'Flashback area usage.'),
+		
+		'Control File Keep Time' => array('BACKUP', "select value from v\$parameter where name='control_file_record_keep_time'",'No of days to keep RMAN info in control file. I recommend it be set to x2 or x3 times the frequency of your full backup.'),
+		'Recent RMAN Jobs' => array('BACKUP', "select '-' from dual", "=RMAN"),
+		
+		//		'Control File Keep Time' => array('BACKUP', "select value from v\$parameter where name='control_file_record_keep_time'",'No of days to keep RMAN info in control file. I recommend it be set to x2 or x3 times the frequency of your full backup.'),
+
 		false
 		
 	);
@@ -167,9 +213,38 @@
 		$savelog = $conn->LogSQL(false);	
 		$this->version = $conn->ServerInfo();
 		$conn->LogSQL($savelog);	
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 	
+	function RMAN()
+	{
+		$rs = $this->conn->Execute("select * from (select start_time, end_time, operation, status, mbytes_processed, output_device_type  
+			from V\$RMAN_STATUS order by start_time desc) where rownum <=10");
+		
+		$ret = rs2html($rs,false,false,false,false);		
+		return "&nbsp;<p>".$ret."&nbsp;</p>";
+		
+	}
+	function DynMemoryUsage()
+	{
+		if (@$this->version['version'] >= 11) {
+			$rs = $this->conn->Execute("select component, current_size/1024./1024 as \"CurrSize (M)\" from  V\$MEMORY_DYNAMIC_COMPONENTS");
+
+		} else
+			$rs = $this->conn->Execute("select name, round(bytes/1024./1024,2) as \"CurrSize (M)\" from  V\$sgainfo");
+
+			
+		$ret = rs2html($rs,false,false,false,false);		
+		return "&nbsp;<p>".$ret."&nbsp;</p>";
+	}
+	
+	function FlashUsage()
+	{
+        $rs = $this->conn->Execute("select * from  V\$FLASH_RECOVERY_AREA_USAGE");
+		$ret = rs2html($rs,false,false,false,false);		
+		return "&nbsp;<p>".$ret."&nbsp;</p>";
+	}
+	
 	function WarnPageCost($val)
 	{
 		if ($val == 100) $s = '<font color=red><b>Too High</b>. </font>';
@@ -184,7 +259,7 @@
 		else $s = '';
 		
 		return $s.'Percentage of indexed data blocks expected in the cache.
-			Recommended is 20 (fast disk array) to 50 (slower hard disks). Default is 0.
+			Recommended is 20 (fast disk array) to 30 (slower hard disks). Default is 0.
 			 See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.';
 		}
 	
@@ -193,10 +268,10 @@
 		if ($this->version['version'] < 9) return 'Oracle 9i or later required';
 		
 		$rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from 
-	   (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+	   (select round(pga_target_for_estimate/1024.0/1024.0,0) MB,
 	   	   pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
 	   	   from v\$pga_target_advice) a left join
-	   (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+	   (select round(pga_target_for_estimate/1024.0/1024.0,0) MB,
 	   	   pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
 	   	   from v\$pga_target_advice) b on 
 	  a.r = b.r+1 where 
@@ -211,7 +286,7 @@
 	function Explain($sql,$partial=false) 
 	{
 		$savelog = $this->conn->LogSQL(false);
-		$rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");
+		$rs = $this->conn->SelectLimit("select ID FROM PLAN_TABLE");
 		if (!$rs) {
 			echo "<p><b>Missing PLAN_TABLE</b></p>
 <pre>
@@ -250,7 +325,7 @@
 	
 		if ($partial) {
 			$sqlq = $this->conn->qstr($sql.'%');
-			$arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
 			if ($arr) {
 				foreach($arr as $row) {
 					$sql = reset($row);
@@ -264,7 +339,7 @@
 		$this->conn->BeginTrans();
 		$id = "ADODB ".microtime();
 
-		$rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
+		$rs = $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
 		$m = $this->conn->ErrorMsg();
 		if ($m) {
 			$this->conn->RollbackTrans();
@@ -272,7 +347,7 @@
 			$s .= "<p>$m</p>";
 			return $s;
 		}
-		$rs =& $this->conn->Execute("
+		$rs = $this->conn->Execute("
 		select 
   '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, 
   object_name,COST,CARDINALITY,bytes
@@ -292,16 +367,18 @@
 	{
 		if ($this->version['version'] < 9) return 'Oracle 9i or later required';
 		
-		 $rs =& $this->conn->Execute("
-select  a.size_for_estimate as cache_mb_estimate,
-	case when a.size_factor=1 then 
-   		'&lt;&lt;= current'
-	 when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then
-		'- BETTER - '
-	else ' ' end as currsize, 
-   a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0
-   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice) a , 
-   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice) b where a.r = b.r-1");
+		 $rs = $this->conn->Execute("
+select  b.size_for_estimate as cache_mb_estimate, 
+	case when b.size_factor=1 then 
+   		'&lt;&lt;= Current'
+	 when a.estd_physical_read_factor-b.estd_physical_read_factor > 0.001 and b.estd_physical_read_factor<1 then
+		'- BETTER than current by ' || round((1-b.estd_physical_read_factor)/b.estd_physical_read_factor*100,2) || '%'
+	else ' ' end as RATING, 
+   b.estd_physical_read_factor \"Phys. Reads Factor\",
+   round((a.estd_physical_read_factor-b.estd_physical_read_factor)/b.estd_physical_read_factor*100,2) as \"% Improve\"
+   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice order by 1) a , 
+   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice order by 1) b where a.r = b.r-1
+  ");
 		if (!$rs) return false;
 		
 		/*
@@ -311,7 +388,7 @@
 		if ($rs->EOF) {
 			$s .= "<p>Cache that is 50% of current size is still too big</p>";
 		} else {
-			$s .= "Ideal size of Data Cache is when \"best_when_0\" changes from a positive number and becomes zero.";
+			$s .= "Ideal size of Data Cache is when %Improve gets close to zero.";
 			$s .= rs2html($rs,false,false,false,false);
 		}
 		return $s;
@@ -412,7 +489,11 @@
 		if (isset($_GET['sql'])) return $this->_SuspiciousSQL($numsql);
 		
 		$s = '';
+		$timer = time();
 		$s .= $this->_SuspiciousSQL($numsql);
+		$timer = time() - $timer;
+		
+		if ($timer > $this->noShowIxora) return $s;
 		$s .= '<p>';
 		
 		$save = $ADODB_CACHE_MODE;
@@ -420,7 +501,7 @@
 		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
 		
 		$savelog = $this->conn->LogSQL(false);
-		$rs =& $this->conn->SelectLimit($sql);
+		$rs = $this->conn->SelectLimit($sql);
 		$this->conn->LogSQL($savelog);
 		
 		if (isset($savem)) $this->conn->SetFetchMode($savem);
@@ -484,14 +565,18 @@
 		}
 		
 		$s = '';		
+		$timer = time();
 		$s .= $this->_ExpensiveSQL($numsql);
+		$timer = time() - $timer;
+		if ($timer > $this->noShowIxora) return $s;
+		
 		$s .= '<p>';
 		$save = $ADODB_CACHE_MODE;
 		$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
 		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
 		
 		$savelog = $this->conn->LogSQL(false);
-		$rs =& $this->conn->Execute($sql);
+		$rs = $this->conn->Execute($sql);
 		$this->conn->LogSQL($savelog);
 		
 		if (isset($savem)) $this->conn->SetFetchMode($savem);
@@ -505,5 +590,29 @@
 		return $s;
 	}
 	
+	function clearsql() 
+	{
+		$perf_table = adodb_perf::table();
+	// using the naive "delete from $perf_table where created<".$this->conn->sysTimeStamp will cause the table to lock, possibly
+	// for a long time
+		$sql = 
+"DECLARE cnt pls_integer;
+BEGIN
+	cnt := 0;
+	FOR rec IN (SELECT ROWID AS rr FROM $perf_table WHERE created<SYSDATE) 
+	LOOP
+	  cnt := cnt + 1;
+	  DELETE FROM $perf_table WHERE ROWID=rec.rr;
+	  IF cnt = 1000 THEN
+	  	COMMIT;
+		cnt := 0;
+	  END IF;
+	END LOOP;
+	commit;
+END;";
+
+		$ok = $this->conn->Execute($sql);
+	}
+	
 }
 ?>
\ No newline at end of file
Index: perf/perf-postgres.inc.php
===================================================================
--- perf/perf-postgres.inc.php	(revision 13354)
+++ perf/perf-postgres.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /* 
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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. 
@@ -89,9 +89,38 @@
 	
 	function perf_postgres(&$conn)
 	{
-		$this->conn =& $conn;
+		$this->conn = $conn;
 	}
 	
+	var $optimizeTableLow  = 'VACUUM %s'; 
+	var $optimizeTableHigh = 'VACUUM ANALYZE %s';
+
+/**
+ * @see adodb_perf#optimizeTable
+ */
+
+	function optimizeTable($table, $mode = ADODB_OPT_LOW) 
+	{
+	    if(! is_string($table)) return false;
+	    
+	    $conn = $this->conn;
+	    if (! $conn) return false;
+	    
+	    $sql = '';
+	    switch($mode) {
+	        case ADODB_OPT_LOW : $sql = $this->optimizeTableLow;  break;
+	        case ADODB_OPT_HIGH: $sql = $this->optimizeTableHigh; break;
+	        default            : 
+	        {
+	            ADOConnection::outp(sprintf("<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, 'optimizeTable', $mode));
+	            return false;
+	        }
+	    }
+	    $sql = sprintf($sql, $table);
+	    
+	    return $conn->Execute($sql) !== false;  
+	}
+	
 	function Explain($sql,$partial=false)
 	{
 		$save = $this->conn->LogSQL(false);
Index: pivottable.inc.php
===================================================================
--- pivottable.inc.php	(revision 13354)
+++ pivottable.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V4.93 10 Oct 2006 (c) 2000-2010 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. 
Index: readme.txt
===================================================================
--- readme.txt	(revision 0)
+++ readme.txt	(revision 0)
@@ -0,0 +1,62 @@
+>> ADODB Library for PHP4
+
+(c) 2000-2004 John Lim (jlim@natsoft.com.my)
+
+Released under both BSD and GNU Lesser GPL library license. 
+This means you can use it in proprietary products.
+ 
+ 
+>> Introduction
+
+PHP's database access functions are not standardised. This creates a 
+need for a database class library to hide the differences between the 
+different databases (encapsulate the differences) so we can easily 
+switch databases.
+
+We currently support MySQL, Interbase, Sybase, PostgreSQL, Oracle, 
+Microsoft SQL server,  Foxpro ODBC, Access ODBC, Informix, DB2,
+Sybase SQL Anywhere, generic ODBC and Microsoft's ADO. 
+
+We hope more people will contribute drivers to support other databases.
+
+
+>> Documentation and Examples
+
+Refer to the adodb/docs directory for full documentation and examples. 
+There is also a  tutorial tute.htm that contrasts ADODB code with 
+mysql code.
+
+
+>>> Files
+Adodb.inc.php is the main file. You need to include only this file.
+
+Adodb-*.inc.php are the database specific driver code.
+
+Test.php contains a list of test commands to exercise the class library.
+
+Adodb-session.php is the PHP4 session handling code.
+
+Testdatabases.inc.php contains the list of databases to apply the tests on.
+
+Benchmark.php is a simple benchmark to test the throughput of a simple SELECT 
+statement for databases described in testdatabases.inc.php. The benchmark
+tables are created in test.php.
+
+readme.htm is the main documentation.
+
+tute.htm is the tutorial.
+
+
+>> More Info
+
+For more information, including installation see readme.htm
+or visit
+           http://adodb.sourceforge.net/
+
+
+>> Feature Requests and Bug Reports
+
+Email to jlim@natsoft.com.my 
+
+
+ 
\ No newline at end of file

Property changes on: readme.txt
___________________________________________________________________
Added: svn:eol-style
   + native

Index: rsfilter.inc.php
===================================================================
--- rsfilter.inc.php	(revision 13354)
+++ rsfilter.inc.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V4.93 10 Oct 2006 (c) 2000-2010 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. 
@@ -33,12 +33,12 @@
 	}
 	$rs = RSFilter($rs,'do_ucwords');
  */
-function &RSFilter($rs,$fn)
+function RSFilter($rs,$fn)
 {
 	if ($rs->databaseType != 'array') {
 		if (!$rs->connection) return false;
 		
-		$rs = &$rs->connection->_rs2rs($rs);
+		$rs = $rs->connection->_rs2rs($rs);
 	}
 	$rows = $rs->RecordCount();
 	for ($i=0; $i < $rows; $i++) {
Index: server.php
===================================================================
--- server.php	(revision 13354)
+++ server.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V4.93 10 Oct 2006 (c) 2000-2010 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. 
@@ -76,7 +76,7 @@
 if (empty($_REQUEST['sql'])) err('No SQL');
 
 
-$conn = &ADONewConnection($driver);
+$conn = ADONewConnection($driver);
 
 if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
 $sql = undomq($_REQUEST['sql']);
Index: session/adodb-compress-bzip2.php
===================================================================
--- session/adodb-compress-bzip2.php	(revision 13354)
+++ session/adodb-compress-bzip2.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
Index: session/adodb-compress-gzip.php
===================================================================
--- session/adodb-compress-gzip.php	(revision 13354)
+++ session/adodb-compress-gzip.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
Index: session/adodb-cryptsession.php
===================================================================
--- session/adodb-cryptsession.php	(revision 13354)
+++ session/adodb-cryptsession.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
@@ -16,7 +16,10 @@
 
 */
 
-require_once dirname(__FILE__) . '/adodb-session.php';
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session.php';
+}
+
 require_once  ADODB_SESSION . '/adodb-encrypt-md5.php';
 
 ADODB_Session::filter(new ADODB_Encrypt_MD5());
Index: session/adodb-cryptsession2.php
===================================================================
--- session/adodb-cryptsession2.php	(revision 0)
+++ session/adodb-cryptsession2.php	(revision 0)
@@ -0,0 +1,27 @@
+<?php
+
+
+/*
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session2.php';
+}
+
+require_once  ADODB_SESSION . '/adodb-encrypt-md5.php';
+
+ADODB_Session::filter(new ADODB_Encrypt_MD5());
+
+?>
\ No newline at end of file

Property changes on: session\adodb-cryptsession2.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: session/adodb-encrypt-mcrypt.php
===================================================================
--- session/adodb-encrypt-mcrypt.php	(revision 13354)
+++ session/adodb-encrypt-mcrypt.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
Index: session/adodb-encrypt-md5.php
===================================================================
--- session/adodb-encrypt-md5.php	(revision 13354)
+++ session/adodb-encrypt-md5.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
@@ -21,14 +21,14 @@
 	/**
 	 */
 	function write($data, $key) {
-		$md5crypt =& new MD5Crypt();
+		$md5crypt = new MD5Crypt();
 		return $md5crypt->encrypt($data, $key);
 	}
 
 	/**
 	 */
 	function read($data, $key) {
-		$md5crypt =& new MD5Crypt();
+		$md5crypt = new MD5Crypt();
 		return $md5crypt->decrypt($data, $key);
 	}
 
Index: session/adodb-encrypt-secret.php
===================================================================
--- session/adodb-encrypt-secret.php	(revision 13354)
+++ session/adodb-encrypt-secret.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
Index: session/adodb-encrypt-sha1.php
===================================================================
--- session/adodb-encrypt-sha1.php	(revision 13354)
+++ session/adodb-encrypt-sha1.php	(working copy)
@@ -1,32 +1,32 @@
-<?php
-if (!defined('ADODB_SESSION')) die();
-
-include_once ADODB_SESSION . '/crypt.inc.php';
-
-
-/**
-
- */
-
-class ADODB_Encrypt_SHA1 {
-
-	function write($data, $key) 
-	{
-		$sha1crypt =& new SHA1Crypt();
-		return $sha1crypt->encrypt($data, $key);
-
-	}
-
-
-	function read($data, $key) 
-	{
-		$sha1crypt =& new SHA1Crypt();
-		return $sha1crypt->decrypt($data, $key);
-
-	}
-}
-
-
-
-return 1;
+<?php
+if (!defined('ADODB_SESSION')) die();
+
+include_once ADODB_SESSION . '/crypt.inc.php';
+
+
+/**
+
+ */
+
+class ADODB_Encrypt_SHA1 {
+
+	function write($data, $key) 
+	{
+		$sha1crypt = new SHA1Crypt();
+		return $sha1crypt->encrypt($data, $key);
+
+	}
+
+
+	function read($data, $key) 
+	{
+		$sha1crypt = new SHA1Crypt();
+		return $sha1crypt->decrypt($data, $key);
+
+	}
+}
+
+
+
+return 1;
 ?>
\ No newline at end of file
Index: session/adodb-sess.txt
===================================================================
--- session/adodb-sess.txt	(revision 0)
+++ session/adodb-sess.txt	(revision 0)
@@ -0,0 +1,131 @@
+John,
+
+I have been an extremely satisfied ADODB user for several years now.
+
+To give you something back for all your hard work, I've spent the last 3
+days rewriting the adodb-session.php code.
+
+----------
+What's New
+----------
+
+Here's a list of the new code's benefits:
+
+* Combines the functionality of the three files:
+
+adodb-session.php
+adodb-session-clob.php
+adodb-cryptsession.php
+
+each with very similar functionality, into a single file adodb-session.php.
+This will ease maintenance and support issues.
+
+* Supports multiple encryption and compression schemes.
+  Currently, we support:
+
+  MD5Crypt (crypt.inc.php)
+  MCrypt
+  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)
+  GZip
+  BZip2
+
+These can be stacked, so if you want to compress and then encrypt your
+session data, it's easy.
+Also, the built-in MCrypt functions will be *much* faster, and more secure,
+than the MD5Crypt code.
+
+* adodb-session.php contains a single class ADODB_Session that encapsulates
+all functionality.
+  This eliminates the use of global vars and defines (though they are
+supported for backwards compatibility).
+
+* All user defined parameters are now static functions in the ADODB_Session
+class.
+
+New parameters include:
+
+* encryptionKey(): Define the encryption key used to encrypt the session.
+Originally, it was a hard coded string.
+
+* persist(): Define if the database will be opened in persistent mode.
+Originally, the user had to call adodb_sess_open().
+
+* dataFieldName(): Define the field name used to store the session data, as
+'DATA' appears to be a reserved word in the following cases:
+	ANSI SQL
+	IBM DB2
+	MS SQL Server
+	Postgres
+	SAP
+
+* filter(): Used to support multiple, simulataneous encryption/compression
+schemes.
+
+* Debug support is improved thru _rsdump() function, which is called after
+every database call.
+
+------------
+What's Fixed
+------------
+
+The new code includes several bug fixes and enhancements:
+
+* sesskey is compared in BINARY mode for MySQL, to avoid problems with
+session keys that differ only by case.
+  Of course, the user should define the sesskey field as BINARY, to
+correctly fix this problem, otherwise performance will suffer.
+
+* In ADODB_Session::gc(), if $expire_notify is true, the multiple DELETES in
+the original code have been optimized to a single DELETE.
+
+* In ADODB_Session::destroy(), since "SELECT expireref, sesskey FROM $table
+WHERE sesskey = $qkey" will only return a single value, we don't loop on the
+result, we simply process the row, if any.
+
+* We close $rs after every use.
+
+---------------
+What's the Same
+---------------
+
+I know backwards compatibility is *very* important to you.  Therefore, the
+new code is 100% backwards compatible.
+
+If you like my code, but don't "trust" it's backwards compatible, maybe we
+offer it as beta code, in a new directory for a release or two?
+
+------------
+What's To Do
+------------
+
+I've vascillated over whether to use a single function to get/set
+parameters:
+
+$user = ADODB_Session::user(); 	// get
+ADODB_Session::user($user);		// set
+
+or to use separate functions (which is the PEAR/Java way):
+
+$user = ADODB_Session::getUser();
+ADODB_Session::setUser($user);
+
+I've chosen the former as it's makes for a simpler API, and reduces the
+amount of code, but I'd be happy to change it to the latter.
+
+Also, do you think the class should be a singleton class, versus a static
+class?
+
+Let me know if you find this code useful, and will be including it in the
+next release of ADODB.
+
+If so, I will modify the current documentation to detail the new
+functionality.  To that end, what file(s) contain the documentation?  Please
+send them to me if they are not publically available.
+
+Also, if there is *anything* in the code that you like to see changed, let
+me know.
+
+Thanks,
+
+Ross
+

Property changes on: session\adodb-sess.txt
___________________________________________________________________
Added: svn:eol-style
   + native

Index: session/adodb-session-clob.php
===================================================================
--- session/adodb-session-clob.php	(revision 13354)
+++ session/adodb-session-clob.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
@@ -16,8 +16,9 @@
 
 */
 
-require_once dirname(__FILE__) . '/adodb-session.php';
-
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session.php';
+}
 ADODB_Session::clob('CLOB');
 
 ?>
\ No newline at end of file
Index: session/adodb-session-clob2.php
===================================================================
--- session/adodb-session-clob2.php	(revision 0)
+++ session/adodb-session-clob2.php	(revision 0)
@@ -0,0 +1,24 @@
+<?php
+
+
+/*
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session2.php';
+}
+ADODB_Session::clob('CLOB');
+
+?>
\ No newline at end of file

Property changes on: session\adodb-session-clob2.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: session/adodb-session.php
===================================================================
--- session/adodb-session.php	(revision 13354)
+++ session/adodb-session.php	(working copy)
@@ -2,7 +2,7 @@
 
 
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Contributed by Ross Smith (adodb@netebb.com). 
   Released under both BSD license and Lesser GPL library license.
   Whenever there is any discrepancy between the two licenses,
@@ -59,7 +59,7 @@
 */
 function adodb_session_regenerate_id() 
 {
-	$conn =& ADODB_Session::_conn();
+	$conn = ADODB_Session::_conn();
 	if (!$conn) return false;
 
 	$old_id = session_id();
@@ -72,7 +72,7 @@
 		//@session_start();
 	}
 	$new_id = session_id();
-	$ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	$ok = $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
 	
 	/* it is possible that the update statement fails due to a collision */
 	if (!$ok) {
@@ -95,7 +95,7 @@
 {
     // set default values
     if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema.xml';
-    if ($conn===null) $conn =& ADODB_Session::_conn();
+    if ($conn===null) $conn = ADODB_Session::_conn();
 
 	if (!$conn) return 0;
 
@@ -421,7 +421,7 @@
 
 	/*!
 	*/
-	function &_conn($conn=null) {
+	function _conn($conn=null) {
 		return $GLOBALS['ADODB_SESS_CONN'];
 	}
 
@@ -463,7 +463,7 @@
 	/*!
 	*/
 	function _dumprs($rs) {
-		$conn	=& ADODB_Session::_conn();
+		$conn	= ADODB_Session::_conn();
 		$debug	= ADODB_Session::debug();
 
 		if (!$conn) {
@@ -501,9 +501,11 @@
 		ADODB_Session::password($password);
 		ADODB_Session::database($database);
 		
+		if ($driver == 'oci8' || $driver == 'oci8po') $options['lob'] = 'CLOB';
+		
 		if (isset($options['table'])) ADODB_Session::table($options['table']);
-		if (isset($options['clob'])) ADODB_Session::table($options['clob']);
-		if (isset($options['field'])) ADODB_Session::dataFieldName($options['field']);
+		if (isset($options['lob'])) ADODB_Session::clob($options['lob']);
+		if (isset($options['debug'])) ADODB_Session::debug($options['debug']);
 	}
 
 	/*!
@@ -511,8 +513,9 @@
 
 		If $conn already exists, reuse that connection
 	*/
-	function open($save_path, $session_name, $persist = null) {
-		$conn =& ADODB_Session::_conn();
+	function open($save_path, $session_name, $persist = null) 
+	{
+		$conn = ADODB_Session::_conn();
 
 		if ($conn) {
 			return true;
@@ -536,7 +539,7 @@
 #		assert('$driver');
 #		assert('$host');
 
-		$conn =& ADONewConnection($driver);
+		$conn = ADONewConnection($driver);
 
 		if ($debug) {
 			$conn->debug = true;
@@ -554,7 +557,7 @@
 			$ok = $conn->Connect($host, $user, $password, $database);
 		}
 
-		if ($ok) $GLOBALS['ADODB_SESS_CONN'] =& $conn;
+		if ($ok) $GLOBALS['ADODB_SESS_CONN'] = $conn;
 		else
 			ADOConnection::outp('<p>Session: connection failed</p>', false);
 		
@@ -565,9 +568,10 @@
 	/*!
 		Close the connection
 	*/
-	function close() {
+	function close() 
+	{
 /*
-		$conn =& ADODB_Session::_conn();
+		$conn = ADODB_Session::_conn();
 		if ($conn) $conn->Close();
 */
 		return true;
@@ -576,8 +580,9 @@
 	/*
 		Slurp in the session variables and return the serialized string
 	*/
-	function read($key) {
-		$conn	=& ADODB_Session::_conn();
+	function read($key) 
+	{
+		$conn	= ADODB_Session::_conn();
 		$data	= ADODB_Session::dataFieldName();
 		$filter	= ADODB_Session::filter();
 		$table	= ADODB_Session::table();
@@ -586,7 +591,7 @@
 			return '';
 		}
 
-		assert('$table');
+		//assert('$table');
 
 		$qkey = $conn->quote($key);
 		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
@@ -596,10 +601,10 @@
 		  developer has commited elsewhere... :(
 		 */
 		#if (ADODB_Session::Lock())
-		#	$rs =& $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), $data);
+		#	$rs = $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), $data);
 		#else
 		
-			$rs =& $conn->Execute($sql);
+			$rs = $conn->Execute($sql);
 		//ADODB_Session::_dumprs($rs);
 		if ($rs) {
 			if ($rs->EOF) {
@@ -629,13 +634,14 @@
 
 		If the data has not been modified since the last read(), we do not write.
 	*/
-	function write($key, $val) {
+	function write($key, $val) 
+	{
 	global $ADODB_SESSION_READONLY;
 	
 		if (!empty($ADODB_SESSION_READONLY)) return;
 		
 		$clob			= ADODB_Session::clob();
-		$conn			=& ADODB_Session::_conn();
+		$conn			= ADODB_Session::_conn();
 		$crc			= ADODB_Session::_crc();
 		$data			= ADODB_Session::dataFieldName();
 		$debug			= ADODB_Session::debug();
@@ -650,7 +656,7 @@
 		}
 		$qkey = $conn->qstr($key);
 	
-		assert('$table');
+		//assert('$table');
 
 		$expiry = time() + $lifetime;
 
@@ -660,7 +666,7 @@
 		// now we only update expiry date, thx to sebastian thom in adodb 2.32
 		if ($crc !== false && $crc == (strlen($val) . crc32($val))) {
 			if ($debug) {
-				echo '<p>Session: Only updating date - crc32 not changed</p>';
+				ADOConnection::outp( '<p>Session: Only updating date - crc32 not changed</p>');
 			}
 			
 			$expirevar = '';
@@ -674,7 +680,7 @@
 			
 			
 			$sql = "UPDATE $table SET expiry = ".$conn->Param('0').",expireref=".$conn->Param('1')." WHERE $binary sesskey = ".$conn->Param('2')." AND expiry >= ".$conn->Param('3');
-			$rs =& $conn->Execute($sql,array($expiry,$expirevar,$key,time()));
+			$rs = $conn->Execute($sql,array($expiry,$expirevar,$key,time()));
 			return true;
 		}
 		$val = rawurlencode($val);
@@ -694,7 +700,7 @@
 		}
 
 		if (!$clob) {	// no lobs, simply use replace()
-			$arr[$data] = $conn->qstr($val);
+			$arr[$data] = $val;
 			$rs = $conn->Replace($table, $arr, 'sesskey', $autoQuote = true);
 			
 		} else {
@@ -714,35 +720,27 @@
 					break;
 			}
 			
+			$conn->StartTrans();
 			$expiryref = $conn->qstr($arr['expireref']);
 			// do we insert or update? => as for sesskey
-			$rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = $qkey");
+			$rs = $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = $qkey");
 			if ($rs && reset($rs->fields) > 0) {
 				$sql = "UPDATE $table SET expiry = $expiry, $data = $lob_value, expireref=$expiryref WHERE  sesskey = $qkey";
 			} else {
 				$sql = "INSERT INTO $table (expiry, $data, sesskey,expireref) VALUES ($expiry, $lob_value, $qkey,$expiryref)";
 			}
-			if ($rs) {
-				$rs->Close();
-			}
+			if ($rs)$rs->Close();
+			
 
 			$err = '';
-			$rs1 =& $conn->Execute($sql);
-			if (!$rs1) {
-				$err = $conn->ErrorMsg()."\n";
-			}
-			$rs2 =& $conn->UpdateBlob($table, $data, $val, " sesskey=$qkey", strtoupper($clob));
+			$rs1 = $conn->Execute($sql);
+			if (!$rs1) $err = $conn->ErrorMsg()."\n";
 			
-			if (!$rs2) {
-				$err .= $conn->ErrorMsg()."\n";
-			}
+			$rs2 = $conn->UpdateBlob($table, $data, $val, " sesskey=$qkey", strtoupper($clob));
+			if (!$rs2) $err .= $conn->ErrorMsg()."\n";
+			
 			$rs = ($rs && $rs2) ? true : false;
-			if ($rs1) {
-				$rs1->Close();
-			}
-			if (is_object($rs2)) {
-				$rs2->Close();
-			}
+			$conn->CompleteTrans();
 		}
 
 		if (!$rs) {
@@ -753,7 +751,7 @@
 			// properly unless select statement executed in Win2000
 			if ($conn->databaseType == 'access') {
 				$sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey";
-				$rs =& $conn->Execute($sql);
+				$rs = $conn->Execute($sql);
 				ADODB_Session::_dumprs($rs);
 				if ($rs) {
 					$rs->Close();
@@ -769,7 +767,7 @@
 	/*!
 	*/
 	function destroy($key) {
-		$conn			=& ADODB_Session::_conn();
+		$conn			= ADODB_Session::_conn();
 		$table			= ADODB_Session::table();
 		$expire_notify	= ADODB_Session::expireNotify();
 
@@ -777,7 +775,7 @@
 			return false;
 		}
 
-		assert('$table');
+		//assert('$table');
 
 		$qkey = $conn->quote($key);
 		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
@@ -787,7 +785,7 @@
 			$fn = next($expire_notify);
 			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
 			$sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey";
-			$rs =& $conn->Execute($sql);
+			$rs = $conn->Execute($sql);
 			ADODB_Session::_dumprs($rs);
 			$conn->SetFetchMode($savem);
 			if (!$rs) {
@@ -804,19 +802,17 @@
 		}
 
 		$sql = "DELETE FROM $table WHERE $binary sesskey = $qkey";
-		$rs =& $conn->Execute($sql);
+		$rs = $conn->Execute($sql);
 		ADODB_Session::_dumprs($rs);
-		if ($rs) {
-			$rs->Close();
-		}
 
 		return $rs ? true : false;
 	}
 
 	/*!
 	*/
-	function gc($maxlifetime) {
-		$conn			=& ADODB_Session::_conn();
+	function gc($maxlifetime) 
+	{
+		$conn			= ADODB_Session::_conn();
 		$debug			= ADODB_Session::debug();
 		$expire_notify	= ADODB_Session::expireNotify();
 		$optimize		= ADODB_Session::optimize();
@@ -827,10 +823,8 @@
 			return false;
 		}
 
-		assert('$table');
 
 		$time			= time();
-
 		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
 
 		if ($expire_notify) {
@@ -838,35 +832,35 @@
 			$fn = next($expire_notify);
 			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
 			$sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time";
-			$rs =& $conn->Execute($sql);
+			$rs = $conn->Execute($sql);
 			ADODB_Session::_dumprs($rs);
 			$conn->SetFetchMode($savem);
 			if ($rs) {
-				$conn->BeginTrans();
+				$conn->StartTrans();
 				$keys = array();
 				while (!$rs->EOF) {
 					$ref = $rs->fields[0];
 					$key = $rs->fields[1];
 					$fn($ref, $key);
-					$del = $conn->Execute("DELETE FROM $table WHERE sesskey='$key'");
+					$del = $conn->Execute("DELETE FROM $table WHERE sesskey=".$conn->Param('0'),array($key));
 					$rs->MoveNext();
 				}
 				$rs->Close();
 				
-				$conn->CommitTrans();
+				$conn->CompleteTrans();
 			}
 		} else {
 		
 			if (1) {
 				$sql = "SELECT sesskey FROM $table WHERE expiry < $time";
-				$arr =& $conn->GetAll($sql);
+				$arr = $conn->GetAll($sql);
 				foreach ($arr as $row) {
-					$sql2 = "DELETE FROM $table WHERE sesskey='$row[0]'";
-					$conn->Execute($sql2);
+					$sql2 = "DELETE FROM $table WHERE sesskey=".$conn->Param('0');
+					$conn->Execute($sql2,array(reset($row)));
 				}
 			} else {
 				$sql = "DELETE FROM $table WHERE expiry < $time";
-				$rs =& $conn->Execute($sql);
+				$rs = $conn->Execute($sql);
 				ADODB_Session::_dumprs($rs);
 				if ($rs) $rs->Close();
 			}
@@ -899,7 +893,7 @@
 			}
 			$sql .= " FROM $table";
 
-			$rs =& $conn->SelectLimit($sql, 1);
+			$rs = $conn->SelectLimit($sql, 1);
 			if ($rs && !$rs->EOF) {
 				$dbts = reset($rs->fields);
 				$rs->Close();
Index: session/adodb-session2.php
===================================================================
--- session/adodb-session2.php	(revision 0)
+++ session/adodb-session2.php	(revision 0)
@@ -0,0 +1,946 @@
+<?php
+
+
+/*
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+	  
+
+*/
+
+/*
+
+CREATE Table SCripts
+
+Oracle
+======
+
+CREATE TABLE SESSIONS2
+(
+  SESSKEY    VARCHAR2(48 BYTE)                  NOT NULL,
+  EXPIRY     DATE                               NOT NULL,
+  EXPIREREF  VARCHAR2(200 BYTE),
+  CREATED    DATE                               NOT NULL,
+  MODIFIED   DATE                               NOT NULL,
+  SESSDATA   CLOB,
+  PRIMARY KEY(SESSKEY)
+);
+
+
+CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
+CREATE UNIQUE INDEX SESS2_PK ON SESSIONS2(SESSKEY);
+CREATE INDEX SESS2_EXP_REF ON SESSIONS2(EXPIREREF);
+
+
+ 
+ MySQL
+ =====
+ 
+CREATE TABLE sessions2(
+	sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
+	expiry TIMESTAMP NOT NULL ,
+	expireref VARCHAR( 250 ) DEFAULT '',
+	created TIMESTAMP NOT NULL ,
+	modified TIMESTAMP NOT NULL ,
+	sessdata LONGTEXT DEFAULT '',
+	PRIMARY KEY ( sesskey ) ,
+	INDEX sess2_expiry( expiry ),
+	INDEX sess2_expireref( expireref )
+)
+
+
+*/
+
+if (!defined('_ADODB_LAYER')) {
+	require realpath(dirname(__FILE__) . '/../adodb.inc.php');
+}
+
+if (defined('ADODB_SESSION')) return 1;
+
+define('ADODB_SESSION', dirname(__FILE__));
+define('ADODB_SESSION2', ADODB_SESSION);
+
+/* 
+	Unserialize session data manually. See http://phplens.com/lens/lensforum/msgs.php?id=9821 
+	
+	From Kerr Schere, to unserialize session data stored via ADOdb. 
+	1. Pull the session data from the db and loop through it. 
+	2. Inside the loop, you will need to urldecode the data column. 
+	3. After urldecode, run the serialized string through this function:
+
+*/
+function adodb_unserialize( $serialized_string ) 
+{
+	$variables = array( );
+	$a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
+	for( $i = 0; $i < count( $a ); $i = $i+2 ) {
+		$variables[$a[$i]] = unserialize( $a[$i+1] );
+	}
+	return( $variables );
+}
+
+/*
+	Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1
+	Since adodb 4.61.
+*/
+function adodb_session_regenerate_id() 
+{
+	$conn = ADODB_Session::_conn();
+	if (!$conn) return false;
+
+	$old_id = session_id();
+	if (function_exists('session_regenerate_id')) {
+		session_regenerate_id();
+	} else {
+		session_id(md5(uniqid(rand(), true)));
+		$ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		//@session_start();
+	}
+	$new_id = session_id();
+	$ok = $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	
+	/* it is possible that the update statement fails due to a collision */
+	if (!$ok) {
+		session_id($old_id);
+		if (empty($ck)) $ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		return false;
+	}
+	
+	return true;
+}
+
+/*
+    Generate database table for session data
+    @see http://phplens.com/lens/lensforum/msgs.php?id=12280
+    @return 0 if failure, 1 if errors, 2 if successful.
+	@author Markus Staab http://www.public-4u.de
+*/
+function adodb_session_create_table($schemaFile=null,$conn = null)
+{
+    // set default values
+    if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema2.xml';
+    if ($conn===null) $conn = ADODB_Session::_conn();
+
+	if (!$conn) return 0;
+
+    $schema = new adoSchema($conn);
+    $schema->ParseSchema($schemaFile);
+    return $schema->ExecuteSchema();
+}
+
+/*!
+	\static
+*/
+class ADODB_Session {
+	/////////////////////
+	// getter/setter methods
+	/////////////////////
+	
+	/*
+	
+	function Lock($lock=null)
+	{
+	static $_lock = false;
+	
+		if (!is_null($lock)) $_lock = $lock;
+		return $lock;
+	}
+	*/
+	/*!
+	*/
+	static function driver($driver = null) 
+	{
+		static $_driver = 'mysql';
+		static $set = false;
+
+		if (!is_null($driver)) {
+			$_driver = trim($driver);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DRIVER'])) {
+				return $GLOBALS['ADODB_SESSION_DRIVER'];
+			}
+		}
+
+		return $_driver;
+	}
+
+	/*!
+	*/
+	static function host($host = null) {
+		static $_host = 'localhost';
+		static $set = false;
+
+		if (!is_null($host)) {
+			$_host = trim($host);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_CONNECT'])) {
+				return $GLOBALS['ADODB_SESSION_CONNECT'];
+			}
+		}
+
+		return $_host;
+	}
+
+	/*!
+	*/
+	static function user($user = null) 
+	{
+		static $_user = 'root';
+		static $set = false;
+
+		if (!is_null($user)) {
+			$_user = trim($user);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USER'])) {
+				return $GLOBALS['ADODB_SESSION_USER'];
+			}
+		}
+
+		return $_user;
+	}
+
+	/*!
+	*/
+	static function password($password = null) 
+	{
+		static $_password = '';
+		static $set = false;
+
+		if (!is_null($password)) {
+			$_password = $password;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_PWD'])) {
+				return $GLOBALS['ADODB_SESSION_PWD'];
+			}
+		}
+
+		return $_password;
+	}
+
+	/*!
+	*/
+	static function database($database = null) 
+	{
+		static $_database = '';
+		static $set = false;
+		
+		if (!is_null($database)) {
+			$_database = trim($database);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DB'])) {
+				return $GLOBALS['ADODB_SESSION_DB'];
+			}
+		}
+		return $_database;
+	}
+
+	/*!
+	*/
+	static function persist($persist = null) 
+	{
+		static $_persist = true;
+
+		if (!is_null($persist)) {
+			$_persist = trim($persist);
+		}
+
+		return $_persist;
+	}
+
+	/*!
+	*/
+	static function lifetime($lifetime = null) 
+	{
+		static $_lifetime;
+		static $set = false;
+
+		if (!is_null($lifetime)) {
+			$_lifetime = (int) $lifetime;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_LIFE'])) {
+				return $GLOBALS['ADODB_SESS_LIFE'];
+			}
+		}
+		if (!$_lifetime) {
+			$_lifetime = ini_get('session.gc_maxlifetime');
+			if ($_lifetime <= 1) {
+				// bug in PHP 4.0.3 pl 1  -- how about other versions?
+				//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $lifetime</h3>";
+				$_lifetime = 1440;
+			}
+		}
+
+		return $_lifetime;
+	}
+
+	/*!
+	*/
+	static function debug($debug = null) 
+	{
+		static $_debug = false;
+		static $set = false;
+
+		if (!is_null($debug)) {
+			$_debug = (bool) $debug;
+
+			$conn = ADODB_Session::_conn();
+			if ($conn) {
+				#$conn->debug = $_debug;
+			}
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_DEBUG'])) {
+				return $GLOBALS['ADODB_SESS_DEBUG'];
+			}
+		}
+
+		return $_debug;
+	}
+
+	/*!
+	*/
+	static function expireNotify($expire_notify = null) 
+	{
+		static $_expire_notify;
+		static $set = false;
+
+		if (!is_null($expire_notify)) {
+			$_expire_notify = $expire_notify;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'])) {
+				return $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'];
+			}
+		}
+
+		return $_expire_notify;
+	}
+
+	/*!
+	*/
+	static function table($table = null) 
+	{
+		static $_table = 'sessions2';
+		static $set = false;
+
+		if (!is_null($table)) {
+			$_table = trim($table);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_TBL'])) {
+				return $GLOBALS['ADODB_SESSION_TBL'];
+			}
+		}
+
+		return $_table;
+	}
+
+	/*!
+	*/
+	static function optimize($optimize = null) 
+	{
+		static $_optimize = false;
+		static $set = false;
+
+		if (!is_null($optimize)) {
+			$_optimize = (bool) $optimize;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (defined('ADODB_SESSION_OPTIMIZE')) {
+				return true;
+			}
+		}
+
+		return $_optimize;
+	}
+
+	/*!
+	*/
+	static function syncSeconds($sync_seconds = null) {
+		//echo ("<p>WARNING: ADODB_SESSION::syncSeconds is longer used, please remove this function for your code</p>");
+		
+		return 0;
+	}
+
+	/*!
+	*/
+	static function clob($clob = null) {
+		static $_clob = false;
+		static $set = false;
+
+		if (!is_null($clob)) {
+			$_clob = strtolower(trim($clob));
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USE_LOBS'])) {
+				return $GLOBALS['ADODB_SESSION_USE_LOBS'];
+			}
+		}
+
+		return $_clob;
+	}
+
+	/*!
+	*/
+	static function dataFieldName($data_field_name = null) {
+		//echo ("<p>WARNING: ADODB_SESSION::dataFieldName() is longer used, please remove this function for your code</p>");
+		return '';
+	}
+
+	/*!
+	*/
+	static function filter($filter = null) {
+		static $_filter = array();
+
+		if (!is_null($filter)) {
+			if (!is_array($filter)) {
+				$filter = array($filter);
+			}
+			$_filter = $filter;
+		}
+
+		return $_filter;
+	}
+
+	/*!
+	*/
+	static function encryptionKey($encryption_key = null) {
+		static $_encryption_key = 'CRYPTED ADODB SESSIONS ROCK!';
+
+		if (!is_null($encryption_key)) {
+			$_encryption_key = $encryption_key;
+		}
+
+		return $_encryption_key;
+	}
+
+	/////////////////////
+	// private methods
+	/////////////////////
+
+	/*!
+	*/
+	static function _conn($conn=null) {
+		return isset($GLOBALS['ADODB_SESS_CONN']) ? $GLOBALS['ADODB_SESS_CONN'] : false;
+	}
+
+	/*!
+	*/
+	static function _crc($crc = null) {
+		static $_crc = false;
+
+		if (!is_null($crc)) {
+			$_crc = $crc;
+		}
+
+		return $_crc;
+	}
+
+	/*!
+	*/
+	static function _init() {
+		session_module_name('user');
+		session_set_save_handler(
+			array('ADODB_Session', 'open'),
+			array('ADODB_Session', 'close'),
+			array('ADODB_Session', 'read'),
+			array('ADODB_Session', 'write'),
+			array('ADODB_Session', 'destroy'),
+			array('ADODB_Session', 'gc')
+		);
+	}
+
+
+	/*!
+	*/
+	static function _sessionKey() {
+		// use this function to create the encryption key for crypted sessions
+		// crypt the used key, ADODB_Session::encryptionKey() as key and session_id() as salt
+		return crypt(ADODB_Session::encryptionKey(), session_id());
+	}
+
+	/*!
+	*/
+	static function _dumprs(&$rs) {
+		$conn	= ADODB_Session::_conn();
+		$debug	= ADODB_Session::debug();
+
+		if (!$conn) {
+			return;
+		}
+
+		if (!$debug) {
+			return;
+		}
+
+		if (!$rs) {
+			echo "<br />\$rs is null or false<br />\n";
+			return;
+		}
+
+		//echo "<br />\nAffected_Rows=",$conn->Affected_Rows(),"<br />\n";
+
+		if (!is_object($rs)) {
+			return;
+		}
+		$rs = $conn->_rs2rs($rs);
+		
+		require_once ADODB_SESSION.'/../tohtml.inc.php';
+		rs2html($rs);
+		$rs->MoveFirst();
+	}
+
+	/////////////////////
+	// public methods
+	/////////////////////
+	
+	static function config($driver, $host, $user, $password, $database=false,$options=false)
+	{
+		ADODB_Session::driver($driver);
+		ADODB_Session::host($host);
+		ADODB_Session::user($user);
+		ADODB_Session::password($password);
+		ADODB_Session::database($database);
+		
+		if ($driver == 'oci8' || $driver == 'oci8po') $options['lob'] = 'CLOB';
+		
+		if (isset($options['table'])) ADODB_Session::table($options['table']);
+		if (isset($options['lob'])) ADODB_Session::clob($options['lob']);
+		if (isset($options['debug'])) ADODB_Session::debug($options['debug']);
+	}
+
+	/*!
+		Create the connection to the database.
+
+		If $conn already exists, reuse that connection
+	*/
+	static function open($save_path, $session_name, $persist = null) 
+	{
+		$conn = ADODB_Session::_conn();
+
+		if ($conn) {
+			return true;
+		}
+
+		$database	= ADODB_Session::database();
+		$debug		= ADODB_Session::debug();
+		$driver		= ADODB_Session::driver();
+		$host		= ADODB_Session::host();
+		$password	= ADODB_Session::password();
+		$user		= ADODB_Session::user();
+
+		if (!is_null($persist)) {
+			ADODB_Session::persist($persist);
+		} else {
+			$persist = ADODB_Session::persist();
+		}
+
+# these can all be defaulted to in php.ini
+#		assert('$database');
+#		assert('$driver');
+#		assert('$host');
+
+		$conn = ADONewConnection($driver);
+
+		if ($debug) {
+			$conn->debug = true;		
+			ADOConnection::outp( " driver=$driver user=$user db=$database ");
+		}
+		
+		if (empty($conn->_connectionID)) { // not dsn
+			if ($persist) {
+				switch($persist) {
+				default:
+				case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break;
+				case 'C': $ok = $conn->Connect($host, $user, $password, $database); break;
+				case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break;
+				}
+			} else {
+				$ok = $conn->Connect($host, $user, $password, $database);
+			}
+		}
+
+		if ($ok) $GLOBALS['ADODB_SESS_CONN'] = $conn;
+		else
+			ADOConnection::outp('<p>Session: connection failed</p>', false);
+		
+
+		return $ok;
+	}
+
+	/*!
+		Close the connection
+	*/
+	static function close() 
+	{
+/*
+		$conn = ADODB_Session::_conn();
+		if ($conn) $conn->Close();
+*/
+		return true;
+	}
+
+	/*
+		Slurp in the session variables and return the serialized string
+	*/
+	static function read($key) 
+	{
+		$conn	= ADODB_Session::_conn();
+		$filter	= ADODB_Session::filter();
+		$table	= ADODB_Session::table();
+
+		if (!$conn) {
+			return '';
+		}
+
+		//assert('$table');
+
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+	
+		$sql = "SELECT sessdata FROM $table WHERE sesskey = $binary ".$conn->Param(0)." AND expiry >= " . $conn->sysTimeStamp;
+		/* Lock code does not work as it needs to hold transaction within whole page, and we don't know if 
+		  developer has commited elsewhere... :(
+		 */
+		#if (ADODB_Session::Lock())
+		#	$rs = $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), sessdata);
+		#else
+			$rs = $conn->Execute($sql, array($key));
+		//ADODB_Session::_dumprs($rs);
+		if ($rs) {
+			if ($rs->EOF) {
+				$v = '';
+			} else {
+				$v = reset($rs->fields);
+				$filter = array_reverse($filter);
+				foreach ($filter as $f) {
+					if (is_object($f)) {
+						$v = $f->read($v, ADODB_Session::_sessionKey());
+					}
+				}
+				$v = rawurldecode($v);
+			}
+
+			$rs->Close();
+
+			ADODB_Session::_crc(strlen($v) . crc32($v));
+			return $v;
+		}
+
+		return '';
+	}
+
+	/*!
+		Write the serialized data to a database.
+
+		If the data has not been modified since the last read(), we do not write.
+	*/
+	static function write($key, $oval) 
+	{
+	global $ADODB_SESSION_READONLY;
+	
+		if (!empty($ADODB_SESSION_READONLY)) return;
+		
+		$clob			= ADODB_Session::clob();
+		$conn			= ADODB_Session::_conn();
+		$crc			= ADODB_Session::_crc();
+		$debug			= ADODB_Session::debug();
+		$driver			= ADODB_Session::driver();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$filter			= ADODB_Session::filter();
+		$lifetime		= ADODB_Session::lifetime();
+		$table			= ADODB_Session::table();
+	
+		if (!$conn) {
+			return false;
+		}
+		if ($debug) $conn->debug = 1;
+		$sysTimeStamp = $conn->sysTimeStamp;
+		
+		//assert('$table');
+
+		$expiry = $conn->OffsetDate($lifetime/(24*3600),$sysTimeStamp);
+
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		// crc32 optimization since adodb 2.1
+		// now we only update expiry date, thx to sebastian thom in adodb 2.32
+		if ($crc !== false && $crc == (strlen($oval) . crc32($oval))) {
+			if ($debug) {
+				echo '<p>Session: Only updating date - crc32 not changed</p>';
+			}
+			
+			$expirevar = '';
+			if ($expire_notify) {
+				$var = reset($expire_notify);
+				global $$var;
+				if (isset($$var)) {
+					$expirevar = $$var;
+				}
+			}
+			
+			
+			$sql = "UPDATE $table SET expiry = $expiry ,expireref=".$conn->Param('0').", modified = $sysTimeStamp WHERE $binary sesskey = ".$conn->Param('1')." AND expiry >= $sysTimeStamp";
+			$rs = $conn->Execute($sql,array($expirevar,$key));
+			return true;
+		}
+		$val = rawurlencode($oval);
+		foreach ($filter as $f) {
+			if (is_object($f)) {
+				$val = $f->write($val, ADODB_Session::_sessionKey());
+			}
+		}
+
+		$expireref = '';
+		if ($expire_notify) {
+			$var = reset($expire_notify);
+			global $$var;
+			if (isset($$var)) {
+				$expireref = $$var;
+			}
+		} 
+
+		if (!$clob) {	// no lobs, simply use replace()
+			$rs = $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
+			if ($rs) $rs->Close();
+					
+			if ($rs && reset($rs->fields) > 0) {
+				$sql = "UPDATE $table SET expiry=$expiry, sessdata=".$conn->Param(0).", expireref= ".$conn->Param(1).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param('2');
+				
+			} else {
+				$sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified) 
+					VALUES ($expiry,".$conn->Param('0').", ". $conn->Param('1').", ".$conn->Param('2').", $sysTimeStamp, $sysTimeStamp)";
+			}
+			
+	
+			$rs = $conn->Execute($sql,array($val,$expireref,$key));
+			
+		} else {
+			// what value shall we insert/update for lob row?
+			switch ($driver) {
+				// empty_clob or empty_lob for oracle dbs
+				case 'oracle':
+				case 'oci8':
+				case 'oci8po':
+				case 'oci805':
+					$lob_value = sprintf('empty_%s()', strtolower($clob));
+					break;
+
+				// null for all other
+				default:
+					$lob_value = 'null';
+					break;
+			}
+			
+			$conn->StartTrans();
+			
+			$rs = $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
+					
+			if ($rs && reset($rs->fields) > 0) {
+				$sql = "UPDATE $table SET expiry=$expiry, sessdata=$lob_value, expireref= ".$conn->Param(0).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param('1');
+				
+			} else {
+				$sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified) 
+					VALUES ($expiry,$lob_value, ". $conn->Param('0').", ".$conn->Param('1').", $sysTimeStamp, $sysTimeStamp)";
+			}
+			
+			$rs = $conn->Execute($sql,array($expireref,$key));
+			
+			$qkey = $conn->qstr($key);
+			$rs2 = $conn->UpdateBlob($table, 'sessdata', $val, " sesskey=$qkey", strtoupper($clob));
+			if ($debug) echo "<hr>",htmlspecialchars($oval), "<hr>";
+			$rs = @$conn->CompleteTrans();
+			
+			
+		}
+
+		if (!$rs) {
+			ADOConnection::outp('<p>Session Replace: ' . $conn->ErrorMsg() . '</p>', false);
+			return false;
+		}  else {
+			// bug in access driver (could be odbc?) means that info is not committed
+			// properly unless select statement executed in Win2000
+			if ($conn->databaseType == 'access') {
+				$sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey";
+				$rs = $conn->Execute($sql);
+				ADODB_Session::_dumprs($rs);
+				if ($rs) {
+					$rs->Close();
+				}
+			}
+		}/*
+		if (ADODB_Session::Lock()) {
+			$conn->CommitTrans();
+		}*/
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	static function destroy($key) {
+		$conn			= ADODB_Session::_conn();
+		$table			= ADODB_Session::table();
+		$expire_notify	= ADODB_Session::expireNotify();
+
+		if (!$conn) {
+			return false;
+		}
+		$debug			= ADODB_Session::debug();
+		if ($debug) $conn->debug = 1;
+		//assert('$table');
+
+		$qkey = $conn->quote($key);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+			$sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey";
+			$rs = $conn->Execute($sql);
+			ADODB_Session::_dumprs($rs);
+			$conn->SetFetchMode($savem);
+			if (!$rs) {
+				return false;
+			}
+			if (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				//assert('$ref');
+				//assert('$key');
+				$fn($ref, $key);
+			}
+			$rs->Close();
+		}
+
+		$sql = "DELETE FROM $table WHERE $binary sesskey = $qkey";
+		$rs = $conn->Execute($sql);
+		if ($rs) {
+			$rs->Close();
+		}
+
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	static function gc($maxlifetime) 
+	{
+		$conn			= ADODB_Session::_conn();
+		$debug			= ADODB_Session::debug();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$optimize		= ADODB_Session::optimize();
+		$table			= ADODB_Session::table();
+
+		if (!$conn) {
+			return false;
+		}
+
+
+		$debug			= ADODB_Session::debug();
+		if ($debug) {
+			$conn->debug = 1;
+			$COMMITNUM = 2;
+		} else {
+			$COMMITNUM = 20;
+		}
+		
+		//assert('$table');
+
+		$time = $conn->OffsetDate(-$maxlifetime/24/3600,$conn->sysTimeStamp);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+		} else {
+			$fn = false;
+		}
+		
+		$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+		$sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time ORDER BY 2"; # add order by to prevent deadlock
+		$rs = $conn->SelectLimit($sql,1000);
+		ADODB_Session::_dumprs($rs);
+		if ($debug) $conn->SetFetchMode($savem);
+		if ($rs) {
+			$tr = $conn->hasTransactions;
+			if ($tr) $conn->BeginTrans();
+			$keys = array();
+			$ccnt = 0;
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				if ($fn) $fn($ref, $key);
+				$del = $conn->Execute("DELETE FROM $table WHERE sesskey=".$conn->Param('0'),array($key));
+				$rs->MoveNext();
+				$ccnt += 1;
+				if ($tr && $ccnt % $COMMITNUM == 0) {
+					if ($debug) echo "Commit<br>\n";
+					$conn->CommitTrans();
+					$conn->BeginTrans();
+				}
+			}
+			$rs->Close();
+			
+			if ($tr) $conn->CommitTrans();
+		}
+		
+
+		// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+		if ($optimize) {
+			$driver = ADODB_Session::driver();
+
+			if (preg_match('/mysql/i', $driver)) {
+				$sql = "OPTIMIZE TABLE $table";
+			}
+			if (preg_match('/postgres/i', $driver)) {
+				$sql = "VACUUM $table";
+			}
+			if (!empty($sql)) {
+				$conn->Execute($sql);
+			}
+		}
+
+		
+		return true;
+	}
+}
+
+ADODB_Session::_init();
+if (empty($ADODB_SESSION_READONLY))
+	register_shutdown_function('session_write_close');
+
+// for backwards compatability only
+function adodb_sess_open($save_path, $session_name, $persist = true) {
+	return ADODB_Session::open($save_path, $session_name, $persist);
+}
+
+// for backwards compatability only
+function adodb_sess_gc($t)
+{	
+	return ADODB_Session::gc($t);
+}
+
+?>
\ No newline at end of file

Property changes on: session\adodb-session2.php
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: session/adodb-sessions.mysql.sql
===================================================================
--- session/adodb-sessions.mysql.sql	(revision 0)
+++ session/adodb-sessions.mysql.sql	(revision 0)
@@ -0,0 +1,16 @@
+-- $CVSHeader$
+
+CREATE DATABASE /*! IF NOT EXISTS */ adodb_sessions;
+
+USE adodb_sessions;
+
+DROP TABLE /*! IF EXISTS */ sessions;
+
+CREATE TABLE /*! IF NOT EXISTS */ sessions (
+	sesskey		CHAR(32)	/*! BINARY */ NOT NULL DEFAULT '',
+	expiry		INT(11)		/*! UNSIGNED */ NOT NULL DEFAULT 0,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		LONGTEXT	DEFAULT '',
+	PRIMARY KEY	(sesskey),
+	INDEX expiry (expiry)
+);
Index: session/adodb-sessions.oracle.clob.sql
===================================================================
--- session/adodb-sessions.oracle.clob.sql	(revision 0)
+++ session/adodb-sessions.oracle.clob.sql	(revision 0)
@@ -0,0 +1,15 @@
+-- $CVSHeader$
+
+DROP TABLE adodb_sessions;
+
+CREATE TABLE sessions (
+	sesskey		CHAR(32)	DEFAULT '' NOT NULL,
+	expiry		INT		DEFAULT 0 NOT NULL,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		CLOB		DEFAULT '',
+	PRIMARY KEY	(sesskey)
+);
+
+CREATE INDEX ix_expiry ON sessions (expiry);
+
+QUIT;
Index: session/adodb-sessions.oracle.sql
===================================================================
--- session/adodb-sessions.oracle.sql	(revision 0)
+++ session/adodb-sessions.oracle.sql	(revision 0)
@@ -0,0 +1,16 @@
+-- $CVSHeader$
+
+DROP TABLE adodb_sessions;
+
+CREATE TABLE sessions (
+	sesskey		CHAR(32)	DEFAULT '' NOT NULL,
+	expiry		INT		DEFAULT 0 NOT NULL,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		VARCHAR(4000)	DEFAULT '',
+	PRIMARY KEY	(sesskey),
+	INDEX expiry (expiry)
+);
+
+CREATE INDEX ix_expiry ON sessions (expiry);
+
+QUIT;
Index: session/old/adodb-cryptsession.php
===================================================================
--- session/old/adodb-cryptsession.php	(revision 13354)
+++ session/old/adodb-cryptsession.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V5.11 5 May 2010   (c) 2000-2010 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.
@@ -281,7 +281,7 @@
 	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
 	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
 	
-	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	$rs = $ADODB_SESS_CONN->SelectLimit($sql,1);
 	if ($rs && !$rs->EOF) {
 	
 		$dbts = reset($rs->fields);
Index: session/old/adodb-session-clob.php
===================================================================
--- session/old/adodb-session-clob.php	(revision 13354)
+++ session/old/adodb-session-clob.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V4.93 10 Oct 2006  (c) 2000-2010 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.
@@ -405,7 +405,7 @@
 	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
 	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
 	
-	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	$rs = $ADODB_SESS_CONN->SelectLimit($sql,1);
 	if ($rs && !$rs->EOF) {
 	
 		$dbts = reset($rs->fields);
Index: session/old/adodb-session.php
===================================================================
--- session/old/adodb-session.php	(revision 13354)
+++ session/old/adodb-session.php	(working copy)
@@ -1,6 +1,6 @@
 <?php
 /*
-V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+V4.93 10 Oct 2006  (c) 2000-2010 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.
@@ -112,7 +112,7 @@
 */
 function adodb_session_regenerate_id() 
 {
-	$conn =& ADODB_Session::_conn();
+	$conn = ADODB_Session::_conn();
 	if (!$conn) return false;
 
 	$old_id = session_id();
@@ -125,7 +125,7 @@
 		//@session_start();
 	}
 	$new_id = session_id();
-	$ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	$ok = $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
 	
 	/* it is possible that the update statement fails due to a collision */
 	if (!$ok) {
@@ -350,7 +350,7 @@
 		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
 		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
 		$t = time();
-		$rs =& $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
 		$ADODB_SESS_CONN->SetFetchMode($savem);
 		if ($rs) {
 			$ADODB_SESS_CONN->BeginTrans();
@@ -394,7 +394,7 @@
 	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
 	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
 	
-	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	$rs = $ADODB_SESS_CONN->SelectLimit($sql,1);
 	if ($rs && !$rs->EOF) {
 	
 		$dbts = reset($rs->fields);
Index: session/session_schema.xml
===================================================================
--- session/session_schema.xml	(revision 0)
+++ session/session_schema.xml	(revision 0)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<schema version="0.2">
+  <table name="sessions">
+    <desc>table for ADOdb session-management</desc>
+
+    <field name="SESSKEY" type="C" size="32">
+      <descr>session key</descr>
+      <KEY/>
+      <NOTNULL/>
+    </field>
+ 
+    <field name="EXPIRY" type="I" size="11">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+
+    <field name="EXPIREREF" type="C" size="64">
+      <descr></descr>
+    </field>
+
+    <field name="DATA" type="XL">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+  </table>
+</schema>

Property changes on: session\session_schema.xml
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: session/session_schema2.xml
===================================================================
--- session/session_schema2.xml	(revision 0)
+++ session/session_schema2.xml	(revision 0)
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<schema version="0.3">
+  <table name="sessions2">
+    <desc>table for ADOdb session-management</desc>
+
+    <field name="SESSKEY" type="C" size="64">
+      <descr>session key</descr>
+      <KEY/>
+      <NOTNULL/>
+    </field>
+ 
+
+	
+    <field name="EXPIRY" type="T">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+	
+	 	<field name="CREATED" type="T">
+	     <descr></descr>
+      <NOTNULL/>
+    </field>
+	
+	 	<field name="MODIFIED" type="T">
+	     <descr></descr>
+      <NOTNULL/>
+    </field>
+
+    <field name="EXPIREREF" type="C" size="250">
+      <descr></descr>
+    </field>
+
+    <field name="SESSDATA" type="XL">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+  </table>
+</schema>

Property changes on: session\session_schema2.xml
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Index: toexport.inc.php
===================================================================
--- toexport.inc.php	(revision 13354)
+++ toexport.inc.php	(working copy)
@@ -1,7 +1,7 @@
 <?php
 
 /** 
- * @version V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * @version V4.93 10 Oct 2006 (c) 2000-2010 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. 
@@ -73,9 +73,10 @@
 	if ($addtitles) {
 		$fieldTypes = $rs->FieldTypesArray();
 		reset($fieldTypes);
+		$i = 0;
 		while(list(,$o) = each($fieldTypes)) {
-			
-			$v = $o->name;
+		
+			$v = ($o) ? $o->name : 'Field'.($i++);
 			if ($escquote) $v = str_replace($quote,$escquotequote,$v);
 			$v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
 			$elements[] = $v;
Index: tohtml.inc.php
===================================================================
--- tohtml.inc.php	(revision 13354)
+++ tohtml.inc.php	(working copy)
@@ -1,13 +1,13 @@
 <?php 
 /*
-  V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+  V4.93 10 Oct 2006  (c) 2000-2010 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.
   
   Some pretty-printing by Chris Oxenreider <oxenreid@state.net>
 */ 
-  
+
 // specific code for tohtml
 GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
 
@@ -84,14 +84,18 @@
 			$type = $typearr[$i];
 			switch($type) {
 			case 'D':
-				if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
-				else if (!strpos($v,':')) {
-					$s .= "	<TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";
+				if (strpos($v,':') !== false);
+				else {
+					if (empty($v)) {
+					$s .= "<TD> &nbsp; </TD>\n";
+					} else {
+						$s .= "	<TD>".$rs->UserDate($v,"D d, M Y") ."</TD>\n";				
+					}
+					break;
 				}
-				break;
 			case 'T':
 				if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
-				else $s .= "	<TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";
+				else $s .= "	<TD>".$rs->UserTimeStamp($v,"D d, M Y, H:i:s") ."</TD>\n";
 			break;
 			
 			case 'N':
@@ -100,7 +104,9 @@
 				else
 					$v = round($v,$ADODB_ROUND);
 			case 'I':
-				$s .= "	<TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";
+				$vv = stripslashes((trim($v)));
+				if (strlen($vv) == 0) $vv .= '&nbsp;';
+				$s .= "	<TD align=right>".$vv ."</TD>\n";
 			   	
 			break;
 			/*
@@ -176,7 +182,7 @@
 	
 	for ($i=0; $i<sizeof($arr); $i++) {
 		$s .= '<TR>';
-		$a = &$arr[$i];
+		$a = $arr[$i];
 		if (is_array($a)) 
 			for ($j=0; $j<sizeof($a); $j++) {
 				$val = $a[$j];
Index: xmlschema.dtd
===================================================================
--- xmlschema.dtd	(revision 0)
+++ xmlschema.dtd	(revision 0)
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+<!DOCTYPE adodb_schema [
+<!ELEMENT schema (table*, sql*)>
+<!ATTLIST schema version CDATA #REQUIRED>
+<!ELEMENT table ((field+|DROP), CONSTRAINT*, descr?, index*, data*)>
+<!ELEMENT field ((NOTNULL|KEY|PRIMARY)?, (AUTO|AUTOINCREMENT)?, (DEFAULT|DEFDATE|DEFTIMESTAMP)?, 
+NOQUOTE?, CONSTRAINT*, descr?)>
+<!ELEMENT data (row+)>
+<!ELEMENT row (f+)>
+<!ELEMENT f (#CDATA)>
+<!ELEMENT descr (#CDATA)>
+<!ELEMENT NOTNULL EMPTY>
+<!ELEMENT KEY EMPTY>
+<!ELEMENT PRIMARY EMPTY>
+<!ELEMENT AUTO EMPTY>
+<!ELEMENT AUTOINCREMENT EMPTY>
+<!ELEMENT DEFAULT EMPTY>
+<!ELEMENT DEFDATE EMPTY>
+<!ELEMENT DEFTIMESTAMP EMPTY>
+<!ELEMENT NOQUOTE EMPTY>
+<!ELEMENT DROP EMPTY>
+<!ELEMENT CONSTRAINT (#CDATA)>
+<!ATTLIST table name CDATA #REQUIRED platform CDATA #IMPLIED version CDATA #IMPLIED>
+<!ATTLIST field name CDATA #REQUIRED type (C|C2|X|X2|B|D|T|L|I|F|N) #REQUIRED size CDATA #IMPLIED>
+<!ATTLIST data platform CDATA #IMPLIED>
+<!ATTLIST f name CDATA #IMPLIED>
+<!ATTLIST DEFAULT VALUE CDATA #REQUIRED>
+<!ELEMENT index ((col+|DROP), CLUSTERED?, BITMAP?, UNIQUE?, FULLTEXT?, HASH?, descr?)>
+<!ELEMENT col (#CDATA)>
+<!ELEMENT CLUSTERED EMPTY>
+<!ELEMENT BITMAP EMPTY>
+<!ELEMENT UNIQUE EMPTY>
+<!ELEMENT FULLTEXT EMPTY>
+<!ELEMENT HASH EMPTY>
+<!ATTLIST index name CDATA #REQUIRED platform CDATA #IMPLIED>
+<!ELEMENT sql (query+, descr?)>
+<!ELEMENT query (#CDATA)>
+<!ATTLIST sql name CDATA #IMPLIED platform CDATA #IMPLIED, key CDATA, prefixmethod (AUTO|MANUAL|NONE) >
+] >
\ No newline at end of file
Index: xmlschema03.dtd
===================================================================
--- xmlschema03.dtd	(revision 0)
+++ xmlschema03.dtd	(revision 0)
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!DOCTYPE adodb_schema [
+<!ELEMENT schema (table*, sql*)>
+<!ATTLIST schema version CDATA #REQUIRED>
+<!ELEMENT table (descr?, (field+|DROP), constraint*, opt*, index*, data*)>
+<!ATTLIST table name CDATA #REQUIRED platform CDATA #IMPLIED version CDATA #IMPLIED>
+<!ELEMENT field (descr?, (NOTNULL|KEY|PRIMARY)?, (AUTO|AUTOINCREMENT)?, (DEFAULT|DEFDATE|DEFTIMESTAMP)?, NOQUOTE?, UNSIGNED?, constraint*, opt*)>
+<!ATTLIST field name CDATA #REQUIRED type (C|C2|X|X2|B|D|T|L|I|F|N) #REQUIRED size CDATA #IMPLIED opts CDATA #IMPLIED>
+<!ELEMENT data (descr?, row+)>
+<!ATTLIST data platform CDATA #IMPLIED>
+<!ELEMENT row (f+)>
+<!ELEMENT f (#CDATA)>
+<!ATTLIST f name CDATA #IMPLIED>
+<!ELEMENT descr (#CDATA)>
+<!ELEMENT NOTNULL EMPTY>
+<!ELEMENT KEY EMPTY>
+<!ELEMENT PRIMARY EMPTY>
+<!ELEMENT AUTO EMPTY>
+<!ELEMENT AUTOINCREMENT EMPTY>
+<!ELEMENT DEFAULT EMPTY>
+<!ATTLIST DEFAULT value CDATA #REQUIRED>
+<!ELEMENT DEFDATE EMPTY>
+<!ELEMENT DEFTIMESTAMP EMPTY>
+<!ELEMENT NOQUOTE EMPTY>
+<!ELEMENT UNSIGNED EMPTY>
+<!ELEMENT DROP EMPTY>
+<!ELEMENT constraint (#CDATA)>
+<!ATTLIST constraint platform CDATA #IMPLIED>
+<!ELEMENT opt (#CDATA)>
+<!ATTLIST opt platform CDATA #IMPLIED>
+<!ELEMENT index ((col+|DROP), CLUSTERED?, BITMAP?, UNIQUE?, FULLTEXT?, HASH?, descr?)>
+<!ATTLIST index name CDATA #REQUIRED platform CDATA #IMPLIED>
+<!ELEMENT col (#CDATA)>
+<!ELEMENT CLUSTERED EMPTY>
+<!ELEMENT BITMAP EMPTY>
+<!ELEMENT UNIQUE EMPTY>
+<!ELEMENT FULLTEXT EMPTY>
+<!ELEMENT HASH EMPTY>
+<!ELEMENT sql (query+, descr?)>
+<!ATTLIST sql name CDATA #IMPLIED platform CDATA #IMPLIED, key CDATA, prefixmethod (AUTO|MANUAL|NONE)>
+<!ELEMENT query (#CDATA)>
+<!ATTLIST query platform CDATA #IMPLIED>
+]>
\ No newline at end of file